Version in base suite: 131.0.6778.139-1~deb12u1 Version in overlay suite: 132.0.6834.110-1~deb12u1 Base version: chromium_132.0.6834.110-1~deb12u1 Target version: chromium_132.0.6834.159-1~deb12u1 Base file: /srv/ftp-master.debian.org/ftp/pool/main/c/chromium/chromium_132.0.6834.110-1~deb12u1.dsc Target file: /srv/ftp-master.debian.org/policy/pool/main/c/chromium/chromium_132.0.6834.159-1~deb12u1.dsc /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/app/resources/shell_speaker_icon.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-hdpi/ic_notification_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-hdpi/ic_settings_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-mdpi/ic_notification_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-mdpi/ic_settings_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xhdpi/ic_notification_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xhdpi/ic_settings_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xxhdpi/ic_notification_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xxhdpi/ic_settings_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xxxhdpi/ic_notification_cast.png |binary /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xxxhdpi/ic_settings_cast.png |binary chromium-132.0.6834.159/DEPS | 4 chromium-132.0.6834.159/ash/strings/ash_strings_de.xtb | 2 chromium-132.0.6834.159/ash/strings/ash_strings_es-419.xtb | 2 chromium-132.0.6834.159/ash/strings/ash_strings_es.xtb | 6 chromium-132.0.6834.159/ash/strings/ash_strings_iw.xtb | 54 chromium-132.0.6834.159/ash/strings/ash_strings_nl.xtb | 6 chromium-132.0.6834.159/ash/strings/ash_strings_pt-BR.xtb | 2 chromium-132.0.6834.159/ash/strings/ash_strings_ru.xtb | 4 chromium-132.0.6834.159/ash/strings/ash_strings_sr-Latn.xtb | 8 chromium-132.0.6834.159/ash/strings/ash_strings_sr.xtb | 8 chromium-132.0.6834.159/ash/webui/camera_app_ui/resources/strings/camera_strings_iw.xtb | 2 chromium-132.0.6834.159/build/util/LASTCHANGE | 2 chromium-132.0.6834.159/build/util/LASTCHANGE.committime | 2 chromium-132.0.6834.159/chrome/VERSION | 2 chromium-132.0.6834.159/chrome/app/resources/chromium_strings_iw.xtb | 6 chromium-132.0.6834.159/chrome/app/resources/chromium_strings_ru.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_ar.xtb | 4 chromium-132.0.6834.159/chrome/app/resources/generated_resources_as.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_bs.xtb | 4 chromium-132.0.6834.159/chrome/app/resources/generated_resources_ca.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_de.xtb | 4 chromium-132.0.6834.159/chrome/app/resources/generated_resources_en-GB.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_es-419.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_es.xtb | 8 chromium-132.0.6834.159/chrome/app/resources/generated_resources_et.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_eu.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_fa.xtb | 6 chromium-132.0.6834.159/chrome/app/resources/generated_resources_fr.xtb | 4 chromium-132.0.6834.159/chrome/app/resources/generated_resources_gl.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_id.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_it.xtb | 8 chromium-132.0.6834.159/chrome/app/resources/generated_resources_iw.xtb | 148 chromium-132.0.6834.159/chrome/app/resources/generated_resources_ja.xtb | 4 chromium-132.0.6834.159/chrome/app/resources/generated_resources_kn.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_mk.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_or.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_pl.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_pt-BR.xtb | 14 chromium-132.0.6834.159/chrome/app/resources/generated_resources_ru.xtb | 6 chromium-132.0.6834.159/chrome/app/resources/generated_resources_sl.xtb | 4 chromium-132.0.6834.159/chrome/app/resources/generated_resources_ur.xtb | 2 chromium-132.0.6834.159/chrome/app/resources/generated_resources_vi.xtb | 6 chromium-132.0.6834.159/chrome/app/resources/generated_resources_zh-TW.xtb | 16 chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_iw.xtb | 6 chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_pt-BR.xtb | 6 chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_ru.xtb | 2 chromium-132.0.6834.159/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_iw.xtb | 60 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_am.xtb | 2 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb | 2 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_de.xtb | 6 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_es.xtb | 2 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_fr.xtb | 2 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_it.xtb | 2 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_iw.xtb | 12 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_kn.xtb | 2 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb | 10 chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb | 2 chromium-132.0.6834.159/chrome/chrome_branch_deps.json | 31 chromium-132.0.6834.159/chromecast/DEPS | 14 chromium-132.0.6834.159/chromecast/DIR_METADATA | 6 chromium-132.0.6834.159/chromecast/OWNERS | 20 chromium-132.0.6834.159/chromecast/README.md | 24 chromium-132.0.6834.159/chromecast/activity/queryable_data_host.h | 28 chromium-132.0.6834.159/chromecast/android/DEPS | 4 chromium-132.0.6834.159/chromecast/android/OWNERS | 5 chromium-132.0.6834.159/chromecast/android/lint-baseline.xml | 55 chromium-132.0.6834.159/chromecast/android/lint-suppressions.xml | 67 chromium-132.0.6834.159/chromecast/app/DEPS | 21 chromium-132.0.6834.159/chromecast/app/android/DEPS | 7 chromium-132.0.6834.159/chromecast/app/android/OWNERS | 1 chromium-132.0.6834.159/chromecast/app/android/cast_browser_module_entrypoint.cc | 18 chromium-132.0.6834.159/chromecast/app/android/cast_crash_reporter_client_android.cc | 86 chromium-132.0.6834.159/chromecast/app/android/cast_crash_reporter_client_android.h | 45 chromium-132.0.6834.159/chromecast/app/android/cast_crash_uploader_android.cc | 129 chromium-132.0.6834.159/chromecast/app/android/cast_crash_uploader_android.h | 54 chromium-132.0.6834.159/chromecast/app/android/cast_jni_loader.cc | 22 chromium-132.0.6834.159/chromecast/app/cast_crash_uploader.h | 24 chromium-132.0.6834.159/chromecast/app/cast_crash_uploader_default.cc | 22 chromium-132.0.6834.159/chromecast/app/cast_crash_uploader_default.h | 21 chromium-132.0.6834.159/chromecast/app/cast_main.cc | 14 chromium-132.0.6834.159/chromecast/app/cast_main_delegate.cc | 363 chromium-132.0.6834.159/chromecast/app/cast_main_delegate.h | 75 chromium-132.0.6834.159/chromecast/app/cast_test_launcher.cc | 66 chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client.cc | 68 chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client.h | 38 chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client_unittest.cc | 152 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_am.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ar.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_bg.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_bn.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ca.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_cs.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_da.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_de.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_el.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_en-GB.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_es-419.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_es.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_et.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fa.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fi.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fil.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fr.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_gu.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_he.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hi.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hr.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hu.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_id.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_it.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ja.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_kn.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ko.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_lt.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_lv.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ml.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_mr.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ms.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_nb.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_nl.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pl.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pt-BR.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pt-PT.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ro.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ru.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sk.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sl.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sr.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sv.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sw.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ta.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_te.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_th.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_tr.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_uk.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_vi.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_zh-CN.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_zh-TW.xtb | 5 chromium-132.0.6834.159/chromecast/app/resources/shell_devtools_discovery_page.html | 57 chromium-132.0.6834.159/chromecast/app/verify_cast_locales.py | 61 chromium-132.0.6834.159/chromecast/base/DEPS | 4 chromium-132.0.6834.159/chromecast/base/OWNERS | 1 chromium-132.0.6834.159/chromecast/base/alarm_manager.cc | 104 chromium-132.0.6834.159/chromecast/base/alarm_manager.h | 132 chromium-132.0.6834.159/chromecast/base/alarm_manager_unittest.cc | 497 chromium-132.0.6834.159/chromecast/base/android/OWNERS | 1 chromium-132.0.6834.159/chromecast/base/android/dumpstate_writer.cc | 24 chromium-132.0.6834.159/chromecast/base/android/dumpstate_writer.h | 26 chromium-132.0.6834.159/chromecast/base/android/system_time_change_notifier_android.cc | 32 chromium-132.0.6834.159/chromecast/base/android/system_time_change_notifier_android.h | 34 chromium-132.0.6834.159/chromecast/base/bind_to_task_runner.h | 54 chromium-132.0.6834.159/chromecast/base/bitstream_audio_codecs.cc | 85 chromium-132.0.6834.159/chromecast/base/bitstream_audio_codecs.h | 46 chromium-132.0.6834.159/chromecast/base/cast_constants.cc | 11 chromium-132.0.6834.159/chromecast/base/cast_constants.h | 14 chromium-132.0.6834.159/chromecast/base/cast_features.cc | 357 chromium-132.0.6834.159/chromecast/base/cast_features.h | 80 chromium-132.0.6834.159/chromecast/base/cast_features_internal.cc | 13 chromium-132.0.6834.159/chromecast/base/cast_features_unittest.cc | 306 chromium-132.0.6834.159/chromecast/base/cast_paths.cc | 117 chromium-132.0.6834.159/chromecast/base/cast_paths.h | 40 chromium-132.0.6834.159/chromecast/base/cast_resource.cc | 23 chromium-132.0.6834.159/chromecast/base/cast_resource.h | 105 chromium-132.0.6834.159/chromecast/base/cast_sys_info_android.cc | 128 chromium-132.0.6834.159/chromecast/base/cast_sys_info_android.h | 55 chromium-132.0.6834.159/chromecast/base/cast_sys_info_android_factory.cc | 16 chromium-132.0.6834.159/chromecast/base/cast_sys_info_dummy.cc | 202 chromium-132.0.6834.159/chromecast/base/cast_sys_info_dummy.h | 79 chromium-132.0.6834.159/chromecast/base/cast_sys_info_shlib.cc | 27 chromium-132.0.6834.159/chromecast/base/cast_sys_info_util.h | 19 chromium-132.0.6834.159/chromecast/base/cast_sys_info_util_shlib.cc | 20 chromium-132.0.6834.159/chromecast/base/cast_sys_info_util_simple.cc | 18 chromium-132.0.6834.159/chromecast/base/chromecast_switches.cc | 343 chromium-132.0.6834.159/chromecast/base/chromecast_switches.h | 156 chromium-132.0.6834.159/chromecast/base/component/component.cc | 426 chromium-132.0.6834.159/chromecast/base/component/component.h | 327 chromium-132.0.6834.159/chromecast/base/component/component_internal.h | 118 chromium-132.0.6834.159/chromecast/base/component/component_unittest.cc | 387 chromium-132.0.6834.159/chromecast/base/device_capabilities.h | 257 chromium-132.0.6834.159/chromecast/base/device_capabilities_impl.cc | 418 chromium-132.0.6834.159/chromecast/base/device_capabilities_impl.h | 123 chromium-132.0.6834.159/chromecast/base/device_capabilities_impl_unittest.cc | 649 chromium-132.0.6834.159/chromecast/base/error_codes.cc | 84 chromium-132.0.6834.159/chromecast/base/error_codes.h | 44 chromium-132.0.6834.159/chromecast/base/error_codes_unittest.cc | 71 chromium-132.0.6834.159/chromecast/base/hash_util.cc | 149 chromium-132.0.6834.159/chromecast/base/hash_util.h | 34 chromium-132.0.6834.159/chromecast/base/hash_util_test.cc | 59 chromium-132.0.6834.159/chromecast/base/init_command_line_shlib.cc | 30 chromium-132.0.6834.159/chromecast/base/init_command_line_shlib.h | 32 chromium-132.0.6834.159/chromecast/base/java/OWNERS | 1 chromium-132.0.6834.159/chromecast/base/legacy_app_id_mapper.h | 20 chromium-132.0.6834.159/chromecast/base/legacy_app_id_mapper_dummy.cc | 19 chromium-132.0.6834.159/chromecast/base/metrics/cast_histograms.h | 44 chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper.cc | 360 chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper.h | 197 chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper_unittest.cc | 191 chromium-132.0.6834.159/chromecast/base/metrics/grouped_histogram.cc | 190 chromium-132.0.6834.159/chromecast/base/metrics/grouped_histogram.h | 25 chromium-132.0.6834.159/chromecast/base/metrics/mock_cast_metrics_helper.cc | 15 chromium-132.0.6834.159/chromecast/base/metrics/mock_cast_metrics_helper.h | 50 chromium-132.0.6834.159/chromecast/base/observer.h | 431 chromium-132.0.6834.159/chromecast/base/observer_unittest.cc | 352 chromium-132.0.6834.159/chromecast/base/path_utils.cc | 55 chromium-132.0.6834.159/chromecast/base/path_utils.h | 31 chromium-132.0.6834.159/chromecast/base/path_utils_unittest.cc | 56 chromium-132.0.6834.159/chromecast/base/pref_names.cc | 42 chromium-132.0.6834.159/chromecast/base/pref_names.h | 24 chromium-132.0.6834.159/chromecast/base/process_types.h | 17 chromium-132.0.6834.159/chromecast/base/process_utils.cc | 45 chromium-132.0.6834.159/chromecast/base/process_utils.h | 22 chromium-132.0.6834.159/chromecast/base/process_utils_unittest.cc | 52 chromium-132.0.6834.159/chromecast/base/reactive_java.md | 1293 - chromium-132.0.6834.159/chromecast/base/scoped_temp_file.cc | 37 chromium-132.0.6834.159/chromecast/base/scoped_temp_file.h | 48 chromium-132.0.6834.159/chromecast/base/statistics/weighted_mean.cc | 35 chromium-132.0.6834.159/chromecast/base/statistics/weighted_mean.h | 45 chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average.cc | 56 chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average.h | 62 chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average_unittest.cc | 148 chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression.cc | 120 chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression.h | 93 chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression_unittest.cc | 155 chromium-132.0.6834.159/chromecast/base/system_time_change_notifier.cc | 96 chromium-132.0.6834.159/chromecast/base/system_time_change_notifier.h | 94 chromium-132.0.6834.159/chromecast/base/system_time_change_notifier_unittest.cc | 213 chromium-132.0.6834.159/chromecast/base/task_runner_impl.cc | 34 chromium-132.0.6834.159/chromecast/base/task_runner_impl.h | 44 chromium-132.0.6834.159/chromecast/base/thread_health_checker.cc | 112 chromium-132.0.6834.159/chromecast/base/thread_health_checker.h | 82 chromium-132.0.6834.159/chromecast/base/thread_health_checker_unittest.cc | 106 chromium-132.0.6834.159/chromecast/base/version.h.in | 17 chromium-132.0.6834.159/chromecast/bindings/DEPS | 18 chromium-132.0.6834.159/chromecast/bindings/OWNERS | 1 chromium-132.0.6834.159/chromecast/bindings/bindings_manager.h | 20 chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast.cc | 67 chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast.h | 59 chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast_browsertest.cc | 280 chromium-132.0.6834.159/chromecast/bindings/bindings_manager_fuchsia.cc | 61 chromium-132.0.6834.159/chromecast/bindings/bindings_manager_fuchsia.h | 53 chromium-132.0.6834.159/chromecast/bindings/public/mojom/OWNERS | 2 chromium-132.0.6834.159/chromecast/bindings/public/mojom/api_bindings.mojom | 29 chromium-132.0.6834.159/chromecast/bindings/shared/proto_serializer.h | 52 chromium-132.0.6834.159/chromecast/browser/DEPS | 113 chromium-132.0.6834.159/chromecast/browser/OWNERS | 11 chromium-132.0.6834.159/chromecast/browser/android/DEPS | 8 chromium-132.0.6834.159/chromecast/browser/android/OWNERS | 2 chromium-132.0.6834.159/chromecast/browser/android/apk/AndroidManifest.xml.jinja2 | 96 chromium-132.0.6834.159/chromecast/browser/android/apk/CastBrowserAndroidManifest.xml.jinja2 | 108 chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values-v17/styles.xml | 12 chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values/colors.xml | 4 chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values/strings.xml | 13 chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-anydpi-v26/ic_settings_cast.xml | 7 chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-nodpi/ic_cast_vector.xml | 18 chromium-132.0.6834.159/chromecast/browser/android/apk/res/layout/cast_web_contents_activity.xml | 18 chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/IDeviceLogsProvider.aidl | 33 chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/OWNERS | 2 chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/logs_provider_service.aidl | 5 chromium-132.0.6834.159/chromecast/browser/android/cast_content_window_android.cc | 145 chromium-132.0.6834.159/chromecast/browser/android/cast_content_window_android.h | 60 chromium-132.0.6834.159/chromecast/browser/android/cast_metrics_helper_android.cc | 22 chromium-132.0.6834.159/chromecast/browser/android/cast_web_service_android.cc | 18 chromium-132.0.6834.159/chromecast/browser/application_media_capabilities.cc | 41 chromium-132.0.6834.159/chromecast/browser/application_media_capabilities.h | 50 chromium-132.0.6834.159/chromecast/browser/application_media_info_manager.cc | 110 chromium-132.0.6834.159/chromecast/browser/application_media_info_manager.h | 74 chromium-132.0.6834.159/chromecast/browser/application_media_info_manager_unittest.cc | 104 chromium-132.0.6834.159/chromecast/browser/audio_socket_broker.cc | 193 chromium-132.0.6834.159/chromecast/browser/audio_socket_broker.h | 93 chromium-132.0.6834.159/chromecast/browser/audio_socket_broker_unittest.cc | 162 chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser.cc | 89 chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser.h | 68 chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser_unittest.cc | 186 chromium-132.0.6834.159/chromecast/browser/bluetooth/public/mojom/OWNERS | 2 chromium-132.0.6834.159/chromecast/browser/bluetooth/public/mojom/web_bluetooth.mojom | 29 chromium-132.0.6834.159/chromecast/browser/cast_browser_context.cc | 145 chromium-132.0.6834.159/chromecast/browser/cast_browser_context.h | 66 chromium-132.0.6834.159/chromecast/browser/cast_browser_interface_binders.cc | 139 chromium-132.0.6834.159/chromecast/browser/cast_browser_interface_binders.h | 24 chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts.cc | 774 chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts.h | 168 chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts_simple.cc | 17 chromium-132.0.6834.159/chromecast/browser/cast_browser_process.cc | 120 chromium-132.0.6834.159/chromecast/browser/cast_browser_process.h | 116 chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client.cc | 911 chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client.h | 374 chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client_receiver_bindings.cc | 211 chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler.cc | 123 chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler.h | 50 chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler_test.cc | 238 chromium-132.0.6834.159/chromecast/browser/cast_content_window.cc | 68 chromium-132.0.6834.159/chromecast/browser/cast_content_window.h | 100 chromium-132.0.6834.159/chromecast/browser/cast_content_window_aura.cc | 201 chromium-132.0.6834.159/chromecast/browser/cast_content_window_aura.h | 71 chromium-132.0.6834.159/chromecast/browser/cast_display_configurator.cc | 302 chromium-132.0.6834.159/chromecast/browser/cast_display_configurator.h | 94 chromium-132.0.6834.159/chromecast/browser/cast_download_manager_delegate.cc | 57 chromium-132.0.6834.159/chromecast/browser/cast_download_manager_delegate.h | 40 chromium-132.0.6834.159/chromecast/browser/cast_feature_list_creator.cc | 76 chromium-132.0.6834.159/chromecast/browser/cast_feature_list_creator.h | 57 chromium-132.0.6834.159/chromecast/browser/cast_feature_update_observer.cc | 52 chromium-132.0.6834.159/chromecast/browser/cast_feature_update_observer.h | 47 chromium-132.0.6834.159/chromecast/browser/cast_http_user_agent_settings.cc | 54 chromium-132.0.6834.159/chromecast/browser/cast_http_user_agent_settings.h | 31 chromium-132.0.6834.159/chromecast/browser/cast_media_blocker.cc | 173 chromium-132.0.6834.159/chromecast/browser/cast_media_blocker.h | 114 chromium-132.0.6834.159/chromecast/browser/cast_media_blocker_browsertest.cc | 104 chromium-132.0.6834.159/chromecast/browser/cast_media_blocker_unittest.cc | 392 chromium-132.0.6834.159/chromecast/browser/cast_navigation_ui_data.cc | 58 chromium-132.0.6834.159/chromecast/browser/cast_navigation_ui_data.h | 43 chromium-132.0.6834.159/chromecast/browser/cast_network_contexts.cc | 374 chromium-132.0.6834.159/chromecast/browser/cast_network_contexts.h | 154 chromium-132.0.6834.159/chromecast/browser/cast_overlay_manifests.cc | 47 chromium-132.0.6834.159/chromecast/browser/cast_overlay_manifests.h | 27 chromium-132.0.6834.159/chromecast/browser/cast_permission_manager.cc | 214 chromium-132.0.6834.159/chromecast/browser/cast_permission_manager.h | 71 chromium-132.0.6834.159/chromecast/browser/cast_permission_user_data.cc | 50 chromium-132.0.6834.159/chromecast/browser/cast_permission_user_data.h | 61 chromium-132.0.6834.159/chromecast/browser/cast_renderer_block_data.cc | 72 chromium-132.0.6834.159/chromecast/browser/cast_renderer_block_data.h | 48 chromium-132.0.6834.159/chromecast/browser/cast_resource_bundle_unittest.cc | 49 chromium-132.0.6834.159/chromecast/browser/cast_session_id_map.cc | 185 chromium-132.0.6834.159/chromecast/browser/cast_session_id_map.h | 109 chromium-132.0.6834.159/chromecast/browser/cast_session_id_map_unittest.cc | 115 chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator.cc | 196 chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator.h | 75 chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.cc | 20 chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.h | 29 chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager.cc | 83 chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager.h | 45 chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager_unittest.cc | 128 chromium-132.0.6834.159/chromecast/browser/cast_web_contents.cc | 81 chromium-132.0.6834.159/chromecast/browser/cast_web_contents.h | 321 chromium-132.0.6834.159/chromecast/browser/cast_web_contents_browsertest.cc | 1177 - chromium-132.0.6834.159/chromecast/browser/cast_web_contents_impl.cc | 1070 chromium-132.0.6834.159/chromecast/browser/cast_web_contents_impl.h | 226 chromium-132.0.6834.159/chromecast/browser/cast_web_contents_observer.cc | 23 chromium-132.0.6834.159/chromecast/browser/cast_web_contents_observer.h | 87 chromium-132.0.6834.159/chromecast/browser/cast_web_preferences.cc | 31 chromium-132.0.6834.159/chromecast/browser/cast_web_preferences.h | 47 chromium-132.0.6834.159/chromecast/browser/cast_web_service.cc | 176 chromium-132.0.6834.159/chromecast/browser/cast_web_service.h | 131 chromium-132.0.6834.159/chromecast/browser/cast_web_service_aura.cc | 19 chromium-132.0.6834.159/chromecast/browser/cast_web_view.cc | 16 chromium-132.0.6834.159/chromecast/browser/cast_web_view.h | 60 chromium-132.0.6834.159/chromecast/browser/cast_web_view_default.cc | 302 chromium-132.0.6834.159/chromecast/browser/cast_web_view_default.h | 94 chromium-132.0.6834.159/chromecast/browser/cast_web_view_factory.cc | 26 chromium-132.0.6834.159/chromecast/browser/cast_web_view_factory.h | 44 chromium-132.0.6834.159/chromecast/browser/default_navigation_throttle.cc | 31 chromium-132.0.6834.159/chromecast/browser/default_navigation_throttle.h | 28 chromium-132.0.6834.159/chromecast/browser/devtools/cast_devtools_manager_delegate.cc | 73 chromium-132.0.6834.159/chromecast/browser/devtools/cast_devtools_manager_delegate.h | 50 chromium-132.0.6834.159/chromecast/browser/devtools/cast_devtools_manager_delegate_unittest.cc | 81 chromium-132.0.6834.159/chromecast/browser/devtools/cast_ui_devtools.cc | 50 chromium-132.0.6834.159/chromecast/browser/devtools/cast_ui_devtools.h | 43 chromium-132.0.6834.159/chromecast/browser/devtools/remote_debugging_server.cc | 248 chromium-132.0.6834.159/chromecast/browser/devtools/remote_debugging_server.h | 53 chromium-132.0.6834.159/chromecast/browser/display_configurator_observer.cc | 32 chromium-132.0.6834.159/chromecast/browser/display_configurator_observer.h | 41 chromium-132.0.6834.159/chromecast/browser/general_audience_browsing/mojom/OWNERS | 2 chromium-132.0.6834.159/chromecast/browser/general_audience_browsing/mojom/general_audience_browsing.mojom | 14 chromium-132.0.6834.159/chromecast/browser/general_audience_browsing_navigation_throttle.cc | 92 chromium-132.0.6834.159/chromecast/browser/general_audience_browsing_navigation_throttle.h | 60 chromium-132.0.6834.159/chromecast/browser/general_audience_browsing_service.cc | 110 chromium-132.0.6834.159/chromecast/browser/general_audience_browsing_service.h | 73 chromium-132.0.6834.159/chromecast/browser/gesture_router.cc | 238 chromium-132.0.6834.159/chromecast/browser/gesture_router.h | 110 chromium-132.0.6834.159/chromecast/browser/lru_renderer_cache.cc | 123 chromium-132.0.6834.159/chromecast/browser/lru_renderer_cache.h | 81 chromium-132.0.6834.159/chromecast/browser/lru_renderer_cache_test.cc | 297 chromium-132.0.6834.159/chromecast/browser/media/media_caps_impl.cc | 61 chromium-132.0.6834.159/chromecast/browser/media/media_caps_impl.h | 47 chromium-132.0.6834.159/chromecast/browser/media/supported_codec_finder.cc | 38 chromium-132.0.6834.159/chromecast/browser/media/supported_codec_finder.h | 24 chromium-132.0.6834.159/chromecast/browser/memory_pressure_controller_impl.cc | 36 chromium-132.0.6834.159/chromecast/browser/memory_pressure_controller_impl.h | 45 chromium-132.0.6834.159/chromecast/browser/metrics/DEPS | 5 chromium-132.0.6834.159/chromecast/browser/metrics/DIR_METADATA | 1 chromium-132.0.6834.159/chromecast/browser/metrics/OWNERS | 2 chromium-132.0.6834.159/chromecast/browser/metrics/cast_browser_metrics.cc | 140 chromium-132.0.6834.159/chromecast/browser/metrics/cast_browser_metrics.h | 53 chromium-132.0.6834.159/chromecast/browser/metrics/cast_metrics_prefs.cc | 19 chromium-132.0.6834.159/chromecast/browser/metrics/cast_metrics_prefs.h | 18 chromium-132.0.6834.159/chromecast/browser/metrics/cast_stability_metrics_provider.cc | 128 chromium-132.0.6834.159/chromecast/browser/metrics/cast_stability_metrics_provider.h | 86 chromium-132.0.6834.159/chromecast/browser/metrics/external_metrics.cc | 185 chromium-132.0.6834.159/chromecast/browser/metrics/external_metrics.h | 90 chromium-132.0.6834.159/chromecast/browser/metrics/metrics_helper_impl.cc | 31 chromium-132.0.6834.159/chromecast/browser/metrics/metrics_helper_impl.h | 40 chromium-132.0.6834.159/chromecast/browser/migration/migration_utils.cc | 52 chromium-132.0.6834.159/chromecast/browser/migration/migration_utils.h | 19 chromium-132.0.6834.159/chromecast/browser/migration/migration_utils_test.cc | 68 chromium-132.0.6834.159/chromecast/browser/mojom/OWNERS | 4 chromium-132.0.6834.159/chromecast/browser/mojom/README.md | 18 chromium-132.0.6834.159/chromecast/browser/mojom/cast_content_window.mojom | 105 chromium-132.0.6834.159/chromecast/browser/mojom/cast_web_contents.mojom | 174 chromium-132.0.6834.159/chromecast/browser/mojom/cast_web_service.mojom | 181 chromium-132.0.6834.159/chromecast/browser/mojom/visibility_mojom_traits.h | 99 chromium-132.0.6834.159/chromecast/browser/mojom/web_mojom_traits.h | 56 chromium-132.0.6834.159/chromecast/browser/named_message_port_connector_cast.cc | 78 chromium-132.0.6834.159/chromecast/browser/named_message_port_connector_cast.h | 43 chromium-132.0.6834.159/chromecast/browser/pref_service_helper.cc | 139 chromium-132.0.6834.159/chromecast/browser/pref_service_helper.h | 46 chromium-132.0.6834.159/chromecast/browser/pref_service_helper_simple.cc | 17 chromium-132.0.6834.159/chromecast/browser/renderer_prelauncher.cc | 52 chromium-132.0.6834.159/chromecast/browser/renderer_prelauncher.h | 54 chromium-132.0.6834.159/chromecast/browser/renderer_prelauncher_test.cc | 74 chromium-132.0.6834.159/chromecast/browser/service/cast_service_simple.cc | 84 chromium-132.0.6834.159/chromecast/browser/service/cast_service_simple.h | 47 chromium-132.0.6834.159/chromecast/browser/service_connector.cc | 85 chromium-132.0.6834.159/chromecast/browser/service_connector.h | 67 chromium-132.0.6834.159/chromecast/browser/service_manager_connection.cc | 230 chromium-132.0.6834.159/chromecast/browser/service_manager_connection.h | 87 chromium-132.0.6834.159/chromecast/browser/service_manager_context.cc | 354 chromium-132.0.6834.159/chromecast/browser/service_manager_context.h | 64 chromium-132.0.6834.159/chromecast/browser/system_connector.cc | 65 chromium-132.0.6834.159/chromecast/browser/system_connector.h | 25 chromium-132.0.6834.159/chromecast/browser/test/DEPS | 5 chromium-132.0.6834.159/chromecast/browser/test/cast_browser_test.cc | 92 chromium-132.0.6834.159/chromecast/browser/test/cast_browser_test.h | 59 chromium-132.0.6834.159/chromecast/browser/test/cast_features_browsertest.cc | 320 chromium-132.0.6834.159/chromecast/browser/test/cast_navigation_browsertest.cc | 116 chromium-132.0.6834.159/chromecast/browser/test/data/dynamic_title.html | 12 chromium-132.0.6834.159/chromecast/browser/test/data/interface_binding.html | 17 chromium-132.0.6834.159/chromecast/browser/test/data/load_cancel.html | 8 chromium-132.0.6834.159/chromecast/browser/test/data/location_redirect.html | 8 chromium-132.0.6834.159/chromecast/browser/test/data/message_port.html | 36 chromium-132.0.6834.159/chromecast/browser/test/data/missing_resource.html | 6 chromium-132.0.6834.159/chromecast/browser/test/data/title1.html | 4 chromium-132.0.6834.159/chromecast/browser/test/data/title2.html | 4 chromium-132.0.6834.159/chromecast/browser/test/data/window_post_message.html | 10 chromium-132.0.6834.159/chromecast/browser/test/mock_cast_web_view.cc | 45 chromium-132.0.6834.159/chromecast/browser/test/mock_cast_web_view.h | 108 chromium-132.0.6834.159/chromecast/browser/test_interfaces.test-mojom | 13 chromium-132.0.6834.159/chromecast/browser/visibility_types.h | 81 chromium-132.0.6834.159/chromecast/browser/web_types.cc | 26 chromium-132.0.6834.159/chromecast/browser/web_types.h | 33 chromium-132.0.6834.159/chromecast/browser/webui/cast_resource_data_source.cc | 133 chromium-132.0.6834.159/chromecast/browser/webui/cast_resource_data_source.h | 56 chromium-132.0.6834.159/chromecast/browser/webui/cast_webui.cc | 76 chromium-132.0.6834.159/chromecast/browser/webui/cast_webui.h | 73 chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_controller_factory.cc | 61 chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_controller_factory.h | 46 chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_default.cc | 16 chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_message_handler.cc | 34 chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_message_handler.h | 39 chromium-132.0.6834.159/chromecast/browser/webui/constants.cc | 13 chromium-132.0.6834.159/chromecast/browser/webui/constants.h | 17 chromium-132.0.6834.159/chromecast/browser/webui/mojom/OWNERS | 2 chromium-132.0.6834.159/chromecast/browser/webui/mojom/webui.mojom | 54 chromium-132.0.6834.159/chromecast/cast_core/DEPS | 6 chromium-132.0.6834.159/chromecast/cast_core/OWNERS | 5 chromium-132.0.6834.159/chromecast/cast_core/README.md | 63 chromium-132.0.6834.159/chromecast/cast_core/cast_core_switches.h | 21 chromium-132.0.6834.159/chromecast/cast_core/cast_runtime_main.cc | 14 chromium-132.0.6834.159/chromecast/cast_core/cast_starboard_runtime_main.cc | 153 chromium-132.0.6834.159/chromecast/cast_core/child_log_process.cc | 100 chromium-132.0.6834.159/chromecast/cast_core/child_log_process.h | 26 chromium-132.0.6834.159/chromecast/cast_core/core_runtime_starboard.sym | 4 chromium-132.0.6834.159/chromecast/cast_core/grpc/DEPS | 4 chromium-132.0.6834.159/chromecast/cast_core/grpc/cancellable_reactor.h | 166 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call.h | 83 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call_options.cc | 59 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call_options.h | 40 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_client_reactor.h | 71 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_handler.cc | 20 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_handler.h | 42 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server.cc | 118 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server.h | 128 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_reactor.h | 155 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_call.h | 134 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_handler.h | 142 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_test.cc | 290 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_test.cc | 57 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or.cc | 63 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or.h | 127 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or_test.cc | 112 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_stub.h | 79 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_call.h | 147 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_handler.h | 125 chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_test.cc | 326 chromium-132.0.6834.159/chromecast/cast_core/grpc/server_reactor_tracker.cc | 58 chromium-132.0.6834.159/chromecast/cast_core/grpc/server_reactor_tracker.h | 38 chromium-132.0.6834.159/chromecast/cast_core/grpc/status_matchers.cc | 20 chromium-132.0.6834.159/chromecast/cast_core/grpc/status_matchers.h | 248 chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service.proto | 28 chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service_extra.proto | 18 chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service_messages.proto | 19 chromium-132.0.6834.159/chromecast/cast_core/grpc/test_utils.cc | 29 chromium-132.0.6834.159/chromecast/cast_core/grpc/test_utils.h | 24 chromium-132.0.6834.159/chromecast/cast_core/grpc/trackable_reactor.h | 38 chromium-132.0.6834.159/chromecast/cast_core/runtime/DEPS | 3 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/DEPS | 33 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_core_switches.h | 17 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.cc | 51 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.h | 41 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc | 165 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.h | 98 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_simple.cc | 27 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.cc | 127 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.h | 61 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard_factory.cc | 31 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.cc | 77 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.h | 19 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener_unittest.cc | 166 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.cc | 326 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.h | 91 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.cc | 104 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.h | 59 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.cc | 28 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.h | 27 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_conversions.cc | 86 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_conversions.h | 21 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager.cc | 240 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager.h | 58 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager_unittest.cc | 141 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_handler.cc | 268 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_handler.h | 113 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_service_grpc.cc | 111 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_service_grpc.h | 75 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_application_service_impl.cc | 754 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_application_service_impl.h | 178 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_service_impl.cc | 547 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_service_impl.h | 142 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/DEPS | 6 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/OWNERS | 2 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.cc | 233 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h | 33 chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters_unittest.cc | 288 chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/DEPS | 9 chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.cc | 21 chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.h | 45 chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client_simple.cc | 18 chromium-132.0.6834.159/chromecast/cast_core/test/cast_core_screenshot_test.py | 170 chromium-132.0.6834.159/chromecast/cast_core/test/cast_project_config.py | 17 chromium-132.0.6834.159/chromecast/cast_core/test/data/screenshot.html | 25 chromium-132.0.6834.159/chromecast/cast_core/test/run_cast_integration_test.py | 17 chromium-132.0.6834.159/chromecast/common/DEPS | 19 chromium-132.0.6834.159/chromecast/common/OWNERS | 4 chromium-132.0.6834.159/chromecast/common/activity_filtering_url_loader_throttle.cc | 49 chromium-132.0.6834.159/chromecast/common/activity_filtering_url_loader_throttle.h | 53 chromium-132.0.6834.159/chromecast/common/activity_url_filter.cc | 31 chromium-132.0.6834.159/chromecast/common/activity_url_filter.h | 38 chromium-132.0.6834.159/chromecast/common/activity_url_filter_unittest.cc | 27 chromium-132.0.6834.159/chromecast/common/cast_content_client.cc | 220 chromium-132.0.6834.159/chromecast/common/cast_content_client.h | 50 chromium-132.0.6834.159/chromecast/common/cast_resource_delegate.cc | 114 chromium-132.0.6834.159/chromecast/common/cast_resource_delegate.h | 73 chromium-132.0.6834.159/chromecast/common/cors_exempt_headers.cc | 54 chromium-132.0.6834.159/chromecast/common/cors_exempt_headers.h | 25 chromium-132.0.6834.159/chromecast/common/cors_exempt_headers_unittest.cc | 19 chromium-132.0.6834.159/chromecast/common/feature_constants.cc | 41 chromium-132.0.6834.159/chromecast/common/feature_constants.h | 64 chromium-132.0.6834.159/chromecast/common/global_descriptors.h | 23 chromium-132.0.6834.159/chromecast/common/media/DEPS | 5 chromium-132.0.6834.159/chromecast/common/media/OWNERS | 2 chromium-132.0.6834.159/chromecast/common/media/cast_media_drm_bridge_client.cc | 30 chromium-132.0.6834.159/chromecast/common/media/cast_media_drm_bridge_client.h | 36 chromium-132.0.6834.159/chromecast/common/mojom/OWNERS | 4 chromium-132.0.6834.159/chromecast/common/mojom/activity_url_filter.mojom | 20 chromium-132.0.6834.159/chromecast/common/mojom/activity_window.mojom | 20 chromium-132.0.6834.159/chromecast/common/mojom/application_media_capabilities.mojom | 30 chromium-132.0.6834.159/chromecast/common/mojom/application_media_capabilities_traits.h | 35 chromium-132.0.6834.159/chromecast/common/mojom/assistant_messenger.mojom | 49 chromium-132.0.6834.159/chromecast/common/mojom/audio_socket.mojom | 15 chromium-132.0.6834.159/chromecast/common/mojom/cast_demo.mojom | 80 chromium-132.0.6834.159/chromecast/common/mojom/constants.mojom | 12 chromium-132.0.6834.159/chromecast/common/mojom/feature_manager.mojom | 24 chromium-132.0.6834.159/chromecast/common/mojom/feature_update.mojom | 23 chromium-132.0.6834.159/chromecast/common/mojom/gesture.mojom | 69 chromium-132.0.6834.159/chromecast/common/mojom/js_channel.mojom | 27 chromium-132.0.6834.159/chromecast/common/mojom/media_caps.mojom | 24 chromium-132.0.6834.159/chromecast/common/mojom/memory_pressure.mojom | 14 chromium-132.0.6834.159/chromecast/common/mojom/metrics_helper.mojom | 15 chromium-132.0.6834.159/chromecast/common/mojom/queryable_data_store.mojom | 15 chromium-132.0.6834.159/chromecast/common/mojom/service_connector.mojom | 19 chromium-132.0.6834.159/chromecast/common/mojom/settings_ui.mojom | 53 chromium-132.0.6834.159/chromecast/common/queryable_data.cc | 51 chromium-132.0.6834.159/chromecast/common/queryable_data.h | 55 chromium-132.0.6834.159/chromecast/common/user_agent.cc | 23 chromium-132.0.6834.159/chromecast/common/user_agent.h | 20 chromium-132.0.6834.159/chromecast/common/user_agent_android.cc | 26 chromium-132.0.6834.159/chromecast/common/user_agent_default.cc | 20 chromium-132.0.6834.159/chromecast/common/user_agent_unittest.cc | 56 chromium-132.0.6834.159/chromecast/crash/DEPS | 5 chromium-132.0.6834.159/chromecast/crash/OWNERS | 1 chromium-132.0.6834.159/chromecast/crash/app_state_tracker.cc | 81 chromium-132.0.6834.159/chromecast/crash/app_state_tracker.h | 42 chromium-132.0.6834.159/chromecast/crash/build_info.cc | 59 chromium-132.0.6834.159/chromecast/crash/build_info.h | 27 chromium-132.0.6834.159/chromecast/crash/build_info_unittest.cc | 51 chromium-132.0.6834.159/chromecast/crash/cast_crash_keys.cc | 19 chromium-132.0.6834.159/chromecast/crash/cast_crash_keys.h | 23 chromium-132.0.6834.159/chromecast/crash/cast_crash_storage.cc | 17 chromium-132.0.6834.159/chromecast/crash/cast_crash_storage.h | 37 chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_fuchsia.cc | 19 chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_impl.cc | 58 chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_impl.h | 34 chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader.cc | 139 chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader.h | 65 chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader_unittest.cc | 181 chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.cc | 85 chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.h | 45 chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc | 142 chromium-132.0.6834.159/chromecast/crash/fuchsia/constants.cc | 15 chromium-132.0.6834.159/chromecast/crash/fuchsia/constants.h | 18 chromium-132.0.6834.159/chromecast/crash/libcurl_wrapper.cc | 227 chromium-132.0.6834.159/chromecast/crash/libcurl_wrapper.h | 71 chromium-132.0.6834.159/chromecast/crash/linux/DEPS | 6 chromium-132.0.6834.159/chromecast/crash/linux/crash_testing_utils.cc | 167 chromium-132.0.6834.159/chromecast/crash/linux/crash_testing_utils.h | 51 chromium-132.0.6834.159/chromecast/crash/linux/crash_uploader.cc | 78 chromium-132.0.6834.159/chromecast/crash/linux/crash_util.cc | 165 chromium-132.0.6834.159/chromecast/crash/linux/crash_util.h | 52 chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator.cc | 34 chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator.h | 37 chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator_unittest.cc | 78 chromium-132.0.6834.159/chromecast/crash/linux/dump_info.cc | 229 chromium-132.0.6834.159/chromecast/crash/linux/dump_info.h | 91 chromium-132.0.6834.159/chromecast/crash/linux/dump_info_unittest.cc | 221 chromium-132.0.6834.159/chromecast/crash/linux/minidump_generator.h | 26 chromium-132.0.6834.159/chromecast/crash/linux/minidump_params.cc | 55 chromium-132.0.6834.159/chromecast/crash/linux/minidump_params.h | 68 chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader.cc | 384 chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader.h | 75 chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader_unittest.cc | 469 chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer.cc | 118 chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer.h | 78 chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer_unittest.cc | 135 chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager.cc | 492 chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager.h | 155 chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager_unittest.cc | 509 chromium-132.0.6834.159/chromecast/crypto/signature_cache.cc | 47 chromium-132.0.6834.159/chromecast/crypto/signature_cache.h | 44 chromium-132.0.6834.159/chromecast/crypto/signature_cache_unittest.cc | 58 chromium-132.0.6834.159/chromecast/device/bluetooth/DEPS | 3 chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util.cc | 125 chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util.h | 58 chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util_test.cc | 112 chromium-132.0.6834.159/chromecast/device/bluetooth/le/DEPS | 3 chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_notification_logger.cc | 72 chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_notification_logger.h | 59 chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_types.h | 24 chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager.h | 140 chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl.cc | 629 chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl.h | 202 chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl_test.cc | 1381 - chromium-132.0.6834.159/chromecast/device/bluetooth/le/instantiate_mocks.cc | 36 chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager.h | 102 chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl.cc | 264 chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl.h | 88 chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl_test.cc | 347 chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result.cc | 314 chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result.h | 78 chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result_fuzzer.cc | 13 chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result_test.cc | 406 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_gatt_client_manager.cc | 16 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_gatt_client_manager.h | 83 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_le_scan_manager.cc | 14 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_le_scan_manager.h | 65 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_characteristic.cc | 17 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_characteristic.h | 82 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_descriptor.cc | 14 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_descriptor.h | 39 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_device.cc | 16 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_device.h | 102 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_service.cc | 16 chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_service.h | 42 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic.h | 99 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic_impl.cc | 347 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic_impl.h | 104 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor.cc | 22 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor.h | 72 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor_impl.cc | 118 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor_impl.h | 70 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device.h | 116 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device_impl.cc | 729 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device_impl.h | 201 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service.h | 51 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service_impl.cc | 77 chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service_impl.h | 66 chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter.cc | 54 chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter.h | 41 chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter_test.cc | 122 chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/gatt_client.h | 58 chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/le_scanner.h | 26 chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/mock_gatt_client.h | 74 chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/mock_le_scanner.h | 31 chromium-132.0.6834.159/chromecast/external_mojo/DEPS | 6 chromium-132.0.6834.159/chromecast/external_mojo/OWNERS | 1 chromium-132.0.6834.159/chromecast/external_mojo/README.md | 17 chromium-132.0.6834.159/chromecast/external_mojo/broker_service/broker_service.cc | 157 chromium-132.0.6834.159/chromecast/external_mojo/broker_service/broker_service.h | 92 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/DEPS | 8 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/README.md | 22 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/chromium_service.cc | 97 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/chromium_service.h | 89 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_builtin.cc | 72 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_client.h | 18 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_system.cc | 29 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector.h | 126 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector_impl.cc | 327 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector_impl.h | 93 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_service.cc | 32 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_service.h | 82 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/fake_external_connector.cc | 105 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/fake_external_connector.h | 87 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/perfetto_tracing_client.cc | 36 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/perfetto_tracing_client.h | 37 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/process_setup.cc | 62 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/process_setup.h | 18 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/reconnecting_remote.h | 112 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/service_process.h | 28 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc | 56 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/standalone_service_main.cc | 103 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client.h | 32 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client_dummy.cc | 19 chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client_dummy.h | 26 chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/common.cc | 51 chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/common.h | 20 chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/external_mojo_broker.cc | 481 chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/external_mojo_broker.h | 57 chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/OWNERS | 2 chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/connector.mojom | 59 chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/test_connector.mojom | 13 chromium-132.0.6834.159/chromecast/fuchsia/DEPS | 4 chromium-132.0.6834.159/chromecast/fuchsia/queryable_data_host_fuchsia.cc | 23 chromium-132.0.6834.159/chromecast/fuchsia/queryable_data_host_fuchsia.h | 32 chromium-132.0.6834.159/chromecast/gpu/DEPS | 11 chromium-132.0.6834.159/chromecast/gpu/cast_content_gpu_client.cc | 39 chromium-132.0.6834.159/chromecast/gpu/cast_content_gpu_client.h | 36 chromium-132.0.6834.159/chromecast/graphics/DEPS | 28 chromium-132.0.6834.159/chromecast/graphics/cast_display_util.cc | 23 chromium-132.0.6834.159/chromecast/graphics/cast_display_util.h | 20 chromium-132.0.6834.159/chromecast/graphics/cast_display_util_unittest.cc | 30 chromium-132.0.6834.159/chromecast/graphics/cast_egl_platform_default.cc | 38 chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura.cc | 254 chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura.h | 83 chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura_test.cc | 198 chromium-132.0.6834.159/chromecast/graphics/cast_screen.cc | 88 chromium-132.0.6834.159/chromecast/graphics/cast_screen.h | 63 chromium-132.0.6834.159/chromecast/graphics/cast_screen_unittest.cc | 59 chromium-132.0.6834.159/chromecast/graphics/cast_touch_activity_observer.h | 24 chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate.cc | 57 chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate.h | 47 chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate_test.cc | 116 chromium-132.0.6834.159/chromecast/graphics/cast_views_test.cc | 51 chromium-132.0.6834.159/chromecast/graphics/cast_window_manager.h | 108 chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura.cc | 346 chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura.h | 90 chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura_test.cc | 186 chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_default.cc | 45 chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_default.h | 45 chromium-132.0.6834.159/chromecast/graphics/cast_window_tree_host_aura.cc | 52 chromium-132.0.6834.159/chromecast/graphics/cast_window_tree_host_aura.h | 40 chromium-132.0.6834.159/chromecast/graphics/gestures/cast_gesture_handler.cc | 13 chromium-132.0.6834.159/chromecast/graphics/gestures/cast_gesture_handler.h | 69 chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher.cc | 120 chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher.h | 56 chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher_test.cc | 217 chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_event_handler.cc | 49 chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_event_handler.h | 42 chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector.cc | 156 chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector.h | 98 chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector_test.cc | 185 chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector.cc | 214 chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector.h | 62 chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector_test.cc | 359 chromium-132.0.6834.159/chromecast/graphics/graphics_properties_default.cc | 28 chromium-132.0.6834.159/chromecast/graphics/osd_plane_default.cc | 78 chromium-132.0.6834.159/chromecast/graphics/run_all_unittests.cc | 50 chromium-132.0.6834.159/chromecast/media/DEPS | 30 chromium-132.0.6834.159/chromecast/media/OWNERS | 1 chromium-132.0.6834.159/chromecast/media/api/audio_clock_simulator.h | 42 chromium-132.0.6834.159/chromecast/media/api/audio_provider.h | 37 chromium-132.0.6834.159/chromecast/media/api/cast_audio_decoder.h | 74 chromium-132.0.6834.159/chromecast/media/api/cast_audio_demuxer.h | 73 chromium-132.0.6834.159/chromecast/media/api/cast_audio_resampler.h | 47 chromium-132.0.6834.159/chromecast/media/api/cast_channel_mixer.h | 33 chromium-132.0.6834.159/chromecast/media/api/cast_sounds_manager.h | 62 chromium-132.0.6834.159/chromecast/media/api/cma_backend.h | 111 chromium-132.0.6834.159/chromecast/media/api/cma_backend_factory.h | 42 chromium-132.0.6834.159/chromecast/media/api/decoder_buffer_base.h | 64 chromium-132.0.6834.159/chromecast/media/api/monotonic_clock.h | 28 chromium-132.0.6834.159/chromecast/media/api/sound_player.h | 70 chromium-132.0.6834.159/chromecast/media/api/test/mock_cast_sounds_manager.cc | 15 chromium-132.0.6834.159/chromecast/media/api/test/mock_cast_sounds_manager.h | 34 chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend.cc | 23 chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend.h | 76 chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend_factory.cc | 14 chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend_factory.h | 33 chromium-132.0.6834.159/chromecast/media/api/test/mock_sound_player.cc | 14 chromium-132.0.6834.159/chromecast/media/api/test/mock_sound_player.h | 39 chromium-132.0.6834.159/chromecast/media/audio/audio_clock_simulator_impl.cc | 148 chromium-132.0.6834.159/chromecast/media/audio/audio_clock_simulator_unittest.cc | 200 chromium-132.0.6834.159/chromecast/media/audio/audio_fader.cc | 250 chromium-132.0.6834.159/chromecast/media/audio/audio_fader.h | 102 chromium-132.0.6834.159/chromecast/media/audio/audio_fader_unittest.cc | 357 chromium-132.0.6834.159/chromecast/media/audio/audio_io_thread.cc | 28 chromium-132.0.6834.159/chromecast/media/audio/audio_io_thread.h | 39 chromium-132.0.6834.159/chromecast/media/audio/audio_log.cc | 203 chromium-132.0.6834.159/chromecast/media/audio/audio_log.h | 58 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/audio_output_service.proto | 94 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/constants.cc | 17 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/constants.h | 19 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection.cc | 96 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection.h | 64 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection_unittest.cc | 163 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_socket.cc | 51 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_socket.h | 57 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_stream_connection.cc | 199 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_stream_connection.h | 114 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.cc | 250 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.h | 63 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.cc | 47 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.h | 36 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.cc | 337 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.h | 147 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/receiver.cc | 79 chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/receiver.h | 50 chromium-132.0.6834.159/chromecast/media/audio/capture_service/DEPS | 4 chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver.cc | 284 chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver.h | 98 chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver_unittest.cc | 251 chromium-132.0.6834.159/chromecast/media/audio/capture_service/constants.h | 111 chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_fuzzer.cc | 21 chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils.cc | 356 chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils.h | 113 chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils_unittest.cc | 255 chromium-132.0.6834.159/chromecast/media/audio/capture_service/packet_header.h | 46 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_bus.cc | 33 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_bus.h | 50 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_device_factory.cc | 267 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_device_factory.h | 37 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_input_stream.cc | 167 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_input_stream.h | 74 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager.cc | 221 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager.h | 142 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa.cc | 244 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa.h | 82 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa_unittest.cc | 71 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_android.cc | 195 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_android.h | 75 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_helper.cc | 51 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_helper.h | 75 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_unittest.cc | 322 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer.cc | 306 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer.h | 68 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer_unittest.cc | 418 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_device.cc | 434 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_device.h | 72 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream.cc | 481 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream.h | 154 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream_unittest.cc | 879 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_utils.cc | 22 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_utils.h | 22 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_renderer.cc | 588 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_renderer.h | 215 chromium-132.0.6834.159/chromecast/media/audio/cast_audio_resampler_impl.cc | 169 chromium-132.0.6834.159/chromecast/media/audio/cast_channel_mixer_impl.cc | 80 chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output.cc | 210 chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output.h | 82 chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output_stream.cc | 292 chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output_stream.h | 105 chromium-132.0.6834.159/chromecast/media/audio/external_audio_pipeline_dummy.cc | 69 chromium-132.0.6834.159/chromecast/media/audio/external_audio_pipeline_sample.cc | 131 chromium-132.0.6834.159/chromecast/media/audio/fake_external_audio_pipeline.cc | 277 chromium-132.0.6834.159/chromecast/media/audio/fake_external_audio_pipeline_support.h | 38 chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer.cc | 76 chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer.h | 55 chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer_unittest.cc | 92 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/DEPS | 6 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/constants.cc | 19 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/constants.h | 24 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/control_connection.cc | 262 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/control_connection.h | 123 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_connection.cc | 95 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_connection.h | 87 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_interrupt_reason.h | 27 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_connection.cc | 121 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_connection.h | 58 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_control.cc | 58 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_control.h | 59 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_service_transport.proto | 287 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_socket.cc | 97 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_socket.h | 133 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mock_mixer_socket.cc | 16 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mock_mixer_socket.h | 50 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/output_stream_connection.cc | 256 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/output_stream_connection.h | 162 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.cc | 227 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.h | 123 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver.cc | 183 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver.h | 73 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_cma.cc | 236 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_cma.h | 63 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_creation.cc | 41 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_creation.h | 31 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection.cc | 125 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection.h | 120 chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection_unittest.cc | 72 chromium-132.0.6834.159/chromecast/media/audio/mock_audio_input_callback.h | 28 chromium-132.0.6834.159/chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h | 33 chromium-132.0.6834.159/chromecast/media/audio/net/DEPS | 14 chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket.cc | 388 chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket.h | 170 chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service.cc | 57 chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service.h | 96 chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_tcp.cc | 79 chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_uds.cc | 138 chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_uds_unittest.cc | 148 chromium-132.0.6834.159/chromecast/media/audio/net/common.proto | 51 chromium-132.0.6834.159/chromecast/media/audio/net/conversions.cc | 97 chromium-132.0.6834.159/chromecast/media/audio/net/conversions.h | 33 chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter.cc | 173 chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter.h | 77 chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter_unittest.cc | 209 chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster.cc | 123 chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster.h | 86 chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster_unittest.cc | 131 chromium-132.0.6834.159/chromecast/media/audio/wav_header.h | 84 chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_dummy.cc | 108 chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_dummy.h | 56 chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_shlib.cc | 59 chromium-132.0.6834.159/chromecast/media/base/aligned_buffer.h | 97 chromium-132.0.6834.159/chromecast/media/base/audio_device_ids.cc | 20 chromium-132.0.6834.159/chromecast/media/base/audio_device_ids.h | 35 chromium-132.0.6834.159/chromecast/media/base/cast_decoder_buffer_impl.cc | 76 chromium-132.0.6834.159/chromecast/media/base/cast_decoder_buffer_impl.h | 50 chromium-132.0.6834.159/chromecast/media/base/decrypt_context_impl.cc | 60 chromium-132.0.6834.159/chromecast/media/base/decrypt_context_impl.h | 68 chromium-132.0.6834.159/chromecast/media/base/default_monotonic_clock.cc | 58 chromium-132.0.6834.159/chromecast/media/base/default_monotonic_clock.h | 35 chromium-132.0.6834.159/chromecast/media/base/key_systems_common.cc | 29 chromium-132.0.6834.159/chromecast/media/base/key_systems_common.h | 23 chromium-132.0.6834.159/chromecast/media/base/media_caps.cc | 112 chromium-132.0.6834.159/chromecast/media/base/media_caps.h | 57 chromium-132.0.6834.159/chromecast/media/base/media_codec_support.cc | 198 chromium-132.0.6834.159/chromecast/media/base/media_codec_support.h | 36 chromium-132.0.6834.159/chromecast/media/base/slew_volume.cc | 236 chromium-132.0.6834.159/chromecast/media/base/slew_volume.h | 95 chromium-132.0.6834.159/chromecast/media/base/slew_volume_unittests.cc | 544 chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo.cc | 44 chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo.h | 42 chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo_unittest.cc | 34 chromium-132.0.6834.159/chromecast/media/base/video_mode_switcher.cc | 13 chromium-132.0.6834.159/chromecast/media/base/video_mode_switcher.h | 39 chromium-132.0.6834.159/chromecast/media/base/video_plane_controller.cc | 337 chromium-132.0.6834.159/chromecast/media/base/video_plane_controller.h | 125 chromium-132.0.6834.159/chromecast/media/base/video_plane_controller_test.cc | 166 chromium-132.0.6834.159/chromecast/media/base/video_resolution_policy.cc | 13 chromium-132.0.6834.159/chromecast/media/base/video_resolution_policy.h | 42 chromium-132.0.6834.159/chromecast/media/cdm/DIR_METADATA | 6 chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm.cc | 202 chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm.h | 118 chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_context.cc | 18 chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_context.h | 46 chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_factory.cc | 86 chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_factory.h | 64 chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_origin_provider.cc | 20 chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_origin_provider.h | 31 chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data.cc | 67 chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data.h | 41 chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data_unittest.cc | 101 chromium-132.0.6834.159/chromecast/media/cma/DEPS | 4 chromium-132.0.6834.159/chromecast/media/cma/backend/DEPS | 4 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_fsm.dot | 91 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control.cc | 394 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control.h | 91 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control_unittest.cc | 40 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_wrapper.cc | 92 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_wrapper.h | 54 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/cast_media_shlib.cc | 165 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc | 550 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h | 94 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.cc | 134 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.h | 56 chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer_unittest.cc | 387 chromium-132.0.6834.159/chromecast/media/cma/backend/android/DEPS | 4 chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_decoder_android.cc | 702 chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_decoder_android.h | 132 chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android.cc | 62 chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android.h | 141 chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.cc | 453 chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h | 175 chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_manager.cc | 108 chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_manager.h | 72 chromium-132.0.6834.159/chromecast/media/cma/backend/android/cast_media_android.cc | 92 chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_codec_support_cast_audio.cc | 25 chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_pipeline_backend_android.cc | 134 chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_pipeline_backend_android.h | 76 chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache.cc | 76 chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache.h | 53 chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache_test.cc | 121 chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_control_android.cc | 372 chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_control_android.h | 95 chromium-132.0.6834.159/chromecast/media/cma/backend/audio_decoder_for_mixer.cc | 607 chromium-132.0.6834.159/chromecast/media/cma/backend/audio_decoder_for_mixer.h | 141 chromium-132.0.6834.159/chromecast/media/cma/backend/audio_video_pipeline_device_unittest.cc | 1259 - chromium-132.0.6834.159/chromecast/media/cma/backend/av_sync.h | 57 chromium-132.0.6834.159/chromecast/media/cma/backend/av_sync_dummy.cc | 16 chromium-132.0.6834.159/chromecast/media/cma/backend/cast_audio_json.cc | 111 chromium-132.0.6834.159/chromecast/media/cma/backend/cast_audio_json.h | 84 chromium-132.0.6834.159/chromecast/media/cma/backend/cast_media_dummy.cc | 94 chromium-132.0.6834.159/chromecast/media/cma/backend/cma_backend_factory_impl.cc | 45 chromium-132.0.6834.159/chromecast/media/cma/backend/cma_backend_factory_impl.h | 50 chromium-132.0.6834.159/chromecast/media/cma/backend/cplay/cplay.cc | 384 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/audio_decoder_desktop.cc | 70 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/audio_decoder_desktop.h | 51 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/cast_media_desktop.cc | 88 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/desktop_system_volume_control.cc | 60 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.cc | 119 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.h | 64 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_sink_desktop.cc | 92 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_sink_desktop.h | 46 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.cc | 62 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.h | 43 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/video_decoder_desktop.cc | 54 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/video_decoder_desktop.h | 47 chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/volume_control_desktop.cc | 217 chromium-132.0.6834.159/chromecast/media/cma/backend/media_codec_support_cast_audio.cc | 23 chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.cc | 317 chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h | 114 chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_manager_mixer.cc | 35 chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_manager_no_mixer.cc | 13 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector.cc | 477 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector.h | 145 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector_input.h | 44 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/channel_layout.cc | 48 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/channel_layout.h | 36 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group.cc | 358 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group.h | 186 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group_unittest.cc | 248 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_handler.cc | 248 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_handler.h | 86 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_test_support.cc | 46 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_test_support.h | 23 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input.cc | 527 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input.h | 248 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input_connection.cc | 1397 - chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input_connection.h | 239 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_loopback_connection.cc | 102 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_loopback_connection.h | 68 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.cc | 49 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.h | 33 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_pipeline.cc | 228 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_pipeline.h | 106 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_service_receiver.cc | 202 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_service_receiver.h | 65 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_mixer_source.cc | 48 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_mixer_source.h | 106 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_post_processor_factory.cc | 77 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_post_processor_factory.h | 93 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.cc | 48 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.h | 62 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline.h | 59 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.cc | 293 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h | 108 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.cc | 215 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h | 81 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_factory.cc | 126 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_factory.h | 53 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_paths.cc | 28 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_paths.h | 22 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_registry.cc | 38 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_registry.h | 81 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor.cc | 100 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor.h | 57 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor_unittest.cc | 138 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_name.cc | 17 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.cc | 356 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.h | 133 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.cc | 66 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.h | 59 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.cc | 75 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.h | 42 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain_unittest.cc | 83 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer.cc | 1105 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer.h | 276 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer_external_audio_pipeline_unittest.cc | 237 chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer_unittest.cc | 1687 - chromium-132.0.6834.159/chromecast/media/cma/backend/mock_media_pipeline_backend_for_mixer.h | 60 chromium-132.0.6834.159/chromecast/media/cma/backend/multizone_backend_unittest.cc | 410 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/DEPS | 4 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/README.md | 156 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.cc | 207 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.h | 250 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h | 72 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.cc | 129 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h | 96 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node_unittest.cc | 144 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager.cc | 188 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager.h | 174 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager_unittest.cc | 258 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.cc | 15 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h | 134 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_manager.h | 27 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_simple.cc | 20 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy.cc | 156 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy.h | 90 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy_unittest.cc | 239 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_proxy_handler.h | 104 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.cc | 228 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.h | 126 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension_unittest.cc | 319 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy.h | 38 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.cc | 164 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.h | 115 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator.cc | 368 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator.h | 122 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator_unittest.cc | 355 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.cc | 131 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h | 103 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler_unittest.cc | 258 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue.cc | 277 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue.h | 184 chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue_unittest.cc | 343 chromium-132.0.6834.159/chromecast/media/cma/backend/saved_volumes.cc | 99 chromium-132.0.6834.159/chromecast/media/cma/backend/saved_volumes.h | 23 chromium-132.0.6834.159/chromecast/media/cma/backend/system_volume_control.h | 73 chromium-132.0.6834.159/chromecast/media/cma/backend/video/av_sync_video.cc | 278 chromium-132.0.6834.159/chromecast/media/cma/backend/video/av_sync_video.h | 80 chromium-132.0.6834.159/chromecast/media/cma/backend/video/cast_media_shlib_common.cc | 25 chromium-132.0.6834.159/chromecast/media/cma/backend/video/cast_media_shlib_default.cc | 40 chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_for_mixer.h | 125 chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_null.cc | 114 chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_null.h | 57 chromium-132.0.6834.159/chromecast/media/cma/backend/volume_control.cc | 452 chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map.cc | 162 chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map.h | 60 chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map_unittest.cc | 95 chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_factory.cc | 253 chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_factory.h | 70 chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_unittest.cc | 297 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller.cc | 246 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller.h | 117 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller_unittest.cc | 115 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_defs.cc | 23 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_defs.h | 19 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider.cc | 142 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider.h | 123 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider_unittest.cc | 196 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_state.cc | 148 chromium-132.0.6834.159/chromecast/media/cma/base/buffering_state.h | 141 chromium-132.0.6834.159/chromecast/media/cma/base/cast_decrypt_config_impl.cc | 45 chromium-132.0.6834.159/chromecast/media/cma/base/cast_decrypt_config_impl.h | 40 chromium-132.0.6834.159/chromecast/media/cma/base/coded_frame_provider.cc | 17 chromium-132.0.6834.159/chromecast/media/cma/base/coded_frame_provider.h | 53 chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter.cc | 110 chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter.h | 58 chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter_unittest.cc | 192 chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter.cc | 387 chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter.h | 39 chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter_unittest.cc | 46 chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter.cc | 181 chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter.h | 94 chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter_unittest.cc | 224 chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_for_test.cc | 87 chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_for_test.h | 71 chromium-132.0.6834.159/chromecast/media/cma/base/media_task_runner.cc | 17 chromium-132.0.6834.159/chromecast/media/cma/base/media_task_runner.h | 42 chromium-132.0.6834.159/chromecast/media/cma/base/multi_demuxer_stream_adapter_unittest.cc | 180 chromium-132.0.6834.159/chromecast/media/cma/base/simple_media_task_runner.cc | 27 chromium-132.0.6834.159/chromecast/media/cma/base/simple_media_task_runner.h | 42 chromium-132.0.6834.159/chromecast/media/cma/decoder/DEPS | 3 chromium-132.0.6834.159/chromecast/media/cma/decoder/cast_audio_decoder.cc | 355 chromium-132.0.6834.159/chromecast/media/cma/decoder/external_audio_decoder_wrapper.cc | 290 chromium-132.0.6834.159/chromecast/media/cma/decoder/external_audio_decoder_wrapper.h | 79 chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_pipeline_impl.cc | 119 chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_pipeline_impl.h | 60 chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_video_pipeline_impl_unittest.cc | 459 chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_client.cc | 21 chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_client.h | 44 chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_impl.cc | 431 chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_impl.h | 206 chromium-132.0.6834.159/chromecast/media/cma/pipeline/backend_decryptor.cc | 94 chromium-132.0.6834.159/chromecast/media/cma/pipeline/backend_decryptor.h | 60 chromium-132.0.6834.159/chromecast/media/cma/pipeline/cdm_decryptor.cc | 60 chromium-132.0.6834.159/chromecast/media/cma/pipeline/cdm_decryptor.h | 42 chromium-132.0.6834.159/chromecast/media/cma/pipeline/decrypt_util.cc | 82 chromium-132.0.6834.159/chromecast/media/cma/pipeline/decrypt_util.h | 58 chromium-132.0.6834.159/chromecast/media/cma/pipeline/load_type.h | 21 chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_client.cc | 22 chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_client.h | 42 chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_impl.cc | 592 chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_impl.h | 143 chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_observer.cc | 47 chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_observer.h | 38 chromium-132.0.6834.159/chromecast/media/cma/pipeline/stream_decryptor.h | 49 chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_client.cc | 21 chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_client.h | 39 chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_impl.cc | 160 chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_impl.h | 61 chromium-132.0.6834.159/chromecast/media/cma/test/DEPS | 5 chromium-132.0.6834.159/chromecast/media/cma/test/frame_generator_for_test.cc | 116 chromium-132.0.6834.159/chromecast/media/cma/test/frame_generator_for_test.h | 63 chromium-132.0.6834.159/chromecast/media/cma/test/frame_segmenter_for_test.cc | 355 chromium-132.0.6834.159/chromecast/media/cma/test/frame_segmenter_for_test.h | 47 chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_consumer.cc | 111 chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_consumer.h | 73 chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_provider.cc | 98 chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_provider.h | 56 chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper.cc | 205 chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper.h | 76 chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper_unittest.cc | 72 chromium-132.0.6834.159/chromecast/media/common/audio_decoder_wrapper.cc | 248 chromium-132.0.6834.159/chromecast/media/common/audio_decoder_wrapper.h | 107 chromium-132.0.6834.159/chromecast/media/common/base/decoder_config_logging.cc | 69 chromium-132.0.6834.159/chromecast/media/common/base/decoder_config_logging.h | 17 chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_manager.cc | 290 chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_manager.h | 206 chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_wrapper.cc | 373 chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_wrapper.h | 69 chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker.cc | 163 chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker.h | 114 chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker_unittest.cc | 180 chromium-132.0.6834.159/chromecast/media/common/test_media_resource_tracker.cc | 44 chromium-132.0.6834.159/chromecast/media/common/test_media_resource_tracker.h | 54 chromium-132.0.6834.159/chromecast/media/common/video_decoder_wrapper.cc | 89 chromium-132.0.6834.159/chromecast/media/common/video_decoder_wrapper.h | 51 chromium-132.0.6834.159/chromecast/media/gpu/DEPS | 8 chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory.h | 61 chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_dummy.cc | 44 chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_dummy.h | 31 chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_impl.cc | 337 chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_impl.h | 116 chromium-132.0.6834.159/chromecast/media/mojom/OWNERS | 6 chromium-132.0.6834.159/chromecast/media/mojom/decoder_config_mojom_traits.cc | 57 chromium-132.0.6834.159/chromecast/media/mojom/decoder_config_mojom_traits.h | 334 chromium-132.0.6834.159/chromecast/media/mojom/media_types.mojom | 69 chromium-132.0.6834.159/chromecast/media/service/DEPS | 6 chromium-132.0.6834.159/chromecast/media/service/cast_mojo_media_client.cc | 74 chromium-132.0.6834.159/chromecast/media/service/cast_mojo_media_client.h | 78 chromium-132.0.6834.159/chromecast/media/service/cast_renderer.cc | 427 chromium-132.0.6834.159/chromecast/media/service/cast_renderer.h | 153 chromium-132.0.6834.159/chromecast/media/service/mojom/OWNERS | 3 chromium-132.0.6834.159/chromecast/media/service/mojom/video_geometry_setter.mojom | 58 chromium-132.0.6834.159/chromecast/media/service/video_geometry_setter_service.cc | 89 chromium-132.0.6834.159/chromecast/media/service/video_geometry_setter_service.h | 79 chromium-132.0.6834.159/chromecast/media/test/run_all_unittests.cc | 38 chromium-132.0.6834.159/chromecast/metrics/DEPS | 8 chromium-132.0.6834.159/chromecast/metrics/OWNERS | 2 chromium-132.0.6834.159/chromecast/metrics/cast_event_builder.cc | 36 chromium-132.0.6834.159/chromecast/metrics/cast_event_builder.h | 131 chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl.cc | 255 chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl.h | 74 chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl_unittest.cc | 166 chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_simple.cc | 173 chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_simple.h | 71 chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client.cc | 413 chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client.h | 156 chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client_unittest.cc | 100 chromium-132.0.6834.159/chromecast/metrics/metrics_recorder.cc | 328 chromium-132.0.6834.159/chromecast/metrics/metrics_recorder.h | 173 chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base.cc | 36 chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base.h | 39 chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base_unittest.cc | 161 chromium-132.0.6834.159/chromecast/metrics/metrics_util.cc | 32 chromium-132.0.6834.159/chromecast/metrics/metrics_util.h | 20 chromium-132.0.6834.159/chromecast/metrics/mock_cast_event_builder.cc | 238 chromium-132.0.6834.159/chromecast/metrics/mock_cast_event_builder.h | 214 chromium-132.0.6834.159/chromecast/metrics/mock_cast_sys_info_util.cc | 22 chromium-132.0.6834.159/chromecast/metrics/mock_cast_sys_info_util.h | 19 chromium-132.0.6834.159/chromecast/metrics/timed_event_recorder.cc | 63 chromium-132.0.6834.159/chromecast/metrics/timed_event_recorder.h | 66 chromium-132.0.6834.159/chromecast/mojo/DEPS | 3 chromium-132.0.6834.159/chromecast/mojo/OWNERS | 2 chromium-132.0.6834.159/chromecast/mojo/binder_factory.cc | 15 chromium-132.0.6834.159/chromecast/mojo/binder_factory.h | 342 chromium-132.0.6834.159/chromecast/mojo/binder_factory_test.cc | 140 chromium-132.0.6834.159/chromecast/mojo/interface_bundle.cc | 43 chromium-132.0.6834.159/chromecast/mojo/interface_bundle.h | 152 chromium-132.0.6834.159/chromecast/mojo/interface_bundle_test.cc | 133 chromium-132.0.6834.159/chromecast/mojo/mojom/OWNERS | 2 chromium-132.0.6834.159/chromecast/mojo/mojom/remote_interfaces.mojom | 31 chromium-132.0.6834.159/chromecast/mojo/remote_interfaces.cc | 59 chromium-132.0.6834.159/chromecast/mojo/remote_interfaces.h | 113 chromium-132.0.6834.159/chromecast/mojo/test/DEPS | 3 chromium-132.0.6834.159/chromecast/mojo/test/run_all_unittests.cc | 16 chromium-132.0.6834.159/chromecast/mojo/test/test_interfaces.test-mojom | 18 chromium-132.0.6834.159/chromecast/net/DEPS | 8 chromium-132.0.6834.159/chromecast/net/connectivity_checker.cc | 84 chromium-132.0.6834.159/chromecast/net/connectivity_checker.h | 121 chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl.cc | 374 chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl.h | 186 chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl_unittest.cc | 449 chromium-132.0.6834.159/chromecast/net/fake_connectivity_checker.cc | 31 chromium-132.0.6834.159/chromecast/net/fake_connectivity_checker.h | 38 chromium-132.0.6834.159/chromecast/net/fake_shared_url_loader_factory.cc | 44 chromium-132.0.6834.159/chromecast/net/fake_shared_url_loader_factory.h | 80 chromium-132.0.6834.159/chromecast/net/fake_stream_socket.cc | 219 chromium-132.0.6834.159/chromecast/net/fake_stream_socket.h | 75 chromium-132.0.6834.159/chromecast/net/fake_stream_socket_unittest.cc | 139 chromium-132.0.6834.159/chromecast/net/io_buffer_pool.cc | 285 chromium-132.0.6834.159/chromecast/net/io_buffer_pool.h | 69 chromium-132.0.6834.159/chromecast/net/io_buffer_pool_unittest.cc | 113 chromium-132.0.6834.159/chromecast/net/mock_stream_socket.cc | 37 chromium-132.0.6834.159/chromecast/net/mock_stream_socket.h | 56 chromium-132.0.6834.159/chromecast/net/net_switches.cc | 17 chromium-132.0.6834.159/chromecast/net/net_switches.h | 15 chromium-132.0.6834.159/chromecast/net/net_util_cast.cc | 33 chromium-132.0.6834.159/chromecast/net/net_util_cast.h | 19 chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_cast.cc | 23 chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_cast.h | 34 chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_fuchsia.cc | 28 chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_fuchsia.h | 33 chromium-132.0.6834.159/chromecast/net/small_message_socket.cc | 491 chromium-132.0.6834.159/chromecast/net/small_message_socket.h | 211 chromium-132.0.6834.159/chromecast/net/small_message_socket_unittest.cc | 355 chromium-132.0.6834.159/chromecast/net/socket_util.cc | 47 chromium-132.0.6834.159/chromecast/net/socket_util.h | 29 chromium-132.0.6834.159/chromecast/net/time_sync_tracker.cc | 27 chromium-132.0.6834.159/chromecast/net/time_sync_tracker.h | 47 chromium-132.0.6834.159/chromecast/net/time_sync_tracker_fuchsia.cc | 47 chromium-132.0.6834.159/chromecast/net/time_sync_tracker_fuchsia.h | 38 chromium-132.0.6834.159/chromecast/public/DEPS | 9 chromium-132.0.6834.159/chromecast/public/avsettings.h | 408 chromium-132.0.6834.159/chromecast/public/bluetooth/bluetooth_types.h | 22 chromium-132.0.6834.159/chromecast/public/bluetooth/gatt.h | 390 chromium-132.0.6834.159/chromecast/public/bluetooth/le_scanner.h | 56 chromium-132.0.6834.159/chromecast/public/cast_egl_platform.h | 53 chromium-132.0.6834.159/chromecast/public/cast_egl_platform_shlib.h | 25 chromium-132.0.6834.159/chromecast/public/cast_media_shlib.h | 81 chromium-132.0.6834.159/chromecast/public/cast_sys_info.h | 78 chromium-132.0.6834.159/chromecast/public/cast_sys_info_shlib.h | 26 chromium-132.0.6834.159/chromecast/public/chromecast_export.h | 12 chromium-132.0.6834.159/chromecast/public/graphics_properties_shlib.h | 32 chromium-132.0.6834.159/chromecast/public/graphics_types.h | 41 chromium-132.0.6834.159/chromecast/public/media/audio_post_processor2_shlib.h | 133 chromium-132.0.6834.159/chromecast/public/media/audio_post_processor_shlib.h | 96 chromium-132.0.6834.159/chromecast/public/media/cast_decoder_buffer.h | 64 chromium-132.0.6834.159/chromecast/public/media/cast_decrypt_config.h | 89 chromium-132.0.6834.159/chromecast/public/media/cast_key_status.h | 19 chromium-132.0.6834.159/chromecast/public/media/cast_key_system.h | 23 chromium-132.0.6834.159/chromecast/public/media/decoder_config.h | 411 chromium-132.0.6834.159/chromecast/public/media/decrypt_context.h | 42 chromium-132.0.6834.159/chromecast/public/media/external_audio_decoder.h | 88 chromium-132.0.6834.159/chromecast/public/media/external_audio_pipeline_shlib.h | 190 chromium-132.0.6834.159/chromecast/public/media/media_capabilities_shlib.h | 45 chromium-132.0.6834.159/chromecast/public/media/media_pipeline_backend.h | 404 chromium-132.0.6834.159/chromecast/public/media/media_pipeline_device_params.h | 192 chromium-132.0.6834.159/chromecast/public/media/mixer_output_stream.h | 62 chromium-132.0.6834.159/chromecast/public/media/stream_id.h | 19 chromium-132.0.6834.159/chromecast/public/osd_plane.h | 45 chromium-132.0.6834.159/chromecast/public/osd_plane_shlib.h | 25 chromium-132.0.6834.159/chromecast/public/osd_surface.h | 56 chromium-132.0.6834.159/chromecast/public/output_restrictions.h | 97 chromium-132.0.6834.159/chromecast/public/reboot_shlib.h | 187 chromium-132.0.6834.159/chromecast/public/task_runner.h | 56 chromium-132.0.6834.159/chromecast/public/video_plane.h | 54 chromium-132.0.6834.159/chromecast/public/volume_control.h | 159 chromium-132.0.6834.159/chromecast/renderer/DEPS | 33 chromium-132.0.6834.159/chromecast/renderer/OWNERS | 1 chromium-132.0.6834.159/chromecast/renderer/activity_filtering_websocket_handshake_throttle.cc | 38 chromium-132.0.6834.159/chromecast/renderer/activity_filtering_websocket_handshake_throttle.h | 48 chromium-132.0.6834.159/chromecast/renderer/assistant_bindings.cc | 169 chromium-132.0.6834.159/chromecast/renderer/assistant_bindings.h | 74 chromium-132.0.6834.159/chromecast/renderer/cast_activity_url_filter_manager.cc | 110 chromium-132.0.6834.159/chromecast/renderer/cast_activity_url_filter_manager.h | 94 chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client.cc | 361 chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client.h | 128 chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client_simple.cc | 20 chromium-132.0.6834.159/chromecast/renderer/cast_content_settings_client.cc | 60 chromium-132.0.6834.159/chromecast/renderer/cast_content_settings_client.h | 51 chromium-132.0.6834.159/chromecast/renderer/cast_demo_bindings.cc | 388 chromium-132.0.6834.159/chromecast/renderer/cast_demo_bindings.h | 97 chromium-132.0.6834.159/chromecast/renderer/cast_url_loader_throttle_provider.cc | 67 chromium-132.0.6834.159/chromecast/renderer/cast_url_loader_throttle_provider.h | 48 chromium-132.0.6834.159/chromecast/renderer/cast_websocket_handshake_throttle_provider.cc | 59 chromium-132.0.6834.159/chromecast/renderer/cast_websocket_handshake_throttle_provider.h | 52 chromium-132.0.6834.159/chromecast/renderer/cast_window_manager_bindings.cc | 342 chromium-132.0.6834.159/chromecast/renderer/cast_window_manager_bindings.h | 108 chromium-132.0.6834.159/chromecast/renderer/feature_manager.cc | 180 chromium-132.0.6834.159/chromecast/renderer/feature_manager.h | 94 chromium-132.0.6834.159/chromecast/renderer/feature_manager_on_associated_interface.cc | 43 chromium-132.0.6834.159/chromecast/renderer/feature_manager_on_associated_interface.h | 56 chromium-132.0.6834.159/chromecast/renderer/media/DEPS | 5 chromium-132.0.6834.159/chromecast/renderer/media/key_systems_cast.cc | 118 chromium-132.0.6834.159/chromecast/renderer/media/key_systems_cast.h | 19 chromium-132.0.6834.159/chromecast/renderer/media/media_caps_observer_impl.cc | 32 chromium-132.0.6834.159/chromecast/renderer/media/media_caps_observer_impl.h | 37 chromium-132.0.6834.159/chromecast/renderer/memory_pressure_observer_impl.cc | 24 chromium-132.0.6834.159/chromecast/renderer/memory_pressure_observer_impl.h | 33 chromium-132.0.6834.159/chromecast/renderer/native_bindings_helper.cc | 89 chromium-132.0.6834.159/chromecast/renderer/native_bindings_helper.h | 79 chromium-132.0.6834.159/chromecast/renderer/queryable_data_store.cc | 33 chromium-132.0.6834.159/chromecast/renderer/queryable_data_store.h | 48 chromium-132.0.6834.159/chromecast/renderer/settings_ui_bindings.cc | 173 chromium-132.0.6834.159/chromecast/renderer/settings_ui_bindings.h | 69 chromium-132.0.6834.159/chromecast/resource_sizes/OWNERS | 2 chromium-132.0.6834.159/chromecast/resource_sizes/chromecast_resource_sizes.py | 330 chromium-132.0.6834.159/chromecast/service/cast_service.cc | 47 chromium-132.0.6834.159/chromecast/service/cast_service.h | 60 chromium-132.0.6834.159/chromecast/shared/DEPS | 5 chromium-132.0.6834.159/chromecast/shared/platform_info_serializer.cc | 361 chromium-132.0.6834.159/chromecast/shared/platform_info_serializer.h | 114 chromium-132.0.6834.159/chromecast/shared/platform_info_serializer_unittest.cc | 300 chromium-132.0.6834.159/chromecast/starboard/DEPS | 8 chromium-132.0.6834.159/chromecast/starboard/OWNERS | 2 chromium-132.0.6834.159/chromecast/starboard/chromecast/events/dummy_ui_event_source.cc | 33 chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source.cc | 159 chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source.h | 54 chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source_test.cc | 170 chromium-132.0.6834.159/chromecast/starboard/chromecast/events/ui_event_source.cc | 11 chromium-132.0.6834.159/chromecast/starboard/chromecast/events/ui_event_source.h | 34 chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h | 62 chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_dummy.cc | 22 chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.cc | 120 chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.h | 59 chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api.h | 40 chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h | 28 chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_dummy/cast_starboard_api_dummy.cc | 134 chromium-132.0.6834.159/chromecast/starboard/graphics/cast_egl_platform_starboard.cc | 129 chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard.cc | 232 chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard.h | 160 chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard_dummy.cc | 194 chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard.cc | 856 chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard.h | 392 chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard_dummy.cc | 561 chromium-132.0.6834.159/chromecast/starboard/graphics/graphics_properties_default.cc | 22 chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast.cc | 864 chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast.h | 246 chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast_test.cc | 714 chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker.cc | 131 chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker.h | 130 chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker_test.cc | 151 chromium-132.0.6834.159/chromecast/starboard/media/media/cast_media_starboard.cc | 112 chromium-132.0.6834.159/chromecast/starboard/media/media/drm_util.cc | 138 chromium-132.0.6834.159/chromecast/starboard/media/media/drm_util.h | 68 chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard.cc | 418 chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard.h | 176 chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard_test.cc | 459 chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils.cc | 63 chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils.h | 30 chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils_test.cc | 91 chromium-132.0.6834.159/chromecast/starboard/media/media/mock_starboard_api_wrapper.cc | 14 chromium-132.0.6834.159/chromecast/starboard/media/media/mock_starboard_api_wrapper.h | 103 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper.cc | 13 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper.h | 517 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_14.cc | 166 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_15.cc | 178 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_base.cc | 404 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_base.h | 112 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_dummy.cc | 15 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder.cc | 217 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder.h | 64 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder_test.cc | 690 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_decoder.cc | 257 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_decoder.h | 148 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler.cc | 299 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler.h | 40 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler_test.cc | 515 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder.cc | 231 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder.h | 60 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder_test.cc | 693 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane.cc | 84 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane.h | 83 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane_test.cc | 83 chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_volume_control.cc | 59 chromium-132.0.6834.159/chromecast/system/reboot/fuchsia_component_restart_reason.cc | 83 chromium-132.0.6834.159/chromecast/system/reboot/fuchsia_component_restart_reason.h | 53 chromium-132.0.6834.159/chromecast/system/reboot/reboot_dummy.cc | 53 chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia.cc | 240 chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia.h | 31 chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia_test.cc | 396 chromium-132.0.6834.159/chromecast/system/reboot/reboot_util.h | 76 chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_core.cc | 127 chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_dummy.cc | 30 chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_test.cc | 23 chromium-132.0.6834.159/chromecast/tools/build/generate_test_lists.py | 195 chromium-132.0.6834.159/chromecast/tools/build/package_test_deps.py | 108 chromium-132.0.6834.159/chromecast/tools/trace.py | 114 chromium-132.0.6834.159/chromecast/tools/tracinglib.py | 298 chromium-132.0.6834.159/chromecast/tracing/OWNERS | 1 chromium-132.0.6834.159/chromecast/tracing/ftrace.cc | 217 chromium-132.0.6834.159/chromecast/tracing/ftrace.h | 50 chromium-132.0.6834.159/chromecast/tracing/system_tracer.cc | 270 chromium-132.0.6834.159/chromecast/tracing/system_tracer.h | 54 chromium-132.0.6834.159/chromecast/tracing/system_tracing_common.cc | 30 chromium-132.0.6834.159/chromecast/tracing/system_tracing_common.h | 25 chromium-132.0.6834.159/chromecast/tracing/tracing_service_main.cc | 418 chromium-132.0.6834.159/chromecast/ui/DEPS | 14 chromium-132.0.6834.159/chromecast/ui/OWNERS | 1 chromium-132.0.6834.159/chromecast/ui/back_gesture_router.h | 22 chromium-132.0.6834.159/chromecast/ui/display_settings/brightness_animation.cc | 73 chromium-132.0.6834.159/chromecast/ui/display_settings/brightness_animation.h | 42 chromium-132.0.6834.159/chromecast/ui/display_settings/color_temperature_animation.cc | 122 chromium-132.0.6834.159/chromecast/ui/display_settings/color_temperature_animation.h | 56 chromium-132.0.6834.159/chromecast/ui/display_settings/gamma_configurator.cc | 77 chromium-132.0.6834.159/chromecast/ui/display_settings/gamma_configurator.h | 43 chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller.h | 61 chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura.cc | 242 chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura.h | 67 chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura_unittest.cc | 217 chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_default.cc | 57 chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_default.h | 34 chromium-132.0.6834.159/chromecast/ui/display_settings_manager.cc | 16 chromium-132.0.6834.159/chromecast/ui/display_settings_manager.h | 63 chromium-132.0.6834.159/chromecast/ui/display_settings_manager_impl.cc | 214 chromium-132.0.6834.159/chromecast/ui/display_settings_manager_impl.h | 105 chromium-132.0.6834.159/chromecast/ui/mojom/OWNERS | 2 chromium-132.0.6834.159/chromecast/ui/mojom/display_settings.mojom | 44 chromium-132.0.6834.159/chromecast/ui/mojom/ui_service.mojom | 27 chromium-132.0.6834.159/chromecast/ui/vector_icons/back30.icon | 90 chromium-132.0.6834.159/chromecast/ui/vector_icons/forward30.icon | 90 chromium-132.0.6834.159/chromecast/ui/vector_icons/next.icon | 21 chromium-132.0.6834.159/chromecast/ui/vector_icons/pause.icon | 16 chromium-132.0.6834.159/chromecast/ui/vector_icons/play.icon | 9 chromium-132.0.6834.159/chromecast/ui/vector_icons/previous.icon | 20 chromium-132.0.6834.159/chromecast/ui/vector_icons/vector_icons.cc.template | 22 chromium-132.0.6834.159/chromecast/ui/vector_icons/vector_icons.h.template | 28 chromium-132.0.6834.159/chromeos/CHROMEOS_LKGM | 2 chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ar.xtb | 2 chromium-132.0.6834.159/chromeos/strings/chromeos_strings_de.xtb | 2 chromium-132.0.6834.159/chromeos/strings/chromeos_strings_iw.xtb | 24 chromium-132.0.6834.159/chromeos/strings/chromeos_strings_mk.xtb | 2 chromium-132.0.6834.159/chromeos/strings/chromeos_strings_nl.xtb | 2 chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ru.xtb | 2 chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ur.xtb | 2 chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_de.xtb | 2 chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_gl.xtb | 2 chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_iw.xtb | 4 chromium-132.0.6834.159/components/certificate_transparency/data/log_list.json | 4 chromium-132.0.6834.159/components/policy/resources/policy_templates_zh-CN.xtb | 4 chromium-132.0.6834.159/components/sessions/BUILD.gn | 1 chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper.cc | 39 chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper.h | 13 chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper_unittest.cc | 99 chromium-132.0.6834.159/components/strings/components_strings_ar.xtb | 2 chromium-132.0.6834.159/components/strings/components_strings_ca.xtb | 2 chromium-132.0.6834.159/components/strings/components_strings_da.xtb | 2 chromium-132.0.6834.159/components/strings/components_strings_de.xtb | 2 chromium-132.0.6834.159/components/strings/components_strings_fa.xtb | 2 chromium-132.0.6834.159/components/strings/components_strings_fr-CA.xtb | 2 chromium-132.0.6834.159/components/strings/components_strings_fr.xtb | 6 chromium-132.0.6834.159/components/strings/components_strings_hi.xtb | 4 chromium-132.0.6834.159/components/strings/components_strings_iw.xtb | 104 chromium-132.0.6834.159/components/strings/components_strings_vi.xtb | 2 chromium-132.0.6834.159/components/strings/privacy_sandbox_strings_fr.xtb | 2 chromium-132.0.6834.159/content/browser/web_contents/web_contents_impl.cc | 10 chromium-132.0.6834.159/debian/changelog | 18 chromium-132.0.6834.159/debian/copyright | 290 chromium-132.0.6834.159/debian/rules | 16 chromium-132.0.6834.159/gpu/config/gpu_lists_version.h | 2 chromium-132.0.6834.159/media/cast/common/encoded_frame.h | 6 chromium-132.0.6834.159/media/cast/encoding/external_video_encoder.cc | 59 chromium-132.0.6834.159/media/cast/encoding/external_video_encoder.h | 7 chromium-132.0.6834.159/media/cast/encoding/size_adaptable_video_encoder_base.cc | 26 chromium-132.0.6834.159/media/cast/encoding/size_adaptable_video_encoder_base.h | 15 chromium-132.0.6834.159/media/cast/encoding/video_encoder.cc | 11 chromium-132.0.6834.159/media/cast/encoding/video_encoder.h | 11 chromium-132.0.6834.159/media/cast/encoding/video_encoder_impl.cc | 18 chromium-132.0.6834.159/media/cast/encoding/video_encoder_impl.h | 7 chromium-132.0.6834.159/media/cast/encoding/video_encoder_unittest.cc | 65 chromium-132.0.6834.159/media/cast/sender/video_sender.cc | 39 chromium-132.0.6834.159/media/cast/sender/video_sender.h | 4 chromium-132.0.6834.159/net/data/ssl/chrome_root_store/root_store.md | 29 chromium-132.0.6834.159/net/http/transport_security_state_static.pins | 4 chromium-132.0.6834.159/net/http/transport_security_state_static_pins.json | 2 chromium-132.0.6834.159/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h | 2 chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/devtools_agent.cc | 1 chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/devtools_agent.h | 4 chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/worker_inspector_controller.h | 2 chromium-132.0.6834.159/third_party/blink/renderer/platform/media/url_index.cc | 5 chromium-132.0.6834.159/third_party/blink/renderer/platform/media/url_index_unittest.cc | 11 chromium-132.0.6834.159/third_party/blink/renderer/platform/runtime_enabled_features.json5 | 4 chromium-132.0.6834.159/third_party/closure_compiler/DIR_METADATA | 6 chromium-132.0.6834.159/third_party/closure_compiler/OWNERS | 10 chromium-132.0.6834.159/third_party/closure_compiler/README.chromium | 26 chromium-132.0.6834.159/third_party/closure_compiler/chromium_patch.diff | 1106 chromium-132.0.6834.159/third_party/closure_compiler/compiler.py | 67 chromium-132.0.6834.159/third_party/closure_compiler/compiler/README.md | 563 chromium-132.0.6834.159/third_party/closure_compiler/externs/OWNERS | 9 chromium-132.0.6834.159/third_party/closure_compiler/externs/accessibility_features.js | 133 chromium-132.0.6834.159/third_party/closure_compiler/externs/accessibility_private.js | 963 chromium-132.0.6834.159/third_party/closure_compiler/externs/arc_apps_private.js | 47 chromium-132.0.6834.159/third_party/closure_compiler/externs/audio.js | 186 chromium-132.0.6834.159/third_party/closure_compiler/externs/bluetooth.js | 193 chromium-132.0.6834.159/third_party/closure_compiler/externs/bluetooth_private.js | 209 chromium-132.0.6834.159/third_party/closure_compiler/externs/braille_display_private.js | 102 chromium-132.0.6834.159/third_party/closure_compiler/externs/chai-3.5.js | 556 chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome.js | 643 chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome_extensions.js |11243 ---------- chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome_send.js | 21 chromium-132.0.6834.159/third_party/closure_compiler/externs/chromeos_info_private.js | 157 chromium-132.0.6834.159/third_party/closure_compiler/externs/clipboard.js | 68 chromium-132.0.6834.159/third_party/closure_compiler/externs/command_line_private.js | 27 chromium-132.0.6834.159/third_party/closure_compiler/externs/crash_report_private.js | 40 chromium-132.0.6834.159/third_party/closure_compiler/externs/events.js | 69 chromium-132.0.6834.159/third_party/closure_compiler/externs/extension_types.js | 118 chromium-132.0.6834.159/third_party/closure_compiler/externs/file_system_provider.js | 670 chromium-132.0.6834.159/third_party/closure_compiler/externs/image_loader_private.js | 55 chromium-132.0.6834.159/third_party/closure_compiler/externs/input_method_private.js | 460 chromium-132.0.6834.159/third_party/closure_compiler/externs/language_settings_private.js | 215 chromium-132.0.6834.159/third_party/closure_compiler/externs/login_state.js | 62 chromium-132.0.6834.159/third_party/closure_compiler/externs/mediasession.js | 88 chromium-132.0.6834.159/third_party/closure_compiler/externs/metrics_private.js | 192 chromium-132.0.6834.159/third_party/closure_compiler/externs/metrics_private_individual_apis.js | 45 chromium-132.0.6834.159/third_party/closure_compiler/externs/mocha-2.5.js | 126 chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo.js | 204 chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo_core.js | 88 chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo_private.js | 25 chromium-132.0.6834.159/third_party/closure_compiler/externs/networking_private.js | 1275 - chromium-132.0.6834.159/third_party/closure_compiler/externs/pending.js | 76 chromium-132.0.6834.159/third_party/closure_compiler/externs/pending_polymer.js | 73 chromium-132.0.6834.159/third_party/closure_compiler/externs/picture_in_picture.js | 73 chromium-132.0.6834.159/third_party/closure_compiler/externs/polymer-1.0.js | 1771 - chromium-132.0.6834.159/third_party/closure_compiler/externs/quick_unlock_private.js | 156 chromium-132.0.6834.159/third_party/closure_compiler/externs/runtime.js | 547 chromium-132.0.6834.159/third_party/closure_compiler/externs/settings_private.js | 114 chromium-132.0.6834.159/third_party/closure_compiler/externs/speech_recognition_private.js | 106 chromium-132.0.6834.159/third_party/closure_compiler/externs/tabs.js | 599 chromium-132.0.6834.159/third_party/closure_compiler/externs/terminal_private.js | 152 chromium-132.0.6834.159/third_party/closure_compiler/externs/test.js | 279 chromium-132.0.6834.159/third_party/closure_compiler/externs/tts.js | 238 chromium-132.0.6834.159/third_party/closure_compiler/externs/ttsEngine.js | 222 chromium-132.0.6834.159/third_party/closure_compiler/externs/virtual_keyboard_private.js | 279 chromium-132.0.6834.159/third_party/closure_compiler/externs/webview_tag.js | 527 chromium-132.0.6834.159/third_party/closure_compiler/externs/windows.js | 211 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/OWNERS | 2 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/README.md | 5 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/bluetooth_interface.js | 94 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/bluetooth_private_interface.js | 101 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/input_method_private_interface.js | 276 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/language_settings_private.js | 157 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/language_settings_private_interface.js | 157 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/mojo_private_interface.js | 20 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/networking_private_interface.js | 282 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/quick_unlock_private_interface.js | 111 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/settings_private_interface.js | 64 chromium-132.0.6834.159/third_party/closure_compiler/interfaces/system_display_interface.js | 181 chromium-132.0.6834.159/third_party/closure_compiler/js_binary.py | 162 chromium-132.0.6834.159/third_party/closure_compiler/js_library.py | 37 chromium-132.0.6834.159/third_party/closure_compiler/roll_closure_compiler | 140 chromium-132.0.6834.159/ui/accessibility/ax_tree.cc | 3 chromium-132.0.6834.159/ui/accessibility/extensions/strings/accessibility_extensions_strings_iw.xtb | 2 chromium-132.0.6834.159/ui/strings/translations/ax_strings_fa.xtb | 2 chromium-132.0.6834.159/ui/strings/translations/ax_strings_iw.xtb | 14 chromium-132.0.6834.159/ui/strings/translations/ui_strings_iw.xtb | 4 chromium-132.0.6834.159/v8/include/v8-version.h | 4 chromium-132.0.6834.159/v8/src/compiler/turboshaft/maglev-graph-building-phase.cc | 9 chromium-132.0.6834.159/v8/src/maglev/maglev-ir.cc | 15 chromium-132.0.6834.159/v8/src/maglev/maglev-ir.h | 21 chromium-132.0.6834.159/v8/src/maglev/maglev-phi-representation-selector.cc | 22 chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/meta.json | 2 chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x64-rl.profile | 2734 +- chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x64.profile | 2195 - chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x86-rl.profile | 2262 +- chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x86.profile | 2301 +- 1661 files changed, 5655 insertions(+), 194389 deletions(-) diff -Nru chromium-132.0.6834.110/DEPS chromium-132.0.6834.159/DEPS --- chromium-132.0.6834.110/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/DEPS 2025-01-27 17:37:37.000000000 +0000 @@ -280,7 +280,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '625e932f21c984db3f9fba8b56b9afa4e977994c', + 'v8_revision': '210ec27ca748c70580fe374f9811761667312b41', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. @@ -1277,7 +1277,7 @@ 'src/clank': { 'url': Var('chrome_git') + '/clank/internal/apps.git' + '@' + - 'f6f3fbddcec34da69f7d669ef10575caf958913c', + '2a522f492943cd51b74f442241518fb7623b4f2b', 'condition': 'checkout_android and checkout_src_internal', }, diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_de.xtb chromium-132.0.6834.159/ash/strings/ash_strings_de.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_de.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_de.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -2007,7 +2007,7 @@ Generative KI ist experimentell, befindet sich noch in einem frühen Entwicklungsstadium und ist derzeit nur eingeschränkt verfügbar. Neue Benachrichtigung ausgeblendet Drücke die Such-Taste oder Umschalttaste, um die Aktivierung aufzuheben. -Nein danke +Nein, danke Suche und Assistant und Mit „Mag ich“ gibst du an, dass dir dieser Vorschlag gefällt diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_es-419.xtb chromium-132.0.6834.159/ash/strings/ash_strings_es-419.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_es-419.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_es-419.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1141,7 +1141,7 @@ Envía comentarios opcionales para mejorar las sugerencias: Tu administrador inhabilitó el Asistente de Google. Asegúrate de que el teléfono esté cerca y tenga la conexión Bluetooth activada. -Control facial +Control con gestos faciales La batería está completa. Tarea sugerida en la que concentrarse Vertical diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_es.xtb chromium-132.0.6834.159/ash/strings/ash_strings_es.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_es.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_es.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -484,7 +484,7 @@ Compartir Internet activado (la conexión Wi-Fi está desactivada) Conectarse a otras redes Wi‑Fi Activar o desactivar micrófono. -Flecha hacia arriba +Arriba Bloquea las ventanas Luz nocturna Se requieren datos móviles para activar el punto de acceso @@ -1141,7 +1141,7 @@ Proporciona comentarios opcionales para mejorar las sugerencias: Tu administrador ha inhabilitado el Asistente de Google. Asegúrate de que tengas el teléfono cerca y de que el Bluetooth esté activado -Control facial +Control con gestos faciales La batería está llena. Tarea sugerida en la que centrarse Vertical @@ -1560,7 +1560,7 @@ Desplegar Google Classroom Enlace con más información abierto en el navegador Ahora puedes grabarte a ti mismo y tu pantalla al mismo tiempo -Flecha hacia abajo +Abajo Reducir el brillo Envía el contenido de la pantalla de tu Chromebook Es posible que el rendimiento de los periféricos esté limitado diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_iw.xtb chromium-132.0.6834.159/ash/strings/ash_strings_iw.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -88,7 +88,7 @@ מה מזג האוויר? ‏לחצת על מקש הקיצור של 'מגדיל למסך מלא'. אפשר להשתמש ב- כדי להגדיל את התצוגה וב- כדי להקטין את התצוגה. כדי לזוז במסך כשמגדילים את התצוגה, משתמשים ב-Ctrl‏ + Alt + מקשי החיצים. אין תמיכה בציוד היקפי במצב אורח -המקלדת שמופיעה במסך מושבתת +המקלדת הווירטואלית מושבתת הפסקה מספק חשמל ל- נבחר @@ -134,7 +134,7 @@ צלילים למצב ריכוז עיצוב כהה . אפשר לעבור בין תאריכים באמצעות מקשי החיצים. -הלחצן האמצעי +הכפתור האמצעי , אפליקציה מותקנת סגירת החלון הנוכחי צפייה ברשימת הרשתות. . @@ -178,7 +178,7 @@ יש ללחוץ לקבלת אפשרויות נוספות כחול הצגת השם של שולחן העבודה הווירטואלי -לחצן מקשי העכבר +כפתור מקשי העכבר הפעולה הזו תאפשר גישה למצלמה ולמיקרופון לכל האפליקציות והאתרים שיש להם הרשאות לכך. יכול להיות שיהיה צורך לרענן את דף האינטרנט או להפעיל מחדש את האפליקציה. הפעלה או השבתה של המצב 'נא לא להפריע'. הקטנת התצוגה כשמפעילים את הזכוכית המגדלת @@ -229,7 +229,7 @@ {HOURS,plural, =0{תוך שעה}=1{לפני שעה}one{לפני # שעות}two{לפני שעתיים}other{לפני # שעות}} מנהל המערכת שלך מגדיר את שיטות הקלט. מועד ההגשה בתאריך -המקלדת שמופיעה במסך מופעלת +המקלדת הווירטואלית מופעלת החלון מוקצה לכל שולחנות העבודה הווירטואליים מותר להשתמש ב- שולחנות עבודה וירטואליים לכל היותר. צריך להסיר שולחן עבודה וירטואלי כדי לפתוח אחד חדש. עזרה בקריאה @@ -318,7 +318,7 @@ פתיחה של בוחר אמוג'י משחקים לא מחובר לרשת -לחצן אחר +כפתור אחר ‏כבל ה-USB-C שחיברת לא תומך ב-Thunderbolt. יכול להיות שביצועי המכשיר יוגבלו. ‏מקשי הקיצור Alt + ‏Backspace הוחלפו. כדי לדמות את הפעולה של המקש Delete, יש להקיש על המקש + המקש Backspace. שולחן עבודה חדש @@ -562,7 +562,7 @@ אמוטיקון מסוג הצגת כל האפליקציות הסתרת כל ההצעות למדיה -לחצן המיקרופן של המכשיר כבוי. +כפתור המיקרופן של המכשיר כבוי. ‏רוצה להשתמש במקש End? שימוש במקש אודיו במונו עריכת גודל המסך @@ -736,7 +736,7 @@ {MINUTES,plural, =1{דקה}one{דקות}two{דקות}other{דקות}} הצגת התמונות, המדיה, ההתראות והאפליקציות שבטלפון מהזמן האחרון ExpressKey 1 -הלחצן הצדדי +הכפתור הצדדי ‏כדי להיכנס להיסטוריית הלוח, יש ללחוץ על + V לצפייה בלוח. כדי להתחיל, צריך להעתיק פריט. כדי להציג את האפליקציות הפתוחות, מחליקים כלפי מעלה ולוחצים לחיצה ארוכה סוללה מלאה @@ -755,7 +755,7 @@ הגדרות אודיו אמוג'י מסוג בהירות -הלחצן הקדמי +הכפתור הקדמי כבויה המקורות הבאים יכולים להציג התראות ‏צריך לפתוח את הגדרות Bluetooth כדי להתאים את המכשיר @@ -924,7 +924,7 @@ ‏פתיחה של 'עזרה' באפליקציה 'מה חדש ב-Chromebook' באמצעות . הגרסה הנוכחית () אני רוצה להמשיך מהמקום שבו הפסקתי -לחצן קליקים אוטומטיים +כפתור קליקים אוטומטיים כבוי התכונה לא זמינה. הצגת חודש קודם @@ -1348,7 +1348,7 @@ טעינה מחדש החלפת מצב השיתוף בקרבת מקום במידת חשיפה גבוהה יצירתיות -לחצן +כפתור פתיחת כרטיסייה חדשה בחלון פרטי חדש ‏Bluetooth מופעל האפליקציות שחייבים להכיר @@ -1482,7 +1482,7 @@ ‏כדי להתקין את העדכון, יש להפעיל מחדש את ה-Chromebook כשהמקלדת מחוברת. ‏פלייליסטים מותאמים אישית עוזרים לך לשמור על מיקוד. נהנים מ-YouTube Music ומ-YouTube ללא פרסומות עם 3 חודשים של YouTube Premium ללא עלות. בכפוף לתנאים. השבתה של פקדי המשחקים -מקשים, לחצנים ועוד +מקשים, כפתורים ועוד דף מתוך הדגשת הפריט הבא במדף סימון כמשימה שהושלמה @@ -1491,7 +1491,7 @@ גלילה שמאלה הגדרת ההצגה של ההתראות והאפליקציות שבטלפון ניקוי הטקסט בתיבת החיפוש -הצגת חלונות מכל שולחנות העבודה הווירטואליים, לחצן הבחירה נבחר +הצגת חלונות מכל שולחנות העבודה הווירטואליים, כפתור הבחירה נבחר אי אפשר להוריד את הקבצים של שליטה באמצעות תנועות הפנים ,‏ , עוצמת האות: , הרשת מנוהלת על ידי מנהל המערכת שלך ‏אין אירועים בתאריך . צריך להקיש על Enter כדי לפתוח את יומן Google בדפדפן. @@ -1546,8 +1546,8 @@ פתיחת האפליקציה 'אבחון' האפליקציות המותקנות כאן אפשר להצמיד את הקבצים החשובים. יש לפתוח את אפליקציית 'קבצים' כדי להתחיל. -לחצן 'הקודם' -לחצן 'הבא' +כפתור 'הקודם' +כפתור 'הבא' פתיחת שולחן העבודה Page up לטעינה מלאה @@ -1567,7 +1567,7 @@ המצלמה והמיקרופון בשימוש כרגע על ידי ‎1X‎ הסיסמה חייבת להכיל תווים תקפים בלבד -הלחצן העליון +הכפתור העליון לשאול בכל פעם פתיחת ההתראות לא ניתן לסמן כ'הושלמה'. אפשר לנסות שוב כשיהיה חיבור לאינטרנט. @@ -1640,7 +1640,7 @@ ‏צריך לוודא ש-Chromebook מחובר לאותה רשת Wi-Fi שאליה מחובר מכשיר Chromecast. הקשר למצלמה אבד, מתבצע ניסיון להתחברות מחדש יש לבחור חלון לצילום -במהלך העדכון, ייתכן שהתצוגה במסך תופסק לפרק זמן ארוך מהרגיל (עד דקה). אין ללחוץ על לחצן ההפעלה עד להשלמת העדכון. +במהלך העדכון, ייתכן שהתצוגה במסך תופסק לפרק זמן ארוך מהרגיל (עד דקה). אין ללחוץ על כפתור ההפעלה עד להשלמת העדכון. נא לא להפריע אמוג'י עוצמת האות: , סוללת הטלפון: @@ -1701,7 +1701,7 @@ ‏חיפוש ב-Google Drive למקלדת הניתנת לניתוק דרוש עדכון קריטי הוספת שולחן עבודה וירטואלי חדש -‏לחצן תפריט IME +‏כפתור תפריט IME ‏כשמשתמשים ב-AI גנרטיבי, האיכות של התוצאות לא תמיד אחידה. מקלדת לקוד האימות הקודם @@ -1912,7 +1912,7 @@ אימות זהות ‏מקשי הקיצור של לחיצה ימנית היו Alt + לחיצה ועכשיו הם מקש + לחיצה , לא נבחר -אפשר להתאים אישית את פעולות הלחצנים במכשיר +אפשר להתאים אישית את פעולות הכפתורים במכשיר נבחר מצב של צילום מסך יומן, השבוע של , התאריך שנבחר הוא . הורדה @@ -1921,7 +1921,7 @@ הפריים האוטומטי פועל במצלמה. לאחר הכיבוי, האדמין ינותק מהחשבון ולא יוכל לשלוט במכשיר שלך. -כדי לכבות את המכשיר, יש ללחוץ שוב לחיצה ארוכה על לחצן ההפעלה במכשיר. +כדי לכבות את המכשיר, יש ללחוץ שוב לחיצה ארוכה על כפתור ההפעלה במכשיר. הפעלת התכונה 'נא לא להפריע' בזמן מצב ריכוז Google Tasks יצירה @@ -1992,7 +1992,7 @@ פתיחת האתר שרשום בסרגל הכתובות בכרטיסייה חדשה ‏השבתת Caps Lock אין התראות -הדגשת הלחצן של מרכז האפליקציות במדף +הדגשת הכפתור של מרכז האפליקציות במדף הגעת למספר המקסימלי של שולחנות עבודה. ExpressKey 4 הצגת הכול @@ -2015,7 +2015,7 @@ אם סימנת 'אהבתי', יישלח אלינו משוב שאהבת את ההצעה הזו מאירוע קרוב ביומן אות חזק -אפשר להתאים אישית את פעולות הלחצנים, מהירות הסמן ועוד במכשיר +אפשר להתאים אישית את פעולות הכפתורים, מהירות הסמן ועוד במכשיר עבר הזמן אזהרה: תכונה ניסיונית מקלדת @@ -2112,7 +2112,7 @@ הפסקת העברת המסך אל ביטול ההצמדה של האפליקציה למדף מופעל, כל האפליקציות -לחצן ההקראה +כפתור ההקראה ‏לא מוגדר בטלפון שלך מסך נעילה. צריך להזין סיסמה כדי לפתוח את ה-Chromebook. הפעלה מחדש פתיחה של אפליקציית המחשבון @@ -2218,7 +2218,7 @@ יצירת שולחן עבודה וירטואלי חדש ‏החיבור של ה-Chromebook ל-Bluetooth כבוי. צריך להזין סיסמה כדי לפתוח את ה-Chromebook. סיבוב אוטומטי -הצגת חלונות משולחן העבודה הווירטואלי הנוכחי, לחצן הבחירה נבחר +הצגת חלונות משולחן העבודה הווירטואלי הנוכחי, כפתור הבחירה נבחר כדאי להשתמש בכלי 'עזרה בקריאה' כדי לסכם תוכן או לשאול שאלות במהירות ייתכן שה- לא ייטען כשהוא פועל. {NUM_APPS,plural, =1{הקלט מהמיקרופון נשלט על ידי }one{הקלט מהמיקרופון נשלט על ידי # אפליקציות}two{הקלט מהמיקרופון נשלט על ידי # אפליקציות}other{הקלט מהמיקרופון נשלט על ידי # אפליקציות}} @@ -2264,7 +2264,7 @@ חובר מטען בעל מתח נמוך הצגת ההגדרות של מצב הריכוז. מצב הריכוז מופעל. הזמן שנותר: . מעקב הביצועים פעיל -‏יש להתחיל בהקלטה. לאחר התחלת ההקלטה, יש להקיש על Alt ‏+ Shift ‏+ L כדי לעבור למדף ולמצוא את הלחצן להפסקת ההקלטה +‏יש להתחיל בהקלטה. לאחר התחלת ההקלטה, יש ללחוץ על Alt ‏+ Shift ‏+ L כדי לעבור למדף ולמצוא את הכפתור להפסקת ההקלטה התמקדות בחלון תמונה בתוך תמונה הפעלה/השבתה של הכתבה (הקלדה קולית) אפשרויות במרכז בקרת המשחקים @@ -2308,7 +2308,7 @@ יש להחליק מצד ימין כדי לחזור אחורה הצגה או הסתרה של סרגל הסימניות מחובר עכשיו -לחצן 'הקודם' +כפתור 'הקודם' הפעלה או השבתה של נעילת הסיבוב. קבלת עזרה הצגת הטמפרטורה במעלות פרנהייט @@ -2391,7 +2391,7 @@ ביטול הפעולה האחרונה ‏‫Bluetooth לא זמין {MINUTES,plural, =1{בעוד דקה}one{בעוד # דקות}two{בעוד # דקות}other{בעוד # דקות}} -הלחצן האחורי +הכפתור האחורי לא ניתן להקליט תוכן מוגן מחיקת האות הבאה יציאה @@ -2442,7 +2442,7 @@ הפקדים של המצלמה והאודיו ‏כדי להפעיל את לוח המגע, יש ללחוץ על מקש Shift‏ 5 פעמים החלון נסגר. -‏שלב מתוך בסיור. בעזרת האפליקציות אפשר לבצע כל מה שצריך ב-. האפליקציות נמצאות במרכז האפליקציות. כדי להתמקד בלחצן של מרכז האפליקציות, מקישים על Alt + Shift + L. +‏שלב מתוך בסיור. בעזרת האפליקציות אפשר לבצע כל מה שצריך ב-. האפליקציות נמצאות במרכז האפליקציות. כדי להתמקד בכפתור של מרכז האפליקציות, לוחצים על Alt + Shift + L. ,‏ קבלה של התכונות ושיפורי האבטחה האחרונים. העדכונים מתבצעים ברקע. \ No newline at end of file diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_nl.xtb chromium-132.0.6834.159/ash/strings/ash_strings_nl.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_nl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_nl.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -178,7 +178,7 @@ Klik voor meer opties Blauw Bureaunaam tonen -Knop voor muisknoppen +Knop voor muistoetsen Hiermee geef je toegang aan alle apps en websites met camera- en microfoonrechten. Je moet misschien de webpagina vernieuwen of de app opnieuw starten. Niet storen aan-/uitzetten. Uitzoomen als vergrootglas aanstaat @@ -867,7 +867,7 @@ Titel Handschrift Niet storen staat aan. -Muisknoppen onderbreken/hervatten als dit actief is +Muistoetsen onderbreken/hervatten als dit actief is Laserpen Stift niet beschikbaar. Open Screencast opnieuw. Omlaag scrollen @@ -1667,7 +1667,7 @@ , Camera uitgelijnd op de linkerbenedenhoek. Conflict met systeemoppervlak. Focus staat aan -Muisknoppen +Muistoetsen , signaalsterkte , beheerd door je beheerder Schermopnamemodus geselecteerd subtaak diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_pt-BR.xtb chromium-132.0.6834.159/ash/strings/ash_strings_pt-BR.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_pt-BR.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_pt-BR.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1559,7 +1559,7 @@ Abrir o Google Sala de Aula Link "Saiba mais" aberto no navegador Agora é possível gravar você e a tela ao mesmo tempo -Seta para baixo +Para baixo Diminuir o brilho Transmitir a tela do Chromebook O desempenho dos periféricos pode ser limitado diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_ru.xtb chromium-132.0.6834.159/ash/strings/ash_strings_ru.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_ru.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_ru.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1667,7 +1667,7 @@ , Окно предварительного просмотра камеры привязано к левому нижнему углу, так как перекрывало элементы системного интерфейса Режим концентрации внимания включен -Клавиши управления мышью +Клавиши управления указателем Статус защиты – "", уровень сигнала – , под управлением администратора Выбран режим записи видео с экрана подзадача @@ -2183,7 +2183,7 @@ и телефон будут подключены друг к другу автоматически Доброй ночи! Защита от чужих взглядов -С возвращением! +Двигаемся дальше? Подписка Music Premium Удалить единственный рабочий стол нельзя. Ваш родитель заблокировал это устройство. diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_sr-Latn.xtb chromium-132.0.6834.159/ash/strings/ash_strings_sr-Latn.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_sr-Latn.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_sr-Latn.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -219,7 +219,7 @@ Titl uživo je uključen. Uključite WiFi sinhronizaciju Hotspot je isključen -Pređite na prethodnog korisnika +Pređi na prethodnog korisnika Prelazite sa tamne na svetlu temu i obratno. Dodirnite i zadržite radnu površinu, pa izaberite Pozadina i stil. Stavka „“ je vidljiva za Bluetooth uređaje. Odbacite podešavanje pregleda obaveštenja na telefonu @@ -278,7 +278,7 @@ manje od 1 min Da biste preuzeli ažuriranje, restartujte Chromebook sa priključenom tastaturom na dodirnom ekranu. Nazad na pitanje -Pređite na sledećeg korisnika +Pređi na sledećeg korisnika Pomoćnik Snimanje ekrana je dovršeno Podesite jezik @@ -1007,7 +1007,7 @@ Privremenu memoriju ćete videti kad pritisnete i zadržite Ctrl + V. Ovu prečicu možete da isključite ako onemogućite oznaku #clipboard-history-longpress u odeljku chrome://flags (os://flags ako koristite Lacros). Prilagodi predloge Dobro veče, -Zaustavite snimanje ekrana +Zaustavi snimanje ekrana Pridružite se WiFi mreži Preuzimaju se datoteke za prepoznavanje govora... % {0,plural, =0{Ažurirajte uređaj}=1{Ažurirajte uređaj u roku od 1 sekunde}one{Ažurirajte uređaj u roku od # sekunde}few{Ažurirajte uređaj u roku od # sekunde}other{Ažurirajte uređaj u roku od # sekundi}} @@ -2288,7 +2288,7 @@ Pregledajte podešavanja VPN-a Možete da počnete sa prilagođavanjem rasporeda aplikacija kada izađete iz ovog prikaza. Nije moguće podesiti višestruko prijavljivanje -Prebacite uređaj u režim spavanja +Prebaci uređaj u režim spavanja 90 °F u C , instalirana aplikacija, blokirana Povežite sa uređajem diff -Nru chromium-132.0.6834.110/ash/strings/ash_strings_sr.xtb chromium-132.0.6834.159/ash/strings/ash_strings_sr.xtb --- chromium-132.0.6834.110/ash/strings/ash_strings_sr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/strings/ash_strings_sr.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -219,7 +219,7 @@ Титл уживо је укључен. Укључите WiFi синхронизацију Хотспот је искључен -Пређите на претходног корисника +Пређи на претходног корисника Прелазите са тамне на светлу тему и обратно. Додирните и задржите радну површину, па изаберите Позадина и стил. Ставка „“ је видљива за Bluetooth уређаје. Одбаците подешавање прегледа обавештења на телефону @@ -278,7 +278,7 @@ мање од 1 мин Да бисте преузели ажурирање, рестартујте Chromebook са прикљученом тастатуром на додирном екрану. Назад на питање -Пређите на следећег корисника +Пређи на следећег корисника Помоћник Снимање екрана је довршено Подесите језик @@ -1007,7 +1007,7 @@ Привремену меморију ћете видети кад притиснете и задржите Ctrl + V. Ову пречицу можете да искључите ако онемогућите ознаку #clipboard-history-longpress у одељку chrome://flags (os://flags ако користите Lacros). Прилагоди предлоге Добро вече, -Зауставите снимање екрана +Заустави снимање екрана Придружите се WiFi мрежи Преузимају се датотеке за препознавање говора... % {0,plural, =0{Ажурирајте уређај}=1{Ажурирајте уређај у року од 1 секунде}one{Ажурирајте уређај у року од # секунде}few{Ажурирајте уређај у року од # секунде}other{Ажурирајте уређај у року од # секунди}} @@ -2288,7 +2288,7 @@ Прегледајте подешавања VPN-а Можете да почнете са прилагођавањем распореда апликација када изађете из овог приказа. Није могуће подесити вишеструко пријављивање -Пребаците уређај у режим спавања +Пребаци уређај у режим спавања 90 °F у C , инсталирана апликација, блокирана Повежите са уређајем diff -Nru chromium-132.0.6834.110/ash/webui/camera_app_ui/resources/strings/camera_strings_iw.xtb chromium-132.0.6834.159/ash/webui/camera_app_ui/resources/strings/camera_strings_iw.xtb --- chromium-132.0.6834.110/ash/webui/camera_app_ui/resources/strings/camera_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ash/webui/camera_app_ui/resources/strings/camera_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -139,7 +139,7 @@ שגיאות במערכת הקבצים. הטקסט הועתק ‏צילום סרטון בפורמט GIF -הצגת טקסט ולחצן להעתקה +הצגת טקסט וכפתור להעתקה מעבר למצלמה הבאה ההורדה בהשהיה 4 על 4 diff -Nru chromium-132.0.6834.110/build/util/LASTCHANGE chromium-132.0.6834.159/build/util/LASTCHANGE --- chromium-132.0.6834.110/build/util/LASTCHANGE 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/build/util/LASTCHANGE 2025-01-27 17:37:37.000000000 +0000 @@ -1,2 +1,2 @@ -LASTCHANGE=df453a35f099772fdb954e33551388add2ca3cde-refs/branch-heads/6834_101@{#3} +LASTCHANGE=2d77d3fc4452661469b78f115e0aed4d71269739-refs/branch-heads/6834@{#4408} LASTCHANGE_YEAR=2025 diff -Nru chromium-132.0.6834.110/build/util/LASTCHANGE.committime chromium-132.0.6834.159/build/util/LASTCHANGE.committime --- chromium-132.0.6834.110/build/util/LASTCHANGE.committime 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/build/util/LASTCHANGE.committime 2025-01-27 17:37:37.000000000 +0000 @@ -1 +1 @@ -1737474076 \ No newline at end of file +1737999457 \ No newline at end of file diff -Nru chromium-132.0.6834.110/chrome/VERSION chromium-132.0.6834.159/chrome/VERSION --- chromium-132.0.6834.110/chrome/VERSION 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/VERSION 2025-01-27 17:37:37.000000000 +0000 @@ -1,4 +1,4 @@ MAJOR=132 MINOR=0 BUILD=6834 -PATCH=110 +PATCH=159 diff -Nru chromium-132.0.6834.110/chrome/app/resources/chromium_strings_iw.xtb chromium-132.0.6834.159/chrome/app/resources/chromium_strings_iw.xtb --- chromium-132.0.6834.110/chrome/app/resources/chromium_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/chromium_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -28,7 +28,7 @@ מכשירי Bluetooth. זיהוי שפה אוטומטי ‏אני רוצה למחוק את הנתונים גם מ-Chromium () -התכונה הוצמדה. מעכשיו אפשר לגשת לחיפוש התמונות דרך הלחצן החדש בסרגל הכלים +התכונה הוצמדה. מעכשיו אפשר לגשת לחיפוש התמונות דרך הכפתור החדש בסרגל הכלים חדש! אפשר לתרגם טקסט ותמונות במסך ‏נכנסת ל-Chromium! ‏קבלת עזרה לגבי Chrome for Testing @@ -564,12 +564,12 @@ ‏ל-Chromium יש אפשרות לבדוק את הסיסמאות שלך רק אם שמרת אותן פרופיל העבודה שלך נפרד לחלוטין מהפרופיל האישי שלך. שגיאה בשירות: . -אפשר להצמיד את התכונה 'חיפוש תמונות' כדי לאפשר גישה נוחה: פשוט לוחצים על הלחצן 'הצמדה' בחלק העליון של החלונית הצדדית +אפשר להצמיד את התכונה 'חיפוש תמונות' כדי לאפשר גישה נוחה: פשוט לוחצים על הכפתור 'הצמדה' בחלק העליון של החלונית הצדדית רשימת שפות לחיפוש ‏Chromium יכול לבדוק את הסיסמאות כשנכנסים באמצעות חשבון Google ‏מספר ארגונים מנהלים את Chromium ‏Copyright The Chromium Authors. כל הזכויות שמורות. -חדש! אפשר לתרגם טקסט ותמונות במסך באמצעות לחיצה על הלחצן 'תרגום המסך' +חדש! אפשר לתרגם טקסט ותמונות במסך באמצעות לחיצה על הכפתור 'תרגום המסך' איך אנחנו משתמשים בנתונים האלה: אתרים יכולים לשמור מידע ב-Chromium לגבי תחומי העניין שלך. לדוגמה, אם ביקרת באתר כדי לקנות נעליים למרתון, האתר עשוי להגדיר 'ריצת מרתון' כתחום עניין שלך. לאחר מכן, בביקור באתר שונה, למשל כדי להירשם למרוץ, יכול להיות שתוצג לך מודעה לנעלי ריצה על סמך תחומי העניין שלך. ‏הפעלת Chromium מתבצעת... ‏ההתקנה נכשלה בשל שגיאה לא מזוהה. יש להוריד שוב את Chromium. diff -Nru chromium-132.0.6834.110/chrome/app/resources/chromium_strings_ru.xtb chromium-132.0.6834.159/chrome/app/resources/chromium_strings_ru.xtb --- chromium-132.0.6834.110/chrome/app/resources/chromium_strings_ru.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/chromium_strings_ru.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -383,7 +383,7 @@ Назначить Chromium браузером по умолчанию Не удалось проверить наличие обновлений в Chromium. Проверьте подключение к Интернету. Выйти из Chromium? -Чтобы поддерживать работу этих вкладок, используется оперативная память. Разрешите Chromium сделать их неактивными, и производительность повысится. +Эти вкладки занимают лишние ресурсы. Чтобы повысить производительность, разрешите Chromium сделать их неактивными. Настроить профиль Chromium Настройте профиль Chromium Расширение запрашивает вход в Chromium diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_ar.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_ar.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_ar.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_ar.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -3582,7 +3582,7 @@ فلنبدأ اللعب ‏تستخدم المواقع الإلكترونية عادةً JavaScript لعرض الميزات التفاعلية، مثل ألعاب الفيديو أو نماذج الويب. ‏أجهزة USB من (المنتج ) -مشاركة رسومات الشعار المبتكرة +‏مشاركة رسومات شعار Google الإرسال إلى أجهزتك يجب إيقاف "" لتغيير إعدادات الميكروفون. للمتابعة، يجب أولاً إيقاف "". ‏حدث خطأ أثناء تثبيت المشاركة. سبَق وأن تمّ تثبيت العديد من مشاركات بروتوكول Server Message Block ‏(SMB). @@ -8128,7 +8128,7 @@ ‏يحتاج "مدير كلمات المرور في Google" إلى الإذن بالوصول إلى تطبيق MacOS Keychain. صغير جدًا &إدارة محركات البحث... -رابط رسومات الشعار المبتكرة +‏رابط رسومات شعار Google يمكن أن تشمل بيانات التطبيق أيّ بيانات حفظها التطبيق (بناءً على إعدادات مطوّر البرامج)، بما في ذلك بيانات مثل جهات الاتصال والرسائل والصور. لن يتم احتساب بيانات النُسخ الاحتياطية ضمن مساحة التخزين المتوفّرة في Drive لحساب طفلك. يمكنك إيقاف هذه الخدمة من خلال الإعدادات. ‏تم إلغاء عملية الاحتفاظ بنسخة احتياطية من Linux diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_as.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_as.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_as.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_as.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -11695,7 +11695,7 @@ ৰ শুধৰণি কৰি কৰাৰ বাবে স্বয়ং শুধৰণি আনডু কৰাৰ ডায়লগ দেখুওৱা হৈছে। এক্সেছ কৰিবলৈ উপৰমুৱা কাঁড়চিহ্নত টিপক, উপেক্ষা কৰিবলৈ এস্কে’প টিপক। আপুনি এগৰাকী অভিভাৱক বুলি সত্যাপন কৰক আৰম্ভণিৰ যতিচিহ্নৰ প্ৰস্থ পূৰ্ণ -এটা বস্তুত দুবাৰ টিপক, দ্বিতীয়বাৰ টিপি ধৰি ৰাখক আৰু তাৰ পিছত বস্তুটো লৰচৰ কৰিবলৈ টানি নিয়ক +এটা বস্তুত দুবাৰ টিপক, দ্বিতীয়বাৰ টিপি ধৰি ৰাখক আৰু তাৰ পাছত বস্তুটো লৰচৰ কৰিবলৈ টানি নিয়ক বাতিল কৰা সম্পূৰ্ণ হ'লে এই ৱিণ্ড'খন বন্ধ হ'ব। কামৰ তালিকাৰ বুটাম অফলাইন diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_bs.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_bs.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_bs.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_bs.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -8740,7 +8740,7 @@ Šaljite podatke o korištenju i dijagnostici. Ovaj uređaj trenutno automatski šalje Googleu podatke o dijagnostici, uređaju i korištenju aplikacija. To će pomoći stabilnosti sistema i aplikacija, kao i drugim poboljšanjima. Neki zbirni podaci će također pomoći Googleovim aplikacijama i partnerima, kao što su Androidovi programeri. Ovu postavku je nametnuo vlasnik. Ako vam je uključena postavka dodatna Aktivnost na webu i u aplikacijama, ti podaci će možda biti sačuvani na vašem Google računu. Pretražite aplikacije Ovdje se prikazuju web aplikacije koje ste instalirali -Premjesti stavke dodirom i prevlačenjem +Pomicanje stavki dodirom i prevlačenjem Štampači ekstenzija Još uvijek nije dodijeljen nijedan prekidač za pristup Unesite sadašnji PIN da ga promijenite. Ako ne znate svoj PIN, moraćete poništiti sigurnosni ključ, a zatim kreirati novi PIN. @@ -8829,7 +8829,7 @@ Uvijek blokiraj da web lokacija kontrolira i reprogramira MIDI uređaje % – do potpune napunjenosti Kupite odmah -Kreirajte teme pomoću AI-ja +Kreiranje tema s AI-jem Greška prilikom preuzimanja Postavke glasa za pretvaranje teksta u govor Upućen je zahtjev za odobrenje diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_ca.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_ca.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_ca.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_ca.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -11679,7 +11679,7 @@ Es mostra el quadre de diàleg Desfés de la correcció automàtica per a la paraula , que s'ha corregit com a . Prem la fletxa amunt per accedir i la tecla d'escapada per ignorar. Verifica que ets el pare o la mare L'amplada inicial de la puntuació és completa -Fes doble toc sobre un element, mantén-lo premut en el segon toc i arrossega'l per moure'l +Per moure un element, fes-hi doble toc, mantén premut en el segon toc i arrossega'l Aquesta finestra es tancarà un cop hagi finalitzat la cancel·lació. Botó del menú d'accions Sense connexió diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_de.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_de.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_de.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_de.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1136,7 +1136,7 @@ App () Gruppe schließen Lesezeichen werden importiert... -Als anstößig / nicht sicher melden +Als anstößig/bedenklich melden Nearby Share einrichten, um Dateien mit Personen in der Nähe auszutauschen Geräuschunterdrückung und Audioverbesserungen anwenden. Aktuelle PIN @@ -9557,7 +9557,7 @@ Nur Geräte, die im Konto angemeldet sind, können Inhalte mit diesem Gerät teilen. Du musst das Teilen von deinen Geräten nicht genehmigen. Hierfür wird die mobile Datenverbindung deines Geräts () verwendet und dein Mobilfunkanbieter berechnet möglicherweise zusätzliche Gebühren. Kann auch den Akkuverbrauch erhöhen. Weitere Informationen &Gegen den Uhrzeigersinn drehen -Nein danke +Nein, danke Wenn du die Einrichtung mit deinem Android-Gerät fortsetzen möchtest, verbinde dein mit einem Netzwerk Tab geschlossen Leicht diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_en-GB.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_en-GB.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_en-GB.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_en-GB.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -4141,7 +4141,7 @@ Select Time Zone Lift, then touch again Name -Use Strong Password +Use strong password Manage '' tab group Username '' is not available Currently using Google Account password. You can set up a password to make it easier to sign in. diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_es-419.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_es-419.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_es-419.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_es-419.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -5561,7 +5561,7 @@ Cuando todo esté listo, busca tu lista de lectura en Favoritos y Listas Acción de inactividad mientras se usa la batería No se puede habilitar la -Control facial +Control con gestos faciales Activar la predicción de palabra siguiente Esta acción borrará permanentemente los datos de navegación de este dispositivo. Buena (DVD) diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_es.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_es.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_es.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_es.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1315,7 +1315,7 @@ Para configurar la huella digital, pídele a tu hijo/a que toque el sensor de huellas digitales, que está en la esquina inferior derecha del teclado. Los datos de la huella digital de tu hijo/a se almacenan de forma segura y nunca salen de este . Usar contraseña segura Error al analizar -Haz una pregunta sobre esta página +Preguntar sobre esta página Es posible que las aplicaciones de Google Play necesiten acceso completo al sistema de archivos para leer y escribir archivos en dispositivos de almacenamiento externo. Los usuarios de la unidad externa podrán ver los archivos y las carpetas que se hayan creado en el dispositivo. Más información Pide a tu administrador que actualice esta aplicación Seleccionar &todo @@ -2479,7 +2479,7 @@ Velocidad del panel táctil Desplázate hasta el final de la pantalla y activa la opción Conexión compartida instantánea si aparece. Si no, ya has terminado. Crea copias de seguridad en Google Drive. Recupera datos de forma sencilla o cambia de dispositivo en cualquier momento. Esta copia de seguridad incluye datos de aplicaciones. Las copias de seguridad se suben a Google y se cifran con la contraseña de la cuenta de Google de tu hijo/a. Más información sobre las copias de seguridadMás información -Flecha hacia arriba +Arriba Por encima de la media Autocompletar Datos de uso y diagnóstico @@ -5563,7 +5563,7 @@ Cuando quieras, busca tu lista de lectura en Marcadores y listas Modo de inactividad con batería No se puede habilitar la -Control facial +Control con gestos faciales Habilitar sugerencia de siguiente palabra Se eliminarán de forma permanente los datos de navegación del dispositivo. Buena - DVD @@ -7368,7 +7368,7 @@ {NUM_OF_FILES,plural, =1{No se ha podido copiar el archivo a }other{No se han podido copiar los archivos a }} El proceso de formateo se ha realizado correctamente. Este contenedor ya existe. -Flecha hacia abajo +Abajo Se eliminará el perfil Conexión de datos disponible desde tu Archivo de clave privada (opcional) diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_et.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_et.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_et.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_et.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -3796,7 +3796,7 @@ Leidke oma pliiatsi nupud Lähtestamine Failide võrguhoidlad -Automaatselt kohanduv +Tundlik Inaktiivseid vahelehti kuvatakse uutmoodi Seda laiendust ei saa kasutada. Vanem või eestkostja on Chrome'is saitide, rakenduste ja laienduste load välja lülitanud. Luba saidil ka edaspidi mikrofoni juurde pääseda diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_eu.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_eu.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_eu.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_eu.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -8312,7 +8312,7 @@ Aurreikusteko ahotsa Ez da onartzen atal hau: Kontu hau sinkronizatzeko aukera aktibatuta daukaten Chrome arakatzaile guztietan sinkronizatuko dira datuak. Chrome OS-ren sinkronizazio-aukerak ikusteko, joan Chrome OS-ren ezarpenetara. -Aukeratu ez ordaintzea +Aukeratu ez erabiltzea Ireki guztiak () Aktibatu sinkronizazioa Bilatu "" diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_fa.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_fa.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_fa.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_fa.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -3802,7 +3802,7 @@ مکان‌یابی دکمه‌های قلم مقداردهی اولیه دستگاه ذخیره‌سازی متصل به شبکه -پاسخگویی +واکنش‌گرا برگه‌های غیرفعال ظاهر جدیدی پیدا می‌کنند ‏نمی‌توانید از این افزونه استفاده کنید. ولی یا سرپرستتان «اجازه‌های سایت‌ها، برنامه‌ها، و افزونه‌ها» را در Chrome خاموش کرده است. ادامه اجازه به برای دسترسی به میکروفون @@ -8736,7 +8736,7 @@ ‏داده‌های استفاده و عیب‌یابی را ارسال کنید. این دستگاه درحال‌حاضر به‌صورت‌ خودکار داده‌های عیب‌یابی و داده‌های استفاده از دستگاه و برنامه را برای Google ارسال می‌کند. این داده‌ها به بهبود پایداری سیستم و برنامه و موارد دیگر کمک خواهد کرد. بعضی داده‌های تجمیعی نیز به برنامه‌ها و شرکای Google (مانند «برنامه‌نویس‌های Android») کمک می‌کند. این تنظیم را مالک اعمال می‌کند. اگر تنظیم «فعالیت‌ها در وب و برنامه» تکمیلی روشن باشد، ممکن است این داده‌ها در «حساب Google» شما ذخیره شود. جستجوی برنامه‌ها برنامه‌های وبی که نصب کرده‌اید در اینجا نشان داده می‌شود -ضربه زدن و کشیدن برای انتقال موارد +حرکت دادن موارد با تک‌ضرب و کشیدن چاپگرهای افزونه هنوز کلیدی تخصیص داده نشده است پین کنونی‌تان را برای تغییر پین وارد کنید. اگر پین‌ خود را نمی‌دانید، باید کلید ایمنی را بازنشانی کنید و سپس پین جدیدی ایجاد کنید. @@ -8825,7 +8825,7 @@ ‏همیشه مسدود شود تا نتواند دستگاه‌های MIDI شما را کنترل و مجدداً برنامه‌ریزی کند ٪ - تا شارژ کامل اکنون بخرید -ساختن زمینه با هوش مصنوعی +موضوع‌سازی با هوش مصنوعی خطای بارگیری تنظیمات صدای نوشتار به گفتار مجوز درخواست شد diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_fr.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_fr.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_fr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_fr.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -5828,7 +5828,7 @@ Recevoir un avertissement avant d'accéder aux sites qui ne prennent pas en charge les connexions sécurisées Échec de la connexion au réseau "" : En savoir plus sur l'utilisation de la localisation -Les sites que vous consultez peuvent déterminer ce que vous aimez, puis vous montrer des annonces alors que vous continuez de naviguer +Les sites que vous consultez peuvent déterminer ce qui vous intéresse, puis vous montrer des annonces lorsque vous continuez de naviguer Outil : Clic automatique à l'arrêt du curseur Dites-nous pourquoi vous téléchargez ce fichier malgré tout @@ -10005,7 +10005,7 @@ ChromeOS est à jour Mettre en veille lorsque l'appareil fonctionne sur batterie Les codes ne correspondent pas - utilise les paramètres de proxy provenant d'une extension + utilise les paramètres du proxy d'une extension Votre administrateur doit d'abord accepter les conditions d'utilisation dans la liste des appareils Chrome via la Console d'administration. Installer et effacer le disque dur ? Connexion réseau nécessaire diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_gl.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_gl.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_gl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_gl.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -463,7 +463,7 @@ Non preguntarme de novo O sistema non puido almacenar o token de acceso á API de longo prazo para este dispositivo. O ficheiro é creación miña, grupo de botóns de opción, 1 de 3 -Elimínanse os datos que repercuten na personalización dos anuncios +Elimínanse os datos que repercuten na personalización de anuncios Estás emitindo unha pestana. Podes pór en pausa ou deter a emisión cando queiras. Descubre a protección mellorada para dispor do máximo nivel de seguranza de Chrome nas descargas A protección mellorada está activada diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_id.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_id.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_id.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_id.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -4807,7 +4807,7 @@ Untuk menelusuri situs tertentu atau bagian dari Chrome, ketik pintasannya di kolom URL, lalu tekan pintasan keyboard yang diinginkan. Akses kamera diizinkan untuk aplikasi dan situs yang memiliki izin kamera, serta layanan sistem. Untuk menggunakan kamera, Anda mungkin perlu memulai ulang aplikasi atau memuat ulang halaman. &Buka di -Konfigurasikan... +Konfigurasi... Nama pengguna tidak dikenali server Tambahkan detail opsional Menghapus akun ini juga akan menghapus profil Chrome yang login dengan akun ini diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_it.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_it.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_it.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_it.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -2722,7 +2722,7 @@ Rimuovi ambiente di sviluppo Linux questa scheda Imposta l'immagine del profilo -Tieni premuti i tasti della tastiera per vedere accenti e caratteri speciali. Verrà disattivata la funzionalità Ripeti la pressione del tasto per i tasti alfabetici. Disponibile solo per l'inglese (USA). +Tieni premuti i tasti della tastiera per vedere accenti e caratteri speciali. Verrà disattivata la ripetizione automatica del carattere quando tieni premuto un tasto alfabetico. Disponibile solo per l'inglese (USA). Screenshot dei programmi attualmente sullo schermo Crea automaticamente i sottotitoli codificati per le lingue supportate. I dati audio non vengono mai inoltrati dal tuo dispositivo. Controllo delle fonti di alimentazione… @@ -2740,7 +2740,7 @@ Impossibile installare l'app. Si è verificato un problema. Traccia precedente (pagine di errore Chrome) -Dito 2 +Impronta 2 Invia a Google gli URL di alcune pagine che visiti quando la tua sicurezza è a rischio Scegli l'intervallo di tempo Ricerca nei siti @@ -3860,7 +3860,7 @@ Disattivare la sincronizzazione e la personalizzazione? Presentazione di () Non consentire ai siti di monitorare la posizione della fotocamera -Correggi subito +Correggi Ricevi un avviso se una password è stata compromessa a causa di una violazione dei dati Inserisci il nome del rivenditore e il numero del negozio per i quali viene configurato questo dispositivo per le demo.* Se non conosci il numero del negozio, puoi inserire "0000" per continuare l'installazione della modalità demo. @@ -5095,7 +5095,7 @@ Blocca le app installate su: . Per limitare il download di app o contenuti, vai alle Impostazioni di Google Play. Scopri di più La lingua di input iniziale è il cinese Rimuovi dall'account -Dito 3 +Impronta 3 Completa la configurazione sul telefono Elimina all'uscita Nascondi password diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_iw.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_iw.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -464,7 +464,7 @@ קוד האימות שלך נוצר אין צורך לשאול אותי שוב ‏אופס! המערכת לא הצליחה לאחסן את טוקן הגישה לטווח ארוך אל ממשק ה-API עבור המכשיר הזה. -יצרתי את הקובץ הזה, קבוצת לחצני בחירה, 1 מתוך 3 +יצרתי את הקובץ הזה, קבוצת כפתורי בחירה, 1 מתוך 3 יימחקו הנתונים שמשפיעים על ההתאמה האישית של מודעות ‏Cast של כרטיסייה מופעל. אפשר להשהות או להפסיק אותו בכל שלב. ‏כדאי להכיר את ההגנה המשופרת כדי ליהנות מרמת האבטחה הגבוהה ביותר ב-Chrome להורדות @@ -481,7 +481,7 @@ לא ניתן היה להתחבר אל . אפשר לנסות שוב. הסנכרון הושהה ‏תחנת העגינה תעבוד במצב התואם ל-USB-C. -לחצן החזרה בדף המשנה +כפתור החזרה בדף המשנה הצגה וניהול של סיסמאות שמורות במסגרת ‏כרטיסי Kerberos @@ -787,7 +787,7 @@ ‏סריקת קוד QR נושא שהותקן "" {COUNT,plural, =1{החלון הפרטי לא ייפתח מחדש.}one{# החלונות הפרטיים לא ייפתחו מחדש.}two{# החלונות הפרטיים לא ייפתחו מחדש.}other{# החלונות הפרטיים לא ייפתחו מחדש.}} -התוסף הזה שינה את הדף שמוצג כשלוחצים על הלחצן 'דף הבית'. +התוסף הזה שינה את הדף שמוצג כשלוחצים על הכפתור 'דף הבית'. רוצה להתקין שיכול: ‏מותר להשתמש בקובצי cookie של צד שלישי ‏ברור לי שפרופילי ה-eSIM שהותקנו לא יוסרו על ידי Powerwash @@ -846,7 +846,7 @@ ‏קונסולת JavaScript& -יש לגעת בלחצן ההפעלה עם האצבע +יש לגעת בכפתור ההפעלה עם האצבע רגיל פתיחת קישור באמצעות... לחיצה ימנית על הכרטיס @@ -1281,7 +1281,7 @@ מוכן להשלים את ההתקנה שלך ‏בדיקת הסיסמאות לא זמינה ב-Chromium ‏שימוש במיקום באפליקציות ובשירותים של Android. -לחצן סימניה +כפתור סימניה ‏פתיחה בדפדפן Chrome היסטוריית ההורדות המלאה פחות אפליקציות @@ -1349,7 +1349,7 @@ ‏רענון היכולות של Wi-Fi ישיר &קטן יותר כשגולשים באתרים, תוכן הדפים שלהם מוצפן ונשמר במכשיר -כדי להגדיר טביעת אצבע, על הילד או הילדה לגעת בחיישן טביעות האצבע שבפינה הימנית העליונה של המקלדת, ליד לחצן ההפעלה. נתוני טביעות האצבע של הילד או הילדה נשמרים באופן מאובטח ואף פעם לא נשלחים ממכשיר ה- הזה. +כדי להגדיר טביעת אצבע, על הילד או הילדה לגעת בחיישן טביעות האצבע שבפינה הימנית העליונה של המקלדת, ליד כפתור ההפעלה. נתוני טביעות האצבע של הילד או הילדה נשמרים באופן מאובטח ואף פעם לא נשלחים ממכשיר ה- הזה. יש לך אפשרות ליצור קבוצת כרטיסיות משלך. אין כרטיסיות דומות לארגון, אבל יכול להיות שהקבוצות האלה יתאימו לך אנשי קשר @@ -1672,7 +1672,7 @@ &חידוש הזנת ביטוי סיסמה שגוי אין לאפשר התראות מהאתר -לחצן ההגדרה +כפתור ההגדרה תקינות הסוללה פתיחת קישור בתור ‏יצירת קוד אימות בן 6 ספרות למנהל הסיסמאות של Google, ספרה מתוך 6 @@ -1737,7 +1737,7 @@ מדיניות הועתק אל הלוח אני רוצה לכלול את יומני השרת שלי. -הלחצן 'המשך' מושבת +הכפתור 'המשך' מושבת כדאי להיכנס לחשבון כדי שהסיסמאות ונתונים נוספים יופיעו בכל המכשירים שלך ‏Chrome יקבע מתי אתרים יכולים להפעיל צלילים (מומלץ) Google Lens @@ -1883,7 +1883,7 @@ ‏כתובת IPP להדפסה {NUM_SITES,plural, =1{כדי להגן על הנתונים שלך, הוסרו ההרשאות מאתר שלא ביקרת בו בזמן האחרון}one{כדי להגן על הנתונים שלך, הוסרו הרשאות מאתרים שלא ביקרת בהם בזמן האחרון}two{כדי להגן על הנתונים שלך, הוסרו הרשאות מאתרים שלא ביקרת בהם בזמן האחרון}other{כדי להגן על הנתונים שלך, הוסרו הרשאות מאתרים שלא ביקרת בהם בזמן האחרון}} מסך התחברות -לחצני ניווט בטאבלט +כפתורי ניווט בטאבלט אפשר לנסות להיעזר בחלונית הצדדית לשמירת סימניות, תהליכים ועוד לא נמצא גופן תואם. ‏הפעלת כמשתמש רגיל. אם ברצונך להפעיל כבסיס לצורך פיתוח, יש להפעיל מחדש עם הסימון ‎--no-sandbox. @@ -2012,7 +2012,7 @@ ניהול התוספים שלך על ידי לחיצה על 'תוספים' בתפריט כלים. ‏חיבור התקן Bluetooth המשך -‏כדי לקבל סיכום של הדף, חיפושים קשורים ומידע שימושי נוסף על הדף הזה, צריך ללחוץ על לחצן החלונית הצדדית של חיפוש Google בסרגל הכלים +‏כדי לקבל סיכום של הדף, חיפושים קשורים ומידע שימושי נוסף על הדף הזה, צריך ללחוץ על כפתור החלונית הצדדית של חיפוש Google בסרגל הכלים בחרת להוסיף פרופיל מנוהל לדפדפן הזה. למנהל המערכת שלך יש שליטה על הפרופיל וגישה לנתונים שלו. אופטימיזציה המשוב מיד יישלח… @@ -2033,7 +2033,7 @@ לתרגם את הדף הזה? {NUM_EXTENSIONS,plural, =1{יכול להיות שבקרוב תופסק התמיכה בתוסף הזה}one{יכול להיות שבקרוב תופסק התמיכה בתוספים האלה}two{יכול להיות שבקרוב תופסק התמיכה בתוספים האלה}other{יכול להיות שבקרוב תופסק התמיכה בתוספים האלה}} בחר את ספריית ההרחבה. -כדי לשנות את סדר הלחצנים בסרגל הכלים, גוררים אותם +כדי לשנות את סדר הכפתורים בסרגל הכלים, גוררים אותם הדפסה באמצעות תיבת דו-שיח של המערכת... הפעולה עשויה לגרום לניתוק הרשת הסלולרית למשך מספר דקות תצוגה מקדימה של כרטיסייה משותפת @@ -2339,7 +2339,7 @@ ‏לפני שמתחילים, צריך לוודא שיש גיבוי של הנתונים. התקנת תחליף את כל הנתונים שבכונן הקשיח שלך. מידע נוסף זמין בכתובת g.co/flex/InstallGuide. ‏ניהול האבטחה של V8 ‏התכונה 'שיתוף בקרבת מקום' מחפשת מכשירים בקרבת מקום באמצעות Bluetooth. -התאמה אישית של לחצני סרגל הכלים +התאמה אישית של כפתורי סרגל הכלים ‏יש גרסה חדשה זמינה של Chrome שם המשתמש הועתק ללוח יש להחליק כלפי מעלה כדי להתחיל @@ -2460,7 +2460,7 @@ ‏התוסף הזה הושבת על ידי מדיניות הארגון כי הוא לא זמין יותר בחנות האינטרנט של Chrome. יציאה הפעלה מחדש -‏לוחצים על לחצן Google Lens +‏לוחצים על כפתור Google Lens הי&סטוריה פרופילים של אורחים אינם נתמכים בוצע עדכון על-ידי הורה @@ -2763,7 +2763,7 @@ בלחיצה על התוסף יבצע אתחול ואיפוס בעוד מספר רגעים ‏בדיקת הסוללה, המעבד (CPU), הזיכרון, קישוריות ועוד -יש לחצן עם שם זהה. עליך לבחור שם אחר. +יש כפתור עם שם זהה. עליך לבחור שם אחר. מנהל המשימות התרחשה בעיה במהלך פענוח תגובת השרת. התהליך עשוי להימשך עד 30 דקות @@ -2950,7 +2950,7 @@ הפעלה מחדש עכשיו אין רשומות ביומן כלי החץ -לחצן למעבר אל דף משנה +כפתור למעבר אל דף משנה ‏שירות VPN קיצורי דרך מספר סידורי: @@ -2986,7 +2986,7 @@ אותיות ומספרים הצגת כל האתרים הוספה ידנית של מדפסת -איתור לחצנים בעכבר +איתור כפתורים בעכבר התקנת המדיניות במצב אופליין במכשיר נכשלה. ‏נשמח לעזרתך בשיפור של Steam ב-Chromebook צריך להיכנס לחשבון כדי לראות את הסימניות @@ -3077,7 +3077,7 @@ גודל האפליקציה: הוסיף/ה הכרטיסייה את הזו לא לאפשר לאתרים לערוך קבצים או תיקיות במכשיר -הצמדת הלחצן בוטלה +הצמדת הכפתור בוטלה בהמתנה למטמון... כיווץ הכול ‏ניהול השפה בחשבון Google @@ -3210,7 +3210,7 @@ קדם-עיבוד: התחברות אל הפסקת השימוש במפתחות הגישה במכשיר הזה -לחצן איפוס +כפתור איפוס דמות ברירת מחדל סגולה חתימת קוד החלפת מצב לחלונית הצדדית משמאל @@ -3324,7 +3324,7 @@ ניתן לנהל את ההגדרות דרך התפריט בכרטיס או לראות עוד אפשרויות ב'התאמה אישית של Chrome'. -לחצן 'הסתרה' +כפתור 'הסתרה' {GROUP_COUNT,plural, =1{הכרטיסיות יישארו פתוחות במכשיר הזה, אבל הקבוצה תימחק לתמיד.}one{הכרטיסיות יישארו פתוחות במכשיר הזה, אבל הקבוצות יימחקו לתמיד.}two{הכרטיסיות יישארו פתוחות במכשיר הזה, אבל הקבוצות יימחקו לתמיד.}other{הכרטיסיות יישארו פתוחות במכשיר הזה, אבל הקבוצות יימחקו לתמיד.}} ‏טעינת Google Assistant מתבצעת... מבנים @@ -3377,7 +3377,7 @@ זוהה התקן נשלף ‏הצעות לאמוג'י. כדי לעבור בין ההצעות, מקישים על החיצים למעלה או למטה. כדי להוסיף אמוג'י, מקישים על Enter. הזיכרון שבשימוש -הוספה או זיהוי לחצנים בעט +הוספה או זיהוי כפתורים בעט צריך להפעיל את האפשרות 'הצגת מסך הנעילה ביציאה ממצב שינה' ולנסות שוב ‏גרסאות ישנות של אפליקציות Chrome לא ייפתחו במכשירי Mac אחרי דצמבר 2022. ניתן לבדוק אם יש גרסה חדשה להורדה. לא ניתן היה לבצע התאמה למכשיר . יש לבחור מכשיר כדי לנסות שוב @@ -3439,7 +3439,7 @@ ‏המחשב מחובר בחיבור קווי ומכשיר ה-Cast מחובר ל-Wi-Fi אתרים שמורשים להשתמש במזהים כדי להפעיל תוכן מוגן אימות הזהות שלך -‏לחיצה על הלחצן "קבלה והמשך" מבטאת את הסכמתך לעיבוד שתואר קודם לכן לגבי השירותים האלה של Google. +‏לחיצה על הכפתור "קבלה והמשך" מבטאת את הסכמתך לעיבוד שתואר קודם לכן לגבי השירותים האלה של Google. קופא הצעה לקבוצת כרטיסיות הודעות יושבתו @@ -3549,7 +3549,7 @@ כלי הבחירה ‏אי אפשר להשתמש בו-זמנית ביציאות HDMI ו-USB C לווידאו. עליך לבחור יציאת וידאו אחרת. נפתח בכרטיסייה חדשה -במצב טאבלט אפשר להשתמש בלחצנים כדי לעבור אל דף הבית, לחזור לדף הקודם ולעבור בין אפליקציות. +במצב טאבלט אפשר להשתמש בכפתורים כדי לעבור אל דף הבית, לחזור לדף הקודם ולעבור בין אפליקציות. מגדיל התצוגה יש לכתוב מילים חדשות עם 99 אותיות או פחות המשך כ- @@ -3801,7 +3801,7 @@ העלאת היומן בהמתנה. הענקת גישה ל-"": ‏ניתוק חיבור ה-Wi-Fi -איתור לחצנים בעט +איתור כפתורים בעט מתבצע אתחול התקני רשת לשיתוף קבצים רספונסיבית @@ -3986,7 +3986,7 @@ נוף ‏פעולות נוספות שקשורות לכרטיס , קוד האימות (CVC) נשמר ‏אפשר לחסום אתרים שלא רוצים לתת להם הרשאה. בנוסף, אתרים שנוספו לפני יותר מ-30 יום נמחקים מהרשימה ב-Chrome באופן אוטומטי. -לחצן 'הקודם' במדריך בנושא פרטיות +כפתור 'הקודם' במדריך בנושא פרטיות מידע מפורט על הגרסה {NUM_DEVICES,plural, =1{‏תקשורת עם מכשיר USB אחד}one{‏תקשורת עם # מכשירי USB}two{‏תקשורת עם # מכשירי USB}other{‏תקשורת עם # מכשירי USB}} {COUNT,plural, =1{המערכת שולחת אל }one{המערכת שולחת אל }two{המערכת שולחת אל }other{המערכת שולחת אל }} @@ -4051,7 +4051,7 @@ איכות הווידאו יכול להיות שאתרים שביקרת בהם יפסיקו לפעול כמו שצריך ‏הפעלת האפשרות לאיסוף נתוני ביצועים תסייע ל-Google לשפר את המערכת עם הזמן. הנתונים נשלחים רק לאחר שמגישים דוח משוב (Alt-Shift-I) וכוללים את נתוני הביצועים. ניתן לחזור למסך זה כדי להשבית את איסוף הנתונים בכל עת. -השם החדש ללחצן +השם החדש לכפתור לא ניתן להשתמש ב- (מזהה תוסף "") במסך התחברות. &ביטול עמעום תוכן ברקע @@ -4350,7 +4350,7 @@ ‏צריך לסנכרן את כדי שההעדפות שלך יהיו מוכנות בכל המכשירים בעת הכניסה לחשבון Google. ההעדפות מתייחסות לאפליקציות, להגדרות, לסיסמאות ל-Wi-Fi, לשפות, לטפט, למקשי קיצור ועוד. ‏לצערנו, המחשב שלך מוגדר באמצעות מזהה חומרה פגום. המצב הזה מונע מ-ChromeOS Flex להתקין את עדכוני האבטחה האחרונים, ויכול להיות שהמחשב שלך יהיה חשוף להתקפות זדוניות. עליך לבטל את נעילת הטלפון ולקרב אותו ל- כדי לבטל את הנעילה שלו. -איתור לחצנים בטאבלט +איתור כפתורים בטאבלט חלק מהסיסמאות שלך נחשפו בפרצה באבטחת מידע. כדי לאבטח את החשבונות שלך, עליך לשנות את הסיסמאות האלה עכשיו. מרחק מתצוגה ‏מכשיר עם יציאת USB-C (יציאה ימנית-אחורית) @@ -4724,7 +4724,7 @@ אתרים יכולים לבקש להתקין אפליקציות אינטרנט במכשיר שלך יצירה תנאי שירות -התאמה אישית של לחצני העט +התאמה אישית של כפתורי העט ‏Smart Lock מופעל ‏הקראה וקורא המסך ChromeVox עדכון סיסמה @@ -5038,7 +5038,7 @@ משוב ‏יש לפנות אל Dell כדי לקבל סיוע. אביזר העגינה יכבה אם המאוורר לא פועל. הארגון שלך מגביל את מה שאפשר לשמור -לחצני סרגל הכלים אופסו +כפתורי סרגל הכלים אופסו ‏הסגנון של מקש Shift אתרים יכולים לבקש הרשאה להשתמש במצלמה סנכרון הקבצים מופעל @@ -5080,7 +5080,7 @@ דמות ברירת מחדל כחולה כדי להפעיל את התוסף מחדש, יש לאשר את ההרשאות החדשות: לא ניתן לשמור עקב הרשאות לא מספיקות. יש לשמור במיקום אחר. -הלחצן הימני +הכפתור הימני רוצה להשתמש בתוסף הזה: ‏קלט קולי ב-Google Assistant אין כרטיסיות ממכשירים אחרים @@ -5389,7 +5389,7 @@ שיתוף קבוצת הכרטיסיות '' מתן הרשאה לתוסף לקרוא את האתר הזה ולשנות אותו המכשיר חובר -כדי להוסיף דף לקריאה במועד מאוחר יותר, לוחצים על הלחצן +כדי להוסיף דף לקריאה במועד מאוחר יותר, לוחצים על הכפתור משתמשים אחרים במכשיר הזה יכולים להשתמש ברשת הזו פועל • הפרסום של התוסף הזה בוטל על ידי המפתח שלו ‏חנות Play @@ -5647,7 +5647,7 @@ פוטבול נדרשת סיסמה שירות האימות הזה מתארח בדומיין -כדי להגדיר טביעת אצבע, על הילד או הילדה לגעת בלחצן ההפעלה. נתוני טביעות האצבע של הילד או הילדה מאוחסנים באופן מאובטח ואף פעם לא נשלחים מה- הזה. +כדי להגדיר טביעת אצבע, על הילד או הילדה לגעת בכפתור ההפעלה. נתוני טביעות האצבע של הילד או הילדה מאוחסנים באופן מאובטח ואף פעם לא נשלחים מה- הזה. מרכז האפליקציות + חץ למעלה נתונים מהאתר שאליו נכנסת צור פרופיל @@ -5675,7 +5675,7 @@ הוספת הערה הורדת הקובץ המסוכן ‏השבתת פרופילים של eSIM -התאמה אישית של לחצני העכבר +התאמה אישית של כפתורי העכבר שם המכשיר ב פתיחה בסיום ההורדה עריכת מדפסת @@ -5807,7 +5807,7 @@ {0,plural,offset:2 =1{}=2{,‏ }one{,‏ ועוד אחד}other{,‏ ועוד #}} ייתכן שיהיה צורך לטעון מחדש דף זה על מנת שההגדרות החדשות ייכנסו לתוקף. עדיין נדרשת הרשאה כדי להשלים את ההגדרה -שליטה במכשיר באמצעות מתג אחד או יותר. המתגים יכולים להיות מקשי מקלדת, לחצני גיימפאד או מכשירים ייעודיים. +שליטה במכשיר באמצעות מתג אחד או יותר. המתגים יכולים להיות מקשי מקלדת, כפתורי גיימפאד או מכשירים ייעודיים. תוכן לא מאובטח נחסם כברירת מחדל באתרים מאובטחים יצירת סימנייה לכל הכרטיסיות ‏PIN שגוי @@ -5907,7 +5907,7 @@ &פתיחה חשבון ראשי ‏לדגמה, אפשר להקליד oà, oè, uỳ במקום òa, òe, ùy -התוסף "" שינה את הדף שמוצג בלחיצה על הלחצן 'דף הבית'. +התוסף "" שינה את הדף שמוצג בלחיצה על הכפתור 'דף הבית'. הקובץ הזה מסוכן מעבר למסך מלא מביטים למטה @@ -6086,7 +6086,7 @@ יכול להיות שבודקים אנושיים יראו את הנתונים האלה כדי לשפר את התכונה הזו. עריכה של כתובת האתר מילוני משתמש -לחצן של קבוצת הכרטיסיות שנשמרה +כפתור של קבוצת הכרטיסיות שנשמרה כלב השתקת כרטיסייה ‏לאפשר תמיד JavaScript ב- @@ -6232,7 +6232,7 @@ מי יכול לשתף איתך ‏הסיסמה הזו שמורה רק במכשיר הזה. כדי להשתמש בה במכשירים אחרים, עליך לשמור אותה בחשבון Google. עריכת -מדיניות הארגון השתנתה. לחצן הניסויים התווסף לסרגל הכלים. יש ללחוץ על הלחצן כדי לפתוח תיבת דו-שיח ולהפעיל ניסויים. +מדיניות הארגון השתנתה. כפתור הניסויים התווסף לסרגל הכלים. יש ללחוץ על הכפתור כדי לפתוח תיבת דו-שיח ולהפעיל ניסויים. שירותי מערכת וגם אפליקציות ואתרים עם הרשאת גישה למצלמה יכולים להשתמש במצלמה. כדי להשתמש במצלמה, יכול להיות שצריך להפעיל מחדש את האפליקציה או לרענן את הדף. {NUM_SITES,plural, =1{נמצא אתר אחד עם הרבה התראות}one{נמצאו {NUM_SITES} אתרים עם הרבה התראות}two{נמצאו {NUM_SITES} אתרים עם הרבה התראות}other{נמצאו {NUM_SITES} אתרים עם הרבה התראות}} מתואם @@ -6357,7 +6357,7 @@ ההרשאות הבאות נחסמו: , מתבצע איתור של התקני רשת לשיתוף קבצים ‏סטטוס של שיתוף אינטרנט בין מכשירים (tethering): -שינוי שם הלחצן +שינוי שם הכפתור פינוי מקום בזיכרון על סמך שימוש ‏ניתן לנווט בדפים באמצעות סמן הטקסט. כדי להפסיק, אפשר להקיש על F7. ‏כדי לבצע איפוס באמצעות Powerwash, יש להפעיל תחילה את המכשיר מחדש. מידע נוסף @@ -6749,7 +6749,7 @@ אנחנו מצטערים, אבל חלק מהקבצים נפגמו והעדכון לא הצליח. הקבצים המסונכרנים שלך לא נפגעו. אין רשת זמינה הסיסמה לא שותפה -הצגת לחצני ניווט +הצגת כפתורי ניווט ההתקנה מתבצעת... מאפשר להפעיל אפליקציות של Windows®‎ ב-Chromebook. לפני התקנת התוכנה מומלץ לוודא שיש שטח אחסון פנוי בגודל . {NUM_PAGES,plural, =1{אפשר להמתין עד שתתקבל תגובה מהדף, או לצאת ממנו.}one{אפשר להמתין עד שתתקבל תגובה מהדפים, או לצאת מהם.}two{אפשר להמתין עד שתתקבל תגובה מהדפים, או לצאת מהם.}other{אפשר להמתין עד שתתקבל תגובה מהדפים, או לצאת מהם.}} @@ -6811,7 +6811,7 @@ מנהל החלונות נפח האחסון הכולל שבשימוש של האתרים המוצגים: 0° (ברירת מחדל) -הצגה או הסתרה של המקלדת שמופיעה במסך +הצגה או הסתרה של המקלדת הווירטואלית עוד פעולות לגבי האתר קוד האימות חייב להיות באורך של 6 ספרות החשבון הזה לא מתאים לבקרת הורים @@ -6996,7 +6996,7 @@ יש שדרוג אבטחה זמין איפוס לא ניתן ליצור קיצור דרך -בחירת הלחצנים שיוצגו בסרגל הכלים +בחירת הכפתורים שיוצגו בסרגל הכלים מתג לא מזוהה. יש להקיש על מקש כלשהו כדי . הוספת משתמש... כניסה ל-. @@ -7103,7 +7103,7 @@ ניווט אל תוכן נוסף מתוך כל מי שבקרבת מקום ‏אישור פעולת Powerwash בעת חזרה לגרסה קודמת -לחצן לבחירת שפה ומקלדת. השפה המוגדרת עכשיו היא . +כפתור לבחירת שפה ומקלדת. השפה המוגדרת עכשיו היא . ירוק חיתוך ‏מעולה – HD @@ -7121,7 +7121,7 @@ ניהול המידע שמשמש אתרים למדידת ביצועי מודעות אפשרויות קלט בסרגל הכלים כדי להעניק לתוסף גישה לאתר הזה, יש ללחוץ על התוסף. -‏כפתור ביטול בתיקון האוטומטי. חזרה לגרסה הקודמת של . יש להקיש על Enter כדי להפעיל, או על Escape כדי לבטל. +‏כפתור ביטול בתיקון האוטומטי. חזרה לגרסה הקודמת של . יש ללחוץ על Enter כדי להפעיל, או על Escape כדי לבטל. הפארק הלאומי ציון חסימה אם באתר מוצגות מודעות מפריעות או מטעות מילון מאפייני הרשת פגום @@ -7132,7 +7132,7 @@ עוד ניתוח ההגדרה נכשל יציאה עכשיו -‏לחצן TrackPoint ראשי +‏כפתור TrackPoint ראשי הסנכרון לא פועל. יש לנסות לצאת ולהיכנס שוב. ‏בחירה והתאמה אישית של הקולות בהמרת טקסט לדיבור בתכונות ChromeVox והקראה גווני אפור @@ -7258,7 +7258,7 @@ ‏Phone Hub, שיתוף בקרבת מקום מקש במקלדת נתזים -הלחצן הוצמד +הכפתור הוצמד לדלג על ההרשמה לשימוש בית ספרי? ‏הסרת כל חשבונות המשתמשים ואיפוס Chromebook כך שיהיה כמו חדש. אין הרשאה לנהל את החלונות בכל המסכים @@ -7294,7 +7294,7 @@ יצירת מפתח גישה הצגת סרגל הסימניות מטמון סקריפטים -הצגת לחצני ניווט במצב טאבלט +הצגת כפתורי ניווט במצב טאבלט אתרים יכולים להציג תמונות ‏הקוד לא תקין. הפורמט של הרשומה צריך להיות $SM-DP+ address$מזהה תואם אופציונלי אספקת אישורים לאימות @@ -7378,7 +7378,7 @@ כניסה אוטומטית התיקיות המשותפות זמינות ב- בספרייה . לא מחובר לרשת. צריך להתחבר לאינטרנט ולנסות שוב. -אישור לקחת את הסיכון, קבוצת לחצני בחירה, 3 מתוך 3 +אישור לקחת את הסיכון, קבוצת כפתורי בחירה, 3 מתוך 3 אירעה שגיאה בטעינת תוסף {NUM_OF_FILES,plural, =1{לא ניתן להעתיק את הקובץ אל }one{לא ניתן להעתיק את הקבצים אל }two{לא ניתן להעתיק את הקבצים אל }other{לא ניתן להעתיק את הקבצים אל }} הפרמוט הסתיים בהצלחה! @@ -7713,13 +7713,13 @@ סיסמאות ומפתחות גישה הבהוב על התראות השתקת ההתראות -הצגת לחצן 'דף הבית' +הצגת כפתור 'דף הבית' יש לבחור אפשרות ‏לא ניתן לבטל את השיתוף כי אפליקציה משתמשת בתיקייה הזו. השיתוף של התיקייה הזו יבוטל בכיבוי הבא של Linux. ‏ניתוק חשבון Google Drive ‏עליך לפנות נפח אחסון או לשנות בהגדרות את גודל הנפח המיועד ל-Linux מהירות הדיבור -צריך ללחוץ על לחצן שונה מהלחצן השמאלי או הימני בעכבר במכשיר . +צריך ללחוץ על כפתור שונה מהכפתור השמאלי או הימני בעכבר במכשיר . אין תמיכה בסנכרון התראות בטלפונים שמחוברים לפרופיל עבודה. מידע נוסף ‏מקש ההוספה המהירה נמצא מתחת למקש Tab ‏לחנות האינטרנט של Chrome @@ -7749,7 +7749,7 @@ הקטנת הסף כל הקונטיינרים הכי פופולריים -הלחצן השמאלי +הכפתור השמאלי אין הרשאה להשתמש בגופנים שמותקנים במכשיר התחברות לאינטרנט כדי להוסיף מדפסת ‏חתימת X9.62 ECDSA עם SHA-256 @@ -7867,7 +7867,7 @@ התאמה אישית של הגופן וגודל הטקסט בדפדפן האינטרנט גלישה כאורח ‏כשאומרים "Hey Google", מתבצעת גישה ל-Assistant. -החלפת לחצן העכבר העיקרי +החלפת כפתור העכבר העיקרי ‏שימוש ב-DNS מאובטח פנקוטה בדיקת הבטיחות הסתיימה. @@ -7934,7 +7934,7 @@ + רמת אבטחה גבוהה יותר מעוניין בגישה קבועה לאישור כדי לאמת את עצמו בשמך. -האתר מהימן בעיניי, קבוצת לחצני בחירה, 2 מתוך 3 +האתר מהימן בעיניי, קבוצת כפתורי בחירה, 2 מתוך 3 אף אחד לא יכול לשתף איתך אם המכשיר לא יוגדר כגלוי.כדי שהמכשיר יהיה גלוי באופן זמני, יש לפתוח את אזור הסטטוס ואז להפעיל את הרשאות הגישה בקרבת מקום. לא ניתן ליצור חיבור לרשת. צריך לבדוק את החיבור לרשת ולנסות שוב. הצגת התוספים שיש להם הרשאה לקרוא או לשנות אתר @@ -7974,7 +7974,7 @@ בחירת הקול השועל המהיר קפץ מעל לכלב שנח לו בעצלתיים. שרתי הדפסה -מדיניות הארגון השתנתה. לחצן הניסויים הוסר מסרגל הכלים. +מדיניות הארגון השתנתה. כפתור הניסויים הוסר מסרגל הכלים. ‏יש לבצע Powerwash למכשיר ה- שלך ולחזור לגרסה הקודמת. משהו השתבש בפתיחת הפרופיל שלך. יש לצאת ולאחר מכן להיכנס מחדש. פרוע @@ -8171,7 +8171,7 @@ ‏סגירת כל החלונות של Firefox תשלים את פעולת הייבוא. ‏caps lock מופעל פלאגין: -הלחצנים המוסתרים בסרגל הכלים +הכפתורים המוסתרים בסרגל הכלים האפליקציות המובילות ב- {NUM_EXTENSIONS,plural, =1{ניתן לבחור אם התוסף הזה יוכל לקרוא או לשנות את האתר הזה}one{ניתן לבחור אם התוספים האלה יוכלו לקרוא או לשנות את האתר הזה}two{ניתן לבחור אם התוספים האלה יוכלו לקרוא או לשנות את האתר הזה}other{ניתן לבחור אם התוספים האלה יוכלו לקרוא או לשנות את האתר הזה}} כיול מסך המגע @@ -8800,7 +8800,7 @@ מקישים על || כדי להתמקד בבועה, ומקישים שוב כדי להתמקד ברכיב שאליו היא מפנה. &למידע נוסף ברצונך באמת להפעיל את "" במצב אבחון? -לחצן תיקיית סימניות +כפתור תיקיית סימניות יש לך כרגע כרטיס אחד שאפשר להשתמש בו רק במכשיר הזה החלה האתר משתמש במצלמה @@ -8948,7 +8948,7 @@ בורר האמוג'י בחירת חלון יש ללחוץ לחיצה ימנית כדי להפעיל את -יש לגעת עם האצבע בלחצן ההפעלה. נתוני טביעות האצבע נשמרים באופן מאובטח ואף פעם לא נשלחים ממכשיר . +יש לגעת עם האצבע בכפתור ההפעלה. נתוני טביעות האצבע נשמרים באופן מאובטח ואף פעם לא נשלחים ממכשיר . ‏אתרים יכולים לבקש הרשאה להתחבר למכשירי Bluetooth מדריך לבחירות שלך בנושא פרטיות התקבלה בקשת גישה @@ -8969,7 +8969,7 @@ ‏ניהול התקני USB ‏אי אפשר להשתמש בקישור הזה. יש לבדוק אם הקישור מתחיל ב-'http://‎' או ב-'https://‎' ולנסות שוב. הדגשת סמן העכבר כשהסמן בתנועה -כדי לחזור לכמה דפים, לוחצים לחיצה ארוכה על לחצן 'הקודם'. +כדי לחזור לכמה דפים, לוחצים לחיצה ארוכה על כפתור 'הקודם'. ייתכן שתיעוד של ביקורך באתר יישמר במפתח האבטחה שלך. המשך חסימת הגישה לחיישנים התחברות באמצעות קוד @@ -9331,7 +9331,7 @@ מנהל המערכת הצמיד את התוסף הזה ‏אתרים שמורשים להשתמש בקובצי cookie של צד שלישי התקנה במכשיר זה -אפשר לגעת בחיישן טביעות האצבע שבפינה הימנית העליונה של המקלדת, ליד לחצן ההפעלה. נתוני טביעות האצבע נשמרים באופן מאובטח ואף פעם לא נשלחים ממכשיר ה-. +אפשר לגעת בחיישן טביעות האצבע שבפינה הימנית העליונה של המקלדת, ליד כפתור ההפעלה. נתוני טביעות האצבע נשמרים באופן מאובטח ואף פעם לא נשלחים ממכשיר ה-. אין מספיק נפח אחסון בדיסק ‏נכשל הניסיון לאחזר את ההפניה האוטומטית אל SAML מהשרת ‏ה-IMEI של המכשיר הוא והמספר הסידורי של המכשיר הוא . המספרים האלה יכולים לשמש להפעלת השירות. @@ -9382,7 +9382,7 @@ היסטוריית ההורדות המלאה הצגת הדומיינים לא ניתן לייבא את הסיסמאות. צריך לבדוק את הקובץ ולוודא שהפורמט שלו תקין. למידע נוסף -הלחצן 'המשך' מופעל +הכפתור 'המשך' מופעל {NUM_WEEKS,plural, =1{יש להחזיר את מכשיר ה- בתוך שבוע ({NUM_WEEKS})}one{יש להחזיר את מכשיר ה- בתוך {NUM_WEEKS} שבועות}two{יש להחזיר את מכשיר ה- בתוך שבועיים ({NUM_WEEKS})}other{יש להחזיר את מכשיר ה- בתוך {NUM_WEEKS} שבועות}} ‏ההגדרות לקובצי Office ‏שמורה במנהל הסיסמאות של Google בחשבון @@ -9419,7 +9419,7 @@ ‏לא ניתן להפעיל Cast ‏זיכרון JavaScript נדרש קוד אימות -צריך ללחוץ על לחצן כלשהו במכשיר . +צריך ללחוץ על כפתור כלשהו במכשיר . מידע נוסף על הצעות למודעות באתרים () בחירה מתוך רשימה @@ -9460,7 +9460,7 @@ הורדה: הפעולה הזו תמחק באופן סופי את נתוני הגלישה שלך במכשיר הזה. כדי לשחזר את הנתונים, יש להפעיל סנכרון חיפוש עדכונים -מקלדת שמופיעה במסך, הכתבה, גישה באמצעות מתג ועוד +מקלדת וירטואלית, הכתבה, גישה באמצעות מתג ועוד מרחק מתצוגה בדף שם המכשיר ארוך מדי , פרטים נוספים @@ -9603,7 +9603,7 @@ Microsoft OneDrive עריכת קיצור הדרך עבור הורדה מסוכנת נחסמה -‏המקלדת שמופיעה במסך לא עובדת עדיין באפליקציות Linux +‏המקלדת הווירטואלית לא עובדת עדיין באפליקציות Linux עיצוב חדש נוסף () נחסם על ידי הארגון שלך יש למחוק את כדי שמשתמשים אחרים במכשיר לא יוכלו לראות את הסיסמאות שלך @@ -10216,7 +10216,7 @@ ‏הפעלת חנות Play המשך ייתכן שאיכות המדיה תהיה נמוכה יותר -‏לחצן להצגת מידע נוסף על התיקון האוטומטי. ייפתח דף ההגדרות של התיקון האוטומטי. יש להקיש על Enter כדי להפעיל, או על Escape כדי לבטל. +‏כפתור להצגת מידע נוסף על התיקון האוטומטי. ייפתח דף ההגדרות של התיקון האוטומטי. יש ללחוץ על Enter כדי להפעיל, או על Escape כדי לבטל. עוד מעט כיבוי אורות אפשר להגן על מפתח האבטחה באמצעות קוד אימות הורדת קובץ לא מאובטח @@ -10258,7 +10258,7 @@ אישור לקוח לא חוקי Drive היסטוריית ההורדות מהתקופה האחרונה -הצגת לחצן 'דף הבית' +הצגת כפתור 'דף הבית' בלחיצה ימנית או בלחיצה ארוכה על טקסט, יוצגו הגדרות, תרגומים או המרת יחידות. בשפות לאתרים אפשר להתאים אישית את השפות לתרגום. עכשיו יש כמה שלבים שהורים צריכים להשלים. אפשר יהיה להחזיר את ה- לילד/ה לאחר הגדרת החשבון. הורד תמונה @@ -10384,11 +10384,11 @@ האם לשחזר את הדפים? ‏שמירה בחשבון Google שלך התאמה אישית של עיצוב המסך -לחצן לשליחת משוב +כפתור לשליחת משוב יציב לא ניתן להשתמש במיקרופון בדף זה אוקיינוס -קישוריות הרשת שלך התחדשה. יש לבחור רשת אחרת או ללחוץ על הלחצן 'המשך' שלמטה כדי להפעיל את יישום הקיוסק. +קישוריות הרשת שלך התחדשה. יש לבחור רשת אחרת או ללחוץ על הכפתור 'המשך' שלמטה כדי להפעיל את יישום הקיוסק. מקשי בחירה &פתיחת כל הסימניות מעבר למצב שינה כשהמחשב הנייד נסגר @@ -10814,7 +10814,7 @@ אנחנו בוחנים דרכים חדשות להגביל מעקב בין-אתרים ולאפשר לאתרים לעצור ניסיונות הונאה וספאם של מודעות. יכול להיות שהמכשיר שלך לא יעבוד כמו שצריך ושיהיו בעיות באבטחה ובביצועים. חמים יותר -כדי לחזור לכאן במהירות, יש ללחוץ על לחצן ההתקנה ולהתקין את +כדי לחזור לכאן במהירות, יש ללחוץ על כפתור ההתקנה ולהתקין את התרחשה שגיאת שרת זמנית. התאמה אישית של הטפט, העיצוב הכהה ועוד חיפוש באינטרנט... @@ -10982,7 +10982,7 @@ כדי לעבוד עם הדומיין , צריך להשאיר את הכרטיס החכם בפנים.}other{מכשיר ה- יינעל אוטומטית בעוד # שניות. כדי לעבוד עם הדומיין , צריך להשאיר את הכרטיס החכם בפנים.}} ‏הקובץ הזה גדול מדי לבדיקת אבטחה ולכן הוא נחסם על ידי הארגון שלך. אפשר לפתוח קבצים בגודל של עד 50MB. -הוספה או זיהוי לחצנים בטאבלט +הוספה או זיהוי כפתורים בטאבלט ‏סיסמת root A4 ‏אתרים יכולים להשתמש בקובצי cookie רק כדי לראות את פעילות הגלישה בהם, ולא באתרים אחרים @@ -11049,7 +11049,7 @@ הצעת סיסמה... ‏אפשר גם לבחור ב-PPD של המדפסת. מידע נוסף הוספת &דף... -התאמה אישית של לחצני הלוח +התאמה אישית של כפתורי הלוח בוצעה חסימה להרשאות ועוד הצמדת התוסף ‏שם DNS @@ -11096,7 +11096,7 @@ לא ניתן לטעון את התנאים וההגבלות חשבון הורה {COUNT,plural, =1{חשבון אחד ({COUNT})}one{{COUNT} חשבונות}two{{COUNT} חשבונות}other{{COUNT} חשבונות}} -‏משתמשים בלחצנים במסך כדי לנווט למסך הבית, לחזור למסך הקודם או לעבור בין אפליקציות. ההגדרה הזו מופעלת אוטומטית כשמפעילים את ChromeVox או את התכונה 'לחיצות אוטומטיות'. +‏משתמשים בכפתורים במסך כדי לנווט למסך הבית, לחזור למסך הקודם או לעבור בין אפליקציות. ההגדרה הזו מופעלת אוטומטית כשמפעילים את ChromeVox או את התכונה "לחיצות אוטומטיות". ‏ההרשאה להפעלת Cast נדחתה. מידע נוסף זמין במאמר במרכז העזרה. פתיחת הקישור ב- המערכת משתפת את עם @@ -11136,7 +11136,7 @@ הגדרות העכבר ולוח המגע הפעלת האצה של לוח מגע ‏שליחת מידע לגבי אופן השימוש בנתונים וניתוח הביצועים. המכשיר הזה שולח עכשיו אל Google נתוני אבחון, נתוני מכשיר ונתוני שימוש באפליקציות באופן אוטומטי. הנתונים האלה יעזרו לשמור על היציבות של המערכת ושל האפליקציות ולבצע שיפורים אחרים. חלק מהנתונים הנצברים יעזרו גם לשפר את האפליקציות של Google ויעזרו לשותפים של Google, כמו מפתחים של Android. ההגדרה הזו נאכפת על ידי הבעלים. אם ההגדרה 'פעילות באפליקציות ובאתרי אינטרנט נוספים' הופעלה, יכול להיות שהנתונים האלה יישמרו בחשבון שלך ב-Google. מידע נוסף על מדדיםמידע נוסף -האתר מהימן בעיניי (), קבוצת לחצני בחירה, 2 מתוך 3 +האתר מהימן בעיניי (), קבוצת כפתורי בחירה, 2 מתוך 3 איך לנהל את הנתונים שלך: כדי להגן על הפרטיות שלך, האתרים שנוספו לרשימה לפני יותר מ-4 שבועות נמחקים ממנה אוטומטית. אתר שביקרת בו שוב עשוי לחזור ולהופיע ברשימה. אפשר גם להסיר אתר אם לא רוצים שתחומי העניין יוגדרו לפי הביקור בו. המכשיר שלך יינעל רק ב-. ‏דיווח על ההגדרות הנוכחיות כדי לעזור לשפר את ChromeOS @@ -11314,7 +11314,7 @@ התרה בכל האתרים &כניסה מחדש סגירה -לחצן 'הקודם' לדף הפרטים של +כפתור 'הקודם' לדף הפרטים של בחרת בעבר לתת הרשאה לכל התוספים ב‑ בטעינה (%)... ‏יובאו מ-Windows @@ -11473,7 +11473,7 @@ ‏הגדרת Microsoft 365 לפתיחת קבצים ביטול נעילה לא הוגדר רישיון -הוספה או זיהוי לחצנים בעכבר +הוספה או זיהוי כפתורים בעכבר : מעבר אל הגדרות הגלישה הבטוחה ברוך בואך לפרופיל החדש שלך @@ -11576,7 +11576,7 @@ - מכשיר Bluetooth מחובר כדי להמשיך, הפרטים '' ישותפו על ידי עם האתר הזה. כאן מפורטת מדיניות הפרטיות של האתר הזה. מחיקת פרטי הכניסה -אפשר ללחוץ על הלחצן 'שיתוף' שבתחתית הכרטיס כדי לשתף עותק של הסיסמה עם אחד מהחברים בקבוצה המשפחתית +אפשר ללחוץ על הכפתור 'שיתוף' שבתחתית הכרטיס כדי לשתף עותק של הסיסמה עם אחד מהחברים בקבוצה המשפחתית הצגת שם המשתמש במסך הכניסה ‏הפעולה עשויה להימשך מספר דקות. מתבצעת הפעלה של הקונטיינר של Linux. האתר רשאי לשתף את המסך @@ -11706,7 +11706,7 @@ רוחב סימן הפיסוק הראשוני הוא מלא לחיצה כפולה על פריט, לחיצה ארוכה בלחיצה השנייה וגרירת הפריט כדי להזיז אותו החלון הזה ייסגר לאחר השלמת הביטול. -לחצן תפריט פעולות +כפתור תפריט פעולות לא מקוון שלום, סגירת כל הכרטיסיות diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_ja.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_ja.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_ja.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_ja.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -2512,7 +2512,7 @@     Google は、位置情報の精度と、位置情報を利用したサービスを改善し、Google のサービスを全般的に改善、提供、維持する目的でこの情報を使用します。また、ユーザーのニーズに応えるうえでの Google およびサードパーティの正当な利益に基づき、この情報を処理します。この情報が個人の特定に使用されることはありません。 [位置情報の精度] は、このデバイスの位置情報の設定([設定] > [プライバシーとセキュリティ] > [プライバシー管理] > [位置情報へのアクセス] > [位置情報の詳細設定])でいつでもオフにできます。[位置情報の精度] をオフにした場合、位置情報の精度に関するデータは一切収集されません。Android アプリやサービスでは、IP アドレスのみを使用して(可能な場合)、このデバイスの位置情報を判断します。そのため、Google マップなどの Android アプリやサービスでの位置情報の利用範囲と精度に影響する可能性があります。 Linux アプリとファイルのバックアップ -自身で選択 +自分で設定 すべての個人情報を含める 絵文字候補 このページはカメラにアクセスしています。 @@ -5890,7 +5890,7 @@ Alt+ デバイスの前から離れると、画面が自動的にロックされます。デバイスの前にいるときは、画面がロックされるまでの時間が長くなります。ロック画面を無効にしている場合、デバイスはロックされずにスリープ状態になります。 デバイスを登録しない -自身で選択 +自分で設定 システム音声 OS のシステムページをお探しですか? にアクセスしてください。 おすすめ diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_kn.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_kn.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_kn.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_kn.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -8273,7 +8273,7 @@ ಗಾಗಿ ಇನ್ನಷ್ಟು ಕ್ರಿಯೆಗಳು ಹೆಸರು 32 ಅಕ್ಷರಗಳನ್ನು ಮೀರುವಂತಿಲ್ಲ ಎಲ್ಲಾ ವಿಸ್ತರಣೆಗಳನ್ನು ಅನುಮತಿಸಲಾಗಿದೆ -ಪಾಸ್‌ವರ್ಡ್ ಅಳಿಸುವುದೇ? +ಪಾಸ್‌ವರ್ಡ್ ಅಳಿಸಬೇಕೆ? ಕೊಲೊಸಿಯಮ್ ಸ್ವಯಂತುಂಬುವಿಕೆ ಫಾರ್ಮ್ ಡೇಟಾ WebRTC ಈವೆಂಟ್‌ ಲಾಗ್‌ಗಳು () diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_mk.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_mk.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_mk.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_mk.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -807,7 +807,7 @@ Активноста во заднина и некои визуелни ефекти, како што е непреченото лизгање, може да се ограничени Не може да го премести директориумот за наставки во профилот. Создајте профил -Подлога за допир +Допирна подлога Продолжи со емитување на Ова овозможува пристап до локацијата за апликациите, веб-сајтовите со дозволата за локација и системските услуги Ако го додадете контактов, ќе биде запомнет следниот пат кога ќе споделува diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_or.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_or.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_or.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_or.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -11674,7 +11674,7 @@ କୁ ସଂଶୋଧନ କରି କରିବା ପାଇଁ 'ସ୍ୱତଃସଂଶୋଧନକୁ ପୂର୍ବବତ୍ କରନ୍ତୁ' ଡାଏଲଗ୍ ଦେଖାଯାଇଛି। ଆକ୍ସେସ୍ କରିବାକୁ ଅପ୍ ତୀର କୀ, ଅଣଦେଖା କରିବାକୁ Escape କୀ ଦବାନ୍ତୁ। ଆପଣ ଜଣେ ବାପା କିମ୍ବା ମା' ବୋଲି ଯାଞ୍ଚ କରନ୍ତୁ ପ୍ରାରମ୍ଭିକ ବିରାମ ଚିହ୍ନର ଚଉଡ଼ା ପୂର୍ଣ୍ଣ ଅଛି -କୌଣସି ଆଇଟମରେ ଦୁଇ-ଥର ଟାପ କରନ୍ତୁ, ଦ୍ୱିତୀୟ ଥର ଟାପ କରି ଏହାକୁ ଦବାଇ ଧରନ୍ତୁ ଏବଂ ତା'ପରେ ଆଇଟମକୁ ମୁଭ କରିବା ପାଇଁ ଏହାକୁ ଡ୍ରାଗ କରନ୍ତୁ +କୌଣସି ଆଇଟମରେ ଦୁଇ-ଥର ଟାପ କରନ୍ତୁ, ଦ୍ୱିତୀୟ ଥରର ଟାପରେ ଏହାକୁ ଦବାଇ ଧରନ୍ତୁ ଏବଂ ତା'ପରେ ଆଇଟମକୁ ମୁଭ କରିବା ପାଇଁ ଏହାକୁ ଡ୍ରାଗ କରନ୍ତୁ ବାତିଲ୍ ହୋଇସାରିବା ପରେ ଏହି ୱିଣ୍ଡୋ ବନ୍ଦ ହୋଇଯିବ। କାର୍ଯ୍ୟ ମେନୁ ବଟନ୍ ଅଫ୍‍ଲାଇନ୍ diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_pl.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_pl.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_pl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_pl.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -3124,7 +3124,7 @@ Język strony: Twoje urządzenie ma licencję na Chrome Education, ale Twoja nazwa użytkownika nie jest powiązana z kontem Google for Education. Utwórz takie konto na stronie g.co/workspace/edusignup, korzystając z dodatkowego urządzenia. Czcionka tekstu -Zapisuj m.in. swoje zakładki i hasła dzięki synchronizacji +Korzystaj z synchronizacji, aby zapisywać m.in. swoje zakładki i hasła Przesunięcie żuchwy w lewo Bezpieczne przeglądanie (chroni Ciebie i Twoje urządzenie przed niebezpiecznymi witrynami) Sprawdzanie pisowni diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_pt-BR.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_pt-BR.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_pt-BR.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_pt-BR.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -976,7 +976,7 @@ A exibição de solicitações está bloqueada Nenhum destino de transmissão encontrado. Precisa de ajuda? Opacidade do plano de fundo -Ajudar a aprimorar o enviando automaticamente estatísticas de uso e relatórios de problemas ao Google. +Ajudar o a melhorar enviando automaticamente estatísticas de uso e relatórios de problemas ao Google. Para fazer login novamente e ter acesso a recursos educacionais, peça permissão a um dos responsáveis Esta página está acessando seu microfone. Problema com o adaptador de energia @@ -4142,7 +4142,7 @@ Selecionar fuso horário Tire o dedo e toque novamente Nome -Use uma senha forte +Usar uma senha forte Gerenciar o grupo de guias "" O nome de usuário "" não está disponível A senha da Conta do Google está sendo usada. Você pode definir uma senha do para facilitar o login. @@ -5163,7 +5163,7 @@ Wi-Fi disponível por meio de vários dispositivos Sem permissão para capturar e usar a entrada do teclado Número de sugestões -Verificações detalhadas de downloads suspeitos. +Faz verificações detalhadas de downloads suspeitos. Marcar como não lido Mostrar senhas Sempre permitir que acesse sua câmera e seu microfone @@ -7272,7 +7272,7 @@ Confirmar download Receber ajuda Escolha o idioma da página que você gostaria de traduzir -Ajudar a melhorar os Chromebooks +Ajude a melhorar os Chromebooks A sincronização não está funcionando. Tente fazer login novamente. A visualização de impressão falhou. Para desbloquear o perfil, faça login com o e-mail da sua conta principal: @@ -7385,7 +7385,7 @@ {NUM_OF_FILES,plural, =1{Não é possível copiar o arquivo para o }one{Não é possível copiar o arquivo para o }other{Não é possível copiar os arquivos para o }} A formatação foi concluída. Esse contêiner já existe. -Seta para baixo +Para baixo O perfil será excluído Conexão de dados disponível a partir do seu Arquivo de chaves particulares (opcional) @@ -9060,7 +9060,7 @@ na parte superior da tela do painel do ChromeVox O arquivo pode ser perigoso. Adicione uma senha se quiser que o Chrome o verifique ou baixe de forma direta. Nenhum dispositivo HID encontrado -Controlar como o histórico de navegação é usado para personalizar a Pesquisa e mais +Controle como o histórico de navegação é usado para personalizar a Pesquisa e mais Seu administrador bloqueou a extensão : ID do app Insira o cartão inteligente para continuar usando seu Manter assim @@ -9543,7 +9543,7 @@ Excesso de solicitações. A guia foi movida para um grupo sem nome: poderá ver arquivos em até que você feche todas as guias desse site -Quando sua conta está conectada, essa opção protege você nos Serviços do Google. +Protege você em todos os Serviços do Google quando sua conta está conectada. Nenhuma voz encontrada Tente de novo depois que a sincronização do arquivo for concluída. Atalho para a extensão diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_ru.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_ru.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_ru.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_ru.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -4130,7 +4130,7 @@ Выберите часовой пояс Коснитесь несколько раз Название -Используйте надежный пароль +Использовать надежный пароль Управление группой вкладок "" Имя пользователя "" недоступно. Используется пароль аккаунта Google. Чтобы входить ещё быстрее, задайте отдельный пароль для . @@ -10415,7 +10415,7 @@ Более подробная информация доступна на странице g.co/flex/InstallErrors. -С возвращением! +Двигаемся дальше? Политика не найдена. Запретить сайтам определять ваше местоположение Подтвердите личность @@ -10424,7 +10424,7 @@ Установка ПО для сканера… Сервер недоступен. Виниловая пластинка -Оповещение о проблеме производительности +Проблемы с производительностью Настройки озвучивания при нажатии Остановить плагин Сведения об устройстве Bluetooth diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_sl.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_sl.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_sl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_sl.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -6373,7 +6373,7 @@ Če nadaljujete, se strinjate, da lahko ta naprava tudi samodejno prenaša in namešča posodobitve in aplikacije Googla, operaterja in proizvajalca te otrokove naprave – morda s prenosom podatkov v mobilnih omrežjih. Nekatere od teh aplikacij morda ponujajo nakupe v aplikaciji. {NUM_CHARACTERS,plural, =1{Koda PIN mora vsebovati najmanj en znak}one{Koda PIN mora vsebovati najmanj # znak}two{Koda PIN mora vsebovati najmanj # znaka}few{Koda PIN mora vsebovati najmanj # znake}other{Koda PIN mora vsebovati najmanj # znakov}} Domena zahteva, da se povežete z omrežjem Wi-Fi in prenesete posodobitev. Prenesete jo lahko tudi prek povezave z omejenim prenosom podatkov (prenos podatkov se morda zaračuna). -Prilagodite hitrost posebej za vsako smer +Prilagoditev hitrosti ločeno za vsako smer Konfiguriranje dostopne točke naprave Ni dovoljeno samodejno prenesti več datotek Ponudi pomoč pri pisanju @@ -11028,7 +11028,7 @@ Ogromni prihranki Brskanje je hitrejše, ker je manj verjetno, da vas bo spletno mesto pozvalo, da potrdite, da ste resnična oseba. Kadar ni povezana nobena naprava -Stabilna +Stabilno Spletna trgovina Mačka Svetlo zelenomodra diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_ur.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_ur.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_ur.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_ur.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -177,7 +177,7 @@ ہیرا لِڈ بند ہونے پر سلیپ وضع میں بھیجیں آپ کی شناخت کی تصدیق نہیں کی جا سکی -کے بارے میں +تعارف "" ایکسٹینشن اس ترتیب کو نافذ کرتی ہے۔ پاس ورڈز اور آٹو فل سسٹم آلہ کے ماڈل یا نمبر شمار کا تعین کرنے میں ناکام ہو گیا۔ diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_vi.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_vi.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_vi.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_vi.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -76,7 +76,7 @@ Đã di chuyển cửa sổ lên trên và sang bên trái Khởi động lại Linux? Sao chép &văn bản liên kết -Hiển thị +Màn hình Tự động phân bổ {COUNT,plural, =1{Đang nhận từ thiết bị }other{Đang nhận từ thiết bị }} Ẩn danh @@ -2388,7 +2388,7 @@ Để bật tùy chọn gỡ lỗi ADB, bạn cần phải đặt lại Chromebook này về trạng thái ban đầu. Tìm hiểu thêm Phát triển ứng dụng Android Xoá canvas -Hiển thị tùy chọn nhập trên kệ +Hiện các tuỳ chọn nhập trong thanh ứng dụng Các trang web có thể yêu cầu cuộn và thu phóng các thẻ được chia sẻ Xóa ""? không thể hoàn tất cài đặt nhưng sẽ tiếp tục chạy từ hình ảnh đĩa của trình duyệt này. @@ -11591,7 +11591,7 @@ sẽ chỉnh sửa được các tệp trong Tìm kiếm trên Từng xem trước đây -Các phương thức khóa màn hình +Các phương thức khoá màn hình Đã xảy ra lỗi. Vui lòng liên hệ với quản trị viên hoặc chủ sở hữu thiết bị. Mã lỗi: . Đỏ – xanh lục, phân biệt màu lục kém (Mù màu lục nhẹ) &Bật cấu hình diff -Nru chromium-132.0.6834.110/chrome/app/resources/generated_resources_zh-TW.xtb chromium-132.0.6834.159/chrome/app/resources/generated_resources_zh-TW.xtb --- chromium-132.0.6834.110/chrome/app/resources/generated_resources_zh-TW.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/generated_resources_zh-TW.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -2636,7 +2636,7 @@ 已登入 螢幕大小 沒有受管理的印表機。 -手勢設定: +表情設定: 開啟資料夾 請確認藍牙裝置「」上顯示的密碼金鑰為 無法開啟替代瀏覽器 @@ -3789,7 +3789,7 @@ 點選觸控筆按鈕 正在初始化 網路檔案共用 -回應式 +靈敏 閒置分頁新外觀登場 你的家長或監護人已關閉 Chrome 的「網站、應用程式和擴充功能的權限」,因此你無法使用這個擴充功能。 繼續允許 存取你的麥克風 @@ -5694,7 +5694,7 @@ 開啟 開啟「零打擾」模式 第三方 Cookie -使用手勢進入捲動模式,然後將頭部轉向要捲動的方向。再次做出手勢即可退出捲動模式。 +使用表情進入捲動模式,然後將頭部轉向要捲動的方向。再次做出表情即可退出捲動模式。 下一句 複製密碼 Crostini Android 應用程式 ADB @@ -7005,7 +7005,7 @@ 同步功能已開啟 網路無法使用 放大鏡跟隨「隨選朗讀」讀出的字詞 -指派手勢 +指派表情 區段 個 (最多 個) {COUNT,plural, =0{在新視窗中開啟所有網址(&N)}=1{在新視窗中開啟(&N)}other{在新視窗中開啟所有 ({COUNT} 個) 網址(&N)}} @@ -7973,7 +7973,7 @@ 訓練聲音時,建議你使用耳罩式耳機 你的分頁、網頁標題和網址會傳送給 Google 正在接收 Wi-Fi 資訊... -已將「」手勢設為 +已將「」表情設為 海上大浪噴濺,遠處背景可見陸地。在黑暗陰鬱的天空中,地平線上出現些微橘色光芒。 查詢網址 可用空間: @@ -8371,7 +8371,7 @@ 你即將啟用 Chrome OS 偵錯功能,這會一併設定 sshd Daemon,並允許從 USB 隨身碟執行啟動作業。 再指派 1 個切換工具 這個安全金鑰不支援 PIN 碼 -手勢偵測門檻 +表情偵測門檻 不使用票證造訪 選取分頁群組並啟用內容選單,即可編輯群組 必須更新 Linux @@ -10966,7 +10966,7 @@ 觸控筆 如果你的孩子看到這個圖示,就表示他們可以透過指紋進行身分認證或購買交易。 請說明你允許使用第三方 Cookie 的原因,協助我們改善 Chrome -選取「」的手勢 +選取「」的表情 這個分頁群組已額滿 進一步瞭解如何更新 將「Do Not Track」要求與瀏覽流量一併送出 @@ -10990,7 +10990,7 @@ 節省量:極大 降低網站確認你是否為真人的機率,提供更快速的瀏覽體驗 沒有任何裝置連線時 -穩定版 +穩定 線上應用程式商店 貓咪 淺藍綠色 diff -Nru chromium-132.0.6834.110/chrome/app/resources/google_chrome_strings_iw.xtb chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_iw.xtb --- chromium-132.0.6834.110/chrome/app/resources/google_chrome_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -284,7 +284,7 @@ נוסף ל-‏Chrome ‏כדי להשתמש בהתאמה אישית, צריך לכלול את Chrome ב'פעילות באינטרנט ובאפליקציות' ‏‫Chrome חסם את ההורדה הזו כי הקובץ יכול לפגוע בחשבונות האישיים ובחשבונות שלך ברשתות החברתיות -‏אפשר להצמיד את Google Lens כדי לאפשר גישה נוחה: פשוט לוחצים על הלחצן 'הצמדה' בחלק העליון של החלונית הצדדית +‏אפשר להצמיד את Google Lens כדי לאפשר גישה נוחה: פשוט לוחצים על הכפתור 'הצמדה' בחלק העליון של החלונית הצדדית ‏Chrome לא יכול לבדוק את הסיסמאות שלך כי לא נכנסת לחשבון ‏בגלישה במצב פרטי, Chrome יציג אזהרה לפני טעינת אתר באמצעות חיבור לא מאובטח עם ההגנה המשופרת, החסימה של פישינג ותוכנות זדוניות מקיפה יותר @@ -400,7 +400,7 @@ ‏אפשר להתאים אישית את Chrome בדרך שנוחה לך ‏Google Chrome יופעל מחדש בעוד סגירה -‏התכונה הוצמדה. מעכשיו אפשר לגשת אל Google Lens דרך הלחצן החדש בסרגל הכלים +‏התכונה הוצמדה. מעכשיו אפשר לגשת אל Google Lens דרך הכפתור החדש בסרגל הכלים ‏פתיחת Lens העתקה כתמונה ‏לשיפור האבטחה, Google Chrome יצפין את הנתונים @@ -626,7 +626,7 @@ שגיאה בשירות: . רשימת שפות לחיפוש ‏בעזרת פרופילים ב-Chrome, אפשר להפריד בין הפריטים ששומרים ב-Chrome. באופן הזה קל יותר להפריד בין עבודה לפנאי. -חדש! אפשר לתרגם טקסט ותמונות במסך באמצעות לחיצה על הלחצן 'תרגום המסך' +חדש! אפשר לתרגם טקסט ותמונות במסך באמצעות לחיצה על הכפתור 'תרגום המסך' ‏Google Chrome אינו מגיב. להפעיל מחדש עכשיו? ‏Chrome זקוק להרשאת גישה למצלמה כדי ליצור מפה תלת-ממדית של הסביבה שלך {0,plural, =1{‏Chrome יופעל מחדש בעוד דקה}one{‏Chrome יופעל מחדש בעוד # דקות}two{‏Chrome יופעל מחדש בעוד # דקות}other{‏Chrome יופעל מחדש בעוד # דקות}} diff -Nru chromium-132.0.6834.110/chrome/app/resources/google_chrome_strings_pt-BR.xtb chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_pt-BR.xtb --- chromium-132.0.6834.110/chrome/app/resources/google_chrome_strings_pt-BR.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_pt-BR.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -192,7 +192,7 @@ Teste novos recursos de IA para criar temas, receber ajuda com a escrita e se organizar Se você também compartilhar os relatórios de uso do Chrome, eles vão incluir os URLs acessados Personalize seu navegador com uma nova cor -Fazer login no Google Chrome +Fazer login no Chrome Reiniciar agora Depois, o Chrome vai perguntar se você quer usar as informações salvas para preencher formulários automaticamente Depois, é necessário reiniciar o Chrome. @@ -339,7 +339,7 @@ Fazer login no Chrome ao se conectar a outros Serviços do Google O Chrome pré-carrega mais páginas que você provavelmente vai visitar para que elas sejam carregadas mais rapidamente ao serem acessadas Descubra ótimos aplicativos, jogos, extensões e temas para o Google Chrome. -Personalize seu perfil do Chrome +Personalizar perfil do Chrome O Chrome pode deixar esta guia inativa para melhorar sua experiência de navegação e liberar recursos. Conheça o Chrome. Nova janela do navegador aberta O Chrome precisa de permissão para rastrear suas mãos @@ -499,7 +499,7 @@ O Chrome libera memória de guias inativas. Isso permite que essas guias e outros apps usem mais recursos do computador e mantém a velocidade do Chrome. Suas guias inativas são reativadas automaticamente quando você volta a elas. {COUNT,plural, =0{Uma nova atualização está disponível para o Chrome e será feita assim que você reiniciá-lo.}=1{Uma nova atualização está disponível para o Chrome e será feita assim que você reiniciá-lo. Sua janela anônima não será aberta novamente.}one{Uma nova atualização está disponível para o Chrome e será feita assim que você reiniciá-lo. Sua janela anônima não será aberta novamente.}other{Uma nova atualização está disponível para o Chrome e será feita assim que você reiniciá-lo. Suas # janelas anônimas não serão abertas novamente.}} Se tiver mudado, edite a senha salva no Chrome para que ela seja igual à nova senha. -Bem-vindo ao Google Chrome +Que bom te ver no Google Chrome! Saiba mais sobre esses recursos nas configurações do Chrome. Sua organização vai fechar o Chrome se ele não for usado por . Você está fazendo login com uma conta gerenciada e concedendo ao administrador da conta o controle sobre seu perfil do Google Chrome. Seus dados do Google Chrome, como aplicativos, favoritos, histórico, senhas e outras configurações serão permanentemente vinculados a . Você pode excluir esses dados pelo painel das Contas do Google, mas não pode associá-los a outra conta. Você tem a opção de criar um novo perfil para manter seus dados existentes do Google Chrome separados. diff -Nru chromium-132.0.6834.110/chrome/app/resources/google_chrome_strings_ru.xtb chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_ru.xtb --- chromium-132.0.6834.110/chrome/app/resources/google_chrome_strings_ru.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/app/resources/google_chrome_strings_ru.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -409,7 +409,7 @@ Chrome становится все лучше На этом языке показываются меню, настройки, оповещения и другой текст в Chrome Чтобы использовать микрофон, предоставьте Chrome доступ к нему в системных настройках -Чтобы поддерживать работу этих вкладок, используется оперативная память. Разрешите Chrome сделать их неактивными, и производительность повысится. +Эти вкладки занимают лишние ресурсы. Чтобы повысить производительность, разрешите Chrome сделать их неактивными. Открывать PDF-файлы в Chrome Чтобы использовать и сохранять данные Chrome в аккаунте Google, обновите Chrome. Ваша организация удаляет данные Chrome, если они не используются в течение . Они могут включать в себя историю, сведения для автозаполнения и скачанные файлы. diff -Nru chromium-132.0.6834.110/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_iw.xtb chromium-132.0.6834.159/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_iw.xtb --- chromium-132.0.6834.110/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -39,7 +39,7 @@ marquee אין עוד כותרות מרמה 4 ‏מקשי הקיצור הבאים אינם פקודות ChromeVox, אבל הם עדיין שימושיים מאוד אם רוצים לנצל את כל היתרונות של Chrome. - כדי לנווט קדימה בין פריטים שמאפשרים לבצע פעולה, כמו לחצנים וקישורים, מקישים על המקש Tab. כדי לנווט אחורה, מקישים על Shift+Tab. + כדי לנווט קדימה בין פריטים שמאפשרים לבצע פעולה, כמו כפתורים וקישורים, מקישים על המקש Tab. כדי לנווט אחורה, מקישים על Shift+Tab. כדי לעבור אל תיבת הכתובות בדפדפן Chrome, שנקראת גם סרגל הכתובות, מקישים על Control+L. כדי לפתוח באופן אוטומטי כרטיסייה חדשה ולעבור אליה, מקישים על Control+T. הסמן יופיע בסרגל הכתובות. כדי לסגור כרטיסייה, מקישים על Control+W. @@ -59,13 +59,13 @@ אין ביטוי מתמטי קודם נבחר ‏אפשר להציג את המדריכים בכל שלב. פשוט לוחצים בעזרת ארבע אצבעות כדי לפתוח את התפריטים. לאחר מכן, מפעילים את המדריך שבקטע ChromeVox. -לחצן החלפת מצב +כפתור החלפת מצב כחול שמיים בהיר ‏לוחצים עם 4 אצבעות כדי לעבור אל התפריטים של ChromeVox לחיצה על מקש הרווח חזרה לקטע הקודם. הדוגמאות כוללות את מגש הסטטוס ואת מרכז האפליקציות. הדרכה להפעלה באמצעות מגע -, ביטלת את הסימון בלחצן הבחירה של האפשרות בתפריט +, ביטלת את הסימון בכפתור הבחירה של האפשרות בתפריט חום צהבהב מנמיכים את הגבות מתוך @@ -228,7 +228,7 @@ תיבת סימון move to the next sentence כרגע -קבוצת לחצני בחירה +קבוצת כפתורי בחירה ביטול הבחירה כותרת 6 {COUNT,plural, =1{כוכבית}one{# סימני כוכבית}two{# סימני כוכבית}other{# סימני כוכבית}} @@ -300,7 +300,7 @@ {COUNT,plural, =1{דקה}one{דקות}two{דקות}other{דקות}} מידע {COUNT,plural, =1{סוגר מסולסל שמאלי}one{# סימני סוגר מסולסל שמאלי}two{# סימני סוגר מסולסל שמאלי}other{# סימני סוגר מסולסל שמאלי}} -אין עוד לחצנים +אין עוד כפתורים ‏פתיחת המדריך של ChromeVox החלקה ימינה עם שלוש אצבעות התכונה 'הפעלה חכמה של ההקשה ביד אחת' פעילה @@ -319,7 +319,7 @@ ‏מקש החיפוש + O, ואז S. אפשר להשתמש במקשי הקיצור האלה לצורך התקנה, ניהול והתאמה אישית של קולות. ‏‎@עריכה 8 נק'‎ ‏ChromeVox בטעינה -לחצן בחירה של פריט בתפריט +כפתור בחירה של פריט בתפריט {COUNT,plural, =1{גרש}one{# סימני גרש}two{# סימני גרש}other{# סימני גרש}} סמן התקדמות ‏אפשרויות של ChromeVox @@ -367,7 +367,7 @@ , כרטיסייה ללא קו חוצה chk -לחצן קופץ +כפתור קופץ הקישור הקודם שאליו נכנסת תאים בכל שורה: : @@ -493,7 +493,7 @@ ירוק ליים sts מתבצעת טעינת דף -צריך להקיש על מקש החיפוש ועל החץ ימינה כדי למצוא את הלחצן 'הבא'. כדי ללחוץ עליו, יש להקיש על מקש החיפוש ומקש הרווח. +צריך ללחוץ על מקש החיפוש ועל החץ ימינה כדי למצוא את הכפתור 'הבא'. כדי ללחוץ עליו, יש ללחוץ על מקש החיפוש ומקש הרווח. {COUNT,plural, =1{טילדה (~)}one{# סימני טילדה (~)}two{# סימני טילדה (~)}other{# סימני טילדה (~)}} האובייקט הקודם כולל תפריט משנה @@ -508,7 +508,7 @@ מושבת מחליקים מעלה או מטה כדי לעבור שורה אחר שורה המשפט הקודם -לחצן +כפתור מעבר לעמודה הקודמת העברה ימינה תכלת @@ -627,16 +627,16 @@ עריכת הטקסט שדה הטקסט ריק מינימום -אין לחצן קודם -לחצן 'הקודם' +אין כפתור קודם +כפתור 'הקודם' קלט לא מזוהה ‏נתחיל במספר מקשים שישמשו אותך באופן שוטף. אפשר להשתמש במקש Control כדי להפסיק דיבור שפועל. מקש Control נמצא בפינה השמאלית התחתונה של המקלדת. כדי להמשיך, יש להקיש על המקש Control. דילוג לחלק העליון של הדף , חלון אחוזים מקצב הדיבור הקראת מצב הסוללה הנוכחי -, לחצן בחירה מסומן -, סימנת את לחצן הבחירה של האפשרות בתפריט +, כפתור בחירה מסומן +, סימנת את כפתור הבחירה של האפשרות בתפריט לא ניתן , הפעלה של תיעוד דיבור העברת תצוגת ברייל לחלק העליון של הדף @@ -708,20 +708,20 @@ מילה תפריט הקשר כחול בינוני -לחצן בחירה +כפתור בחירה השלמת את ההדרכה המהירה! hdr גיינסבורו הפעלת הכתבה או הפסקתה הפעלה או השבתה של המשוב הקולי (צלילי חיווי) -לחצן +כפתור הרשימה הבאה hdnggrp ‏מצב למידה של ChromeVox התפריט הראשי עריכת טקסט, רשומת אימייל תיבת הסימון הבאה -, לחצן הבחירה לא נבחר +, כפתור הבחירה לא נבחר ביצוע פעולת ברירת המחדל {COUNT,plural, =1{תבליט מרובע}one{# תבליטים מרובעים}two{# תבליטים מרובעים}other{# תבליטים מרובעים}} השלמה אוטומטית מוטבעת @@ -731,8 +731,8 @@ יומן h4 סמל גרפי -‏כל הכבוד! למדת את כל המידע הבסיסי שיאפשר לך להשתמש ב-ChromeVox. חשוב לזכור שאפשר לפתוח את תפריט הפקודות של ChromeVox בכל שלב על ידי הקשה על Search+מקש הנקודה. כדי לקבל מידע נוסף על ChromeVox ו-ChromeOS, אפשר לעיין במאמרים הבאים. - אם סיימת עם המדריך, אפשר להשתמש ב-ChromeVox כדי לנווט ללחצן 'סגירה' וללחוץ עליו. +‏כל הכבוד! למדת את כל המידע הבסיסי שיאפשר לך להשתמש ב-ChromeVox. חשוב לזכור שאפשר לפתוח את תפריט הפקודות של ChromeVox בכל שלב על ידי לחיצה על Search+מקש הנקודה. כדי לקבל מידע נוסף על ChromeVox ו-ChromeOS, אפשר לעיין במאמרים הבאים. + אם סיימת עם המדריך, אפשר להשתמש ב-ChromeVox כדי לנווט לכפתור 'סגירה' וללחוץ עליו. ‏שימוש בתכונות הנגישות של מסך המגע ב-Chromebook פקודות דילוג אזור טקסט @@ -752,11 +752,11 @@ ‏זו הכותרת השנייה. כדי להמשיך בשיעור יש להקיש על מקש החיפוש ועל H או על מקש החיפוש, על Shift ועל H הכותרת הקודמת של רמה 5 נספח -‏כל הכבוד! למדת את המידע הבסיסי לשימוש ב-ChromeVox באמצעות מגע. אפשר לעבור שוב על המידע במדריך, או לצאת ממנו על ידי לחיצה על הלחצנים שלמטה. +‏כל הכבוד! למדת את המידע הבסיסי לשימוש ב-ChromeVox באמצעות מגע. אפשר לעבור שוב על המידע במדריך, או לצאת ממנו על ידי לחיצה על הכפתורים שלמטה. ‏תוסף המרת טקסט לדיבור (TTS) של Google Enhanced Network התכונה 'שליטה באמצעות תנועות הפנים' מאפשרת לשלוט בסמן באמצעות הבעות פנים, ולבצע פעולות כמו לחיצה שמאלית בעזרת תנועות פנים, כמו חיוך. לחיצה עם שתי אצבעות -הצגה או הסתרה של המקלדת שמופיעה במסך +הצגה או הסתרה של המקלדת הווירטואלית פריט עץ טורקיז כהה הקראת הדף באופן אוטומטי אחרי שהטעינה שלו מסתיימת @@ -850,7 +850,7 @@ {COUNT,plural, =1{נקודתיים}one{# סימני נקודתיים}two{# סימני נקודתיים}other{# סימני נקודתיים}} תיבת דו-שיח של התראה תוכן העניינים -הלחצן הבא +הכפתור הבא אינדקס הפחתת הבהירות טורקיז @@ -940,7 +940,7 @@ מתבצע חיבור לבנדר תקציר -לחצן קופץ +כפתור קופץ הד תו כחול מידנייט () @@ -954,7 +954,7 @@ פתיחת תיאור ארוך בכרטיסייה חדשה אין גרפיקה קודמת יישום -לחצן הבחירה הבא +כפתור הבחירה הבא קול ברירת המחדל של המרת טקסט לדיבור אין סימני פיסוק הפעלת תיאורים מפורטים @@ -970,7 +970,7 @@ עזרה נבחר באופן חלקי גילוי באמצעות מגע -‏דוגמאות לפקודות קפיצה נוספות: קפיצה באמצעות קישור, לחצן או תיבת סימון. רשימה מלאה של פקודות קפיצה מופיעה בתפריטי ChromeVox, שאותם ניתן לפתוח על ידי הקשה על מקש החיפוש ועל מקש הנקודה. +‏דוגמאות לפקודות קפיצה נוספות: קפיצה באמצעות קישור, כפתור או תיבת סימון. רשימה מלאה של פקודות קפיצה מופיעה בתפריטי ChromeVox, שאותם ניתן לפתוח על ידי לחיצה על מקש החיפוש ועל מקש הנקודה. מעבר לברייל 8 נקודות פרטי רשימת תיאורים {COUNT,plural, =1{אמפרסנד (&)}one{# סימני אמפרסנד (&)}two{# סימני אמפרסנד (&)}other{# סימני אמפרסנד (&)}} @@ -1009,7 +1009,7 @@ השהיית כל הווידאג'טים של מדיה הפועלים כעת הטבלה הבאה (), רמה -כדי למצוא את אזור התרגול או את הלחצן 'השיעור הבא', מקישים על מקש החיפוש ועל החץ ימינה. לאחר מכן מקישים על מקש החיפוש ועל הרווח כדי להפעיל. +כדי למצוא את אזור התרגול או את הכפתור 'השיעור הבא', לוחצים על מקש החיפוש ועל החץ ימינה. לאחר מכן לוחצים על מקש החיפוש ועל הרווח כדי להפעיל. אפור כהה כותרת 2 {COUNT,plural, =1{שעה}one{שעות}two{שעות}other{שעות}} @@ -1018,7 +1018,7 @@ איפוס ההגדרות של המרת טקסט לדיבור עריכת טקסט, רשומת כתובת אתר tlbar -לחצן הבחירה הקודם +כפתור הבחירה הקודם move to the next word אין autolst @@ -1130,7 +1130,7 @@ ‏אני רוצה להשהות את ההשמעה כשתוסף ה-ChromeVox מקריא עכשיו נלמד פעולות ניווט בסיסיות. אפשר להקיש הקשה ארוכה על מקש החיפוש ועל מקשי החיצים כדי לנוע במסך. כדי להמשיך, יש להקיש על מקש החיפוש + החץ ימינה. צמצום רמת הפירוט של ניווט -לחצן סיבוב +כפתור סיבוב עיצוב ‏כדי לראות את כל הפקודות והקיצורים הזמינים ב-ChromeVox, יש להקיש על מקש החיפוש ומקש הנקודה. לאחר מכן יש להשתמש במקשי החיצים כדי לנווט בתפריטים. יש להשתמש במקש Enter כדי להפעיל פקודה. הקשה על מקש החיפוש יחד עם o ולאחר מכן t תחזיר אותך לכאן. תו @@ -1143,7 +1143,7 @@ ‏חלונית ChromeVox בקרת תאריך ביסק -‏כל הכבוד! למדת את המידע הבסיסי לשימוש ב-ChromeVox. אפשר לעבור שוב על המידע במדריך, או לצאת ממנו על ידי לחיצה על אחד הלחצנים שלמטה. +‏כל הכבוד! למדת את המידע הבסיסי לשימוש ב-ChromeVox. אפשר לעבור שוב על המידע במדריך, או לצאת ממנו על ידי לחיצה על אחד הכפתורים שלמטה. אין עוד כותרות מרמה 6 עגבנייה הקראת הקואורדינטות של התא הנוכחי @@ -1185,7 +1185,7 @@ ליים מסומנת באופן חלקי שע -אין לחצן בחירה קודם +אין כפתור בחירה קודם אין קטע קודם Esc tltip @@ -1197,7 +1197,7 @@ יש לבחור טבלת ברייל 8 נקודות: מעבר לתו הקודם ‎+popup‎ -אין עוד לחצני בחירה +אין עוד כפתורי בחירה מעבר דף אין כותרת קודמת הוסר מהבחירה diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_am.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_am.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_am.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_am.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -647,7 +647,7 @@ Google Play አገልግሎቶችን ያዘምኑ በማንኛውም ጣቢያ ላይ ዋጋው ቢቀንስ ማንቂያዎችን ያግኙ ቀይ ቡናማ -የህግ መረጃ +የሕግ መረጃ {NUM_SITES,plural, =1{በቀን 1 ያህል ማሳወቂያ}one{በቀን # ያህል ማሳወቂያ}other{በቀን # ያህል ማሳወቂያዎች}} ቆይተው እንደገና ይሞክሩ ዕልባት diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -62,7 +62,7 @@ جهاز إغلاق علامة التبويب الحالية هل تريد إزالة اقتراح من الحافظة؟ -‏رسم الشعار المبتكر من Google: +‏ رسم شعار Google: ‏سيظهر لك الآن محتوى من موقع "" وحوله في القسم "تتم متابعته حاليًا". يتم حفظ المواقع الإلكترونية وعمليات البحث التي تُتابعها في حسابك على Google. يمكنك إدارة المحتوى الذي تُتابعه من خلال الإعدادات في أي وقت. قائمة القراءة سيظهر لك السجلّ هنا. diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_de.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_de.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_de.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_de.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -578,7 +578,7 @@ Suchleiste öffnen Diese Seite benötigt zu viel Arbeitsspeicher und wurde daher von Chrome angehalten. Möglicherweise siehst du den Verlauf von anderen Apps, die Links in Chrome öffnen. -Nein, danke +Nein danke Google und ich Übersetzungseinstellungen Zum Suchen antippen @@ -1484,7 +1484,7 @@ Hinzufügen  Tabs wiederhergestellt Lesezeichen, Passwörter und andere Daten auf allen deinen Geräten aufrufen -Nein danke +Nein, danke Durch das Entfernen dieses Passworts wird dein -Konto nicht gelöscht. Ändere dein Passwort oder lösche dein Konto auf , um das Konto gegen unbefugten Zugriff zu schützen. Öffnen mit… {FILE_COUNT,plural, =1{Alle Dateien, 1 Datei in der Liste}other{Alle Dateien, # Dateien in der Liste}} @@ -1666,7 +1666,7 @@ Diese Seite öffnen {ARCHIVED_TAB_COUNT,plural, =1{Inaktiver Tab (1)}other{Inaktive Tabs (#)}} Inkognitotabs beim Verlassen von Chrome sperren -Anstößig oder nicht sicher +Anstößig oder bedenklich Chrome beschränkt die Gesamtmenge an Daten, die Websites über den Browser zur Analyse der Werbeleistung teilen können Übersetzung von fremdsprachigen Seiten anbieten In den Lesezeichen findest du deine Leseliste diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_es.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_es.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_es.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_es.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -416,7 +416,7 @@ La lista de dispositivos con los que puedes compartir una pestaña está abierta a altura completa. Historias no leídas listas Plataforma de notificaciones de Google -Usa el bloqueo de pantalla para ver las pestañas de Incógnito abiertas +Usa el método de desbloqueo de la pantalla para ver las pestañas de Incógnito abiertas El nombre no es válido Almacenamiento de Google Tu teclado no cambiará diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_fr.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_fr.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_fr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_fr.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -880,7 +880,7 @@ Connectez-vous à ce site et à Chrome pour accéder sur tous vos appareils à vos favoris et bien plus Vous verrez bientôt les stories de quand vous ouvrirez un onglet. Les sites que vous suivez seront enregistrés dans votre compte Google. Vous pourrez les gérer dans les paramètres Discover. Une erreur s'est produite. -Les sites que vous consultez peuvent déterminer ce que vous aimez, puis vous montrer des annonces alors que vous continuez de naviguer +Les sites que vous consultez peuvent déterminer ce qui vous intéresse, puis vous montrer des annonces lorsque vous continuez de naviguer 1 heure restante La feuille de filtrage des applis est fermée. vers diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_it.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_it.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_it.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_it.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -571,7 +571,7 @@ Download di non riuscito perché non è possibile trovare il percorso di archiviazione. Ordina per sito Vuoi scaricare il file? -Correggi subito +Correggi Ricevi un avviso se una password è stata compromessa a causa di una violazione dei dati Se il problema persiste, scegli "Altri dettagli" di seguito per ottenere maggiori informazioni da . Per continuare, condividerà il tuo con questo sito. diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_iw.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_iw.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -261,7 +261,7 @@ חלון ריק פעילות באינטרנט ובאפליקציות המדריך בנושא פרטיות -‏בעזרת הלחצן 'אפשרויות של Discover' ניתן לקבוע אילו מאמרים יוצגו +‏בעזרת הכפתור 'אפשרויות של Discover' ניתן לקבוע אילו מאמרים יוצגו תוקף הכרטיס פג ‏הסיסמאות שלך מוצפנות במכשיר לפני שהן נשמרות במנהל הסיסמאות של Google התאמה אישית של המידע שמשמש אתרים להצגת מודעות @@ -500,7 +500,7 @@ האם להוריד את התוכן? לא נמצאו תוצאות חיפוש שליחה למכשיר -תרגום הדפים באמצעות הלחצן 'אפשרויות נוספות' +תרגום הדפים באמצעות הכפתור 'אפשרויות נוספות' אפשר לחפש לפי אפליקציה, תאריך ועוד. לשנות את סיומת הקובץ? לא ניתן לבטל את המעקב. משהו השתבש. @@ -979,7 +979,7 @@ לאחר הכניסה לחשבון, הסימניות, הסיסמאות ונתונים נוספים יופיעו בכל המכשירים שלך הארגון שלך הפעיל את הגלישה הבטוחה אין סיסמאות שמורות -איתור הקבצים והדפים שלך ב'הורדות' דרך הלחצן 'אפשרויות נוספות' +איתור הקבצים והדפים שלך ב'הורדות' דרך הכפתור 'אפשרויות נוספות' ניהול התגובות שם: לא נקראו – זמינים במצב אופליין @@ -993,7 +993,7 @@ ‏מערכת Chrome לא יכולה לבדוק אם יש עדכונים שם הקובץ ארוך מדי ‏אתרים שנוספו לפני יותר מ-30 יום נמחקים מ-Chrome באופן אוטומטי. אתר שמבקרים בו פעם נוספת עשוי להופיע שוב ברשימה. אפשר גם לחסום את האפשרות של אתרים להציע מודעות. מידע נוסף על ניהול הפרטיות בפרסום ב-Chrome -דרך לחצן האפשרויות הנוספות אפשר לתרגם את הדף הזה לשפה כלשהי +דרך כפתור האפשרויות הנוספות אפשר לתרגם את הדף הזה לשפה כלשהי ‏Chrome יכול להגן עליך מפני פרצות באבטחת מידע, אתרים לא בטוחים וסכנות נוספות עליך לבדוק אם יש תמיכה בחשבון שנבחר. מעבר לכרטיסייה @@ -1675,7 +1675,7 @@ מארבעת השבועות האחרונים כאן יופיעו הכרטיסיות שפתוחות במכשירים אחרים שירותי מילוי אוטומטי -אפשר לעקוב אחר המחיר באמצעות לחצן האפשרויות הנוספות +אפשר לעקוב אחר המחיר באמצעות כפתור האפשרויות הנוספות קבוצת הכרטיסיות נמחקה שם בעל הכרטיס ‏כניסה ל-Chrome, סגור. @@ -1733,7 +1733,7 @@ ‏שולח ל-Google כתובות URL של חלק מהדפים שאליהם נכנסת, פרטים מוגבלים לגבי המערכת וחלק מתוכן הדפים. פעולה זו עוזרת לזהות איומים חדשים ולהגן על כל המשתמשים באינטרנט. שיתוף… אפשר לבצע סנכרון כדי להוסיף את הסימניות מהמכשירים האחרים שלך -כדי להשתמש בדפים במצב אופליין, אפשר להוריד אותם דרך הלחצן 'אפשרויות נוספות' +כדי להשתמש בדפים במצב אופליין, אפשר להוריד אותם דרך הכפתור 'אפשרויות נוספות' מידע נוסף מוכנה לשימוש ‏האם להסיר את הפעילות שלך ב-Chrome מ'שימוש חכם בדיגיטל'? diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_kn.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_kn.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_kn.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_kn.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1261,7 +1261,7 @@ ಟ್ಯಾಬ್‌ಗಳನ್ನು ಮುಚ್ಚಲಾಗಿದೆ {FILE_COUNT,plural, =1{ಆಡಿಯೋ ಫೈಲ್‌ಗಳು, ಪಟ್ಟಿಯಲ್ಲಿರುವ 1 ಆಡಿಯೋ ಫೈಲ್}one{ಆಡಿಯೋ ಫೈಲ್‌ಗಳು, ಪಟ್ಟಿಯಲ್ಲಿರುವ # ಆಡಿಯೋ ಫೈಲ್‌ಗಳು}other{ಆಡಿಯೋ ಫೈಲ್‌ಗಳು, ಪಟ್ಟಿಯಲ್ಲಿರುವ # ಆಡಿಯೋ ಫೈಲ್‌ಗಳು}} Google ನಿಂದ Discover - ಆಫ್ ಆಗಿದೆ -ಪಾಸ್‌ವರ್ಡ್ ಅಳಿಸುವುದೇ? +ಪಾಸ್‌ವರ್ಡ್ ಅಳಿಸಬೇಕೆ? ಚಿತ್ರ ಡೌನ್‌ಲೋಡ್ ಮಾಡಿ ಆ್ಯಪ್ ಫಿಲ್ಟರ್ ಶೀಟ್ ಸ್ವಯಂತುಂಬುವಿಕೆ ಫಾರ್ಮ್ ಡೇಟಾ diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -493,7 +493,7 @@ Carregar imagem Mudamos a forma como as senhas neste dispositivo são salvas Pesquisa por voz -Fazer login no Google Chrome +Fazer login no Chrome {TAB_COUNT,plural, =1{, guia}one{, guia}other{, guias}} Seu histórico de navegação é mantido no seu dispositivo, e os relatórios são enviados com um atraso para proteger sua identidade Restaurar grupo , cor , como um novo grupo de guias em segundo plano. @@ -757,7 +757,7 @@ Sites Esta página off-line é de e pode ser diferente da versão on-line. Erro na Conta do Google -Verificações detalhadas de downloads suspeitos. +Faz verificações detalhadas de downloads suspeitos. Quando um site ou app pede para pré-carregar links anonimamente, o Chrome criptografa e pré-carrega as páginas pelos servidores do Google sem cookies. Isso oculta sua identidade do site pré-carregado. Suas listas de senhas salvas do Chrome e do foram fundidas. Você ainda pode preencher automaticamente todas as senhas salvas nos dois apps. Abrir @@ -1237,7 +1237,7 @@ Você pode consultar ou excluir as páginas visitadas do histórico Fazendo o download... É comum que os sites que você visita se lembrem dos seus interesses para personalizar a experiência. Os sites também podem armazenar informações sobre seus interesses com o Chrome. -Analisar os dados da sua conta +Analise os dados da sua conta Abrir rapidamente uma nova guia. Para editar este atalho, toque e pressione. Compartilhar feedback , . @@ -1398,7 +1398,7 @@ Usuário da Conta do Google Sim Sempre usar conexões seguras -Controlar como o histórico de navegação é usado para personalizar a Pesquisa e mais +Controle como o histórico de navegação é usado para personalizar a Pesquisa e mais Desativado pelo administrador Sair do Google Chrome Desconecta você da maioria dos sites, mas não da sua Conta do Google. @@ -1480,7 +1480,7 @@ Fechar Com base na legislação da sua região, é necessário definir um navegador e um mecanismo de pesquisa {PAYMENT_METHOD,plural, =1{\u2026 e mais }one{\u2026 e mais }other{\u2026 e mais }} -Quando sua conta está conectada, essa opção protege você nos Serviços do Google. +Protege você em todos os Serviços do Google quando sua conta está conectada. Volte mais tarde para ver novas matérias Adicionar guias restauradas diff -Nru chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb --- chromium-132.0.6834.110/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -211,7 +211,7 @@ Не удалось выполнить проверку личности Стандартная защита Обновите учетные данные -При удалении данных о работе в браузере вы не выйдете из аккаунта Google. Это потребуется сделать вручную. +Удаление данных о работе в браузере не приведет к выходу из аккаунта Google. Вы можете сделать это вручную. Сохранить Не удалять данные Дополнительные настройки diff -Nru chromium-132.0.6834.110/chrome/chrome_branch_deps.json chromium-132.0.6834.159/chrome/chrome_branch_deps.json --- chromium-132.0.6834.110/chrome/chrome_branch_deps.json 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chrome/chrome_branch_deps.json 2025-01-27 17:37:37.000000000 +0000 @@ -1,16 +1,19 @@ { - "src": "refs/branch-heads/6834_101", - "src:src/clank": "refs/heads/chromium/6834_101", - "src:src/components/optimization_guide/internal": "refs/heads/chromium/6834_101", - "src:src/internal": "refs/heads/chromium/6834_101", - "src:src/ios_internal": "refs/heads/chromium/6834_101", - "src:src/third_party/angle": "refs/heads/chromium/6834_101", - "src:src/third_party/dawn": "refs/heads/chromium/6834_101", - "src:src/third_party/devtools-frontend/src": "refs/heads/chromium/6834_101", - "src:src/third_party/instrumented_libs": "refs/heads/chromium/6834_101", - "src:src/third_party/openscreen/src": "refs/heads/chromium/6834_101", - "src:src/third_party/pdfium": "refs/heads/chromium/6834_101", - "src:src/third_party/vulkan-deps": "refs/heads/chromium/6834_101", - "src:src/third_party/webrtc": "refs/branch-heads/6834_101", - "src:src/v8": "refs/heads/chromium/6834_101" + "src": "refs/branch-heads/6834", + "src:src/clank": "refs/heads/chromium/6834", + "src:src/components/optimization_guide/internal": "refs/heads/chromium/6834", + "src:src/internal": "refs/heads/chromium/6834", + "src:src/ios_internal": "refs/heads/chromium/6834", + "src:src/third_party/angle": "refs/heads/chromium/6834", + "src:src/third_party/dawn": "refs/heads/chromium/6834", + "src:src/third_party/devtools-frontend-internal": "refs/heads/chromium/6834", + "src:src/third_party/devtools-frontend-internal:devtools-frontend": "refs/heads/chromium/6834", + "src:src/third_party/devtools-frontend/src": "refs/heads/chromium/6834", + "src:src/third_party/instrumented_libs": "refs/heads/chromium/6834", + "src:src/third_party/openscreen/src": "refs/heads/chromium/6834", + "src:src/third_party/pdfium": "refs/heads/chromium/6834", + "src:src/third_party/skia": "refs/heads/chrome/m132", + "src:src/third_party/vulkan-deps": "refs/heads/chromium/6834", + "src:src/third_party/webrtc": "refs/branch-heads/6834", + "src:src/v8": "refs/heads/chromium/6834" } diff -Nru chromium-132.0.6834.110/chromecast/DEPS chromium-132.0.6834.159/chromecast/DEPS --- chromium-132.0.6834.110/chromecast/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -# Do not add any includes under chrome/ anywhere in chromecast. - -include_rules = [ - # Chromecast code should explicitly declare its dependencies on each - # sub-directory within chromecast/. - "-chromecast", - - # Other Chromecast-wide dependencies. - "+chromecast/base", - "+chromecast/chromecast_buildflags.h", - "+chromecast/public", - "+third_party/boringssl/src/include", - "+third_party/widevine/cdm", -] diff -Nru chromium-132.0.6834.110/chromecast/DIR_METADATA chromium-132.0.6834.159/chromecast/DIR_METADATA --- chromium-132.0.6834.110/chromecast/DIR_METADATA 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/DIR_METADATA 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -monorail: { - component: "Chromecast" -} -buganizer_public: { - component_id: 1456570 -} diff -Nru chromium-132.0.6834.110/chromecast/OWNERS chromium-132.0.6834.159/chromecast/OWNERS --- chromium-132.0.6834.110/chromecast/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -set noparent - -antoniori@google.com -sandv@google.com -sanfin@chromium.org -vigeni@google.com -yucliu@chromium.org - -# Android -per-file *android*=file://chromecast/android/OWNERS -per-file *.java=file://chromecast/android/OWNERS - -# Fuchsia integration owners: -per-file ...fuchsia*=file://build/fuchsia/OWNERS - -# For major changes, please use one of the reviewers above! -dnicoara@chromium.org -spang@chromium.org -halliwell@chromium.org -seantopping@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/README.md chromium-132.0.6834.159/chromecast/README.md --- chromium-132.0.6834.110/chromecast/README.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -# Cast base - -## cast_features - -This file contains tools for checking the feature state of all of the features -which affect Cast products. Cast features build upon -[the Chrome feature system](https://chromium.googlesource.com/chromium/src/+/main/base/feature_list.h). -Some aspects of Cast require the feature system to work differently, however, -so some additional logic has been layered on top. Details are available in -comments of the header file. The basics are: - - * If you are adding a new feature, add it to `cast_features.cc` so it lives - alongside existing features - * Add your new feature to the list of `kFeatures` in `cast_features.cc` - -```c++ -BASE_FEATURE(kMyFeature, "my_feature", base::FEATURE_DISABLED_BY_DEFAULT); - - -const base::Feature* kFeatures[] = { - // ..other features - &kMyFeature -} -``` diff -Nru chromium-132.0.6834.110/chromecast/activity/queryable_data_host.h chromium-132.0.6834.159/chromecast/activity/queryable_data_host.h --- chromium-132.0.6834.110/chromecast/activity/queryable_data_host.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/activity/queryable_data_host.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_ACTIVITY_QUERYABLE_DATA_HOST_H_ -#define CHROMECAST_ACTIVITY_QUERYABLE_DATA_HOST_H_ - -#include - -#include "base/values.h" - -namespace chromecast { - -// Sends queryable data to a host where it will be consumed. -// Either through to WebContents (non-fuchsia) or through FIDL to the -// Cast Runner (Fuchsia). -class QueryableDataHost { - public: - virtual ~QueryableDataHost() = default; - - // Send the queryable data entry |key|:|value| - virtual void SendQueryableValue(const std::string& key, - const base::Value& value) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_ACTIVITY_QUERYABLE_DATA_HOST_H_ diff -Nru chromium-132.0.6834.110/chromecast/android/DEPS chromium-132.0.6834.159/chromecast/android/DEPS --- chromium-132.0.6834.110/chromecast/android/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/android/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+chromecast/media/cma/backend", - "+jni", -] diff -Nru chromium-132.0.6834.110/chromecast/android/OWNERS chromium-132.0.6834.159/chromecast/android/OWNERS --- chromium-132.0.6834.110/chromecast/android/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/android/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -sanfin@chromium.org -sandv@google.com -vigeni@google.com - -per-file lint-*.xml=* diff -Nru chromium-132.0.6834.110/chromecast/android/lint-baseline.xml chromium-132.0.6834.159/chromecast/android/lint-baseline.xml --- chromium-132.0.6834.110/chromecast/android/lint-baseline.xml 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/android/lint-baseline.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff -Nru chromium-132.0.6834.110/chromecast/android/lint-suppressions.xml chromium-132.0.6834.159/chromecast/android/lint-suppressions.xml --- chromium-132.0.6834.110/chromecast/android/lint-suppressions.xml 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/android/lint-suppressions.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff -Nru chromium-132.0.6834.110/chromecast/app/DEPS chromium-132.0.6834.159/chromecast/app/DEPS --- chromium-132.0.6834.110/chromecast/app/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -include_rules = [ - "+chromecast/browser", - "+chromecast/common", - "+chromecast/crash", - "+chromecast/gpu", - "+chromecast/renderer", - "+components/crash", - "+components/prefs", - "+content/public/app", - "+content/public/browser", - "+content/public/common", - "+sandbox/policy", - "+ui/base", -] - -specific_include_rules = { - "cast_test_launcher\.cc": [ - "+content/public/test", - "+mojo/core/embedder/embedder.h", - ], -} diff -Nru chromium-132.0.6834.110/chromecast/app/android/DEPS chromium-132.0.6834.159/chromecast/app/android/DEPS --- chromium-132.0.6834.110/chromecast/app/android/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/android/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -include_rules = [ - "+chromecast/android", - "+chromecast/browser/android", - "+jni", - "+third_party/jni_zero", - "+components/prefs", -] diff -Nru chromium-132.0.6834.110/chromecast/app/android/OWNERS chromium-132.0.6834.159/chromecast/app/android/OWNERS --- chromium-132.0.6834.110/chromecast/app/android/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/android/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -file://chromecast/android/OWNERS diff -Nru chromium-132.0.6834.110/chromecast/app/android/cast_browser_module_entrypoint.cc chromium-132.0.6834.159/chromecast/app/android/cast_browser_module_entrypoint.cc --- chromium-132.0.6834.110/chromecast/app/android/cast_browser_module_entrypoint.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/android/cast_browser_module_entrypoint.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/android/jni_utils.h" -#include "chromecast/app/cast_main_delegate.h" -#include "content/public/app/content_main.h" -#include "content/public/browser/android/compositor.h" -#include "third_party/jni_zero/jni_zero.h" - -extern "C" { -// This JNI registration method is found and called by module framework code. -JNI_BOUNDARY_EXPORT bool JNI_OnLoad_cast_browser(JNIEnv* env) { - content::Compositor::Initialize(); - content::SetContentMainDelegate(new chromecast::shell::CastMainDelegate); - return true; -} -} // extern "C" diff -Nru chromium-132.0.6834.110/chromecast/app/android/cast_crash_reporter_client_android.cc chromium-132.0.6834.159/chromecast/app/android/cast_crash_reporter_client_android.cc --- chromium-132.0.6834.110/chromecast/app/android/cast_crash_reporter_client_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/android/cast_crash_reporter_client_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/app/android/cast_crash_reporter_client_android.h" - -#include "base/android/build_info.h" -#include "base/base_paths.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/path_service.h" -#include "chromecast/base/cast_sys_info_android.h" -#include "chromecast/base/version.h" -#include "chromecast/common/global_descriptors.h" -#include "content/public/common/content_switches.h" - -namespace chromecast { - -CastCrashReporterClientAndroid::CastCrashReporterClientAndroid( - const std::string& process_type) - : process_type_(process_type) { -} - -CastCrashReporterClientAndroid::~CastCrashReporterClientAndroid() { -} - -void CastCrashReporterClientAndroid::GetProductNameAndVersion( - std::string* product_name, - std::string* version, - std::string* channel) { - *product_name = "media_shell"; - *version = CAST_BUILD_RELEASE "."; - *version += base::android::BuildInfo::GetInstance()->package_version_code(); -#if CAST_IS_DEBUG_BUILD() - *version += ".debug"; -#endif - CastSysInfoAndroid sys_info; - *channel = sys_info.GetSystemReleaseChannel(); -} - -base::FilePath CastCrashReporterClientAndroid::GetReporterLogFilename() { - return base::FilePath(FILE_PATH_LITERAL("uploads.log")); -} - -// static -bool CastCrashReporterClientAndroid::GetCrashReportsLocation( - const std::string& process_type, - base::FilePath* crash_dir) { - base::FilePath crash_dir_local; - if (!base::PathService::Get(base::DIR_ANDROID_APP_DATA, &crash_dir_local)) { - return false; - } - crash_dir_local = crash_dir_local.Append("crashes"); - - // Only try to create the directory in the browser process (empty value). - if (process_type.empty()) { - if (!base::DirectoryExists(crash_dir_local)) { - if (!base::CreateDirectory(crash_dir_local)) { - return false; - } - } - } - - // Provide value to crash_dir once directory is known to be a valid path. - *crash_dir = crash_dir_local; - return true; -} - -bool CastCrashReporterClientAndroid::GetCrashDumpLocation( - base::FilePath* crash_dir) { - base::FilePath app_data; - if (!base::PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data)) { - return false; - } - - *crash_dir = app_data.Append("Crashpad"); - return true; -} - -bool CastCrashReporterClientAndroid::EnableBreakpadForProcess( - const std::string& process_type) { - return process_type == switches::kRendererProcess || - process_type == switches::kGpuProcess; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/app/android/cast_crash_reporter_client_android.h chromium-132.0.6834.159/chromecast/app/android/cast_crash_reporter_client_android.h --- chromium-132.0.6834.110/chromecast/app/android/cast_crash_reporter_client_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/android/cast_crash_reporter_client_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_APP_ANDROID_CAST_CRASH_REPORTER_CLIENT_ANDROID_H_ -#define CHROMECAST_APP_ANDROID_CAST_CRASH_REPORTER_CLIENT_ANDROID_H_ - -#include - -#include "base/compiler_specific.h" -#include "components/crash/core/app/crash_reporter_client.h" - -namespace chromecast { - -class CastCrashReporterClientAndroid - : public crash_reporter::CrashReporterClient { - public: - explicit CastCrashReporterClientAndroid(const std::string& process_type); - - CastCrashReporterClientAndroid(const CastCrashReporterClientAndroid&) = - delete; - CastCrashReporterClientAndroid& operator=( - const CastCrashReporterClientAndroid&) = delete; - - ~CastCrashReporterClientAndroid() override; - - // Return the path to a directory of MIME-encoded crash reports. - static bool GetCrashReportsLocation(const std::string& process_type, - base::FilePath* crash_dir); - - // crash_reporter::CrashReporterClient implementation: - void GetProductNameAndVersion(std::string* product_name, - std::string* version, - std::string* channel) override; - base::FilePath GetReporterLogFilename() override; - bool GetCrashDumpLocation(base::FilePath* crash_dir) override; - bool EnableBreakpadForProcess(const std::string& process_type) override; - - private: - std::string process_type_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_APP_ANDROID_CAST_CRASH_REPORTER_CLIENT_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/app/android/cast_crash_uploader_android.cc chromium-132.0.6834.159/chromecast/app/android/cast_crash_uploader_android.cc --- chromium-132.0.6834.110/chromecast/app/android/cast_crash_uploader_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/android/cast_crash_uploader_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,129 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/app/android/cast_crash_uploader_android.h" - -#include -#include -#include -#include - -#include "base/android/java_exception_reporter.h" -#include "base/android/jni_android.h" -#include "base/android/jni_string.h" -#include "base/files/file_path.h" -#include "base/path_service.h" - -#include "base/command_line.h" -#include "base/logging.h" -#include "base/task/task_traits.h" -#include "base/task/thread_pool.h" -#include "chromecast/app/android/cast_crash_reporter_client_android.h" -#include "chromecast/base/cast_paths.h" -#include "chromecast/base/pref_names.h" -#include "components/crash/core/app/crash_reporter_client.h" -#include "components/crash/core/app/crashpad.h" -#include "components/crash/core/common/crash_key.h" -#include "content/public/common/content_switches.h" - -// Must come after all headers that specialize FromJniType() / ToJniType(). -#include "chromecast/browser/android/crash_handler_jni_headers/CastCrashHandler_jni.h" - -namespace chromecast { -// static -std::unique_ptr CastCrashUploader::Create( - PrefService* pref_service) { - const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess()); - std::string process_type = - command_line->GetSwitchValueASCII(switches::kProcessType); - - base::FilePath log_file; - base::PathService::Get(FILE_CAST_ANDROID_LOG, &log_file); - - return std::make_unique( - std::move(process_type), std::move(log_file), pref_service); -} - -CastCrashUploaderAndroid::CastCrashUploaderAndroid( - const std::string process_type, - const base::FilePath log_file_path, - PrefService* pref_service) - : log_file_path_(log_file_path), - pref_service_(pref_service), - process_type_(process_type), - crash_reporter_client_(new CastCrashReporterClientAndroid(process_type)), - weak_factory_(this) { - crash_reporter::SetCrashReporterClient(crash_reporter_client_.get()); - crash_reporter::InitializeCrashpad(process_type_.empty(), process_type_); - crash_reporter::InitializeCrashKeys(); - base::android::InitJavaExceptionReporter(); - crash_reporter_runner_ = base::ThreadPool::CreateSequencedTaskRunner( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); - StartPeriodicCrashReportUpload(); -} - -CastCrashUploaderAndroid::~CastCrashUploaderAndroid() = default; - -void CastCrashUploaderAndroid::UploadDumps( - const std::string& uuid, - const std::string& application_feedback, - const bool can_send_usage_stats) { - base::FilePath crash_dump_path; - if (!crash_reporter_client_->GetCrashDumpLocation(&crash_dump_path)) { - LOG(ERROR) << "Could not get crash dump location."; - return; - } - base::FilePath crash_reports_path; - if (!crash_reporter_client_->GetCrashReportsLocation(process_type_, - &crash_reports_path)) { - LOG(ERROR) << "Could not get crash report location."; - return; - } - - JNIEnv* env = base::android::AttachCurrentThread(); - base::android::ScopedJavaLocalRef crash_dump_path_java = - base::android::ConvertUTF8ToJavaString(env, crash_dump_path.value()); - base::android::ScopedJavaLocalRef reports_path_java = - base::android::ConvertUTF8ToJavaString(env, crash_reports_path.value()); - base::android::ScopedJavaLocalRef uuid_java = - base::android::ConvertUTF8ToJavaString(env, uuid); - base::android::ScopedJavaLocalRef application_feedback_java = - base::android::ConvertUTF8ToJavaString(env, application_feedback); - // TODO(servolk): Remove the UploadToStaging param and clean up Java code, if - // dev crash uploading to prod server works fine (b/113130776) - - if (can_send_usage_stats) { - Java_CastCrashHandler_uploadOnce(env, crash_dump_path_java, - reports_path_java, uuid_java, - application_feedback_java, - /* uploadCrashToStaging = */ false); - } else { - Java_CastCrashHandler_removeCrashDumps(env, crash_dump_path_java, - reports_path_java, uuid_java, - application_feedback_java, - /* uploadCrashToStaging = */ false); - } -} - -void CastCrashUploaderAndroid::StartPeriodicCrashReportUpload() { - OnStartPeriodicCrashReportUpload(); - crash_reporter_timer_ = std::make_unique(); - crash_reporter_timer_->Start( - FROM_HERE, base::Minutes(20), this, - &CastCrashUploaderAndroid::OnStartPeriodicCrashReportUpload); -} - -void CastCrashUploaderAndroid::OnStartPeriodicCrashReportUpload() { - crash_reporter_runner_->PostTask( - FROM_HERE, base::BindOnce(&CastCrashUploaderAndroid::UploadCrashReport, - weak_factory_.GetWeakPtr(), - pref_service_->GetBoolean(prefs::kOptInStats))); -} - -void CastCrashUploaderAndroid::UploadCrashReport(bool opt_in_stats) { - DCHECK(crash_reporter_runner_->RunsTasksInCurrentSequence()); - CastCrashUploaderAndroid::UploadDumps("", "", opt_in_stats); -} -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/app/android/cast_crash_uploader_android.h chromium-132.0.6834.159/chromecast/app/android/cast_crash_uploader_android.h --- chromium-132.0.6834.110/chromecast/app/android/cast_crash_uploader_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/android/cast_crash_uploader_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_APP_ANDROID_CAST_CRASH_UPLOADER_ANDROID_H_ -#define CHROMECAST_APP_ANDROID_CAST_CRASH_UPLOADER_ANDROID_H_ - -#include - -#include -#include - -#include "base/files/file_path.h" -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "base/timer/timer.h" -#include "chromecast/app/cast_crash_uploader.h" -#include "components/prefs/pref_service.h" - -namespace chromecast { -class CastCrashReporterClientAndroid; - -class CastCrashUploaderAndroid : public CastCrashUploader { - public: - void UploadDumps(const std::string& uuid, - const std::string& application_feedback, - const bool can_send_usage_stats) override; - - CastCrashUploaderAndroid(const std::string process_type, - const base::FilePath log_file_path, - PrefService* pref_service); - ~CastCrashUploaderAndroid() override; - - private: - void StartPeriodicCrashReportUpload(); - void OnStartPeriodicCrashReportUpload(); - void UploadCrashReport(bool opt_in_stats); - - // Path to the current process's log file. - base::FilePath log_file_path_; - - PrefService* pref_service_; - - std::string process_type_; - scoped_refptr crash_reporter_runner_; - std::unique_ptr crash_reporter_timer_; - - std::unique_ptr crash_reporter_client_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_APP_ANDROID_CAST_CRASH_UPLOADER_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/app/android/cast_jni_loader.cc chromium-132.0.6834.159/chromecast/app/android/cast_jni_loader.cc --- chromium-132.0.6834.110/chromecast/app/android/cast_jni_loader.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/android/cast_jni_loader.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/android/jni_android.h" -#include "base/android/library_loader/library_loader_hooks.h" -#include "base/functional/bind.h" -#include "chromecast/app/cast_main_delegate.h" -#include "content/public/app/content_jni_onload.h" -#include "content/public/app/content_main.h" -#include "content/public/browser/android/compositor.h" - -// This is called by the VM when the shared library is first loaded. -JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { - base::android::InitVM(vm); - if (!content::android::OnJNIOnLoadInit()) - return false; - - content::Compositor::Initialize(); - content::SetContentMainDelegate(new chromecast::shell::CastMainDelegate); - return JNI_VERSION_1_4; -} diff -Nru chromium-132.0.6834.110/chromecast/app/cast_crash_uploader.h chromium-132.0.6834.159/chromecast/app/cast_crash_uploader.h --- chromium-132.0.6834.110/chromecast/app/cast_crash_uploader.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/cast_crash_uploader.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_APP_CAST_CRASH_UPLOADER_H_ -#define CHROMECAST_APP_CAST_CRASH_UPLOADER_H_ - -#include - -#include "components/prefs/pref_service.h" - -namespace chromecast { -class CastCrashUploader { - public: - static std::unique_ptr Create(PrefService*); - virtual ~CastCrashUploader() = default; - - virtual void UploadDumps(const std::string& uuid, - const std::string& application_feedback, - const bool can_send_usage_stats) = 0; -}; -} // namespace chromecast - -#endif // CHROMECAST_APP_CAST_CRASH_UPLOADER_H_ diff -Nru chromium-132.0.6834.110/chromecast/app/cast_crash_uploader_default.cc chromium-132.0.6834.159/chromecast/app/cast_crash_uploader_default.cc --- chromium-132.0.6834.110/chromecast/app/cast_crash_uploader_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/cast_crash_uploader_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/app/cast_crash_uploader_default.h" -#include - -namespace chromecast { - -// static -std::unique_ptr CastCrashUploader::Create( - PrefService* pref_service) { - return std::make_unique(); -} -void CastCrashUploaderDefault::UploadDumps( - const std::string& uuid, - const std::string& application_feedback, - const bool can_send_usage_stats) { - NOTREACHED() << "TODO(b/258269114): Move non-android implementations of " - "crash reporting here."; -} -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/app/cast_crash_uploader_default.h chromium-132.0.6834.159/chromecast/app/cast_crash_uploader_default.h --- chromium-132.0.6834.110/chromecast/app/cast_crash_uploader_default.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/cast_crash_uploader_default.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_APP_CAST_CRASH_UPLOADER_DEFAULT_H_ -#define CHROMECAST_APP_CAST_CRASH_UPLOADER_DEFAULT_H_ - -#include "chromecast/app/cast_crash_uploader.h" -#include "components/prefs/pref_service.h" - -namespace chromecast { -class CastCrashUploaderDefault : public CastCrashUploader { - public: - static CastCrashUploader* Create(PrefService*); - void UploadDumps(const std::string& uuid, - const std::string& application_feedback, - const bool can_send_usage_stats) override; -}; -} // namespace chromecast - -#endif // CHROMECAST_APP_CAST_CRASH_UPLOADER_DEFAULT_H_ diff -Nru chromium-132.0.6834.110/chromecast/app/cast_main.cc chromium-132.0.6834.159/chromecast/app/cast_main.cc --- chromium-132.0.6834.110/chromecast/app/cast_main.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/cast_main.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/app/cast_main_delegate.h" -#include "content/public/app/content_main.h" - -int main(int argc, const char** argv) { - chromecast::shell::CastMainDelegate delegate; - content::ContentMainParams params(&delegate); - params.argc = argc; - params.argv = argv; - return content::ContentMain(std::move(params)); -} diff -Nru chromium-132.0.6834.110/chromecast/app/cast_main_delegate.cc chromium-132.0.6834.159/chromecast/app/cast_main_delegate.cc --- chromium-132.0.6834.110/chromecast/app/cast_main_delegate.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/cast_main_delegate.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,363 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/app/cast_main_delegate.h" - -#include -#include -#include -#include - -#include "base/command_line.h" -#include "base/cpu.h" -#include "base/debug/leak_annotations.h" -#include "base/files/file.h" -#include "base/files/file_enumerator.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/metrics/field_trial.h" -#include "base/no_destructor.h" -#include "base/path_service.h" -#include "base/posix/global_descriptors.h" -#include "build/build_config.h" -#include "chromecast/base/cast_paths.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/process_types.h" -#include "chromecast/browser/cast_content_browser_client.h" -#include "chromecast/browser/cast_feature_list_creator.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/common/cast_resource_delegate.h" -#include "chromecast/common/global_descriptors.h" -#include "chromecast/gpu/cast_content_gpu_client.h" -#include "chromecast/renderer/cast_content_renderer_client.h" -#include "components/crash/core/app/crash_reporter_client.h" -#include "components/crash/core/common/crash_key.h" -#include "content/public/app/initialize_mojo_core.h" -#include "content/public/browser/browser_main_runner.h" -#include "content/public/common/content_switches.h" -#include "third_party/abseil-cpp/absl/types/variant.h" -#include "ui/base/resource/resource_bundle.h" - -#if BUILDFLAG(IS_ANDROID) -#include "base/android/apk_assets.h" -#include "chromecast/app/android/cast_crash_reporter_client_android.h" -#include "ui/base/resource/resource_bundle_android.h" -#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -#include "chromecast/app/linux/cast_crash_reporter_client.h" -#include "sandbox/policy/switches.h" -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - -namespace { - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -chromecast::CastCrashReporterClient* GetCastCrashReporter() { - static base::NoDestructor - crash_reporter_client; - return crash_reporter_client.get(); -} -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - -#if BUILDFLAG(IS_ANDROID) -const int kMaxCrashFiles = 10; -#endif // BUILDFLAG(IS_ANDROID) - -} // namespace - -namespace chromecast { -namespace shell { - -CastMainDelegate::CastMainDelegate() {} - -CastMainDelegate::~CastMainDelegate() {} - -std::optional CastMainDelegate::BasicStartupComplete() { - RegisterPathProvider(); - - logging::LoggingSettings settings; - settings.logging_dest = - logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR; - - const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess()); - std::string process_type = - command_line->GetSwitchValueASCII(switches::kProcessType); - - // Must be created outside of the if scope below to avoid lifetime concerns. - std::string log_path_as_string; - if (command_line->HasSwitch(switches::kLogFile)) { - auto file_path = command_line->GetSwitchValuePath(switches::kLogFile); - DCHECK(!file_path.empty()); - log_path_as_string = file_path.value(); - - settings.logging_dest = logging::LOG_TO_ALL; - settings.log_file_path = log_path_as_string.c_str(); - settings.lock_log = logging::DONT_LOCK_LOG_FILE; - - // If this is the browser process, delete the old log file. Else, append to - // it. - settings.delete_old = process_type.empty() - ? logging::DELETE_OLD_LOG_FILE - : logging::APPEND_TO_OLD_LOG_FILE; - } - -#if BUILDFLAG(IS_ANDROID) - // Browser process logs are recorded for attaching with crash dumps. - if (process_type.empty()) { - base::FilePath log_file; - base::PathService::Get(FILE_CAST_ANDROID_LOG, &log_file); - settings.logging_dest = - logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR; - log_path_as_string = log_file.value(); - settings.log_file_path = log_path_as_string.c_str(); - settings.delete_old = logging::DELETE_OLD_LOG_FILE; - } -#endif // BUILDFLAG(IS_ANDROID) - logging::InitLogging(settings); -#if BUILDFLAG(IS_CAST_DESKTOP_BUILD) - logging::SetLogItems(true, true, true, false); -#else - // Timestamp available through logcat -v time. - logging::SetLogItems(true, true, false, false); -#endif // BUILDFLAG(IS_CAST_DESKTOP_BUILD) - -#if BUILDFLAG(IS_ANDROID) - // Only delete the old crash dumps if the current process is the browser - // process. Empty |process_type| signifies browser process. - if (process_type.empty()) { - // Get a listing of all of the crash dump files. - base::FilePath crash_directory; - if (CastCrashReporterClientAndroid::GetCrashReportsLocation( - process_type, &crash_directory)) { - base::FileEnumerator crash_directory_list(crash_directory, false, - base::FileEnumerator::FILES); - std::vector crash_files; - for (base::FilePath file = crash_directory_list.Next(); !file.empty(); - file = crash_directory_list.Next()) { - crash_files.push_back(file); - } - // Delete crash dumps except for the |kMaxCrashFiles| most recent ones. - if (crash_files.size() > kMaxCrashFiles) { - auto newest_first = - [](const base::FilePath& l, const base::FilePath& r) -> bool { - base::File::Info l_info, r_info; - base::GetFileInfo(l, &l_info); - base::GetFileInfo(r, &r_info); - return l_info.last_modified > r_info.last_modified; - }; - std::partial_sort(crash_files.begin(), - crash_files.begin() + kMaxCrashFiles, - crash_files.end(), newest_first); - for (auto file = crash_files.begin() + kMaxCrashFiles; - file != crash_files.end(); ++file) { - base::DeleteFile(*file); - } - } - } - } -#endif // BUILDFLAG(IS_ANDROID) - - if (settings.logging_dest & logging::LOG_TO_FILE) { - LOG(INFO) << "Logging to file: " << settings.log_file_path; - } - return std::nullopt; -} - -void CastMainDelegate::PreSandboxStartup() { -#if defined(ARCH_CPU_ARM_FAMILY) && \ - (BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) - // Create an instance of the CPU class to parse /proc/cpuinfo and cache the - // results. This data needs to be cached when file-reading is still allowed, - // since base::CPU expects to be callable later, when file-reading is no - // longer allowed. - base::CPU cpu_info; -#endif - - const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess()); - std::string process_type = - command_line->GetSwitchValueASCII(switches::kProcessType); - - bool enable_crash_reporter = - !command_line->HasSwitch(switches::kDisableCrashReporter); - if (enable_crash_reporter) { - // TODO(crbug.com/40188745): Complete crash reporting integration on - // Fuchsia. -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - crash_reporter::SetCrashReporterClient(GetCastCrashReporter()); - - if (process_type != switches::kZygoteProcess) { - CastCrashReporterClient::InitCrashReporter(process_type); - } - crash_reporter::InitializeCrashKeys(); -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - } - - InitializeResourceBundle(); -} - -absl::variant CastMainDelegate::RunProcess( - const std::string& process_type, - content::MainFunctionParams main_function_params) { -#if BUILDFLAG(IS_ANDROID) - if (!process_type.empty()) - return std::move(main_function_params); - - // Note: Android must handle running its own browser process. - // See ChromeMainDelegateAndroid::RunProcess. - browser_runner_ = content::BrowserMainRunner::Create(); - int exit_code = browser_runner_->Initialize(std::move(main_function_params)); - // On Android we do not run BrowserMain(), so the above initialization of a - // BrowserMainRunner is all we want to occur. Preserve any error codes > 0. - if (exit_code > 0) - return exit_code; - return 0; -#else - return std::move(main_function_params); -#endif // BUILDFLAG(IS_ANDROID) -} - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -void CastMainDelegate::ZygoteForked() { - const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess()); - bool enable_crash_reporter = !command_line->HasSwitch( - switches::kDisableCrashReporter); - if (enable_crash_reporter) { - std::string process_type = - command_line->GetSwitchValueASCII(switches::kProcessType); - CastCrashReporterClient::InitCrashReporter(process_type); - } -} -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - -bool CastMainDelegate::ShouldCreateFeatureList(InvokedIn invoked_in) { - return absl::holds_alternative(invoked_in); -} - -bool CastMainDelegate::ShouldInitializeMojo(InvokedIn invoked_in) { - return ShouldCreateFeatureList(invoked_in); -} - -std::optional CastMainDelegate::PostEarlyInitialization( - InvokedIn invoked_in) { - if (ShouldCreateFeatureList(invoked_in)) { - // content is handling the feature list. - return std::nullopt; - } - - DCHECK(cast_feature_list_creator_); - -#if !BUILDFLAG(IS_ANDROID) - // PrefService requires the home directory to be created before the pref store - // can be initialized properly. - base::FilePath home_dir; - CHECK(base::PathService::Get(DIR_CAST_HOME, &home_dir)); - CHECK(base::CreateDirectory(home_dir)); -#endif // !BUILDFLAG(IS_ANDROID) - - // TODO(crbug.com/40791269): If we're able to create the MetricsStateManager - // earlier, clean up the below if and else blocks and call - // MetricsStateManager::InstantiateFieldTrialList(). - // - // The FieldTrialList is a dependency of the feature list. In tests, it is - // constructed as part of the test suite. - const auto* invoked_in_browser = - absl::get_if(&invoked_in); - if (invoked_in_browser && invoked_in_browser->is_running_test) { - DCHECK(base::FieldTrialList::GetInstance()); - } else { - // This is intentionally leaked since it needs to live for the duration of - // the browser process and there's no benefit to cleaning it up at exit. - base::FieldTrialList* leaked_field_trial_list = new base::FieldTrialList(); - ANNOTATE_LEAKING_OBJECT_PTR(leaked_field_trial_list); - std::ignore = leaked_field_trial_list; - } - - // Initialize the base::FeatureList and the PrefService (which it depends on), - // so objects initialized after this point can use features from - // base::FeatureList. - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - const bool use_browser_config = - command_line->HasSwitch(switches::kUseCastBrowserPrefConfig); - ProcessType process_type = use_browser_config ? ProcessType::kCastBrowser - : ProcessType::kCastService; - cast_feature_list_creator_->CreatePrefServiceAndFeatureList(process_type); - - content::InitializeMojoCore(); - - return std::nullopt; -} - -void CastMainDelegate::InitializeResourceBundle() { - base::FilePath pak_file; - CHECK(base::PathService::Get(FILE_CAST_PAK, &pak_file)); -#if BUILDFLAG(IS_ANDROID) - // On Android, the renderer runs with a different UID and can never access - // the file system. Use the file descriptor passed in at launch time. - auto* global_descriptors = base::GlobalDescriptors::GetInstance(); - int pak_fd = global_descriptors->MaybeGet(kAndroidPakDescriptor); - base::MemoryMappedFile::Region pak_region; - if (pak_fd >= 0) { - pak_region = global_descriptors->GetRegion(kAndroidPakDescriptor); - - base::File android_pak_file(pak_fd); - ui::ResourceBundle::InitSharedInstanceWithPakFileRegion( - android_pak_file.Duplicate(), pak_region); - ui::ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion( - std::move(android_pak_file), pak_region, ui::k100Percent); - return; - } else { - pak_fd = base::android::OpenApkAsset("assets/cast_shell.pak", &pak_region); - // Loaded from disk for browsertests. - if (pak_fd < 0) { - int flags = base::File::FLAG_OPEN | base::File::FLAG_READ; - pak_fd = base::File(pak_file, flags).TakePlatformFile(); - pak_region = base::MemoryMappedFile::Region::kWholeFile; - } - DCHECK_GE(pak_fd, 0); - global_descriptors->Set(kAndroidPakDescriptor, pak_fd, pak_region); - } - - ui::SetLocalePaksStoredInApk(true); -#endif // BUILDFLAG(IS_ANDROID) - - resource_delegate_.reset(new CastResourceDelegate()); - // TODO(gunsch): Use LOAD_COMMON_RESOURCES once ResourceBundle no longer - // hardcodes resource file names. - ui::ResourceBundle::InitSharedInstanceWithLocale( - "en-US", resource_delegate_.get(), - ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES); - -#if BUILDFLAG(IS_ANDROID) - ui::ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion( - base::File(pak_fd), pak_region, ui::kScaleFactorNone); -#else - ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath( - pak_file, ui::kScaleFactorNone); -#endif // BUILDFLAG(IS_ANDROID) -} - -content::ContentClient* CastMainDelegate::CreateContentClient() { - return &content_client_; -} - -content::ContentBrowserClient* CastMainDelegate::CreateContentBrowserClient() { - DCHECK(!cast_feature_list_creator_); - cast_feature_list_creator_ = std::make_unique(); - browser_client_ = - CastContentBrowserClient::Create(cast_feature_list_creator_.get()); - return browser_client_.get(); -} - -content::ContentGpuClient* CastMainDelegate::CreateContentGpuClient() { - gpu_client_ = CastContentGpuClient::Create(); - return gpu_client_.get(); -} - -content::ContentRendererClient* -CastMainDelegate::CreateContentRendererClient() { - renderer_client_ = CastContentRendererClient::Create(); - return renderer_client_.get(); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/app/cast_main_delegate.h chromium-132.0.6834.159/chromecast/app/cast_main_delegate.h --- chromium-132.0.6834.110/chromecast/app/cast_main_delegate.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/cast_main_delegate.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_APP_CAST_MAIN_DELEGATE_H_ -#define CHROMECAST_APP_CAST_MAIN_DELEGATE_H_ - -#include -#include - -#include "build/build_config.h" -#include "chromecast/common/cast_content_client.h" -#include "content/public/app/content_main_delegate.h" - -namespace content { -class BrowserMainRunner; -} // namespace content - -namespace chromecast { - -class CastResourceDelegate; -class CastFeatureListCreator; - -namespace shell { - -class CastContentBrowserClient; -class CastContentGpuClient; -class CastContentRendererClient; - -class CastMainDelegate : public content::ContentMainDelegate { - public: - CastMainDelegate(); - - CastMainDelegate(const CastMainDelegate&) = delete; - CastMainDelegate& operator=(const CastMainDelegate&) = delete; - - ~CastMainDelegate() override; - - // content::ContentMainDelegate implementation: - std::optional BasicStartupComplete() override; - void PreSandboxStartup() override; - absl::variant RunProcess( - const std::string& process_type, - content::MainFunctionParams main_function_params) override; -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - void ZygoteForked() override; -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - bool ShouldCreateFeatureList(InvokedIn invoked_in) override; - bool ShouldInitializeMojo(InvokedIn invoked_in) override; - std::optional PostEarlyInitialization(InvokedIn invoked_in) override; - content::ContentClient* CreateContentClient() override; - content::ContentBrowserClient* CreateContentBrowserClient() override; - content::ContentGpuClient* CreateContentGpuClient() override; - content::ContentRendererClient* CreateContentRendererClient() override; - - private: - void InitializeResourceBundle(); - - std::unique_ptr browser_client_; - std::unique_ptr gpu_client_; - std::unique_ptr renderer_client_; - std::unique_ptr resource_delegate_; - CastContentClient content_client_; - -#if BUILDFLAG(IS_ANDROID) - std::unique_ptr browser_runner_; -#endif // BUILDFLAG(IS_ANDROID) - - std::unique_ptr cast_feature_list_creator_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_APP_CAST_MAIN_DELEGATE_H_ diff -Nru chromium-132.0.6834.110/chromecast/app/cast_test_launcher.cc chromium-132.0.6834.159/chromecast/app/cast_test_launcher.cc --- chromium-132.0.6834.110/chromecast/app/cast_test_launcher.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/cast_test_launcher.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/command_line.h" -#include "base/system/sys_info.h" -#include "base/test/launcher/test_launcher.h" -#include "base/test/test_suite.h" -#include "build/build_config.h" -#include "chromecast/app/cast_main_delegate.h" -#include "content/public/browser/network_service_util.h" -#include "content/public/test/test_launcher.h" -#include "ipc/ipc_channel.h" -#include "mojo/core/embedder/embedder.h" - -#if BUILDFLAG(IS_WIN) -#include "base/win/win_util.h" -#endif // BUILDFLAG(IS_WIN) - -namespace chromecast { -namespace shell { - -class CastTestLauncherDelegate : public content::TestLauncherDelegate { - public: - CastTestLauncherDelegate() {} - - CastTestLauncherDelegate(const CastTestLauncherDelegate&) = delete; - CastTestLauncherDelegate& operator=(const CastTestLauncherDelegate&) = delete; - - ~CastTestLauncherDelegate() override {} - - int RunTestSuite(int argc, char** argv) override { - base::TestSuite test_suite(argc, argv); - // Browser tests are expected not to tear-down various globals . - test_suite.DisableCheckForLeakedGlobals(); - return test_suite.Run(); - } - - protected: -#if !BUILDFLAG(IS_ANDROID) - content::ContentMainDelegate* CreateContentMainDelegate() override { - return new CastMainDelegate(); - } -#endif // BUILDFLAG(IS_ANDROID) -}; - -} // namespace shell -} // namespace chromecast - -int main(int argc, char** argv) { - base::CommandLine::Init(argc, argv); - size_t parallel_jobs = base::NumParallelJobs(/*cores_per_job=*/2); - if (parallel_jobs == 0U) - return 1; - -#if BUILDFLAG(IS_WIN) - // Load and pin user32.dll to avoid having to load it once tests start while - // on the main thread loop where blocking calls are disallowed. - base::win::PinUser32(); -#endif // BUILDFLAG(IS_WIN) - - chromecast::shell::CastTestLauncherDelegate launcher_delegate; - mojo::core::Init(); - content::ForceInProcessNetworkService(); - return content::LaunchTests(&launcher_delegate, parallel_jobs, argc, argv); -} diff -Nru chromium-132.0.6834.110/chromecast/app/linux/cast_crash_reporter_client.cc chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client.cc --- chromium-132.0.6834.110/chromecast/app/linux/cast_crash_reporter_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/app/linux/cast_crash_reporter_client.h" - -#include "base/time/time.h" -#include "chromecast/base/error_codes.h" -#include "chromecast/crash/linux/crash_util.h" -#include "components/crash/core/app/breakpad_linux.h" -#include "content/public/common/content_switches.h" -#include "sandbox/policy/switches.h" - -namespace chromecast { - -namespace { - -uint64_t g_process_start_time_ms = 0u; - -} // namespace - -// static -void CastCrashReporterClient::InitCrashReporter( - const std::string& process_type) { - DCHECK(!g_process_start_time_ms); - g_process_start_time_ms = - (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds(); - - // Start up breakpad for this process, if applicable. - breakpad::InitCrashReporter(process_type); -} - -// static -uint64_t CastCrashReporterClient::GetProcessStartTime() { - return g_process_start_time_ms; -} - -CastCrashReporterClient::CastCrashReporterClient() {} - -CastCrashReporterClient::~CastCrashReporterClient() {} - -bool CastCrashReporterClient::EnableBreakpadForProcess( - const std::string& process_type) { - return process_type == switches::kRendererProcess || - process_type == switches::kZygoteProcess || - process_type == switches::kGpuProcess || - process_type == switches::kUtilityProcess; -} - -bool CastCrashReporterClient::HandleCrashDump(const char* crashdump_filename, - uint64_t crash_pid) { - // Set the initial error code to ERROR_WEB_CONTENT_RENDER_VIEW_GONE to show - // an error message on next cast_shell run. Though the error code is for - // renderer process crash, the actual messages can be used for browser process - // as well. - SetInitialErrorCode(ERROR_WEB_CONTENT_RENDER_VIEW_GONE); - - // Upload crash dump. If user didn't opt-in crash report, minidump writer - // instantiated within CrashUtil::RequestUploadCrashDump() does nothing. - CrashUtil::RequestUploadCrashDump(crashdump_filename, crash_pid, - GetProcessStartTime()); - - // Always return true to indicate that this crash dump has been processed, - // so that it won't fallback to use chrome's default uploader. - return true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/app/linux/cast_crash_reporter_client.h chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client.h --- chromium-132.0.6834.110/chromecast/app/linux/cast_crash_reporter_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_APP_LINUX_CAST_CRASH_REPORTER_CLIENT_H_ -#define CHROMECAST_APP_LINUX_CAST_CRASH_REPORTER_CLIENT_H_ - -#include - -#include - -#include "components/crash/core/app/crash_reporter_client.h" - -namespace chromecast { - -class CastCrashReporterClient : public crash_reporter::CrashReporterClient { - public: - static void InitCrashReporter(const std::string& process_type); - - CastCrashReporterClient(); - - CastCrashReporterClient(const CastCrashReporterClient&) = delete; - CastCrashReporterClient& operator=(const CastCrashReporterClient&) = delete; - - ~CastCrashReporterClient() override; - - // crash_reporter::CrashReporterClient implementation: - bool EnableBreakpadForProcess(const std::string& process_type) override; - bool HandleCrashDump(const char* crashdump_filename, - uint64_t crash_pid) override; - - private: - static uint64_t GetProcessStartTime(); -}; - -} // namespace chromecast - -#endif // CHROMECAST_APP_LINUX_CAST_CRASH_REPORTER_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/app/linux/cast_crash_reporter_client_unittest.cc chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client_unittest.cc --- chromium-132.0.6834.110/chromecast/app/linux/cast_crash_reporter_client_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/linux/cast_crash_reporter_client_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,152 +0,0 @@ -// 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 -#include - -#include "base/base_paths.h" -#include "base/files/file.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/functional/bind.h" -#include "base/test/scoped_path_override.h" -#include "base/threading/scoped_blocking_call.h" -#include "base/threading/thread_restrictions.h" -#include "base/values.h" -#include "chromecast/app/linux/cast_crash_reporter_client.h" -#include "chromecast/base/scoped_temp_file.h" -#include "chromecast/crash/app_state_tracker.h" -#include "chromecast/crash/linux/crash_testing_utils.h" -#include "chromecast/crash/linux/crash_util.h" -#include "chromecast/crash/linux/dump_info.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -const char kFakeDumpstateContents[] = "Dumpstate Contents\nDumpdumpdumpdump\n"; -const char kFakeMinidumpContents[] = "Minidump Contents\nLine1\nLine2\n"; - -int WriteFakeDumpStateFile(const std::string& path) { - // Append the correct extension and write the data to file. - base::File dumpstate(base::FilePath(path).AddExtension(".txt.gz"), - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - dumpstate.Write( - 0, kFakeDumpstateContents, sizeof(kFakeDumpstateContents) - 1); - return 0; -} - -} // namespace - -class CastCrashReporterClientTest : public testing::Test { - public: - CastCrashReporterClientTest(const CastCrashReporterClientTest&) = delete; - CastCrashReporterClientTest& operator=(const CastCrashReporterClientTest&) = - delete; - - protected: - CastCrashReporterClientTest() {} - ~CastCrashReporterClientTest() override {} - - static void SetUpTestCase() { - // Set a callback to be used in place of the |dumpstate| executable. - CrashUtil::SetDumpStateCbForTest(base::BindOnce(&WriteFakeDumpStateFile)); - } - - // testing::Test implementation: - void SetUp() override { - // Override the $HOME path. - ASSERT_TRUE(fake_home_dir_.CreateUniqueTempDir()); - home_override_.reset( - new base::ScopedPathOverride(base::DIR_HOME, home_path())); - - // "Launch" YouTube. - AppStateTracker::SetLastLaunchedApp("youtube"); - AppStateTracker::SetCurrentApp("youtube"); - - // "Launch" and switch to Pandora. - AppStateTracker::SetLastLaunchedApp("pandora"); - AppStateTracker::SetCurrentApp("pandora"); - - // "Launch" Netflix. - AppStateTracker::SetLastLaunchedApp("netflix"); - // Netflix crashed. - - // A minidump file is written. - minidump_.Write(kFakeMinidumpContents); - } - - void TearDown() override { - // Assert that the original file has been moved. - ASSERT_FALSE(base::PathExists(minidump_path())); - - // Assert that the file has been moved to "minidumps", with the expected - // contents. - std::string contents; - base::FilePath new_minidump = - home_path().Append("minidumps").Append(minidump_path().BaseName()); - ASSERT_TRUE(base::PathExists(new_minidump)); - ASSERT_TRUE(base::ReadFileToString(new_minidump, &contents)); - ASSERT_EQ(kFakeMinidumpContents, contents); - - // Assert that the dumpstate file has been written with the expected - // contents. - base::FilePath dumpstate = new_minidump.AddExtension(".txt.gz"); - ASSERT_TRUE(base::PathExists(dumpstate)); - ASSERT_TRUE(base::ReadFileToString(dumpstate, &contents)); - ASSERT_EQ(kFakeDumpstateContents, contents); - - // Assert that the lockfile has logged the correct information. - base::FilePath lockfile = - home_path().Append("minidumps").Append("lockfile"); - ASSERT_TRUE(base::PathExists(lockfile)); - std::vector> dumps; - ASSERT_TRUE(FetchDumps(lockfile.value(), &dumps)); - ASSERT_EQ(1u, dumps.size()); - - const DumpInfo& dump_info = *(dumps[0]); - ASSERT_TRUE(dump_info.valid()); - EXPECT_EQ(new_minidump.value(), dump_info.crashed_process_dump()); - EXPECT_EQ(dumpstate.value(), dump_info.logfile()); - EXPECT_EQ("youtube", dump_info.params().previous_app_name); - EXPECT_EQ("pandora", dump_info.params().current_app_name); - EXPECT_EQ("netflix", dump_info.params().last_app_name); - } - - base::FilePath minidump_path() { return minidump_.path(); } - base::FilePath home_path() { return fake_home_dir_.GetPath(); } - - private: - base::ScopedTempDir fake_home_dir_; - ScopedTempFile minidump_; - std::unique_ptr home_override_; -}; - -TEST_F(CastCrashReporterClientTest, EndToEndTestOnIORestrictedThread) { - // Handle a "crash" on an IO restricted thread. - base::ScopedDisallowBlocking disallow_blocking; - CastCrashReporterClient client; - ASSERT_TRUE(client.HandleCrashDump(minidump_path().value().c_str(), 0)); -} - -TEST_F(CastCrashReporterClientTest, EndToEndTestOnNonIORestrictedThread) { - { - // ScopedBlockingCall will DCHECK if blocking isn't allowed at the beginning - // of this test. - base::ScopedBlockingCall test_blocking_allowed( - FROM_HERE, base::BlockingType::WILL_BLOCK); - } - - // Handle a crash on a non-IO restricted thread. - CastCrashReporterClient client; - ASSERT_TRUE(client.HandleCrashDump(minidump_path().value().c_str(), 0)); - - // Assert that the thread is not IO restricted when the function exits. - { - base::ScopedBlockingCall test_blocking_allowed( - FROM_HERE, base::BlockingType::WILL_BLOCK); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_am.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_am.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_am.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_am.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -am,en-GB,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ar.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ar.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ar.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ar.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ar,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_bg.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_bg.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_bg.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_bg.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -bg-BG,bg - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_bn.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_bn.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_bn.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_bn.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -bn-IN,bn,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ca.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ca.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ca.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ca.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ca-ES,ca - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_cs.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_cs.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_cs.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_cs.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -cs-CZ,cs - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_da.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_da.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_da.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_da.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -da-DK,da,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_de.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_de.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_de.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_de.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -de-DE,de,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_el.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_el.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_el.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_el.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -el-GR,el - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_en-GB.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_en-GB.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_en-GB.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_en-GB.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -en-GB,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_es-419.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_es-419.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_es-419.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_es-419.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -es-419,es - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_es.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_es.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_es.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_es.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -es-ES,es - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_et.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_et.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_et.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_et.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -et-EE,et,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_fa.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fa.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_fa.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fa.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -fa,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_fi.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fi.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_fi.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fi.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -fi-FI,fi,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_fil.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fil.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_fil.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fil.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -fil,fil-PH,tl,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_fr.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fr.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_fr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_fr.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -fr-FR,fr,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_gu.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_gu.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_gu.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_gu.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -gu-IN,gu,hi-IN,hi,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_he.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_he.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_he.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_he.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -he-IL,he,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_hi.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hi.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_hi.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hi.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -hi-IN,hi,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_hr.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hr.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_hr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hr.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -hr-HR,hr,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_hu.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hu.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_hu.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_hu.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -hu-HU,hu,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_id.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_id.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_id.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_id.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -id-ID,id,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_it.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_it.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_it.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_it.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -it-IT,it,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ja.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ja.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ja.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ja.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ja,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_kn.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_kn.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_kn.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_kn.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -kn-IN,kn,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ko.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ko.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ko.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ko.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ko-KR,ko,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_lt.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_lt.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_lt.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_lt.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -lt,en-US,en,ru,pl - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_lv.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_lv.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_lv.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_lv.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -lv-LV,lv,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ml.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ml.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ml.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ml.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ml-IN,ml,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_mr.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_mr.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_mr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_mr.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -mr-IN,mr,hi-IN,hi,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ms.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ms.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ms.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ms.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ms-MY,ms,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_nb.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_nb.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_nb.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_nb.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -nb-NO,nb,no,nn,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_nl.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_nl.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_nl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_nl.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -nl-NL,nl,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_pl.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pl.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_pl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pl.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -pl-PL,pl,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_pt-BR.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pt-BR.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_pt-BR.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pt-BR.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -pt-BR,pt,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_pt-PT.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pt-PT.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_pt-PT.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_pt-PT.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -pt-PT,pt,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ro.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ro.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ro.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ro.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ro-RO,ro,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ru.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ru.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ru.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ru.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ru-RU,ru,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sk.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sk.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sk.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sk.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -sk-SK,sk,cs,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sl.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sl.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sl.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -sl-SI,sl,en-GB,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sr.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sr.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sr.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -sr-RS,sr,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sv.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sv.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sv.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sv.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -sv-SE,sv,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sw.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sw.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_sw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_sw.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -sw,en-GB,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ta.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ta.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_ta.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_ta.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -ta-IN,ta,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_te.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_te.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_te.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_te.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -te-IN,te,hi-IN,hi,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_th.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_th.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_th.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_th.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -th-TH,th - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_tr.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_tr.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_tr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_tr.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -tr-TR,tr,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_uk.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_uk.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_uk.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_uk.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -uk-UA,uk,ru,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_vi.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_vi.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_vi.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_vi.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -vi-VN,vi,fr-FR,fr,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_zh-CN.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_zh-CN.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_zh-CN.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_zh-CN.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -zh-CN,zh - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_zh-TW.xtb chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_zh-TW.xtb --- chromium-132.0.6834.110/chromecast/app/resources/chromecast_settings_zh-TW.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/chromecast_settings_zh-TW.xtb 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ - - - -zh-TW,zh,en-US,en - diff -Nru chromium-132.0.6834.110/chromecast/app/resources/shell_devtools_discovery_page.html chromium-132.0.6834.159/chromecast/app/resources/shell_devtools_discovery_page.html --- chromium-132.0.6834.110/chromecast/app/resources/shell_devtools_discovery_page.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/resources/shell_devtools_discovery_page.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ - - -Cast shell remote debugging - - - - -
Inspectable WebContents
-
- - - -

Help

-
- You may have to select the shield icon in the address bar to establish a connection. - See the help - center for more information. -
- - - Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/app/resources/shell_speaker_icon.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/app/resources/shell_speaker_icon.png differ diff -Nru chromium-132.0.6834.110/chromecast/app/verify_cast_locales.py chromium-132.0.6834.159/chromecast/app/verify_cast_locales.py --- chromium-132.0.6834.110/chromecast/app/verify_cast_locales.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/app/verify_cast_locales.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# Copyright 2017 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Ensures that Chromecast developers are notified of locale changes.""" - -from __future__ import print_function - -import argparse -import sys - -CAST_LOCALES = [ - 'am', 'ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en-GB', 'en-US', - 'es-419', 'es', 'et', 'fa', 'fi', 'fil', 'fr', 'gu', 'he', 'hi', 'hr', 'hu', - 'id', 'it', 'ja', 'kn', 'ko', 'lt', 'lv', 'ml', 'mr', 'ms', 'nb', 'nl', - 'pl', 'pt-BR', 'pt-PT', 'ro', 'ru', 'sk', 'sl', 'sr', 'sv', 'sw', 'ta', - 'te', 'th', 'tr', 'uk', 'vi', 'zh-CN', 'zh-TW' -] - -SUCCESS_RETURN_CODE = 0 -FAILURE_RETURN_CODE = 1 - - -# Chromecast OWNERS need to know if the list of locales used in -# //build/config/locales.gni changes, so that the Chromecast build process -# can be updated accordingly when it does. -# -# This script runs a check to verify that the list of locales maintained in GN -# matches CAST_LOCALES above. If a CL changes that list, it must also change -# CAST_LOCALES in this file to make the Cast trybot pass. This change will -# require adding a //chromecast OWNER to the change, keeping the team aware of -# any locale changes. -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('locales', type=str, nargs='+', - help='Locales from the GN locale list') - parser.add_argument('--stamp-file', '-s', type=str, required=True, - help='The script will stamp this file if successful.') - args = parser.parse_args() - - if set(CAST_LOCALES) == set(args.locales): - open(args.stamp_file, 'w') - return SUCCESS_RETURN_CODE - - # The lists do not match. Compute the difference and log it to the developer. - removed_locales = set(CAST_LOCALES) - set(args.locales) - added_locales = set(args.locales) - set(CAST_LOCALES) - - print('CAST_LOCALES no longer matches the locales list from GN!') - if removed_locales: - print('These locales have been removed: {}'.format(list(removed_locales))) - if added_locales: - print('These locales have been added: {}'.format(list(added_locales))) - print(('Please update CAST_LOCALES in {file} and add a reviewer from ' - '//chromecast/OWNERS to your CL. ').format(file=__file__)) - return FAILURE_RETURN_CODE - - -if __name__ == '__main__': - sys.exit(main()) diff -Nru chromium-132.0.6834.110/chromecast/base/DEPS chromium-132.0.6834.159/chromecast/base/DEPS --- chromium-132.0.6834.110/chromecast/base/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+chromecast/base/jni_headers", - "+chromecast/browser/jni_headers", -] diff -Nru chromium-132.0.6834.110/chromecast/base/OWNERS chromium-132.0.6834.159/chromecast/base/OWNERS --- chromium-132.0.6834.110/chromecast/base/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -per-file BUILD.gn=file://chromecast/android/OWNERS diff -Nru chromium-132.0.6834.110/chromecast/base/alarm_manager.cc chromium-132.0.6834.159/chromecast/base/alarm_manager.cc --- chromium-132.0.6834.110/chromecast/base/alarm_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/alarm_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/alarm_manager.h" - -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/clock.h" -#include "base/time/default_clock.h" - -#define MAKE_SURE_OWN_THREAD(callback, ...) \ - if (!task_runner_->BelongsToCurrentThread()) { \ - task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&AlarmManager::callback, \ - weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); \ - return; \ - } - -namespace chromecast { - -namespace { -int kClockPollInterval = 5; - -void VerifyHandleCallback(base::OnceClosure task, - base::WeakPtr handle) { - if (!handle.get()) { - return; - } - std::move(task).Run(); -} -} // namespace - -AlarmHandle::AlarmHandle() = default; -AlarmHandle::~AlarmHandle() = default; - -AlarmManager::AlarmInfo::AlarmInfo( - base::OnceClosure task, - base::Time time, - scoped_refptr task_runner) - : task_(std::move(task)), - time_(time), - task_runner_(std::move(task_runner)) {} - -AlarmManager::AlarmInfo::~AlarmInfo() {} - -void AlarmManager::AlarmInfo::PostTask() { - task_runner_->PostTask(FROM_HERE, std::move(task_)); -} - -AlarmManager::AlarmManager( - const base::Clock* clock, - scoped_refptr task_runner) - : clock_(clock), - task_runner_(std::move(task_runner)), - weak_factory_(this) { - DCHECK(clock_); - DCHECK(task_runner_); - clock_tick_timer_.SetTaskRunner(task_runner_); - base::TimeDelta polling_frequency = base::Seconds(kClockPollInterval); - clock_tick_timer_.Start(FROM_HERE, polling_frequency, - base::BindRepeating(&AlarmManager::CheckAlarm, - weak_factory_.GetWeakPtr())); -} - -AlarmManager::AlarmManager() - : AlarmManager(base::DefaultClock::GetInstance(), - base::SingleThreadTaskRunner::GetCurrentDefault()) {} - -AlarmManager::~AlarmManager() {} - -std::unique_ptr AlarmManager::PostAlarmTask(base::OnceClosure task, - base::Time time) { - DCHECK(task); - std::unique_ptr handle = std::make_unique(); - AddAlarm(base::BindOnce(&VerifyHandleCallback, std::move(task), - handle->AsWeakPtr()), - time, base::SingleThreadTaskRunner::GetCurrentDefault()); - return handle; -} - -void AlarmManager::AddAlarm( - base::OnceClosure task, - base::Time time, - scoped_refptr task_runner) { - MAKE_SURE_OWN_THREAD(AddAlarm, std::move(task), time, std::move(task_runner)); - next_alarm_.push(std::make_unique(std::move(task), time, - std::move(task_runner))); -} - -void AlarmManager::CheckAlarm() { - DCHECK(task_runner_->BelongsToCurrentThread()); - base::Time now = clock_->Now(); - // Fire appropriate alarms. - while (!next_alarm_.empty() && now >= next_alarm_.top()->time()) { - next_alarm_.top()->PostTask(); - next_alarm_.pop(); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/alarm_manager.h chromium-132.0.6834.159/chromecast/base/alarm_manager.h --- chromium-132.0.6834.110/chromecast/base/alarm_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/alarm_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,132 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_ALARM_MANAGER_H_ -#define CHROMECAST_BASE_ALARM_MANAGER_H_ - -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/raw_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "base/timer/timer.h" - -namespace base { -class Clock; -class SingleThreadTaskRunner; -} - -namespace chromecast { - -// Alarm handle for scoping the in-flight alarm. -class AlarmHandle final { - public: - AlarmHandle(); - ~AlarmHandle(); - - base::WeakPtr AsWeakPtr() { - return weak_ptr_factory_.GetWeakPtr(); - } - - private: - base::WeakPtrFactory weak_ptr_factory_{this}; -}; - -// Alarm manager allows setting a task for wall clock time rather than for an -// elapsed amount of time. This is different from using long PostDelayedTasks -// that are sensitive to time changes, clock drift, and other factors. -// -// Alarm manager polls the wall clock time every 5 seconds. If the clock is -// equal or past the requested time, the alarm will fire. -class AlarmManager { - public: - // Construct and start the alarm manager. The clock poller will run on the - // caller's thread. - AlarmManager(); - - AlarmManager(const AlarmManager&) = delete; - AlarmManager& operator=(const AlarmManager&) = delete; - - ~AlarmManager(); - - // For testing only. Allows setting a fake clock and using a custom task - // runner. - AlarmManager(const base::Clock* clock, - scoped_refptr task_runner); - - // Add an alarm. - // |task| will be executed at around |time|. - // Returns an AlarmHandle that must be kept alive. If the AlarmHandle is - // destroyed, the alarm will not fire. - // - // Any thread can add alarms. The alarm will be fired on the original - // thread used to set the alarm. - // - // When an alarm is added to the alarm manager, the task is guaranteed to not - // run before the clock passes the requested time. The task may not run even - // if it is past the requested time if the software is suspended. However, - // once woken up, the event will fire within 5 seconds if the target time has - // passed. - [[nodiscard]] std::unique_ptr PostAlarmTask( - base::OnceClosure task, - base::Time time); - - private: - class AlarmInfo { - public: - AlarmInfo(base::OnceClosure task, - base::Time time, - scoped_refptr task_runner); - - AlarmInfo(const AlarmInfo&) = delete; - AlarmInfo& operator=(const AlarmInfo&) = delete; - - ~AlarmInfo(); - - void PostTask(); - - base::Time time() const { return time_; } - - private: - base::OnceClosure task_; - const base::Time time_; - const scoped_refptr task_runner_; - }; - - // Check if an alarm should fire. - void CheckAlarm(); - // Add the alarm to the queue. - void AddAlarm(base::OnceClosure task, - base::Time time, - scoped_refptr task_runner); - - // Ordering alarms by earliest time. - struct alarm_compare { - bool operator()(const std::unique_ptr& lhs, - const std::unique_ptr& rhs) const { - return lhs->time() > rhs->time(); - } - }; - - // Store a list of the alarms to fire with the earliest getting priority. - std::priority_queue, - std::vector>, - alarm_compare> - next_alarm_; - - // Poller for wall clock time. - const raw_ptr clock_; - base::RepeatingTimer clock_tick_timer_; - scoped_refptr task_runner_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_ALARM_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/alarm_manager_unittest.cc chromium-132.0.6834.159/chromecast/base/alarm_manager_unittest.cc --- chromium-132.0.6834.110/chromecast/base/alarm_manager_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/alarm_manager_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,497 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/alarm_manager.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/simple_test_clock.h" -#include "base/test/task_environment.h" -#include "base/time/clock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -class AlarmManagerTest : public ::testing::Test { - protected: - class WallClockDependantTask { - public: - WallClockDependantTask() : fired_(false), weak_factory_(this) {} - base::WeakPtr GetWeakPtr() { - return weak_factory_.GetWeakPtr(); - } - void OnAlarmFire() { fired_ = true; } - bool fired_; - base::WeakPtrFactory weak_factory_; - }; - - base::test::SingleThreadTaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; -}; - -TEST_F(AlarmManagerTest, AlarmNotFire) { - WallClockDependantTask task; - ASSERT_FALSE(task.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - base::Time alarm_time = now + base::Minutes(10); - std::unique_ptr handle(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), - alarm_time)); - task_environment_.FastForwardBy(base::Minutes(9)); - clock->Advance(base::Minutes(9)); - task_environment_.RunUntilIdle(); - ASSERT_FALSE(task.fired_); -} - -TEST_F(AlarmManagerTest, AlarmFire) { - WallClockDependantTask task; - ASSERT_FALSE(task.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add an alarm. - base::Time alarm_time = now + base::Minutes(10); - std::unique_ptr handle(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), - alarm_time)); - clock->Advance(base::Minutes(10)); - task_environment_.FastForwardBy(base::Minutes(10)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task.fired_); - - // Fires only once. - task.fired_ = false; - clock->Advance(base::Minutes(10)); - task_environment_.FastForwardBy(base::Minutes(10)); - task_environment_.RunUntilIdle(); - ASSERT_FALSE(task.fired_); -} - -TEST_F(AlarmManagerTest, AlarmPast) { - WallClockDependantTask task; - ASSERT_FALSE(task.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - std::unique_ptr manager = std::make_unique( - test_clock.get(), base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add an alarm in the past. Should fire right away. - base::Time alarm_time = base::Time::Now() - base::Minutes(10); - std::unique_ptr handle(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), - alarm_time)); - task_environment_.FastForwardBy(base::Seconds(10)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task.fired_); -} - -TEST_F(AlarmManagerTest, AlarmTimeJump) { - WallClockDependantTask task; - ASSERT_FALSE(task.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add an alarm. The time jumps to the future. - base::Time alarm_time = now + base::Minutes(10); - std::unique_ptr handle(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), - alarm_time)); - clock->Advance(base::Minutes(10)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task.fired_); -} - -TEST_F(AlarmManagerTest, AlarmJumpFuture) { - WallClockDependantTask task; - ASSERT_FALSE(task.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add an alarm. The time jumps far into the future. - base::Time alarm_time = now + base::Minutes(10); - std::unique_ptr handle(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), - alarm_time)); - clock->Advance(base::Minutes(60)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task.fired_); -} - -TEST_F(AlarmManagerTest, AlarmMultiple) { - WallClockDependantTask task1; - WallClockDependantTask task2; - ASSERT_FALSE(task1.fired_); - ASSERT_FALSE(task2.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add first task. - base::Time alarm_time = now + base::Minutes(10); - std::unique_ptr handle1(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), - alarm_time)); - - // Add second task. - alarm_time = now + base::Minutes(12); - std::unique_ptr handle2(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), - alarm_time)); - - // First task should fire. - clock->Advance(base::Minutes(10)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task1.fired_); - ASSERT_FALSE(task2.fired_); - - // Reset state; - task1.fired_ = false; - task2.fired_ = false; - - // Second task should fire. - clock->Advance(base::Minutes(2)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_FALSE(task1.fired_); - ASSERT_TRUE(task2.fired_); -} - -TEST_F(AlarmManagerTest, AlarmMultipleReverseOrder) { - WallClockDependantTask task1; - WallClockDependantTask task2; - ASSERT_FALSE(task1.fired_); - ASSERT_FALSE(task2.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add first task. - base::Time alarm_time = now + base::Minutes(12); - std::unique_ptr handle1(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), - alarm_time)); - - // Add second task. - alarm_time = now + base::Minutes(10); - std::unique_ptr handle2(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), - alarm_time)); - - // Second task should fire. - clock->Advance(base::Minutes(10)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_FALSE(task1.fired_); - ASSERT_TRUE(task2.fired_); - - // Reset state; - task1.fired_ = false; - task2.fired_ = false; - - // First task should fire. - clock->Advance(base::Minutes(2)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task1.fired_); - ASSERT_FALSE(task2.fired_); -} - -TEST_F(AlarmManagerTest, AlarmMultipleSameTime) { - WallClockDependantTask task1; - WallClockDependantTask task2; - WallClockDependantTask task3; - ASSERT_FALSE(task1.fired_); - ASSERT_FALSE(task2.fired_); - ASSERT_FALSE(task3.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add first task. - base::Time alarm_time = now + base::Minutes(12); - std::unique_ptr handle1(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), - alarm_time)); - - // Add second task. - alarm_time = now + base::Minutes(16); - std::unique_ptr handle2(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), - alarm_time)); - - // Add third task. - alarm_time = now + base::Minutes(12); - std::unique_ptr handle3(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task3.GetWeakPtr()), - alarm_time)); - - // First and third task should fire. - clock->Advance(base::Minutes(12)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task1.fired_); - ASSERT_FALSE(task2.fired_); - ASSERT_TRUE(task3.fired_); -} - -TEST_F(AlarmManagerTest, AlarmMultipleShuffle) { - WallClockDependantTask task1; - WallClockDependantTask task2; - WallClockDependantTask task3; - ASSERT_FALSE(task1.fired_); - ASSERT_FALSE(task2.fired_); - ASSERT_FALSE(task3.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add first task. - base::Time alarm_time = now + base::Minutes(15); - std::unique_ptr handle1(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), - alarm_time)); - - // Add second task. - alarm_time = now + base::Minutes(16); - std::unique_ptr handle2(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), - alarm_time)); - - // Add third task. - alarm_time = now + base::Minutes(11); - std::unique_ptr handle3(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task3.GetWeakPtr()), - alarm_time)); - - // Third task should fire. - clock->Advance(base::Minutes(12)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_FALSE(task1.fired_); - ASSERT_FALSE(task2.fired_); - ASSERT_TRUE(task3.fired_); - - clock->Advance(base::Minutes(3)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task1.fired_); - ASSERT_FALSE(task2.fired_); - ASSERT_TRUE(task3.fired_); -} - -TEST_F(AlarmManagerTest, AlarmTwice) { - WallClockDependantTask task1; - WallClockDependantTask task2; - ASSERT_FALSE(task1.fired_); - ASSERT_FALSE(task2.fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add first task. - base::Time alarm_time = now + base::Minutes(15); - std::unique_ptr handle1(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), - alarm_time)); - - // Add it again with less time. - alarm_time = now + base::Minutes(1); - std::unique_ptr handle2(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), - alarm_time)); - - // Add second task. - alarm_time = now + base::Minutes(16); - std::unique_ptr handle3(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), - alarm_time)); - - // First task should fire. - clock->Advance(base::Minutes(1)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task1.fired_); - ASSERT_FALSE(task2.fired_); - - task1.fired_ = false; - task2.fired_ = false; - - // First task should fire again because it was added twice. - clock->Advance(base::Minutes(14)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(task1.fired_); - ASSERT_FALSE(task2.fired_); -} - -TEST_F(AlarmManagerTest, AlarmCancel) { - std::unique_ptr task1 = - std::make_unique(); - std::unique_ptr task2 = - std::make_unique(); - std::unique_ptr task3 = - std::make_unique(); - ASSERT_FALSE(task1->fired_); - ASSERT_FALSE(task2->fired_); - ASSERT_FALSE(task3->fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add first task. - base::Time alarm_time = now + base::Minutes(12); - std::unique_ptr handle1(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1->GetWeakPtr()), - alarm_time)); - - // Add second task. - alarm_time = now + base::Minutes(16); - std::unique_ptr handle2(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2->GetWeakPtr()), - alarm_time)); - - // Add third task. - alarm_time = now + base::Minutes(12); - std::unique_ptr handle3(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task3->GetWeakPtr()), - alarm_time)); - - // Remove the first task. - task1.reset(nullptr); - - // Third task should fire. - clock->Advance(base::Minutes(15)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_FALSE(task2->fired_); - ASSERT_TRUE(task3->fired_); -} - -TEST_F(AlarmManagerTest, AlarmDeleteHandle) { - std::unique_ptr task1 = - std::make_unique(); - std::unique_ptr task2 = - std::make_unique(); - std::unique_ptr task3 = - std::make_unique(); - ASSERT_FALSE(task1->fired_); - ASSERT_FALSE(task2->fired_); - ASSERT_FALSE(task3->fired_); - - // Create the AlarmManager. - base::Time now = base::Time::Now(); - std::unique_ptr test_clock = - std::make_unique(); - test_clock->SetNow(now); - base::SimpleTestClock* clock = test_clock.get(); - std::unique_ptr manager = std::make_unique( - clock, base::SingleThreadTaskRunner::GetCurrentDefault()); - - // Add first task. - base::Time alarm_time = now + base::Minutes(12); - std::unique_ptr handle1(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1->GetWeakPtr()), - alarm_time)); - - // Add second task. - alarm_time = now + base::Minutes(16); - std::unique_ptr handle2(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2->GetWeakPtr()), - alarm_time)); - - // Add third task. - alarm_time = now + base::Minutes(12); - std::unique_ptr handle3(manager->PostAlarmTask( - base::BindOnce(&WallClockDependantTask::OnAlarmFire, task3->GetWeakPtr()), - alarm_time)); - - // Delete the first task's handle. - handle1.reset(); - - // Third task should fire. - clock->Advance(base::Minutes(15)); - task_environment_.FastForwardBy(base::Minutes(1)); - task_environment_.RunUntilIdle(); - ASSERT_FALSE(task1->fired_); - ASSERT_FALSE(task2->fired_); - ASSERT_TRUE(task3->fired_); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/android/OWNERS chromium-132.0.6834.159/chromecast/base/android/OWNERS --- chromium-132.0.6834.110/chromecast/base/android/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/android/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -file://chromecast/android/OWNERS diff -Nru chromium-132.0.6834.110/chromecast/base/android/dumpstate_writer.cc chromium-132.0.6834.159/chromecast/base/android/dumpstate_writer.cc --- chromium-132.0.6834.110/chromecast/base/android/dumpstate_writer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/android/dumpstate_writer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// 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 "chromecast/base/android/dumpstate_writer.h" - -#include "base/android/jni_android.h" -#include "base/android/jni_string.h" - -// Must come after all headers that specialize FromJniType() / ToJniType(). -#include "chromecast/base/jni_headers/DumpstateWriter_jni.h" - -namespace chromecast { - -// static -void DumpstateWriter::AddDumpValue(const std::string& name, - const std::string& value) { - JNIEnv* env = base::android::AttachCurrentThread(); - Java_DumpstateWriter_addDumpValue( - env, base::android::ConvertUTF8ToJavaString(env, name), - base::android::ConvertUTF8ToJavaString(env, value)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/android/dumpstate_writer.h chromium-132.0.6834.159/chromecast/base/android/dumpstate_writer.h --- chromium-132.0.6834.110/chromecast/base/android/dumpstate_writer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/android/dumpstate_writer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_ANDROID_DUMPSTATE_WRITER_H_ -#define CHROMECAST_BASE_ANDROID_DUMPSTATE_WRITER_H_ - -#include - -#include - -namespace chromecast { - -// JNI wrapper for DumpstateWriter.java. -class DumpstateWriter { - public: - DumpstateWriter() = delete; - DumpstateWriter(const DumpstateWriter&) = delete; - DumpstateWriter& operator=(const DumpstateWriter&) = delete; - - static void AddDumpValue(const std::string& name, const std::string& value); -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_ANDROID_DUMPSTATE_WRITER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/android/system_time_change_notifier_android.cc chromium-132.0.6834.159/chromecast/base/android/system_time_change_notifier_android.cc --- chromium-132.0.6834.110/chromecast/base/android/system_time_change_notifier_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/android/system_time_change_notifier_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// 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 "chromecast/base/android/system_time_change_notifier_android.h" - -// Must come after all headers that specialize FromJniType() / ToJniType(). -#include "chromecast/base/jni_headers/SystemTimeChangeNotifierAndroid_jni.h" - -using jni_zero::JavaParamRef; - -namespace chromecast { - -SystemTimeChangeNotifierAndroid::SystemTimeChangeNotifierAndroid() { - JNIEnv* env = jni_zero::AttachCurrentThread(); - java_notifier_.Reset(Java_SystemTimeChangeNotifierAndroid_create(env)); - Java_SystemTimeChangeNotifierAndroid_initializeFromNative( - env, java_notifier_, reinterpret_cast(this)); -} - -SystemTimeChangeNotifierAndroid::~SystemTimeChangeNotifierAndroid() { - JNIEnv* env = jni_zero::AttachCurrentThread(); - Java_SystemTimeChangeNotifierAndroid_finalizeFromNative(env, java_notifier_); -} - -void SystemTimeChangeNotifierAndroid::OnTimeChanged( - JNIEnv* env, - const JavaParamRef& jobj) { - NotifySystemTimeChanged(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/android/system_time_change_notifier_android.h chromium-132.0.6834.159/chromecast/base/android/system_time_change_notifier_android.h --- chromium-132.0.6834.110/chromecast/base/android/system_time_change_notifier_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/android/system_time_change_notifier_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_ANDROID_SYSTEM_TIME_CHANGE_NOTIFIER_ANDROID_H_ -#define CHROMECAST_BASE_ANDROID_SYSTEM_TIME_CHANGE_NOTIFIER_ANDROID_H_ - -#include "base/android/scoped_java_ref.h" -#include "chromecast/base/system_time_change_notifier.h" - -namespace chromecast { - -class SystemTimeChangeNotifierAndroid : public SystemTimeChangeNotifier { - public: - SystemTimeChangeNotifierAndroid(); - - SystemTimeChangeNotifierAndroid(const SystemTimeChangeNotifierAndroid&) = - delete; - SystemTimeChangeNotifierAndroid& operator=( - const SystemTimeChangeNotifierAndroid&) = delete; - - ~SystemTimeChangeNotifierAndroid() override; - - // Called from Java. - void OnTimeChanged(JNIEnv* env, - const base::android::JavaParamRef& jobj); - - private: - base::android::ScopedJavaGlobalRef java_notifier_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_ANDROID_SYSTEM_TIME_CHANGE_NOTIFIER_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/bind_to_task_runner.h chromium-132.0.6834.159/chromecast/base/bind_to_task_runner.h --- chromium-132.0.6834.110/chromecast/base/bind_to_task_runner.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/bind_to_task_runner.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_BIND_TO_TASK_RUNNER_H_ -#define CHROMECAST_BASE_BIND_TO_TASK_RUNNER_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/location.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" - -// Helpers for using base::BindPostTask() with the TaskRunner for the current -// sequence, ie. base::SequencedTaskRunner::GetCurrentDefault(), or current -// thread, ie, base::SingleThreadTaskRunner::GetCurrentDefault(). -namespace chromecast { - -template -base::OnceCallback BindToCurrentThread( - base::OnceCallback callback, - const base::Location& location = FROM_HERE) { - return base::BindPostTask(base::SingleThreadTaskRunner::GetCurrentDefault(), - std::move(callback), location); -} - -template -base::RepeatingCallback BindToCurrentThread( - base::RepeatingCallback callback, - const base::Location& location = FROM_HERE) { - return base::BindPostTask(base::SingleThreadTaskRunner::GetCurrentDefault(), - std::move(callback), location); -} - -template -base::OnceCallback BindToCurrentSequence( - base::OnceCallback callback, - const base::Location& location = FROM_HERE) { - return base::BindPostTaskToCurrentDefault(std::move(callback), location); -} - -template -base::RepeatingCallback BindToCurrentSequence( - base::RepeatingCallback callback, - const base::Location& location = FROM_HERE) { - return base::BindPostTaskToCurrentDefault(std::move(callback), location); -} - -} // namespace chromecast - -#endif // CHROMECAST_BASE_BIND_TO_TASK_RUNNER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/bitstream_audio_codecs.cc chromium-132.0.6834.159/chromecast/base/bitstream_audio_codecs.cc --- chromium-132.0.6834.110/chromecast/base/bitstream_audio_codecs.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/bitstream_audio_codecs.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,85 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/bitstream_audio_codecs.h" - -#include -#include - -#include "base/strings/strcat.h" -#include "base/strings/string_util.h" - -namespace chromecast { - -namespace { - -const char* BitstreamAudioCodecToString(int codec) { - switch (codec) { - case kBitstreamAudioCodecNone: - return "None"; - case kBitstreamAudioCodecAc3: - return "AC3"; - case kBitstreamAudioCodecDts: - return "DTS"; - case kBitstreamAudioCodecDtsHd: - return "DTS-HD"; - case kBitstreamAudioCodecEac3: - return "EAC3"; - case kBitstreamAudioCodecPcmSurround: - return "PCM"; - case kBitstreamAudioCodecMpegHAudio: - return "MPEG-H Audio"; - default: - return ""; - } -} - -} // namespace - -BitstreamAudioCodecsInfo BitstreamAudioCodecsInfo::operator&( - const BitstreamAudioCodecsInfo& other) const { - return BitstreamAudioCodecsInfo{codecs & other.codecs, - spatial_rendering & other.spatial_rendering}; -} - -bool BitstreamAudioCodecsInfo::operator==( - const BitstreamAudioCodecsInfo& other) const { - return codecs == other.codecs && spatial_rendering == other.spatial_rendering; -} - -bool BitstreamAudioCodecsInfo::operator!=( - const BitstreamAudioCodecsInfo& other) const { - return !(*this == other); -} - -BitstreamAudioCodecsInfo BitstreamAudioCodecsInfo::ApplyCodecMask( - int mask) const { - return BitstreamAudioCodecsInfo{codecs & mask, spatial_rendering & mask}; -} - -std::string BitstreamAudioCodecsToString(int codecs) { - std::string codec_string = BitstreamAudioCodecToString(codecs); - if (!codec_string.empty()) { - return codec_string; - } - std::vector codec_strings; - for (int codec : - {kBitstreamAudioCodecAc3, kBitstreamAudioCodecDts, - kBitstreamAudioCodecDtsHd, kBitstreamAudioCodecEac3, - kBitstreamAudioCodecPcmSurround, kBitstreamAudioCodecMpegHAudio}) { - if ((codec & codecs) != 0) { - codec_strings.push_back(BitstreamAudioCodecToString(codec)); - } - } - return "[" + base::JoinString(codec_strings, ", ") + "]"; -} - -std::string BitstreamAudioCodecsInfoToString( - const BitstreamAudioCodecsInfo& info) { - return base::StrCat({"[codecs]", BitstreamAudioCodecsToString(info.codecs), - "[spatial_rendering]", - BitstreamAudioCodecsToString(info.spatial_rendering)}); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/bitstream_audio_codecs.h chromium-132.0.6834.159/chromecast/base/bitstream_audio_codecs.h --- chromium-132.0.6834.110/chromecast/base/bitstream_audio_codecs.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/bitstream_audio_codecs.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_BITSTREAM_AUDIO_CODECS_H_ -#define CHROMECAST_BASE_BITSTREAM_AUDIO_CODECS_H_ - -#include - -namespace chromecast { - -constexpr int kBitstreamAudioCodecNone = 0b000000; -constexpr int kBitstreamAudioCodecAc3 = 0b000001; -constexpr int kBitstreamAudioCodecDts = 0b000010; -constexpr int kBitstreamAudioCodecDtsHd = 0b000100; -constexpr int kBitstreamAudioCodecEac3 = 0b001000; -constexpr int kBitstreamAudioCodecPcmSurround = 0b010000; -constexpr int kBitstreamAudioCodecMpegHAudio = 0b100000; -constexpr int kBitstreamAudioCodecDtsXP2 = 0b1000000; -constexpr int kBitstreamAudioCodecAll = 0b1111111; - -// Supported bitstream audio codecs and their associated properties. -struct BitstreamAudioCodecsInfo { - // Bitmap of supported bitstream audio codecs. - int codecs = kBitstreamAudioCodecNone; - - // Bitmap specifying which of the corresponding codecs in |codecs| support - // spatial rendering. - int spatial_rendering = kBitstreamAudioCodecNone; - - BitstreamAudioCodecsInfo operator&( - const BitstreamAudioCodecsInfo& other) const; - - bool operator==(const BitstreamAudioCodecsInfo& other) const; - bool operator!=(const BitstreamAudioCodecsInfo& other) const; - - BitstreamAudioCodecsInfo ApplyCodecMask(int mask) const; -}; - -std::string BitstreamAudioCodecsToString(int codecs); -std::string BitstreamAudioCodecsInfoToString( - const BitstreamAudioCodecsInfo& info); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_BITSTREAM_AUDIO_CODECS_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/cast_constants.cc chromium-132.0.6834.159/chromecast/base/cast_constants.cc --- chromium-132.0.6834.110/chromecast/base/cast_constants.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_constants.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/cast_constants.h" - -namespace chromecast { - -const char kChromeResourceScheme[] = "chrome-resource"; - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_constants.h chromium-132.0.6834.159/chromecast/base/cast_constants.h --- chromium-132.0.6834.110/chromecast/base/cast_constants.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_constants.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_CAST_CONSTANTS_H_ -#define CHROMECAST_BASE_CAST_CONSTANTS_H_ - -namespace chromecast { - -extern const char kChromeResourceScheme[]; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_CAST_CONSTANTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/cast_features.cc chromium-132.0.6834.159/chromecast/base/cast_features.cc --- chromium-132.0.6834.110/chromecast/base/cast_features.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_features.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,357 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/cast_features.h" - -#include -#include - -#include "base/command_line.h" -#include "base/containers/contains.h" -#include "base/feature_list.h" -#include "base/metrics/field_trial.h" -#include "base/metrics/field_trial_param_associator.h" -#include "base/metrics/field_trial_params.h" -#include "base/no_destructor.h" -#include "base/strings/string_number_conversions.h" -#include "base/values.h" -#include "build/build_config.h" - -namespace chromecast { -namespace { - -// The name of the default group to use for Cast DCS features. -const char kDefaultDCSFeaturesGroup[] = "default_dcs_features_group"; - -std::unordered_set& GetExperimentIds() { - static base::NoDestructor> g_experiment_ids; - return *g_experiment_ids; -} - -bool g_experiment_ids_initialized = false; - -// The collection of features that have been registered by unit tests -std::vector& GetTestFeatures() { - static base::NoDestructor> - features_for_test; - return *features_for_test; -} - -void SetExperimentIds(const base::Value::List& list) { - DCHECK(!g_experiment_ids_initialized); - std::unordered_set ids; - for (const auto& it : list) { - if (it.is_int()) { - ids.insert(it.GetInt()); - } else { - LOG(ERROR) << "Non-integer value found in experiment id list!"; - } - } - GetExperimentIds().swap(ids); - g_experiment_ids_initialized = true; -} - -} // namespace - -// PLEASE READ! -// Cast Platform Features are listed below. These features may be -// toggled via configs fetched from DCS for devices in the field, or via -// command-line flags set by the developer. For the end-to-end details of the -// system design, please see go/dcs-experiments. -// -// Below are useful steps on how to use these features in your code. -// -// 1) Declaring and defining the feature. -// All Cast Platform Features should be declared in a common file with other -// Cast Platform Features (ex. chromecast/base/cast_features.h). When -// defining your feature, you will need to assign a default value. This is -// the value that the feature will hold until overriden by the server or the -// command line. Here's an exmaple: -// -// BASE_FEATURE(kSuperSecretSauce, "SuperSecretSauce", -// base::FEATURE_DISABLED_BY_DEFAULT); -// -// IMPORTANT NOTE: -// The first parameter that you pass in the definition is the feature's name. -// This MUST match the DCS experiment key for this feature. -// -// While Features elsewhere in Chromium alternatively use dashed-case or -// PascalCase for their names, Chromecast features should use snake_case -// (lowercase letters separated by underscores). This will ensure that DCS -// configs, which are passed around as JSON, remain conformant and readable. -// -// 2) Using the feature in client code. -// Using these features in your code is easy. Here's an example: -// -// #include “base/feature_list.h” -// #include “chromecast/base/chromecast_switches.h” -// -// std::unique_ptr CreateFoo() { -// if (base::FeatureList::IsEnabled(kSuperSecretSauce)) -// return std::make_unique(); -// return std::make_unique(); -// } -// -// base::FeatureList can be called from any thread, in any process, at any -// time after PreCreateThreads(). It will return whether the feature is -// enabled. -// -// 3) Overriding the default value from the server. -// For devices in the field, DCS will issue different configs to different -// groups of devices, allowing us to run experiments on features. These -// feature settings will manifest on the next boot of cast_shell. In the -// example, if the latest config for a particular device set the value of -// kSuperSecretSauce to true, the appropriate code path would be taken. -// Otherwise, the default value, false, would be used. For more details on -// setting up experiments, see go/dcs-launch. -// -// 4) Overriding the default and server values from the command-line. -// While the server value trumps the default values, the command line trumps -// both. Enable features by passing this command line arg to cast_shell: -// -// --enable-features=enable_foo,enable_super_secret_sauce -// -// Features are separated by commas. Disable features by passing: -// -// --disable-features=enable_foo,enable_bar -// -// 5) If you add a new feature to the system you must include it in kFeatures -// This is because the system relies on knowing all of the features so -// it can properly iterate over all features to detect changes. -// - -// Begin Chromecast Feature definitions. - -// Allows applications to access media capture devices (webcams/microphones) -// through getUserMedia API. -BASE_FEATURE(kAllowUserMediaAccess, - "allow_user_media_access", - base::FEATURE_DISABLED_BY_DEFAULT); -// Enables the use of QUIC in Cast-specific NetworkContexts. See -// chromecast/browser/cast_network_contexts.cc for usage. -BASE_FEATURE(kEnableQuic, "enable_quic", base::FEATURE_DISABLED_BY_DEFAULT); -// Enables triple-buffer 720p graphics (overriding default graphics buffer -// settings for a platform). -BASE_FEATURE(kTripleBuffer720, - "enable_triple_buffer_720", - base::FEATURE_DISABLED_BY_DEFAULT); -// Enables single-buffered graphics (overriding default graphics buffer -// settings and takes precedence over triple-buffer feature). -BASE_FEATURE(kSingleBuffer, - "enable_single_buffer", - base::FEATURE_DISABLED_BY_DEFAULT); -// Disable idle sockets closing on memory pressure. See -// chromecast/browser/cast_network_contexts.cc for usage. -BASE_FEATURE(kDisableIdleSocketsCloseOnMemoryPressure, - "disable_idle_sockets_close_on_memory_pressure", - base::FEATURE_DISABLED_BY_DEFAULT); - -BASE_FEATURE(kEnableGeneralAudienceBrowsing, - "enable_general_audience_browsing", - base::FEATURE_DISABLED_BY_DEFAULT); - -BASE_FEATURE(kEnableSideGesturePassThrough, - "enable_side_gesture_pass_through", - base::FEATURE_DISABLED_BY_DEFAULT); - -// Uses AudioManagerAndroid, instead of CastAudioManagerAndroid. This will -// disable lots of Cast features, so it should only be used for development and -// testing. -BASE_FEATURE(kEnableChromeAudioManagerAndroid, - "enable_chrome_audio_manager_android", - base::FEATURE_DISABLED_BY_DEFAULT); - -// Enables CastAudioOutputDevice for audio output on Android. When disabled, -// CastAudioManagerAndroid will be used. -BASE_FEATURE(kEnableCastAudioOutputDevice, - "enable_cast_audio_output_device", - base::FEATURE_DISABLED_BY_DEFAULT); - -// End Chromecast Feature definitions. -const base::Feature* kFeatures[] = { - &kAllowUserMediaAccess, - &kEnableQuic, - &kTripleBuffer720, - &kSingleBuffer, - &kDisableIdleSocketsCloseOnMemoryPressure, - &kEnableGeneralAudienceBrowsing, - &kEnableSideGesturePassThrough, - &kEnableChromeAudioManagerAndroid, - &kEnableCastAudioOutputDevice, -}; - -std::vector GetInternalFeatures(); - -const std::vector& GetFeatures() { - static const base::NoDestructor> features( - [] { - std::vector features(std::begin(kFeatures), - std::end(kFeatures)); - auto internal_features = GetInternalFeatures(); - features.insert(features.end(), internal_features.begin(), - internal_features.end()); - return features; - }()); - if (GetTestFeatures().size() > 0) - return GetTestFeatures(); - return *features; -} - -void InitializeFeatureList(const base::Value::Dict& dcs_features, - const base::Value::List& dcs_experiment_ids, - const std::string& cmd_line_enable_features, - const std::string& cmd_line_disable_features, - const std::string& extra_enable_features, - const std::string& extra_disable_features) { - DCHECK(!base::FeatureList::GetInstance()); - - // Set the experiments. - SetExperimentIds(dcs_experiment_ids); - - std::string all_enable_features = - cmd_line_enable_features + "," + extra_enable_features; - std::string all_disable_features = - cmd_line_disable_features + "," + extra_disable_features; - - // Initialize the FeatureList from the command line. - auto feature_list = std::make_unique(); - feature_list->InitFromCommandLine(all_enable_features, all_disable_features); - - // Override defaults from the DCS config. - for (const auto kv : dcs_features) { - // Each feature must have its own FieldTrial object. Since experiments are - // controlled server-side for Chromecast, and this class is designed with a - // client-side experimentation framework in mind, these parameters are - // carefully chosen: - // - The field trial name is unused for our purposes. However, we need to - // maintain a 1:1 mapping with Features in order to properly store and - // access parameters associated with each Feature. Therefore, use the - // Feature's name as the FieldTrial name to ensure uniqueness. - // - We don't care about the group_id. - // - const std::string& feature_name = kv.first; - auto* field_trial = base::FieldTrialList::CreateFieldTrial( - feature_name, kDefaultDCSFeaturesGroup); - - // |field_trial| is null only if the trial has already been forced to - // another group. This shouldn't happen, unless we've processed a - // --force-fieldtrial commandline argument that overrides this to some other - // group. - if (!field_trial) { - LOG(ERROR) << "A trial was already created for a DCS feature: " - << feature_name; - continue; - } - - if (kv.second.is_bool()) { - // A boolean entry simply either enables or disables a feature. - feature_list->RegisterFieldTrialOverride( - feature_name, - kv.second.GetBool() ? base::FeatureList::OVERRIDE_ENABLE_FEATURE - : base::FeatureList::OVERRIDE_DISABLE_FEATURE, - field_trial); - continue; - } - - if (kv.second.is_dict()) { - // A dictionary entry implies that the feature is enabled. - feature_list->RegisterFieldTrialOverride( - feature_name, base::FeatureList::OVERRIDE_ENABLE_FEATURE, - field_trial); - - // If the feature has not been overriden from the command line, set its - // parameters accordingly. - if (!feature_list->IsFeatureOverriddenFromCommandLine( - feature_name, base::FeatureList::OVERRIDE_DISABLE_FEATURE)) { - // Build a map of the FieldTrial parameters and associate it to the - // FieldTrial. - base::FieldTrialParams params; - for (const auto params_kv : kv.second.GetDict()) { - if (params_kv.second.is_string()) { - params[params_kv.first] = params_kv.second.GetString(); - } else { - LOG(ERROR) << "Entry in params dict for \"" << feature_name << "\"" - << " feature is not a string. Skipping."; - } - } - - // Register the params, so that they can be queried by client code. - bool success = base::AssociateFieldTrialParams( - feature_name, kDefaultDCSFeaturesGroup, params); - DCHECK(success); - } - continue; - } - - // Other base::Value types are not supported. - LOG(ERROR) << "A DCS feature mapped to an unsupported value. key: " - << feature_name << " type: " << kv.second.type(); - } - - base::FeatureList::SetInstance(std::move(feature_list)); -} - -bool IsFeatureEnabled(const base::Feature& feature) { - DCHECK(base::Contains(GetFeatures(), &feature)) << feature.name; - return base::FeatureList::IsEnabled(feature); -} - -base::Value::Dict GetOverriddenFeaturesForStorage( - const base::Value::Dict& features) { - base::Value::Dict persistent_dict; - - // |features| maps feature names to either a boolean or a dict of params. - for (const auto feature : features) { - if (feature.second.is_bool()) { - persistent_dict.Set(feature.first, feature.second.GetBool()); - continue; - } - - if (feature.second.is_dict()) { - const base::Value* params_dict = &feature.second; - base::Value::Dict params; - - for (const auto [param_key, param_val] : params_dict->GetDict()) { - if (param_val.is_bool()) { - params.Set(param_key, param_val.GetBool() ? "true" : "false"); - } else if (param_val.is_int()) { - params.Set(param_key, base::NumberToString(param_val.GetInt())); - } else if (param_val.is_double()) { - params.Set(param_key, base::NumberToString(param_val.GetDouble())); - } else if (param_val.is_string()) { - params.Set(param_key, param_val.GetString()); - } else { - LOG(ERROR) << "Entry in params dict for \"" << feature.first << "\"" - << " is not of a supported type (key: " << param_key - << ", type: " << param_val.type(); - } - } - persistent_dict.Set(feature.first, std::move(params)); - continue; - } - - // Other base::Value types are not supported. - LOG(ERROR) << "A DCS feature mapped to an unsupported value. key: " - << feature.first << " type: " << feature.second.type(); - } - - return persistent_dict; -} - -const std::unordered_set& GetDCSExperimentIds() { - DCHECK(g_experiment_ids_initialized); - return GetExperimentIds(); -} - -void ResetCastFeaturesForTesting() { - g_experiment_ids_initialized = false; - base::FeatureList::ClearInstanceForTesting(); - GetTestFeatures().clear(); -} - -void SetFeaturesForTest(std::vector features) { - GetTestFeatures() = std::move(features); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_features.h chromium-132.0.6834.159/chromecast/base/cast_features.h --- chromium-132.0.6834.110/chromecast/base/cast_features.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_features.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_CAST_FEATURES_H_ -#define CHROMECAST_BASE_CAST_FEATURES_H_ - -#include -#include -#include -#include -#include - -#include "base/feature_list.h" -#include "base/values.h" - -namespace chromecast { - -// Add Cast Features here. -BASE_DECLARE_FEATURE(kAllowUserMediaAccess); -BASE_DECLARE_FEATURE(kEnableQuic); -BASE_DECLARE_FEATURE(kTripleBuffer720); -BASE_DECLARE_FEATURE(kSingleBuffer); -BASE_DECLARE_FEATURE(kDisableIdleSocketsCloseOnMemoryPressure); -BASE_DECLARE_FEATURE(kEnableGeneralAudienceBrowsing); -BASE_DECLARE_FEATURE(kEnableSideGesturePassThrough); -BASE_DECLARE_FEATURE(kEnableChromeAudioManagerAndroid); -BASE_DECLARE_FEATURE(kEnableCastAudioOutputDevice); - -// Get an iterable list of all of the cast features for checking all features as -// a collection. -const std::vector& GetFeatures(); - -// Below are utilities needed by the Cast receiver to persist feature -// information. Client code which is simply querying the status of a feature -// will not need to use these utilities. - -// Initialize the global base::FeatureList instance, taking into account -// overrides from DCS and the command line. |dcs_features| and -// |dcs_experiment_ids| are read from the PrefService in the browser process. -// |cmd_line_enable_features| and |cmd_line_disable_features| should be passed -// to this function, unmodified from the command line. |extra_enable_features| -// should contain any extra features to be enabled. -// -// This function should be called before the browser's main loop. After this is -// called, the other functions in this file may be called on any thread. -// TODO(juke): Keep type info of params by passing in base::flat_map and -// std::vector instead of base::Value. -void InitializeFeatureList(const base::Value::Dict& dcs_features, - const base::Value::List& dcs_experiment_ids, - const std::string& cmd_line_enable_features, - const std::string& cmd_line_disable_features, - const std::string& extra_enable_features, - const std::string& extra_disable_features); - -// Determine whether or not a feature is enabled. This replaces -// base::FeatureList::IsEnabled for Cast builds. -bool IsFeatureEnabled(const base::Feature& feature); - -// Given a dictionary of features, create a copy that is ready to be persisted -// to disk. Encodes all values as strings, which is how the FieldTrial -// classes expect the param data. -base::Value::Dict GetOverriddenFeaturesForStorage( - const base::Value::Dict& features); - -// Query the set of experiment ids set for this run. Intended only for metrics -// reporting. Must be called after InitializeFeatureList(). May be called on any -// thread. -const std::unordered_set& GetDCSExperimentIds(); - -// Reset static state to ensure clean unittests. For tests only. -void ResetCastFeaturesForTesting(); - -// Set the response to GetFeatures(). Calls to this function should -// be cleaned up by a call to ResetCastFeaturesForTesting() otherwise -// your test will leak the overridden feature state. -void SetFeaturesForTest(std::vector features); -} // namespace chromecast - -#endif // CHROMECAST_BASE_CAST_FEATURES_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/cast_features_internal.cc chromium-132.0.6834.159/chromecast/base/cast_features_internal.cc --- chromium-132.0.6834.110/chromecast/base/cast_features_internal.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_features_internal.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include "base/feature_list.h" - -namespace chromecast { -std::vector GetInternalFeatures() { - return std::vector(); -} -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_features_unittest.cc chromium-132.0.6834.159/chromecast/base/cast_features_unittest.cc --- chromium-132.0.6834.110/chromecast/base/cast_features_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_features_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,306 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/cast_features.h" - -#include "base/metrics/field_trial_params.h" -#include "base/values.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -const char kTestBooleanFeatureName[] = "test_boolean_feature"; -const char kTestBooleanFeatureName2[] = "test_boolean_feature_2"; -const char kTestBooleanFeatureName3[] = "test_boolean_feature_3"; -const char kTestBooleanFeatureName4[] = "test_boolean_feature_4"; - -const char kTestParamsFeatureName[] = "test_params_feature"; - -} // namespace - -class CastFeaturesTest : public testing::Test { - public: - CastFeaturesTest() {} - - CastFeaturesTest(const CastFeaturesTest&) = delete; - CastFeaturesTest& operator=(const CastFeaturesTest&) = delete; - - ~CastFeaturesTest() override {} - - // testing::Test implementation: - void SetUp() override { - original_feature_list_ = base::FeatureList::ClearInstanceForTesting(); - ResetCastFeaturesForTesting(); - } - void TearDown() override { - ResetCastFeaturesForTesting(); - base::FeatureList::RestoreInstanceForTesting( - std::move(original_feature_list_)); - } - - private: - std::unique_ptr original_feature_list_; -}; - -TEST_F(CastFeaturesTest, EnableDisableMultipleBooleanFeatures) { - // Declare several boolean features. - static BASE_FEATURE(bool_feature, kTestBooleanFeatureName, - base::FEATURE_DISABLED_BY_DEFAULT); - static BASE_FEATURE(bool_feature_2, kTestBooleanFeatureName2, - base::FEATURE_ENABLED_BY_DEFAULT); - static BASE_FEATURE(bool_feature_3, kTestBooleanFeatureName3, - base::FEATURE_DISABLED_BY_DEFAULT); - static BASE_FEATURE(bool_feature_4, kTestBooleanFeatureName4, - base::FEATURE_ENABLED_BY_DEFAULT); - - // Properly register them - chromecast::SetFeaturesForTest( - {&bool_feature, &bool_feature_2, &bool_feature_3, &bool_feature_4}); - - // Override those features with DCS configs. - base::Value::List experiments; - base::Value::Dict features; - features.Set(kTestBooleanFeatureName, false); - features.Set(kTestBooleanFeatureName2, false); - features.Set(kTestBooleanFeatureName3, true); - features.Set(kTestBooleanFeatureName4, true); - - InitializeFeatureList(features, experiments, "", "", "", ""); - - // Test that features are properly enabled (they should match the - // DCS config). - ASSERT_FALSE(chromecast::IsFeatureEnabled(bool_feature)); - ASSERT_FALSE(chromecast::IsFeatureEnabled(bool_feature_2)); - ASSERT_TRUE(chromecast::IsFeatureEnabled(bool_feature_3)); - ASSERT_TRUE(chromecast::IsFeatureEnabled(bool_feature_4)); -} - -TEST_F(CastFeaturesTest, EnableSingleFeatureWithParams) { - // Define a feature with params. - static BASE_FEATURE(test_feature, kTestParamsFeatureName, - base::FEATURE_DISABLED_BY_DEFAULT); - chromecast::SetFeaturesForTest({&test_feature}); - - // Pass params via DCS. - base::Value::List experiments; - base::Value::Dict features; - base::Value::Dict params; - params.Set("foo_key", "foo"); - params.Set("bar_key", "bar"); - params.Set("doub_key", "3.14159"); - params.Set("long_doub_key", "1.23459999999999999"); - params.Set("int_key", "4242"); - params.Set("bool_key", "true"); - features.Set(kTestParamsFeatureName, std::move(params)); - - InitializeFeatureList(features, experiments, "", "", "", ""); - - // Test that this feature is enabled, and params are correct. - ASSERT_TRUE(chromecast::IsFeatureEnabled(test_feature)); - ASSERT_EQ("foo", - base::GetFieldTrialParamValueByFeature(test_feature, "foo_key")); - ASSERT_EQ("bar", - base::GetFieldTrialParamValueByFeature(test_feature, "bar_key")); - ASSERT_EQ(3.14159, base::GetFieldTrialParamByFeatureAsDouble( - test_feature, "doub_key", 0.000)); - ASSERT_EQ(1.23459999999999999, base::GetFieldTrialParamByFeatureAsDouble( - test_feature, "long_doub_key", 0.000)); - ASSERT_EQ(4242, base::GetFieldTrialParamByFeatureAsInt(test_feature, - "int_key", -1)); - ASSERT_EQ(true, base::GetFieldTrialParamByFeatureAsBool(test_feature, - "bool_key", false)); -} - -TEST_F(CastFeaturesTest, CommandLineOverridesDcsAndDefault) { - // Declare several boolean features. - static BASE_FEATURE(bool_feature, kTestBooleanFeatureName, - base::FEATURE_DISABLED_BY_DEFAULT); - static BASE_FEATURE(bool_feature_2, kTestBooleanFeatureName2, - base::FEATURE_ENABLED_BY_DEFAULT); - static BASE_FEATURE(bool_feature_3, kTestBooleanFeatureName3, - base::FEATURE_DISABLED_BY_DEFAULT); - static BASE_FEATURE(bool_feature_4, kTestBooleanFeatureName4, - base::FEATURE_ENABLED_BY_DEFAULT); - - // Override those features with DCS configs. - base::Value::List experiments; - base::Value::Dict features; - features.Set(kTestBooleanFeatureName, false); - features.Set(kTestBooleanFeatureName2, false); - features.Set(kTestBooleanFeatureName3, true); - features.Set(kTestBooleanFeatureName4, true); - - // Also override a param feature with DCS config. - static BASE_FEATURE(params_feature, kTestParamsFeatureName, - base::FEATURE_ENABLED_BY_DEFAULT); - chromecast::SetFeaturesForTest({&bool_feature, &bool_feature_2, - &bool_feature_3, &bool_feature_4, - ¶ms_feature}); - - base::Value::Dict params; - params.Set("foo_key", "foo"); - features.Set(kTestParamsFeatureName, std::move(params)); - - // Now override with command line flags. Command line flags should have the - // final say. - std::string enabled_features = std::string(kTestBooleanFeatureName) - .append(",") - .append(kTestBooleanFeatureName2); - - std::string disabled_features = std::string(kTestBooleanFeatureName4) - .append(",") - .append(kTestParamsFeatureName); - - InitializeFeatureList(features, experiments, enabled_features, - disabled_features, "", ""); - - // Test that features are properly enabled (they should match the - // DCS config). - ASSERT_TRUE(chromecast::IsFeatureEnabled(bool_feature)); - ASSERT_TRUE(chromecast::IsFeatureEnabled(bool_feature_2)); - ASSERT_TRUE(chromecast::IsFeatureEnabled(bool_feature_3)); - ASSERT_FALSE(chromecast::IsFeatureEnabled(bool_feature_4)); - - // Test that the params feature is disabled, and params are not set. - ASSERT_FALSE(chromecast::IsFeatureEnabled(params_feature)); - ASSERT_EQ("", - base::GetFieldTrialParamValueByFeature(params_feature, "foo_key")); -} - -TEST_F(CastFeaturesTest, SetEmptyExperiments) { - // Override those features with DCS configs. - base::Value::List experiments; - base::Value::Dict features; - - InitializeFeatureList(features, experiments, "", "", "", ""); - ASSERT_EQ(0u, GetDCSExperimentIds().size()); -} - -TEST_F(CastFeaturesTest, SetGoodExperiments) { - // Override those features with DCS configs. - base::Value::List experiments; - base::Value::Dict features; - - int32_t ids[] = {12345678, 123, 0, -1}; - std::unordered_set expected; - for (int32_t id : ids) { - experiments.Append(id); - expected.insert(id); - } - - InitializeFeatureList(features, experiments, "", "", "", ""); - ASSERT_EQ(expected, GetDCSExperimentIds()); -} - -TEST_F(CastFeaturesTest, SetSomeGoodExperiments) { - // Override those features with DCS configs. - base::Value::List experiments; - base::Value::Dict features; - experiments.Append(1234); - experiments.Append("foobar"); - experiments.Append(true); - experiments.Append(1); - experiments.Append(1.23456); - - std::unordered_set expected; - expected.insert(1234); - expected.insert(1); - - InitializeFeatureList(features, experiments, "", "", "", ""); - ASSERT_EQ(expected, GetDCSExperimentIds()); -} - -TEST_F(CastFeaturesTest, SetAllBadExperiments) { - // Override those features with DCS configs. - base::Value::List experiments; - base::Value::Dict features; - experiments.Append("foobar"); - experiments.Append(true); - experiments.Append(1.23456); - - std::unordered_set expected; - - InitializeFeatureList(features, experiments, "", "", "", ""); - ASSERT_EQ(expected, GetDCSExperimentIds()); -} - -TEST_F(CastFeaturesTest, GetOverriddenFeaturesForStorage) { - base::Value::Dict features; - features.Set("bool_key", false); - features.Set("bool_key_2", true); - - base::Value::Dict params; - params.Set("foo_key", "foo"); - params.Set("bar_key", "bar"); - params.Set("doub_key", 3.14159); - params.Set("long_doub_key", 1.234599999999999); - params.Set("int_key", 4242); - params.Set("negint_key", -273); - params.Set("bool_key", true); - features.Set("params_key", std::move(params)); - - auto dict = GetOverriddenFeaturesForStorage(features); - ASSERT_EQ(3u, dict.size()); - auto bval = dict.FindBool("bool_key"); - ASSERT_TRUE(bval.has_value()); - ASSERT_EQ(false, *bval); - bval = dict.FindBool("bool_key_2"); - ASSERT_TRUE(bval.has_value()); - ASSERT_EQ(true, *bval); - - const auto* dval = dict.FindDict("params_key"); - const std::string* sval = nullptr; - ASSERT_TRUE(dval); - ASSERT_EQ(7u, dval->size()); - sval = dval->FindString("foo_key"); - ASSERT_TRUE(sval); - ASSERT_EQ("foo", *sval); - sval = dval->FindString("bar_key"); - ASSERT_TRUE(sval); - ASSERT_EQ("bar", *sval); - sval = dval->FindString("doub_key"); - ASSERT_TRUE(sval); - ASSERT_EQ("3.14159", *sval); - sval = dval->FindString("long_doub_key"); - ASSERT_TRUE(sval); - ASSERT_EQ("1.234599999999999", *sval); - sval = dval->FindString("int_key"); - ASSERT_TRUE(sval); - ASSERT_EQ("4242", *sval); - sval = dval->FindString("negint_key"); - ASSERT_TRUE(sval); - ASSERT_EQ("-273", *sval); - sval = dval->FindString("bool_key"); - ASSERT_TRUE(sval); - ASSERT_EQ("true", *sval); -} - -TEST_F(CastFeaturesTest, GetOverriddenFeaturesForStorage_BadParams) { - base::Value::Dict features; - features.Set("bool_key", false); - features.Set("str_key", "foobar"); - features.Set("int_key", 12345); - features.Set("doub_key", 4.5678); - - base::Value::Dict params; - params.Set("foo_key", "foo"); - features.Set("params_key", std::move(params)); - - auto dict = GetOverriddenFeaturesForStorage(features); - ASSERT_EQ(2u, dict.size()); - auto bval = dict.FindBool("bool_key"); - ASSERT_TRUE(bval.has_value()); - ASSERT_EQ(false, *bval); - - const auto* dval = dict.FindDict("params_key"); - ASSERT_TRUE(dval); - ASSERT_EQ(1u, dval->size()); - const auto* sval = dval->FindString("foo_key"); - ASSERT_TRUE(sval); - ASSERT_EQ("foo", *sval); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_paths.cc chromium-132.0.6834.159/chromecast/base/cast_paths.cc --- chromium-132.0.6834.110/chromecast/base/cast_paths.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_paths.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,117 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/cast_paths.h" - -#include "base/base_paths.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/path_service.h" -#include "build/build_config.h" -#include "chromecast/chromecast_buildflags.h" -#include "third_party/widevine/cdm/buildflags.h" - -#if BUILDFLAG(IS_FUCHSIA) -#include "base/fuchsia/file_utils.h" -#endif - -#if BUILDFLAG(BUNDLE_WIDEVINE_CDM) -#include "third_party/widevine/cdm/widevine_cdm_common.h" // nogncheck -#endif - -namespace chromecast { - -bool PathProvider(int key, base::FilePath* result) { - switch (key) { - case DIR_CAST_HOME: { -#if BUILDFLAG(IS_FUCHSIA) - // On Fuchsia, use the component's local /data directory. - base::FilePath home(base::kPersistedDataDirectoryPath); -#else - base::FilePath home = base::GetHomeDir(); -#endif -#if BUILDFLAG(IS_CAST_DESKTOP_BUILD) - // When running a development instance as a regular user, use - // a data directory under $HOME (similar to Chrome). - *result = home.Append(".config/cast_shell"); -#else - // When running on the actual device, $HOME is set to the user's - // directory under the data partition. - *result = home; -#endif - return true; - } -#if BUILDFLAG(IS_ANDROID) - case FILE_CAST_ANDROID_LOG: { - base::FilePath base_dir; - CHECK(base::PathService::Get(base::DIR_ANDROID_APP_DATA, &base_dir)); - *result = base_dir.AppendASCII("cast_shell.log"); - return true; - } -#endif // BUILDFLAG(IS_ANDROID) - case FILE_CAST_CONFIG: { - base::FilePath data_dir; -#if BUILDFLAG(IS_ANDROID) - CHECK(base::PathService::Get(base::DIR_ANDROID_APP_DATA, &data_dir)); - *result = data_dir.Append("cast_shell.conf"); -#else - CHECK(base::PathService::Get(DIR_CAST_HOME, &data_dir)); - *result = data_dir.Append(".eureka.conf"); -#endif // BUILDFLAG(IS_ANDROID) - return true; - } - case FILE_CAST_CRL: { - base::FilePath data_dir; -#if BUILDFLAG(IS_ANDROID) - CHECK(base::PathService::Get(base::DIR_ANDROID_APP_DATA, &data_dir)); - *result = data_dir.Append("cast_shell.crl"); -#else - CHECK(base::PathService::Get(DIR_CAST_HOME, &data_dir)); - *result = data_dir.Append(".eureka.crl"); -#endif // BUILDFLAG(IS_ANDROID) - return true; - } - case FILE_CAST_PAK: { - base::FilePath base_dir; -#if BUILDFLAG(IS_ANDROID) - CHECK(base::PathService::Get(base::DIR_ANDROID_APP_DATA, &base_dir)); - *result = base_dir.Append("paks/cast_shell.pak"); -#else - CHECK(base::PathService::Get(base::DIR_ASSETS, &base_dir)); - *result = base_dir.Append("assets/cast_shell.pak"); -#endif // BUILDFLAG(IS_ANDROID) - return true; - } -#if BUILDFLAG(BUNDLE_WIDEVINE_CDM) - case DIR_BUNDLED_WIDEVINE_CDM: { - base::FilePath base_dir; - CHECK(base::PathService::Get(base::DIR_MODULE, &base_dir)); -#if !BUILDFLAG(IS_CAST_DESKTOP_BUILD) - base_dir = base_dir.AppendASCII("lib"); -#endif - *result = base_dir.AppendASCII(kWidevineCdmBaseDirectory); - return true; - } -#endif // BUILDFLAG(BUNDLE_WIDEVINE_CDM) - case FILE_CAST_BROWSER_CONFIG: { - base::FilePath data_dir; -#if BUILDFLAG(IS_ANDROID) - CHECK(base::PathService::Get(base::DIR_ANDROID_APP_DATA, &data_dir)); - *result = data_dir.Append("cast_browser.conf"); -#else - CHECK(base::PathService::Get(DIR_CAST_HOME, &data_dir)); - *result = data_dir.Append(".cast_browser.conf"); -#endif // BUILDFLAG(IS_ANDROID) - return true; - } - } - return false; -} - -void RegisterPathProvider() { - base::PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_paths.h chromium-132.0.6834.159/chromecast/base/cast_paths.h --- chromium-132.0.6834.110/chromecast/base/cast_paths.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_paths.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_CAST_PATHS_H_ -#define CHROMECAST_BASE_CAST_PATHS_H_ - -#include "build/build_config.h" -#include "third_party/widevine/cdm/buildflags.h" - -// This file declares path keys for the chromecast module. These can be used -// with the PathService to access various special directories and files. - -namespace chromecast { - -enum { - PATH_START = 8000, - - DIR_CAST_HOME, // Return a modified $HOME which works for both - // development use and the actual device. - -#if BUILDFLAG(IS_ANDROID) - FILE_CAST_ANDROID_LOG, // Log file location for Android. -#endif - FILE_CAST_CONFIG, // Config/preferences file path. - FILE_CAST_CRL, // CRL persistent cache file path. - FILE_CAST_PAK, // cast_shell.pak file path. -#if BUILDFLAG(BUNDLE_WIDEVINE_CDM) - DIR_BUNDLED_WIDEVINE_CDM, -#endif - FILE_CAST_BROWSER_CONFIG, - PATH_END -}; - -// Call once to register the provider for the path keys defined above. -void RegisterPathProvider(); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_CAST_PATHS_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/cast_resource.cc chromium-132.0.6834.159/chromecast/base/cast_resource.cc --- chromium-132.0.6834.110/chromecast/base/cast_resource.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_resource.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// 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 "chromecast/base/cast_resource.h" - -namespace chromecast { - -void CastResource::SetCastResourceClient(Client* client) { - client_ = client; -} - -void CastResource::RegisterWithClient() { - if (client_) - client_->RegisterCastResource(this); -} - -void CastResource::NotifyResourceReleased(Resource remain) { - if (client_) - client_->OnResourceReleased(this, remain); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_resource.h chromium-132.0.6834.159/chromecast/base/cast_resource.h --- chromium-132.0.6834.110/chromecast/base/cast_resource.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_resource.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,105 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_CAST_RESOURCE_H_ -#define CHROMECAST_BASE_CAST_RESOURCE_H_ - -#include "base/memory/raw_ptr.h" - -namespace chromecast { - -// A CastResource is a user of 1 or more Resources (primary screen, audio, -// etc). As a user, it is responsible for doing any cast-specific component -// initialization when the Resources it uses are granted. This initialization -// is referred to as "acquiring" the Resources. Conversely, when the Resources -// it uses are revoked, it must deinitialize these cast-specific components. -// This deinitialization is referred to as "releasing" the Resources. -// TODO(maclellant): RENAME/DESIGN THIS CLASS IN COMING REFACTOR. -class CastResource { - public: - // Resources necessary to run cast apps. CastResource may contain union of the - // following types. - // TODO(yucliu): Split video resources and graphic resources. - enum Resource { - kResourceNone = 0, - // All resources necessary to render sounds, for example, audio pipeline, - // speaker, etc. - kResourceAudio = 1 << 0, - // All resources necessary to render videos or images, for example, video - // pipeline, primary graphics plane, display, etc. - kResourceScreenPrimary = 1 << 1, - // All resources necessary to render overlaid images, for example, secondary - // graphics plane, LCD, etc. - kResourceScreenSecondary = 1 << 2, - // Collection of resources used for display only combined with bitwise or. - kResourceDisplayOnly = (kResourceScreenPrimary | kResourceScreenSecondary), - // Collection of all resources combined with bitwise or. - kResourceAll = - (kResourceAudio | kResourceScreenPrimary | kResourceScreenSecondary), - }; - - // A Client is responsible for notifying all registered CastResource's when - // Resources are granted/revoked so that they can acquire/release those - // Resources. When a CastResource is done acquiring/releasing, it responds - // to the Client that it has completed. A Client can have multiple registered - // CastResource's, but each CastResouce has 1 Client that it responds to. - class Client { - public: - // Called to register a CastResource with a Client. After registering, a - // CastResource will start getting notified when to acquire/release - // Resources. The Client does not take ownership of |cast_resource|. It can - // be called from any thread. - virtual void RegisterCastResource(CastResource* cast_resource) = 0; - - // TODO(esum): Add OnResourceAcquired() here once AcquireResource is - // allowed to be asynchronous. - - // Called when part or all resources are released. It can be called from any - // thread. - // |cast_resource| the CastResource that is released. The pointer may be - // invalid. Client can't call functions with that pointer. - // |remain| the unreleased resource of CastResource. If kResourceNone is - // returned, Client will remove the resource from its watching - // list. - virtual void OnResourceReleased(CastResource* cast_resource, - Resource remain) = 0; - - protected: - virtual ~Client() {} - }; - - CastResource(const CastResource&) = delete; - CastResource& operator=(const CastResource&) = delete; - - // Sets the Client for the CastResource to respond to when it is done with - // Acquire/ReleaseResource. - void SetCastResourceClient(Client* client); - // Called to acquire resources after OEM has granted them, and before - // they start getting used by consumers. Implementation must be synchronous - // since consumers will start using the resource immediately afterwards. - // TODO(esum): We should allow this method to be asynchronous in case an - // implementer needs to make expensive calls and doesn't want to block the - // UI thread (b/26239576). For now, don't do anything expensive in your - // implementation; if you really need to, then this bug has to be resolved. - virtual void AcquireResource(Resource resource) = 0; - // Called to release resources. Implementation should call - // Client::OnResourceReleased when resource is released on its side. - virtual void ReleaseResource(Resource resource) = 0; - - protected: - CastResource() : client_(nullptr) {} - virtual ~CastResource() {} - - // For derived classes to register themselves with their Client through - // Client::RegisterCastResource. - void RegisterWithClient(); - void NotifyResourceReleased(Resource remain); - - private: - raw_ptr client_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_CAST_RESOURCE_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_android.cc chromium-132.0.6834.159/chromecast/base/cast_sys_info_android.cc --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,128 +0,0 @@ -// 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 "chromecast/base/cast_sys_info_android.h" - -#include -#include -#include - -#include "base/android/build_info.h" -#include "base/android/jni_android.h" -#include "base/android/jni_string.h" -#include "base/system/sys_info.h" -#include "chromecast/base/cast_sys_info_util.h" -#include "chromecast/base/version.h" - -// Must come after all headers that specialize FromJniType() / ToJniType(). -#include "chromecast/base/jni_headers/CastSysInfoAndroid_jni.h" - -namespace chromecast { - -CastSysInfoAndroid::CastSysInfoAndroid() - : build_info_(base::android::BuildInfo::GetInstance()) {} - -CastSysInfoAndroid::~CastSysInfoAndroid() {} - -CastSysInfo::BuildType CastSysInfoAndroid::GetBuildType() { - return CAST_IS_DEBUG_BUILD() ? BUILD_ENG : BUILD_PRODUCTION; -} - -std::string CastSysInfoAndroid::GetSerialNumber() { - JNIEnv* env = base::android::AttachCurrentThread(); - return base::android::ConvertJavaStringToUTF8( - Java_CastSysInfoAndroid_getSerialNumber(env)); -} - -std::string CastSysInfoAndroid::GetProductName() { - return build_info_->device(); -} - -std::string CastSysInfoAndroid::GetDeviceModel() { - return build_info_->model(); -} - -std::string CastSysInfoAndroid::GetManufacturer() { - return build_info_->manufacturer(); -} - -std::string CastSysInfoAndroid::GetSystemBuildNumber() { - return base::SysInfo::GetAndroidBuildID(); -} - -std::string CastSysInfoAndroid::GetSystemReleaseChannel() { - return ""; -} - -std::string CastSysInfoAndroid::GetBoardName() { - JNIEnv* env = base::android::AttachCurrentThread(); - return base::android::ConvertJavaStringToUTF8( - Java_CastSysInfoAndroid_getBoard(env)); -} - -std::string CastSysInfoAndroid::GetBoardRevision() { - return ""; -} - -std::string CastSysInfoAndroid::GetFactoryCountry() { - return GetAndroidProperty("ro.boot.wificountrycode", ""); -} - -std::vector CastSysInfoAndroid::GetFactoryLocaleList() { - const std::string factory_locale_list = - GetAndroidProperty("ro.product.factory_locale_list", ""); - if (!factory_locale_list.empty()) { - std::vector results; - std::stringstream stream(factory_locale_list); - while (stream.good()) { - std::string locale; - getline(stream, locale, ','); - results.push_back(locale); - } - if (!results.empty()) { - return results; - } - } - // This duplicates the read-only property portion of - // frameworks/base/core/jni/AndroidRuntime.cpp in the Android tree, which is - // effectively the "factory locale", i.e. the locale chosen by Android - // assuming the other persist.sys.* properties are not set. - const std::string locale = GetAndroidProperty("ro.product.locale", ""); - if (!locale.empty()) { - return {locale}; - } - - const std::string language = - GetAndroidProperty("ro.product.locale.language", "en"); - const std::string region = - GetAndroidProperty("ro.product.locale.region", "US"); - return {language + "-" + region}; -} - -std::string CastSysInfoAndroid::GetWifiInterface() { - return ""; -} - -std::string CastSysInfoAndroid::GetApInterface() { - return ""; -} - -std::string CastSysInfoAndroid::GetProductSsidSuffix() { - return GetAndroidProperty("ro.odm.cast.ssid_suffix", ""); -} - -std::string CastSysInfoAndroid::GetAndroidProperty( - const std::string& key, - const std::string& default_value) { - char value[PROP_VALUE_MAX]; - int ret = __system_property_get(key.c_str(), value); - if (ret <= 0) { - DVLOG(1) << "No value set for property: " << key; - return default_value; - } - - return std::string(value); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_android.h chromium-132.0.6834.159/chromecast/base/cast_sys_info_android.h --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_CAST_SYS_INFO_ANDROID_H_ -#define CHROMECAST_BASE_CAST_SYS_INFO_ANDROID_H_ - -#include -#include - -#include "chromecast/public/cast_sys_info.h" - -namespace base { -namespace android { -class BuildInfo; -} -} - -namespace chromecast { - -class CastSysInfoAndroid : public CastSysInfo { - public: - CastSysInfoAndroid(); - - CastSysInfoAndroid(const CastSysInfoAndroid&) = delete; - CastSysInfoAndroid& operator=(const CastSysInfoAndroid&) = delete; - - ~CastSysInfoAndroid() override; - - // CastSysInfo implementation: - BuildType GetBuildType() override; - std::string GetSerialNumber() override; - std::string GetProductName() override; - std::string GetDeviceModel() override; - std::string GetManufacturer() override; - std::string GetSystemBuildNumber() override; - std::string GetSystemReleaseChannel() override; - std::string GetBoardName() override; - std::string GetBoardRevision() override; - std::string GetFactoryCountry() override; - std::vector GetFactoryLocaleList() override; - std::string GetWifiInterface() override; - std::string GetApInterface() override; - std::string GetProductSsidSuffix() override; - - static std::string GetAndroidProperty(const std::string& key, - const std::string& default_value); - - private: - const base::android::BuildInfo* const build_info_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_CAST_SYS_INFO_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_android_factory.cc chromium-132.0.6834.159/chromecast/base/cast_sys_info_android_factory.cc --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_android_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_android_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/cast_sys_info_android.h" - -#include - -namespace chromecast { - -// static -std::unique_ptr CreateSysInfo() { - return std::make_unique(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_dummy.cc chromium-132.0.6834.159/chromecast/base/cast_sys_info_dummy.cc --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,202 +0,0 @@ -// 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 "chromecast/base/cast_sys_info_dummy.h" - -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/json/json_reader.h" -#include "base/logging.h" - -namespace chromecast { - -namespace { -const char kJsonKeyProductName[] = "product_name"; -const char kJsonKeySerialNumber[] = "serial_number"; -const char kJsonKeyDeviceModel[] = "device_model"; -const char kJsonKeyManufacture[] = "manufacturer"; - -const char kDefaultProductName[] = "cast_shell"; -const char kDefaultSerialNumber[] = "dummy.serial.number"; -const char kDefaultDeviceModel[] = "dummy model"; -const char kDefaultManufacturer[] = "google"; - -std::string GetStringValue(const base::Value& sys_info_file, - const std::string& key, - const std::string& default_val) { - DCHECK(sys_info_file.is_dict()); - - const std::string* val = sys_info_file.GetDict().FindString(key); - if (!val) { - LOG(WARNING) << "Json key not found: " << key; - return default_val; - } - return *val; -} -} // namespace - -CastSysInfoDummy::CastSysInfoDummy() - : build_type_(BUILD_ENG), - serial_number_("dummy.serial.number"), - product_name_("cast_shell"), - device_model_("dummy model"), - board_name_("dummy board"), - manufacturer_("google"), - system_build_number_(__DATE__ " - " __TIME__), - factory_country_("US"), - factory_locale_list_({"en-US"}) {} - -CastSysInfoDummy::CastSysInfoDummy(const std::string& sys_info_file) - : CastSysInfoDummy() { - std::string content; - if (!base::ReadFileToString(base::FilePath(sys_info_file), &content)) { - LOG(ERROR) << "Failed to read sys info file: " << sys_info_file; - return; - } - - auto value = base::JSONReader::Read(content); - if (!value || !value->is_dict()) { - LOG(ERROR) - << "Invaild sys info json file, using the default values instead."; - return; - } - - product_name_ = - GetStringValue(*value, kJsonKeyProductName, kDefaultProductName); - serial_number_ = - GetStringValue(*value, kJsonKeySerialNumber, kDefaultSerialNumber); - device_model_ = - GetStringValue(*value, kJsonKeyDeviceModel, kDefaultDeviceModel); - manufacturer_ = - GetStringValue(*value, kJsonKeyManufacture, kDefaultManufacturer); -} - -CastSysInfoDummy::~CastSysInfoDummy() {} - -CastSysInfo::BuildType CastSysInfoDummy::GetBuildType() { - return build_type_; -} - -std::string CastSysInfoDummy::GetSystemReleaseChannel() { - return system_release_channel_; -} - -std::string CastSysInfoDummy::GetSerialNumber() { - return serial_number_; -} - -std::string CastSysInfoDummy::GetProductName() { - return product_name_; -} - -std::string CastSysInfoDummy::GetDeviceModel() { - return device_model_; -} - -std::string CastSysInfoDummy::GetBoardName() { - return board_name_; -} - -std::string CastSysInfoDummy::GetBoardRevision() { - return board_revision_; -} - -std::string CastSysInfoDummy::GetManufacturer() { - return manufacturer_; -} - -std::string CastSysInfoDummy::GetSystemBuildNumber() { - return system_build_number_; -} - -std::string CastSysInfoDummy::GetFactoryCountry() { - return factory_country_; -} - -std::vector CastSysInfoDummy::GetFactoryLocaleList() { - return factory_locale_list_; -} - -std::string CastSysInfoDummy::GetWifiInterface() { - return wifi_interface_; -} - -std::string CastSysInfoDummy::GetApInterface() { - return ap_interface_; -} - -std::string CastSysInfoDummy::GetProductSsidSuffix() { - return ssid_suffix_; -} - -void CastSysInfoDummy::SetBuildTypeForTesting( - CastSysInfo::BuildType build_type) { - build_type_ = build_type; -} - -void CastSysInfoDummy::SetSystemReleaseChannelForTesting( - const std::string& system_release_channel) { - system_release_channel_ = system_release_channel; -} - -void CastSysInfoDummy::SetSerialNumberForTesting( - const std::string& serial_number) { - serial_number_ = serial_number; -} - -void CastSysInfoDummy::SetProductNameForTesting( - const std::string& product_name) { - product_name_ = product_name; -} - -void CastSysInfoDummy::SetDeviceModelForTesting( - const std::string& device_model) { - device_model_ = device_model; -} - -void CastSysInfoDummy::SetBoardNameForTesting(const std::string& board_name) { - board_name_ = board_name; -} - -void CastSysInfoDummy::SetBoardRevisionForTesting( - const std::string& board_revision) { - board_revision_ = board_revision; -} - -void CastSysInfoDummy::SetManufacturerForTesting( - const std::string& manufacturer) { - manufacturer_ = manufacturer; -} - -void CastSysInfoDummy::SetSystemBuildNumberForTesting( - const std::string& system_build_number) { - system_build_number_ = system_build_number; -} - -void CastSysInfoDummy::SetFactoryCountryForTesting( - const std::string& factory_country) { - factory_country_ = factory_country; -} - -void CastSysInfoDummy::SetFactoryLocaleListForTesting( - const std::vector& factory_locale_list) { - factory_locale_list_ = factory_locale_list; -} - -void CastSysInfoDummy::SetWifiInterfaceForTesting( - const std::string& wifi_interface) { - wifi_interface_ = wifi_interface; -} - -void CastSysInfoDummy::SetApInterfaceForTesting( - const std::string& ap_interface) { - ap_interface_ = ap_interface; -} - -void CastSysInfoDummy::SetProductSsidSuffixForTesting( - const std::string& ssid_suffix) { - ssid_suffix_ = ssid_suffix; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_dummy.h chromium-132.0.6834.159/chromecast/base/cast_sys_info_dummy.h --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_dummy.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_dummy.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_CAST_SYS_INFO_DUMMY_H_ -#define CHROMECAST_BASE_CAST_SYS_INFO_DUMMY_H_ - -#include - -// Note(slan): This file is needed by internal targets which cannot depend on -// "//base". Amend this include with a comment so gn check ignores it. -#include "chromecast/public/cast_sys_info.h" - -namespace chromecast { - -// Dummy implementation of CastSysInfo. Fields can be overwritten for test. -class CastSysInfoDummy : public CastSysInfo { - public: - CastSysInfoDummy(); - CastSysInfoDummy(const std::string& sys_info_file); - - CastSysInfoDummy(const CastSysInfoDummy&) = delete; - CastSysInfoDummy& operator=(const CastSysInfoDummy&) = delete; - - ~CastSysInfoDummy() override; - - // CastSysInfo implementation: - BuildType GetBuildType() override; - std::string GetSystemReleaseChannel() override; - std::string GetSerialNumber() override; - std::string GetProductName() override; - std::string GetDeviceModel() override; - std::string GetBoardName() override; - std::string GetBoardRevision() override; - std::string GetManufacturer() override; - std::string GetSystemBuildNumber() override; - std::string GetFactoryCountry() override; - std::vector GetFactoryLocaleList() override; - std::string GetWifiInterface() override; - std::string GetApInterface() override; - std::string GetProductSsidSuffix() override; - - void SetBuildTypeForTesting(BuildType build_type); - void SetSystemReleaseChannelForTesting( - const std::string& system_release_channel); - void SetSerialNumberForTesting(const std::string& serial_number); - void SetProductNameForTesting(const std::string& product_name); - void SetDeviceModelForTesting(const std::string& device_model); - void SetBoardNameForTesting(const std::string& board_name); - void SetBoardRevisionForTesting(const std::string& board_revision); - void SetManufacturerForTesting(const std::string& manufacturer); - void SetSystemBuildNumberForTesting(const std::string& system_build_number); - void SetFactoryCountryForTesting(const std::string& factory_country); - void SetFactoryLocaleListForTesting( - const std::vector& factory_locale_list); - void SetWifiInterfaceForTesting(const std::string& wifi_interface); - void SetApInterfaceForTesting(const std::string& ap_interface); - void SetProductSsidSuffixForTesting(const std::string& ssid_suffix); - - private: - BuildType build_type_; - std::string system_release_channel_; - std::string serial_number_; - std::string product_name_; - std::string device_model_; - std::string board_name_; - std::string board_revision_; - std::string manufacturer_; - std::string system_build_number_; - std::string factory_country_; - std::vector factory_locale_list_; - std::string wifi_interface_; - std::string ap_interface_; - std::string ssid_suffix_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_CAST_SYS_INFO_DUMMY_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_shlib.cc chromium-132.0.6834.159/chromecast/base/cast_sys_info_shlib.cc --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_shlib.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_shlib.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/public/cast_sys_info_shlib.h" - -#include "base/command_line.h" -#include "chromecast/base/cast_sys_info_dummy.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/init_command_line_shlib.h" - -namespace chromecast { - -// static -CastSysInfo* CastSysInfoShlib::Create(const std::vector& argv) { - InitCommandLineShlib(argv); - auto* cmd_line = base::CommandLine::ForCurrentProcess(); - - if (cmd_line->HasSwitch(switches::kSysInfoFilePath)) { - return new CastSysInfoDummy( - cmd_line->GetSwitchValueASCII(switches::kSysInfoFilePath)); - } - - return new CastSysInfoDummy(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_util.h chromium-132.0.6834.159/chromecast/base/cast_sys_info_util.h --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_CAST_SYS_INFO_UTIL_H_ -#define CHROMECAST_BASE_CAST_SYS_INFO_UTIL_H_ - -#include -#include - -namespace chromecast { - -class CastSysInfo; - -std::unique_ptr CreateSysInfo(); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_CAST_SYS_INFO_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_util_shlib.cc chromium-132.0.6834.159/chromecast/base/cast_sys_info_util_shlib.cc --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_util_shlib.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_util_shlib.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include "base/command_line.h" -#include "base/memory/ptr_util.h" -#include "chromecast/base/cast_sys_info_util.h" -#include "chromecast/public/cast_sys_info_shlib.h" -#include "chromecast/public/cast_sys_info.h" - -namespace chromecast { - -std::unique_ptr CreateSysInfo() { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - return base::WrapUnique(CastSysInfoShlib::Create(command_line->argv())); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/cast_sys_info_util_simple.cc chromium-132.0.6834.159/chromecast/base/cast_sys_info_util_simple.cc --- chromium-132.0.6834.110/chromecast/base/cast_sys_info_util_simple.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/cast_sys_info_util_simple.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// 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 - -#include "chromecast/base/cast_sys_info_util.h" - -#include "chromecast/base/cast_sys_info_dummy.h" - -namespace chromecast { - -// static -std::unique_ptr CreateSysInfo() { - return std::make_unique(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/chromecast_switches.cc chromium-132.0.6834.159/chromecast/base/chromecast_switches.cc --- chromium-132.0.6834.110/chromecast/base/chromecast_switches.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/chromecast_switches.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,343 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/chromecast_switches.h" - -#include "base/command_line.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" - -namespace switches { - -// Value indicating whether flag from command line switch is true. -const char kSwitchValueTrue[] = "true"; - -// Value indicating whether flag from command line switch is false. -const char kSwitchValueFalse[] = "false"; - -// Server url to upload crash data to. -// Default is "https://clients2.google.com/cr/report" for prod devices. -// Default is "https://clients2.google.com/cr/staging_report" for non prod. -const char kCrashServerUrl[] = "crash-server-url"; - -// Switch to enable daemon-mode in crash_uploader. -const char kCrashUploaderDaemon[] = "daemon"; - -// Switch to disable Crash reporting -const char kDisableCrashReporter[] = "disable-crash-reporter"; - -// Switch to disable Crashpad forwarding -const char kDisableCrashpadForwarding[] = "disable-crashpad-forwarding"; - -// Switch to dumpstate binary path. -const char kDumpstateBinPath[] = "dumpstate-path"; - -// Enable file accesses. It should not be enabled for most Cast devices. -const char kEnableLocalFileAccesses[] = "enable-local-file-accesses"; - -// Override the URL to which metrics logs are sent for debugging. -const char kOverrideMetricsUploadUrl[] = "override-metrics-upload-url"; - -// Only connect to WLAN interfaces. -const char kRequireWlan[] = "require-wlan"; - -// Pass the app id information to the renderer process, to be used for logging. -// last-launched-app should be the app that just launched and is spawning the -// renderer. -const char kLastLaunchedApp[] = "last-launched-app"; -// previous-app should be the app that was running when last-launched-app -// started. -const char kPreviousApp[] = "previous-app"; - -// Flag indicating that a resource provider must be set up to provide cast -// receiver with resources. Apps cannot start until provided resources. -// This flag implies --alsa-check-close-timeout=0. -const char kAcceptResourceProvider[] = "accept-resource-provider"; - -// Name of the device the amp mixer should be opened on. If this flag is not -// specified it will default to the same device as kAlsaVolumeDeviceName. -const char kAlsaAmpDeviceName[] = "alsa-amp-device-name"; - -// Name of the simple mixer control element that the ALSA-based media library -// should use to toggle powersave mode on the system. -const char kAlsaAmpElementName[] = "alsa-amp-element-name"; - -// Time in ms to wait before closing the PCM handle when no more mixer inputs -// remain. Assumed to be 0 if --accept-resource-provider is present. -const char kAlsaCheckCloseTimeout[] = "alsa-check-close-timeout"; - -// Flag that enables resampling audio with sample rate below 32kHz up to 48kHz. -// Should be set to true for internal audio products. -const char kAlsaEnableUpsampling[] = "alsa-enable-upsampling"; - -// Optional flag to set a fixed sample rate for the alsa device. -// Deprecated: Use --audio-output-sample-rate instead. -const char kAlsaFixedOutputSampleRate[] = "alsa-fixed-output-sample-rate"; - -// Name of the device the mute mixer should be opened on. If this flag is not -// specified it will default to the same device as kAlsaVolumeDeviceName. -const char kAlsaMuteDeviceName[] = "alsa-mute-device-name"; - -// Name of the simple mixer control element that the ALSA-based media library -// should use to mute the system. -const char kAlsaMuteElementName[] = "alsa-mute-element-name"; - -// Minimum number of available frames for scheduling a transfer. -const char kAlsaOutputAvailMin[] = "alsa-output-avail-min"; - -// Size of the ALSA output buffer in frames. This directly sets the latency of -// the output device. Latency can be calculated by multiplying the sample rate -// by the output buffer size. -const char kAlsaOutputBufferSize[] = "alsa-output-buffer-size"; - -// Size of the ALSA output period in frames. The period of an ALSA output device -// determines how many frames elapse between hardware interrupts. -const char kAlsaOutputPeriodSize[] = "alsa-output-period-size"; - -// How many frames need to be in the output buffer before output starts. -const char kAlsaOutputStartThreshold[] = "alsa-output-start-threshold"; - -// Name of the device the volume control mixer should be opened on. Will use the -// same device as kAlsaOutputDevice and fall back to "default" if -// kAlsaOutputDevice is not supplied. -const char kAlsaVolumeDeviceName[] = "alsa-volume-device-name"; - -// Name of the simple mixer control element that the ALSA-based media library -// should use to control the volume. -const char kAlsaVolumeElementName[] = "alsa-volume-element-name"; - -// Number of audio output channels. This will be used to send audio buffer with -// specific number of channels to ALSA and generate loopback audio. Default -// value is 2. -const char kAudioOutputChannels[] = "audio-output-channels"; - -// Specify fixed sample rate for audio output stream. If this flag is not -// specified the StreamMixer will choose sample rate based on the sample rate of -// the media stream. -const char kAudioOutputSampleRate[] = "audio-output-sample-rate"; - -// Calibrated max output volume dBa for voice content at 1 meter, if known. -const char kMaxOutputVolumeDba1m[] = "max-output-volume-dba1m"; - -// Enable dynamically changing the channel count in the mixer depending on the -// input streams. -const char kMixerEnableDynamicChannelCount[] = - "mixer-enable-dynamic-channel-count"; - -// Specify the start threshold frames for audio output when using our mixer. -// This is mostly used to override the default value to a larger value, for -// platforms that can't handle the default start threshold without running into -// audio underruns. -const char kMixerSourceAudioReadyThresholdMs[] = - "mixer-source-audio-ready-threshold-ms"; - -// Specify the buffer size for audio output when using our mixer. This is mostly -// used to override the default value to a larger value, for platforms that -// can't handle an audio buffer so small without running into audio underruns. -const char kMixerSourceInputQueueMs[] = "mixer-source-input-queue-ms"; - -// Some platforms typically have very little 'free' memory, but plenty is -// available in buffers+cached. For such platforms, configure this amount -// as the portion of buffers+cached memory that should be treated as -// unavailable. If this switch is not used, a simple pressure heuristic based -// purely on free memory will be used. -const char kMemPressureSystemReservedKb[] = "mem-pressure-system-reserved-kb"; - -// Used to pass initial screen resolution to GPU process. This allows us to set -// screen size correctly (so no need to resize when first window is created). -const char kCastInitialScreenWidth[] = "cast-initial-screen-width"; -const char kCastInitialScreenHeight[] = "cast-initial-screen-height"; -const char kGraphicsBufferCount[] = "graphics-buffer-count"; - -// Overrides the vsync interval used by the GPU process to refresh the display. -const char kVSyncInterval[] = "vsync-interval"; - -// When present, desktop cast_shell will create 1080p window (provided display -// resolution is high enough). Otherwise, cast_shell defaults to 720p. -const char kDesktopWindow1080p[] = "desktop-window-1080p"; - -// When present overrides the screen resolution used by CanDisplayType API, -// instead of using the values obtained from avsettings. -const char kForceMediaResolutionHeight[] = "force-media-resolution-height"; -const char kForceMediaResolutionWidth[] = "force-media-resolution-width"; - -// Enables input event handling by the window manager. -const char kEnableInput[] = "enable-input"; - -// Background color used when Chromium hasn't rendered anything yet. -const char kCastAppBackgroundColor[] = "cast-app-background-color"; - -// The number of pixels from the very left or right of the screen to consider as -// a valid origin for the left or right swipe gesture. Overrides the default -// value in cast_system_gesture_handler.cc. -const char kSystemGestureStartWidth[] = "system-gesture-start-width"; - -// The number of pixels from the very top or bottom of the screen to consider as -// a valid origin for the top or bottom swipe gesture. Overrides the default -// value in cast_system_gesture_handler.cc. -const char kSystemGestureStartHeight[] = "system-gesture-start-height"; - -// The number of pixels up from the bottom of the screen to consider as a valid -// origin for a bottom swipe gesture. If set, overrides the value of both the -// above system-gesture-start-height flag and the default value in -// cast_system_gesture_handler.cc. -const char kBottomSystemGestureStartHeight[] = "bottom-gesture-start-height"; - -// The number of pixels from the start of a left swipe gesture to consider as a -// 'back' gesture. -const char kBackGestureHorizontalThreshold[] = - "back-gesture-horizontal-threshold"; - -// Whether to enable detection and dispatch of a 'drag from the top' gesture. -const char kEnableTopDragGesture[] = "enable-top-drag-gesture"; - -// Whether in hospitality mode -const char kManagedMode[] = "managed-mode"; - -// Endpoint that the mixer service listens on. This is a path for a UNIX domain -// socket (default is /tmp/mixer-service). -const char kMixerServiceEndpoint[] = "mixer-service-endpoint"; - -// TCP port that the mixer service listens on on non-Linux platforms. -// (default 12854). -const char kMixerServicePort[] = "mixer-service-port"; - -extern const char kCastMemoryPressureCriticalFraction[] = - "memory-pressure-critical-fraction"; -extern const char kCastMemoryPressureModerateFraction[] = - "memory-pressure-moderate-fraction"; - -// Rather than use the renderer hosted remotely in the media service, fall back -// to the default renderer within content_renderer. Does not change the behavior -// of the media service. -const char kDisableMojoRenderer[] = "disable-mojo-renderer"; - -// Forces the use of the mojo renderer. In other words, the renderer process -// will run a mojo renderer and CastRenderer will run in the browser process. -// This is necessary for devices that use CastRenderer. -// -// For this flag to have any effect, note that you must build the cast web -// runtime with the gn arg "enable_cast_renderer" set to true, and "renderer" -// must be included in the list "mojo_media_services". -// -// This flag has lower priority than "disable-mojo-renderer". -const char kForceMojoRenderer[] = "force-mojo-renderer"; - -// Per-product customization of force update UI remote url, also used in -// testing. -const char kForceUpdateRemoteUrl[] = "force-update-remote-url"; - -// System info file path. Default is an empty string, which -// means that dummy info will be used. -const char kSysInfoFilePath[] = "sys-info-file-path"; - -// Defer initialization of the base::FeatureList in an external service process, -// allowing the process to include its own non-default features. -const char kDeferFeatureList[] = "defer-feature-list"; - -// Rather than share a common pref config file with cast_service, use a -// dedicated browser pref config file. This must be set when `cast_browser` is -// running in a different process from `cast_service`. -const char kUseCastBrowserPrefConfig[] = "use-cast-browser-pref-config"; - -// Creates the service broker inside of this process. Only one process should -// host the service broker. -const char kInProcessBroker[] = "in-process-broker"; - -// Command-line arg to change the Unix domain socket path to connect to the -// Cast Mojo broker. -const char kCastMojoBrokerPath[] = "cast-mojo-broker-path"; - -} // namespace switches - -namespace chromecast { - -bool GetSwitchValueBoolean(const std::string& switch_string, - const bool default_value) { - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switch_string)) { - if (command_line->GetSwitchValueASCII(switch_string) != - switches::kSwitchValueTrue && - command_line->GetSwitchValueASCII(switch_string) != - switches::kSwitchValueFalse && - command_line->GetSwitchValueASCII(switch_string) != "") { - LOG(WARNING) << "Invalid switch value " << switch_string << "=" - << command_line->GetSwitchValueASCII(switch_string) - << "; assuming default value of " << default_value; - return default_value; - } - return command_line->GetSwitchValueASCII(switch_string) != - switches::kSwitchValueFalse; - } - return default_value; -} - -int GetSwitchValueInt(const std::string& switch_name, const int default_value) { - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - if (!command_line->HasSwitch(switch_name)) { - return default_value; - } - - int arg_value; - if (!base::StringToInt(command_line->GetSwitchValueASCII(switch_name), - &arg_value)) { - LOG(DFATAL) << "--" << switch_name << " only accepts integers as arguments"; - return default_value; - } - return arg_value; -} - -int GetSwitchValueNonNegativeInt(const std::string& switch_name, - const int default_value) { - DCHECK_GE(default_value, 0) - << "--" << switch_name << " must have a non-negative default value"; - - int value = GetSwitchValueInt(switch_name, default_value); - if (value < 0) { - LOG(DFATAL) << "--" << switch_name << " must have a non-negative value"; - return default_value; - } - return value; -} - -double GetSwitchValueDouble(const std::string& switch_name, - const double default_value) { - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - if (!command_line->HasSwitch(switch_name)) { - return default_value; - } - - double arg_value; - if (!base::StringToDouble(command_line->GetSwitchValueASCII(switch_name), - &arg_value)) { - LOG(DFATAL) << "--" << switch_name << " only accepts numbers as arguments"; - return default_value; - } - return arg_value; -} - -uint32_t GetSwitchValueColor(const std::string& switch_name, - const uint32_t default_value) { - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - if (!command_line->HasSwitch(switch_name)) { - return default_value; - } - - uint32_t arg_value = 0; - if (!base::HexStringToUInt( - command_line->GetSwitchValueASCII(switch_name).substr(1), - &arg_value)) { - LOG(ERROR) << "Invalid value for " << switch_name << " (" - << command_line->GetSwitchValueASCII(switch_name) - << "), using default."; - return default_value; - } - return arg_value; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/chromecast_switches.h chromium-132.0.6834.159/chromecast/base/chromecast_switches.h --- chromium-132.0.6834.110/chromecast/base/chromecast_switches.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/chromecast_switches.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,156 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_CHROMECAST_SWITCHES_H_ -#define CHROMECAST_BASE_CHROMECAST_SWITCHES_H_ - -#include -#include - -#include "build/build_config.h" - -namespace switches { - -// Switch values -extern const char kSwitchValueTrue[]; -extern const char kSwitchValueFalse[]; - -// Switches for crash_uploader -extern const char kCrashServerUrl[]; -extern const char kCrashUploaderDaemon[]; - -// Disable Crash Reporting -extern const char kDisableCrashReporter[]; - -// Disable Crashpad forwarding -extern const char kDisableCrashpadForwarding[]; - -// Path to dumpstate binary to be used for crash reporting. -// This gives Chromium's crash reporter the flexibility to switch -// between multiple implementations of dumpstate tool. -extern const char kDumpstateBinPath[]; - -// Content-implementation switches -extern const char kEnableLocalFileAccesses[]; - -// Metrics switches -extern const char kOverrideMetricsUploadUrl[]; - -// Network switches -extern const char kRequireWlan[]; - -// Switches to communicate app state information -extern const char kLastLaunchedApp[]; -extern const char kPreviousApp[]; - -// Cast Receiver switches -extern const char kAcceptResourceProvider[]; - -// ALSA-based CMA switches. (Only valid for audio products.) -// TODO(sergeyu): kAlsaEnableUpsampling and kAlsaCheckCloseTimeout are -// implemented in StreamMixer, which is not ALSA-specific - it's also used on -// Fuchsia. Rename these flags. -extern const char kAlsaAmpDeviceName[]; -extern const char kAlsaAmpElementName[]; -extern const char kAlsaCheckCloseTimeout[]; -extern const char kAlsaEnableUpsampling[]; -extern const char kAlsaFixedOutputSampleRate[]; -extern const char kAlsaMuteDeviceName[]; -extern const char kAlsaMuteElementName[]; -extern const char kAlsaOutputAvailMin[]; -extern const char kAlsaOutputBufferSize[]; -extern const char kAlsaOutputPeriodSize[]; -extern const char kAlsaOutputStartThreshold[]; -extern const char kAlsaVolumeDeviceName[]; -extern const char kAlsaVolumeElementName[]; -extern const char kAudioOutputChannels[]; -extern const char kAudioOutputSampleRate[]; -extern const char kMaxOutputVolumeDba1m[]; -extern const char kMixerEnableDynamicChannelCount[]; -extern const char kMixerSourceAudioReadyThresholdMs[]; -extern const char kMixerSourceInputQueueMs[]; - -// Memory pressure switches -extern const char kMemPressureSystemReservedKb[]; - -// GPU process switches -extern const char kCastInitialScreenWidth[]; -extern const char kCastInitialScreenHeight[]; -extern const char kGraphicsBufferCount[]; -extern const char kVSyncInterval[]; - -// Graphics switches -extern const char kDesktopWindow1080p[]; -extern const char kForceMediaResolutionHeight[]; -extern const char kForceMediaResolutionWidth[]; - -// UI switches -extern const char kEnableInput[]; -extern const char kSystemGestureStartWidth[]; -extern const char kSystemGestureStartHeight[]; -extern const char kBottomSystemGestureStartHeight[]; -extern const char kBackGestureHorizontalThreshold[]; -extern const char kEnableTopDragGesture[]; -extern const char kManagedMode[]; - -// Background color used when Chromium hasn't rendered anything yet. -extern const char kCastAppBackgroundColor[]; - -extern const char kMixerServiceEndpoint[]; -extern const char kMixerServicePort[]; - -extern const char kCastMemoryPressureCriticalFraction[]; -extern const char kCastMemoryPressureModerateFraction[]; - -extern const char kDisableMojoRenderer[]; -extern const char kForceMojoRenderer[]; - -// OTA update related switches. -extern const char kForceUpdateRemoteUrl[]; - -extern const char kSysInfoFilePath[]; - -// Switches for Cast browser decoupling. -extern const char kDeferFeatureList[]; -extern const char kUseCastBrowserPrefConfig[]; -extern const char kInProcessBroker[]; - -extern const char kCastMojoBrokerPath[]; - -} // namespace switches - -namespace chromecast { - -// Gets boolean value from switch |switch_string|. -// --|switch_string| -> true -// --|switch_string|="true" -> true -// --|switch_string|="false" -> false -// no switch named |switch_string| -> |default_value| -bool GetSwitchValueBoolean(const std::string& switch_string, - const bool default_value); - -// Gets an integer value from switch |switch_name|. If the switch is not present -// in the command line, or the value is not an integer, the |default_value| is -// returned. -int GetSwitchValueInt(const std::string& switch_name, const int default_value); - -// Gets a non-negative integer value from switch |switch_name|. If the switch is -// not present in the command line, or the value is not a non-negative integer, -// the |default_value| is returned. -int GetSwitchValueNonNegativeInt(const std::string& switch_name, - const int default_value); - -// Gets a floating point value from switch |switch_name|. If the switch is not -// present in the command line, or the value is not a number, the -// |default_value| is returned. -double GetSwitchValueDouble(const std::string& switch_name, - const double default_value); - -// Gets a color value from the format "#AARRGGBB" (hex). -uint32_t GetSwitchValueColor(const std::string& switch_name, - const uint32_t default_value); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_CHROMECAST_SWITCHES_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/component/component.cc chromium-132.0.6834.159/chromecast/base/component/component.cc --- chromium-132.0.6834.110/chromecast/base/component/component.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/component/component.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,426 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/component/component.h" - -#include -#include - -#include "base/atomicops.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/memory/raw_ptr.h" -#include "base/task/single_thread_task_runner.h" - -namespace chromecast { - -namespace { - -const base::subtle::AtomicWord kEnabledBit = 0x40000000; - -} // namespace - -namespace subtle { - -class DependencyCount : public base::RefCountedThreadSafe { - public: - explicit DependencyCount(ComponentBase* component) - : component_(component), - task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()), - dep_count_(0), - disabling_(false) { - DCHECK(component_); - } - - DependencyCount(const DependencyCount&) = delete; - DependencyCount& operator=(const DependencyCount&) = delete; - - void Detach() { - DCHECK(task_runner_->BelongsToCurrentThread()); - component_ = nullptr; - } - - void Disable() { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(!disabling_); - disabling_ = true; - - std::set dependents(strong_dependents_); - for (DependencyBase* dependent : dependents) - dependent->Disable(); - - while (true) { - AtomicWord deps = base::subtle::NoBarrier_Load(&dep_count_); - AtomicWord old_deps = base::subtle::Acquire_CompareAndSwap( - &dep_count_, deps, deps & ~kEnabledBit); - if (old_deps == deps) { - if ((deps & ~kEnabledBit) == 0) - DisableComplete(); - return; - } - } - } - - void Enable() { - DCHECK(task_runner_->BelongsToCurrentThread()); - disabling_ = false; - while (true) { - AtomicWord deps = base::subtle::NoBarrier_Load(&dep_count_); - DCHECK(!(deps & kEnabledBit)); - AtomicWord old_deps = base::subtle::Release_CompareAndSwap( - &dep_count_, deps, deps | kEnabledBit); - if (old_deps == deps) - break; - } - - for (DependencyBase* dependent : strong_dependents_) - dependent->Ready(component_); - } - - ComponentBase* WeakAcquireDep() { - while (true) { - AtomicWord deps = base::subtle::NoBarrier_Load(&dep_count_); - if (!(deps & kEnabledBit)) - return nullptr; - AtomicWord old_deps = - base::subtle::Acquire_CompareAndSwap(&dep_count_, deps, deps + 1); - // We depend on the fact that a component must be disabled (meaning that - // we will never reach this point) before it is destroyed. Therefore if - // we do reach this point, it is safe to return the raw pointer. - if (old_deps == deps) - return component_; - } - } - - void StrongAcquireDep(DependencyBase* dependent) { - DCHECK(dependent); - DCHECK(task_runner_->BelongsToCurrentThread()); - if (!component_) { - dependent->Disable(); - return; - } - - strong_dependents_.insert(dependent); - AtomicWord count = base::subtle::NoBarrier_AtomicIncrement(&dep_count_, 1); - DCHECK_GT(count, 0); - - if (count & kEnabledBit) { - dependent->Ready(component_); - } else { - component_->Enable(); - } - } - - void StrongReleaseDep(DependencyBase* dependent) { - DCHECK(dependent); - DCHECK(task_runner_->BelongsToCurrentThread()); - strong_dependents_.erase(dependent); - ReleaseDep(); - } - - void ReleaseDep() { - AtomicWord after = base::subtle::Barrier_AtomicIncrement(&dep_count_, -1); - DCHECK_GE(after, 0); - if (after == 0) - DisableComplete(); - } - - bool DependsOn(ComponentBase* component) { - DCHECK(task_runner_->BelongsToCurrentThread()); - if (!component_) - return false; - if (component_ == component) - return true; - return component_->DependsOn(component); - } - - private: - friend class base::RefCountedThreadSafe; - using AtomicWord = base::subtle::AtomicWord; - - ~DependencyCount() {} - - void DisableComplete() { - if (!task_runner_->BelongsToCurrentThread()) { - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&DependencyCount::DisableComplete, this)); - return; - } - // Need to make sure that Enable() was not called in the meantime. - if (base::subtle::NoBarrier_Load(&dep_count_) != 0 || !disabling_) - return; - // Ensure that we don't call DisableComplete() more than once per Disable(). - disabling_ = false; - DCHECK(component_); - DCHECK(strong_dependents_.empty()); - component_->DependencyCountDisableComplete(); - } - - raw_ptr component_; - const scoped_refptr task_runner_; - AtomicWord dep_count_; - bool disabling_; - std::set strong_dependents_; -}; - -DependencyBase::DependencyBase(const WeakReferenceBase& dependency, - ComponentBase* dependent) - : dependent_(dependent), - dependency_(nullptr), - counter_(dependency.counter_) { - DCHECK(dependent_); - dependent_->AddDependency(this); -} - -DependencyBase::~DependencyBase() {} - -void DependencyBase::StartUsing() { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!dependency_); - counter_->StrongAcquireDep(this); -} - -void DependencyBase::StopUsing() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (!dependency_) - return; - dependency_ = nullptr; - counter_->StrongReleaseDep(this); -} - -void DependencyBase::Ready(ComponentBase* dependency) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!dependency_); - DCHECK(dependency); - dependency_ = dependency; - dependent_->DependencyReady(); -} - -void DependencyBase::Disable() { - DCHECK(thread_checker_.CalledOnValidThread()); - dependent_->Disable(); -} - -bool DependencyBase::DependsOn(ComponentBase* component) { - return counter_->DependsOn(component); -} - -WeakReferenceBase::WeakReferenceBase(const ComponentBase& dependency) - : counter_(dependency.counter_) { - DCHECK(counter_); -} - -WeakReferenceBase::WeakReferenceBase(const DependencyBase& dependency) - : counter_(dependency.counter_) { - DCHECK(counter_); -} - -WeakReferenceBase::WeakReferenceBase(const WeakReferenceBase& other) - : counter_(other.counter_) { - DCHECK(counter_); -} - -WeakReferenceBase::WeakReferenceBase(WeakReferenceBase&& other) - : counter_(std::move(other.counter_)) { - DCHECK(counter_); -} - -WeakReferenceBase::~WeakReferenceBase() {} - -ScopedReferenceBase::ScopedReferenceBase( - const scoped_refptr& counter) - : counter_(counter) { - DCHECK(counter_); - dependency_ = counter_->WeakAcquireDep(); -} - -ScopedReferenceBase::ScopedReferenceBase(ScopedReferenceBase&& other) - : counter_(std::move(other.counter_)), dependency_(other.dependency_) { - DCHECK(counter_); - other.dependency_ = nullptr; -} - -ScopedReferenceBase::~ScopedReferenceBase() { - if (dependency_) - counter_->ReleaseDep(); -} - -} // namespace subtle - -ComponentBase::ComponentBase() - : task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()), - state_(kStateDisabled), - async_call_in_progress_(false), - pending_dependency_count_(0), - observers_(new base::ObserverListThreadSafe()) { - counter_ = new subtle::DependencyCount(this); -} - -ComponentBase::~ComponentBase() { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK_EQ(kStateDisabled, state_) << "Components must be disabled " - << "before being destroyed"; - counter_->Detach(); -} - -void ComponentBase::Enable() { - DCHECK(task_runner_->BelongsToCurrentThread()); - if (state_ == kStateEnabling || state_ == kStateEnabled || - state_ == kStateDestroying) { - return; - } - state_ = kStateEnabling; - - if (strong_dependencies_.empty()) { - TryOnEnable(); - } else { - // Enable all strong dependencies first. - pending_dependency_count_ = strong_dependencies_.size(); - for (subtle::DependencyBase* dependency : strong_dependencies_) - dependency->StartUsing(); - } -} - -void ComponentBase::DependencyReady() { - DCHECK(task_runner_->BelongsToCurrentThread()); - if (state_ != kStateEnabling) - return; - DCHECK_GT(pending_dependency_count_, 0); - --pending_dependency_count_; - if (pending_dependency_count_ == 0) - TryOnEnable(); -} - -void ComponentBase::TryOnEnable() { - DCHECK_EQ(kStateEnabling, state_); - if (async_call_in_progress_) - return; - async_call_in_progress_ = true; - OnEnable(); -} - -void ComponentBase::OnEnableComplete(bool success) { - // Always post a task, to prevent the stack from getting too deep. - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&ComponentBase::OnEnableCompleteInternal, - base::Unretained(this), success)); -} - -void ComponentBase::OnEnableCompleteInternal(bool success) { - async_call_in_progress_ = false; - DCHECK(state_ == kStateEnabling || state_ == kStateDisabling || - state_ == kStateDestroying); - if (state_ != kStateEnabling) { - if (success) { - TryOnDisable(); - } else { - OnDisableCompleteInternal(); - } - return; - } - - if (success) { - state_ = kStateEnabled; - counter_->Enable(); - } else { - Disable(); - } - observers_->Notify(FROM_HERE, &Observer::OnComponentEnabled, this, success); -} - -void ComponentBase::Destroy() { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK_NE(kStateDestroying, state_); - if (state_ == kStateDisabled) { - delete this; - } else { - bool should_disable = (state_ != kStateDisabling); - state_ = kStateDestroying; - if (should_disable) - counter_->Disable(); - } -} - -void ComponentBase::AddObserver(Observer* observer) { - DCHECK(observer); - observers_->AddObserver(observer); -} - -void ComponentBase::RemoveObserver(Observer* observer) { - observers_->RemoveObserver(observer); -} - -void ComponentBase::Disable() { - DCHECK(task_runner_->BelongsToCurrentThread()); - if (state_ == kStateDisabling || state_ == kStateDisabled || - state_ == kStateDestroying) { - return; - } - state_ = kStateDisabling; - counter_->Disable(); -} - -void ComponentBase::DependencyCountDisableComplete() { - DCHECK(task_runner_->BelongsToCurrentThread()); - if (state_ == kStateDisabling || state_ == kStateDestroying) - TryOnDisable(); -} - -void ComponentBase::TryOnDisable() { - DCHECK(state_ == kStateDisabling || state_ == kStateDestroying); - if (async_call_in_progress_) - return; - async_call_in_progress_ = true; - OnDisable(); -} - -void ComponentBase::OnDisableComplete() { - // Always post a task, to prevent calls to Disable() from within Enable(). - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&ComponentBase::OnDisableCompleteInternal, - base::Unretained(this))); -} - -void ComponentBase::OnDisableCompleteInternal() { - async_call_in_progress_ = false; - DCHECK(state_ == kStateEnabling || state_ == kStateDisabling || - state_ == kStateDestroying); - if (state_ == kStateEnabling) { - TryOnEnable(); - return; - } - - if (state_ == kStateDestroying) { - StopUsingDependencies(); - observers_->Notify(FROM_HERE, &Observer::OnComponentDisabled, this); - state_ = kStateDisabled; - delete this; - } else { - state_ = kStateDisabled; - StopUsingDependencies(); - observers_->Notify(FROM_HERE, &Observer::OnComponentDisabled, this); - } -} - -void ComponentBase::AddDependency(subtle::DependencyBase* dependency) { - DCHECK_EQ(kStateDisabled, state_); - DCHECK(!dependency->DependsOn(this)) << "Circular dependency detected"; - strong_dependencies_.push_back(dependency); -} - -void ComponentBase::StopUsingDependencies() { - for (subtle::DependencyBase* dependency : strong_dependencies_) - dependency->StopUsing(); -} - -bool ComponentBase::DependsOn(ComponentBase* component) { - for (subtle::DependencyBase* dependency : strong_dependencies_) { - if (dependency->DependsOn(component)) - return true; - } - return false; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/component/component.h chromium-132.0.6834.159/chromecast/base/component/component.h --- chromium-132.0.6834.110/chromecast/base/component/component.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/component/component.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,327 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// A component is a large, long-lived set of functionality that may be enabled -// or disabled at runtime. Some examples include: the multizone features, -// MetricsRecorder, or OpencastController. Components may depend on each other -// (ie, a component may call the public methods of other components); the -// Component infrastructure ensures that when a component is disabled, nothing -// that depends on it will call any of its methods until it is enabled again. -// -// Components may be used without a dependency relationship via a weak -// reference. A weak reference does not allow direct access to the component; -// instead, it must be either used to create a strict dependency (see below), or -// be converted to a scoped reference via Try(). Scoped references must be -// checked for validity before use (they are convertible to bool); an invalid -// scoped reference must not be used. Scoped references should be short-lived; -// to encourage this, they are only move-constructible and cannot be copied or -// assigned. -// -// If component Y depends on Component X, then Y has a Dependency reference -// to X. This causes Y to be disabled as X is being disabled (before X's -// OnDisable() method is called). Similarly, this dependency will cause X to be -// enabled when Y is being enabled (X will be enabled before Y's OnEnable() -// method is called). A component may freely access any of its dependencies -// as long as it is enabled. When a component is disabled, it must ensure that -// none of its dependencies will be used again until it is enabled. It is -// recommended to set up dependencies in your component's constructor; it is an -// error to add a dependency to a component that is not disabled. -// -// When a component is disabled, it will first recursively disable any other -// components that depend on it. It will also disable the creation of -// new scoped references. It then waits for all scoped references to be -// destroyed before calling OnDisable() to actually disable the component. -// -// Components MUST be disabled before they are deleted. For ease of use, a -// Destroy() method is provided. When Destroy() is called, it prevents the -// component from being enabled ever again, and then disables it, deleting it -// once it is disabled. -// -// Example usage: -// -// class MetricsRecorder : public Component { -// public: -// virtual ~MetricsRecorder() {} -// virtual void RecordEvent(const std::string& event) = 0; -// }; -// -// class SetupManager : public Component { -// public: -// virtual ~SetupManager() {} -// virtual int GetMultizoneDelay() = 0; -// }; -// -// class Multizone : public Component { -// public: -// virtual ~Multizone() {} -// virtual void DoMultizoneStuff() = 0; -// }; -// -// class MetricsRecorderImpl : public MetricsRecorder { -// public: -// void OnEnable() override { -// // ... Enable metrics reporting ... -// OnEnableComplete(true); -// } -// -// // Release all resources; public methods will not be called after this. -// void OnDisable() override { -// OnDisableComplete(); -// } -// -// void RecordEvent(const std::string& event) override { -// // ... Record an event ... -// } -// }; -// -// class SetupManagerImpl : public SetupManager { -// public: -// void OnEnable() override { -// // ... Enable setup manager ... -// // OnEnableComplete() may be called asynchronously. -// base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( -// FROM_HERE, base::BindOnce(&SetupManagerImpl::CompleteEnable, -// base::Unretained(this))); -// } -// -// void CompleteEnable() { -// OnEnableComplete(true); -// } -// -// void OnDisable() override { -// OnDisableComplete(); -// } -// -// int GetMultizoneDelay() override { return 0; } -// }; -// -// class MultizoneImpl : public Multizone { -// public: -// MultizoneImpl(const MetricsRecorder::WeakRef& metrics_recorder, -// const SetupManager::WeakRef& setup_manager) -// : metrics_recorder_(metrics_recorder, this), -// setup_manager_(setup_manager) { -// // We can try to use weak deps even before this component is enabled. -// // However, we MUST NOT attempt to use any strong dependencies. -// if (auto setup = setup_manager_.Try()) { -// int delay = setup->GetMultizoneDelay(); -// // ... Do something with delay ... -// } -// } -// -// void OnEnable() override { -// // ... Enable multizone ... -// // Can use strong dependencies directly -// metrics_recorder_->RecordEvent("enable multizone"); -// OnEnableComplete(); -// } -// -// void OnDisable() override { -// // Can still use strong dependencies here. However, this method MUST -// // ensure that strong dependencies will NOT be used after it returns. -// metrics_recorder_->RecordEvent("disable multizone"); -// OnDisableComplete(); -// } -// -// void DoMultizoneStuff() { -// metrics_recorder_->RecordEvent("multizone stuff"); -// // You have to Try() every time you use a weak dependency. -// if (auto setup = setup_manager_.Try()) { -// int delay = setup->GetMultizoneDelay(); -// // ... Do something with delay ... -// } -// } -// -// private: -// MetricsRecorder::Dependency metrics_recorder_; -// SetupManager::WeakRef setup_manager_; -// }; - -#ifndef CHROMECAST_BASE_COMPONENT_COMPONENT_H_ -#define CHROMECAST_BASE_COMPONENT_COMPONENT_H_ - -#include - -#include "base/check.h" -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list_threadsafe.h" -#include "base/threading/thread_checker.h" -#include "chromecast/base/component/component_internal.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { - -class ComponentBase { - public: - class Observer { - public: - // Called when a component finishes being enabled. If the component was - // enabled successfully, |success| will be |true|. Note that access to - // |component| is not guaranteed to be safe; since the observers are - // notified asynchronously, |component| may have been already deleted. - virtual void OnComponentEnabled(ComponentBase* component, bool success) {} - // Called when a component has been disabled. Access to |component| is not - // guaranteed to be safe. - virtual void OnComponentDisabled(ComponentBase* component) {} - - protected: - virtual ~Observer() {} - }; - - ComponentBase(const ComponentBase&) = delete; - ComponentBase& operator=(const ComponentBase&) = delete; - - virtual ~ComponentBase(); - - // Enables this component if possible. Attempts to enable all strong - // dependencies first. It is OK to call Disable() while the component is in - // the process of being enabled. All components MUST be created/enabled/ - // disabled/destroyed on the same thread. - // Note that enabling a component may occur asynchronously; components must - // always be accessed through a Dependency or WeakReference to ensure safety. - // TODO(kmackay) Consider allowing components to be used on any thread. - void Enable(); - - // Disables this component; disabling may complete asynchronously. It is OK to - // call Enable() again while the component is being disabled. Note that a - // component MUST be disabled (or never enabled) before it is deleted. - void Disable(); - - // Deletes this component, disabling it first if necessary. - void Destroy(); - - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - protected: - ComponentBase(); - - // Enables the component implementation. This method must set things up so - // that any public method calls are valid, and then call OnEnableComplete(), - // passing in |true| if the enable was successful, |false| otherwise. - // OnEnableComplete() may be called from any thread. OnEnable() will not be - // called again until after the component has been disabled, and will not be - // called during an ongoing OnDisable() call (so if OnDisable() is called, - // then OnEnable() will not be called until OnDisableComplete() has been - // called). This method is called only on the thread that the component was - // created on. - virtual void OnEnable() = 0; - - // Disables the component implementation. This is not called until there are - // no more live dependencies, so there will be no more public method calls - // to the component until after OnEnable() is called again. This method must - // do whatever is necessary to ensure that no more calls to dependencies of - // this component will be made, and then call the |disabled_cb|. The - // |disabled_cb| may be called from any thread. This method is called only on - // the thread that the component was created on. - virtual void OnDisable() = 0; - - // Handles the success/failure of a call to OnEnable(). When OnEnable() is - // called, it must eventually call OnEnableComplete() (after the component is - // ready to be used by dependents), passing in |true| if the component was - // enabled successfully. If |success| is false, then OnDisable() will be - // called immediately to return the component to a consistent disabled state. - // May be called on any thread. - void OnEnableComplete(bool success); - - // Handles the completion of a call to OnDisable(). When OnDisable() is - // called, it must eventually call OnDisableComplete() (after ensuring that - // none of the component's strong dependencies will be used anymore). May be - // called on any thread. - void OnDisableComplete(); - - private: - friend class subtle::DependencyCount; - friend class subtle::DependencyBase; - friend class subtle::WeakReferenceBase; - - enum State { - kStateDisabled, - kStateDisabling, - kStateEnabled, - kStateEnabling, - kStateDestroying - }; - - void DependencyReady(); - void TryOnEnable(); - void OnEnableCompleteInternal(bool success); - void DependencyCountDisableComplete(); - void TryOnDisable(); - void OnDisableCompleteInternal(); - void AddDependency(subtle::DependencyBase* dependency); - void StopUsingDependencies(); - // Returns |true| if |component| is a transitive dependency of this component. - bool DependsOn(ComponentBase* component); - - const scoped_refptr task_runner_; - scoped_refptr counter_; - std::vector strong_dependencies_; - State state_; - // |true| when a call to OnEnable()/OnDisable() is in progress. - bool async_call_in_progress_; - int pending_dependency_count_; - const scoped_refptr> observers_; -}; - -template -class StrongDependency : public subtle::DependencyBase { - public: - StrongDependency(const WeakReference& dependency, ComponentBase* dependent) - : subtle::DependencyBase(dependency, dependent) {} - - StrongDependency(const StrongDependency&) = delete; - StrongDependency& operator=(const StrongDependency&) = delete; - - C* operator->() const { - DCHECK(dependency_); - return static_cast(dependency_); - } -}; - -template -class WeakReference : public subtle::WeakReferenceBase { - public: - explicit WeakReference(const C& dependency) : WeakReferenceBase(dependency) {} - explicit WeakReference(const StrongDependency& dependency) - : subtle::WeakReferenceBase(dependency) {} - - // Explicitly allow copy. - WeakReference(const WeakReference& other) = default; - WeakReference(WeakReference&& other) = default; - - // Disallow assignment. - void operator=(const WeakReference&) = delete; - - // Try to get a scoped reference. Expected usage: - // if (auto ref = weak.Try()) { - // // ... use ref ... - // } - subtle::Ref_DO_NOT_DECLARE Try() const { - return subtle::Ref_DO_NOT_DECLARE(counter_); - } -}; - -template -class Component : public ComponentBase { - public: - using WeakRef = WeakReference; - using Dependency = StrongDependency; - - Component() = default; - - Component(const Component&) = delete; - Component& operator=(const Component&) = delete; - - WeakRef GetRef() { return WeakRef(*static_cast(this)); } -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_COMPONENT_COMPONENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/component/component_internal.h chromium-132.0.6834.159/chromecast/base/component/component_internal.h --- chromium-132.0.6834.110/chromecast/base/component/component_internal.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/component/component_internal.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_COMPONENT_COMPONENT_INTERNAL_H_ -#define CHROMECAST_BASE_COMPONENT_COMPONENT_INTERNAL_H_ - -#include "base/check.h" -#include "base/functional/callback.h" -#include "base/memory/raw_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" - -namespace chromecast { - -template -class WeakReference; - -class ComponentBase; - -namespace subtle { - -class WeakReferenceBase; - -// Manages thread-safe dependency counting. Instances of this class are -// RefCountedThreadSafe since they must live as long as any dependent. -class DependencyCount; - -// Base class for strong dependencies. A strong dependency is tied to a -// specific dependent component instance. This allows dependents to be -// disabled before the component they depend on. May be used on any thread. -class DependencyBase { - public: - DependencyBase(const WeakReferenceBase& dependency, ComponentBase* dependent); - - DependencyBase(const DependencyBase&) = delete; - DependencyBase& operator=(const DependencyBase&) = delete; - - ~DependencyBase(); - - void StartUsing(); - void StopUsing(); - bool DependsOn(ComponentBase* component); - - protected: - const raw_ptr dependent_; - raw_ptr dependency_; - - private: - friend class DependencyCount; - friend class WeakReferenceBase; - - void Ready(ComponentBase* dependency); - void Disable(); - - const scoped_refptr counter_; - base::ThreadChecker thread_checker_; -}; - -// Base class for weak dependencies. Weak dependencies cannot be used -// directly; they must be converted to a strong dependency or a temp -// dependency first. May be converted on any thread. -class WeakReferenceBase { - protected: - friend class DependencyBase; - - explicit WeakReferenceBase(const ComponentBase& dependency); - explicit WeakReferenceBase(const DependencyBase& dependency); - WeakReferenceBase(const WeakReferenceBase& other); - WeakReferenceBase(WeakReferenceBase&& other); - ~WeakReferenceBase(); - - const scoped_refptr counter_; -}; - -// Base class for temp dependencies. Temp dependencies are meant for -// short-term use only, but can be used from any thread. -class ScopedReferenceBase { - protected: - explicit ScopedReferenceBase(const scoped_refptr& counter); - ScopedReferenceBase(ScopedReferenceBase&& other); - ~ScopedReferenceBase(); - - const scoped_refptr counter_; - raw_ptr dependency_; -}; - -// This class is not intended to be long-lived, and should not be declared as -// a variable type (eg, don't use it as a member variable). Instead, use auto -// (see WeakReference::Try() for an example). -template -class Ref_DO_NOT_DECLARE : public ScopedReferenceBase { - public: - Ref_DO_NOT_DECLARE(Ref_DO_NOT_DECLARE&& other) = default; - - C* operator->() const { - DCHECK(dependency_); - return static_cast(dependency_); - } - - explicit operator bool() const { return (dependency_ != nullptr); } - - private: - friend class WeakReference; - - explicit Ref_DO_NOT_DECLARE(const scoped_refptr& counter) - : ScopedReferenceBase(counter) {} - - Ref_DO_NOT_DECLARE(const Ref_DO_NOT_DECLARE& other) = delete; - Ref_DO_NOT_DECLARE& operator=(const Ref_DO_NOT_DECLARE& rhs) = delete; - Ref_DO_NOT_DECLARE& operator=(Ref_DO_NOT_DECLARE&& rhs) = delete; -}; - -} // namespace subtle -} // namespace chromecast - -#endif // CHROMECAST_BASE_COMPONENT_COMPONENT_INTERNAL_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/component/component_unittest.cc chromium-132.0.6834.159/chromecast/base/component/component_unittest.cc --- chromium-132.0.6834.110/chromecast/base/component/component_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/component/component_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,387 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/component/component.h" - -#include - -#include "base/functional/bind.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "build/build_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -class ComponentTest : public ::testing::Test { - protected: - base::test::SingleThreadTaskEnvironment task_environment_; -}; - -using ComponentDeathTest = ComponentTest; - -class ComponentB; -class ComponentC; -class ComponentA : public Component { - public: - void MakeSelfDependency() { - a_.reset(new Component::Dependency(GetRef(), this)); - } - - void MakeCircularDependency(const Component::WeakRef& b) { - b_.reset(new Component::Dependency(b, this)); - } - - void MakeTransitiveCircularDependency( - const Component::WeakRef& c) { - c_.reset(new Component::Dependency(c, this)); - } - - void OnEnable() override { - if (!fail_enable_) { - enabled_ = true; - Test(); - } - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&ComponentA::OnEnableComplete, - base::Unretained(this), !fail_enable_)); - } - - void OnDisable() override { - if (enabled_) - Test(); - enabled_ = false; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&ComponentA::OnDisableComplete, base::Unretained(this))); - } - - void Test() { - EXPECT_TRUE(enabled_); - EXPECT_FALSE(fail_enable_); - } - - bool enabled() const { return enabled_; } - void FailEnable() { fail_enable_ = true; } - - private: - bool enabled_ = false; - bool fail_enable_ = false; - - std::unique_ptr::Dependency> a_; - std::unique_ptr::Dependency> b_; - std::unique_ptr::Dependency> c_; -}; - -class ComponentB : public Component { - public: - explicit ComponentB(const ComponentA::WeakRef& a) : a_(a, this) {} - - void OnEnable() override { - if (!fail_enable_) { - enabled_ = true; - Test(); - } - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&ComponentB::OnEnableComplete, - base::Unretained(this), !fail_enable_)); - } - - void OnDisable() override { - if (enabled_) - Test(); - enabled_ = false; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&ComponentB::OnDisableComplete, base::Unretained(this))); - } - - void Test() { - EXPECT_TRUE(enabled_); - EXPECT_FALSE(fail_enable_); - a_->Test(); - } - - bool enabled() const { return enabled_; } - void FailEnable() { fail_enable_ = true; } - - private: - bool enabled_ = false; - bool fail_enable_ = false; - - ComponentA::Dependency a_; -}; - -class ComponentC : public Component { - public: - explicit ComponentC(const ComponentB::WeakRef& b) : b_(b, this) {} - - void OnEnable() override { - if (!fail_enable_) { - enabled_ = true; - Test(); - } - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&ComponentC::OnEnableComplete, - base::Unretained(this), !fail_enable_)); - } - - void OnDisable() override { - if (enabled_) - Test(); - enabled_ = false; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&ComponentC::OnDisableComplete, base::Unretained(this))); - } - - void Test() { - EXPECT_TRUE(enabled_); - EXPECT_FALSE(fail_enable_); - b_->Test(); - } - - bool enabled() const { return enabled_; } - void FailEnable() { fail_enable_ = true; } - - private: - bool enabled_ = false; - bool fail_enable_ = false; - - ComponentB::Dependency b_; -}; - -std::string DeathRegex(const std::string& regex) { -#if BUILDFLAG(IS_ANDROID) - return ""; -#else - return regex; -#endif -} - -#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) && GTEST_HAS_DEATH_TEST -TEST_F(ComponentDeathTest, SelfDependency) { - GTEST_FLAG_SET(death_test_style, "threadsafe"); - ComponentA a; - EXPECT_DEATH(a.MakeSelfDependency(), DeathRegex("Circular dependency")); -} - -TEST_F(ComponentDeathTest, CircularDependency) { - GTEST_FLAG_SET(death_test_style, "threadsafe"); - ComponentA a; - ComponentB b(a.GetRef()); - EXPECT_DEATH(a.MakeCircularDependency(b.GetRef()), - DeathRegex("Circular dependency")); -} - -TEST_F(ComponentDeathTest, TransitiveCircularDependency) { - GTEST_FLAG_SET(death_test_style, "threadsafe"); - ComponentA a; - ComponentB b(a.GetRef()); - ComponentC c(b.GetRef()); - EXPECT_DEATH(a.MakeTransitiveCircularDependency(c.GetRef()), - DeathRegex("Circular dependency")); -} -#endif // (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) && - // GTEST_HAS_DEATH_TEST - -TEST_F(ComponentTest, SimpleEnable) { - std::unique_ptr a(new ComponentA()); - a->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, TransitiveEnable) { - std::unique_ptr a(new ComponentA()); - std::unique_ptr b(new ComponentB(a->GetRef())); - std::unique_ptr c(new ComponentC(b->GetRef())); - c->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(a->enabled()); - EXPECT_TRUE(b->enabled()); - EXPECT_TRUE(c->enabled()); - a.release()->Destroy(); - b.release()->Destroy(); - c.release()->Destroy(); -} - -TEST_F(ComponentTest, FailEnable) { - std::unique_ptr a(new ComponentA()); - a->FailEnable(); - a->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, TransitiveFailEnable) { - std::unique_ptr a(new ComponentA()); - std::unique_ptr b(new ComponentB(a->GetRef())); - std::unique_ptr c(new ComponentC(b->GetRef())); - a->FailEnable(); - c->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - EXPECT_FALSE(b->enabled()); - EXPECT_FALSE(c->enabled()); - a.release()->Destroy(); - b.release()->Destroy(); - c.release()->Destroy(); -} - -TEST_F(ComponentTest, DisableWhileEnabling) { - std::unique_ptr a(new ComponentA()); - a->Enable(); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, EnableTwice) { - std::unique_ptr a(new ComponentA()); - a->Enable(); - a->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, DisableTwice) { - std::unique_ptr a(new ComponentA()); - a->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(a->enabled()); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, DisableAfterFailedEnable) { - std::unique_ptr a(new ComponentA()); - a->FailEnable(); - a->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, DisableAfterNeverEnabled) { - std::unique_ptr a(new ComponentA()); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, DisableDependencyWhileEnabling) { - std::unique_ptr a(new ComponentA()); - std::unique_ptr b(new ComponentB(a->GetRef())); - std::unique_ptr c(new ComponentC(b->GetRef())); - b->Enable(); - base::RunLoop().RunUntilIdle(); - c->Enable(); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - EXPECT_FALSE(b->enabled()); - EXPECT_FALSE(c->enabled()); - a.release()->Destroy(); - b.release()->Destroy(); - c.release()->Destroy(); -} - -TEST_F(ComponentTest, EnableDisableEnable) { - std::unique_ptr a(new ComponentA()); - a->Enable(); - a->Disable(); - a->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, DisableEnableDisable) { - std::unique_ptr a(new ComponentA()); - a->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(a->enabled()); - a->Disable(); - a->Enable(); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, TransitiveEnableDisableEnable) { - std::unique_ptr a(new ComponentA()); - std::unique_ptr b(new ComponentB(a->GetRef())); - std::unique_ptr c(new ComponentC(b->GetRef())); - a->Enable(); - base::RunLoop().RunUntilIdle(); - c->Enable(); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - EXPECT_FALSE(b->enabled()); - EXPECT_FALSE(c->enabled()); - c->Enable(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(a->enabled()); - EXPECT_TRUE(b->enabled()); - EXPECT_TRUE(c->enabled()); - a.release()->Destroy(); - b.release()->Destroy(); - c.release()->Destroy(); -} - -TEST_F(ComponentTest, WeakRefs) { - std::unique_ptr a(new ComponentA()); - ComponentA::WeakRef weak = a->GetRef(); - EXPECT_FALSE(weak.Try()); - a->Enable(); - EXPECT_FALSE(weak.Try()); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(weak.Try()); - weak.Try()->Test(); - a->Disable(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(weak.Try()); - a.release()->Destroy(); -} - -TEST_F(ComponentTest, WeakRefsKeepEnabled) { - std::unique_ptr a(new ComponentA()); - ComponentA::WeakRef weak = a->GetRef(); - EXPECT_FALSE(weak.Try()); - a->Enable(); - EXPECT_FALSE(weak.Try()); - base::RunLoop().RunUntilIdle(); - { - auto held_ref = weak.Try(); - EXPECT_TRUE(held_ref); - held_ref->Test(); - a->Disable(); - base::RunLoop().RunUntilIdle(); - // The held ref keeps |a| enabled until it goes out of scope. - EXPECT_TRUE(a->enabled()); - } - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(a->enabled()); - EXPECT_FALSE(weak.Try()); - a.release()->Destroy(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/device_capabilities.h chromium-132.0.6834.159/chromecast/base/device_capabilities.h --- chromium-132.0.6834.110/chromecast/base/device_capabilities.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/device_capabilities.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,257 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_DEVICE_CAPABILITIES_H_ -#define CHROMECAST_BASE_DEVICE_CAPABILITIES_H_ - -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/values.h" - -namespace chromecast { - -// Device capabilities are a set of features used to determine what operations -// are available on the device. They are identified by a key (string) and a -// value (base::Value). The class serves 2 main purposes: -// -// 1) Provide an interface for updating default capabilities and querying their -// current value. Default capabilities are known to the system beforehand -// and used by modules throughout Chromecast to control behavior of operations. -// -// 2) Store dynamic capabilities. Dynamic capabilities are not known to the -// system beforehand and are introduced by external parties. These capabilites -// are stored and then forwarded to app servers that use them to determine how -// to interact with the device. -// -// Capabilities can be classified as either "public" or "private". Capabilities -// of both types can be used by the Chromecast platform to control internal -// behaviors, but only public capabilities will be advertised to app servers. -// Once a capability is set, it retains its privacy classification permanently; -// attempting to change the privacy of a capability results in an error. -// Private capabilities can only be added by Validators. Calling SetCapability() -// on a path without a Validator will default to setting the capability as -// public. -// -// Thread Safety: -// Observers can be added from any thread. Each Observer is guaranteed to be -// notified on same thread that it was added on and must be removed on the same -// thread that it was added on. -// -// Validators can be registered from any thread. Each Validator's Validate() -// method is guaranteed to be called on same thread that the Validator was -// registered on. The Validator must be unregistered on the same thread -// that it was registered on. -// -// All other methods can be called safely from any thread. - -// TODO(esum): -// 1) Add WifiSupported, HotspotSupported, and MultizoneSupported capabilities. -// 2) It's not ideal to have the accessors (BluetoothSupported(), etc.) not -// be valid initially until the capability gets registered. We might want -// to use some kind of builder class to solve this. -class DeviceCapabilities { - public: - class Observer { - public: - // Called when DeviceCapabilities gets written to in any way. |path| - // is full path to capability that has been updated. - virtual void OnCapabilitiesChanged(const std::string& path) = 0; - - protected: - virtual ~Observer() {} - }; - - // When another module attempts to update the value for a capability, - // a manager may want to validate the change or even modify the new value. - // Managers that wish to perform this validation should inherit from the - // Validator class and implement its interface. - class Validator { - public: - Validator(const Validator&) = delete; - Validator& operator=(const Validator&) = delete; - - // |path| is full path to capability, which could include paths expanded on - // the capability key that gets registered through the Register() method. - // For example, if a key of "foo" is registered for a Validator, |path| - // could be "foo", "foo.bar", "foo.bar.what", etc. |proposed_value| is new - // value being proposed for |path|. Determines if |proposed_value| is valid - // change for |path|. This method may be asynchronous, but multiple calls - // to it must be handled serially. Returns response through - // SetPublicValidatedValue() or SetPrivateValidatedValue(). - virtual void Validate(const std::string& path, - base::Value proposed_value) = 0; - - protected: - explicit Validator(DeviceCapabilities* capabilities); - virtual ~Validator() {} - - DeviceCapabilities* capabilities() const { return capabilities_; } - - // Meant to be called when Validate() has finished. |path| is full path to - // capability. |new_value| is new validated value to be used in - // DeviceCapabilities. This method passes these parameters to - // DeviceCapabilities, where |path| is updated internally to |new_value|. - // TODO(seantopping): Change this interface so that Validators are not the - // only means of accessing private capabilities. - void SetPublicValidatedValue(const std::string& path, - base::Value new_value) const; - void SetPrivateValidatedValue(const std::string& path, - base::Value new_value) const; - - private: - const raw_ptr capabilities_; - }; - - // Class used to store/own capabilities-related data. It is immutable and - // RefCountedThreadSafe, so client code can freely query it throughout its - // lifetime without worrying about the data getting invalidated in any way. - class Data : public base::RefCountedThreadSafe { - public: - Data(const Data&) = delete; - Data& operator=(const Data&) = delete; - - // Accessor for complete capabilities in dictionary format. - const base::Value::Dict& dictionary() const { return dictionary_; } - - // Accessor for complete capabilities string in JSON format. - const std::string& json_string() const { return json_string_; } - - private: - friend class base::RefCountedThreadSafe; - // DeviceCapabilities should be the only one responsible for Data - // construction. See CreateData() methods. - friend class DeviceCapabilities; - - // Constructs empty dictionary with no capabilities. - Data(); - // Uses |dictionary| as capabilities dictionary. - explicit Data(base::Value::Dict dictionary); - ~Data(); - - const base::Value::Dict dictionary_; - std::string json_string_; - }; - - // Default Capability keys - static const char kKeyAssistantSupported[]; - static const char kKeyBluetoothSupported[]; - static const char kKeyDisplaySupported[]; - static const char kKeyHiResAudioSupported[]; - - DeviceCapabilities(const DeviceCapabilities&) = delete; - DeviceCapabilities& operator=(const DeviceCapabilities&) = delete; - - // This class should get destroyed after all Validators have been - // unregistered, all Observers have been removed, and the class is no longer - // being accessed. - virtual ~DeviceCapabilities() {} - - // Create empty instance with no capabilities. Although the class is not - // singleton, there is meant to be a single instance owned by another module. - // The instance should be created early enough for all managers to register - // themselves, and then live long enough for all managers to unregister. - static std::unique_ptr Create(); - // Creates an instance where all the default capabilities are initialized - // to a predefined default value, and no Validators are registered. For use - // only in unit tests. - static std::unique_ptr CreateForTesting(); - - // Registers a Validator for a capability. A given key must only be - // registered once, and must be unregistered before calling Register() again. - // If the capability has a value of Dictionary type, |key| must be just - // the capability's top-level key and not include path expansions to levels - // farther down. For example, "foo" is a valid value for |key|, but "foo.bar" - // is not. Note that if "foo.bar" is updated in SetCapability(), the - // Validate() method for "foo"'s Validator will be called, with a |path| of - // "foo.bar". Note that this method does not add or modify the capability. - // To do this, SetCapability() should be called, or Validators can call - // SetPublicValidatedValue() or SetPrivateValidatedValue(). This method is - // synchronous to ensure Validators know exactly when they may start receiving - // validation requests. - virtual void Register(const std::string& key, - Validator* validator) = 0; - // Unregisters Validator for |key|. |validator| argument must match - // |validator| argument that was passed in to Register() for |key|. Note that - // the capability and its value remain untouched. This method is synchronous - // to ensure Validators know exactly when they will stop receiving validation - // requests. - virtual void Unregister(const std::string& key, - const Validator* validator) = 0; - // Gets the Validator currently registered for |key|. Returns nullptr if - // no Validator is registered. - virtual Validator* GetValidator(const std::string& key) const = 0; - - // Accessors for default capabilities. Note that the capability must be added - // through SetCapability() (or Set[Private]ValidatedValue() for Validators) - // before accessors are called. - virtual bool AssistantSupported() const = 0; - virtual bool BluetoothSupported() const = 0; - virtual bool DisplaySupported() const = 0; - virtual bool HiResAudioSupported() const = 0; - - // Returns a deep copy of the value at |path|. If the capability at |path| - // does not exist, a null scoped_ptr is returned. - virtual base::Value GetCapability(const std::string& path) const = 0; - - // Use this method to access dictionary and JSON string. No deep copying is - // performed, so this method is inexpensive. Note that any capability updates - // that occur after GetAllData() has been called will not be reflected in the - // returned scoped_refptr. You can think of this method as taking a snapshot - // of the capabilities when it gets called. All capabilities (those set by - // SetPrivateValidatedValue() and SetPublicValidatedValue()) will be present - // in the returned Data object. - virtual scoped_refptr GetAllData() const = 0; - // Similar to GetAllData(), but this only returns public capabilities. - virtual scoped_refptr GetPublicData() const = 0; - - // Updates the value at |path| to |proposed_value| if |path| already exists - // and adds new capability if |path| doesn't. Note that if a key has been - // registered that is at the beginning of |path|, then the Validator will be - // used to determine if |proposed_value| is accepted. - // Ex: If "foo" has a Validator registered, a |path| of "foo.bar" - // will cause |proposed_value| to go through the Validator's Validate() - // method. Client code may use the Observer interface to determine the - // ultimate value used. - // This method is asynchronous. By default, this method will classify the new - // value at |path| as a public capability; if a Validator is present, it may - // classify the value as public or private via SetPublicValidatedValue() or - // SetPrivateValidatedValue() respectively. - virtual void SetCapability(const std::string& path, - base::Value proposed_value) = 0; - - // Iterates through entries in |dict| and calls SetCapability() for each one. - // This method is asynchronous. - virtual void MergeDictionary(const base::Value::Dict& dict) = 0; - - // Adds/removes an observer. It doesn't take the ownership of |observer|. - virtual void AddCapabilitiesObserver(Observer* observer) = 0; - virtual void RemoveCapabilitiesObserver(Observer* observer) = 0; - - protected: - DeviceCapabilities() {} - - // For derived implementation classes to create Data instances since they do - // not have access to Data constructors. - // Creates empty dictionary with no capabilities. - static scoped_refptr CreateData(); - // Uses |dictionary| as capabilities dictionary. - static scoped_refptr CreateData(base::Value::Dict dictionary); - - private: - // Internally update the capability residing at |path| to |new_value|. This - // capability will be visible in GetAllData() and GetPublicData(). - virtual void SetPublicValidatedValue(const std::string& path, - base::Value new_value) = 0; - // Similar to SetPublicValidatedValue(), but this capability will only be - // visible in GetAllData(). - virtual void SetPrivateValidatedValue(const std::string& path, - base::Value new_value) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_DEVICE_CAPABILITIES_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/device_capabilities_impl.cc chromium-132.0.6834.159/chromecast/base/device_capabilities_impl.cc --- chromium-132.0.6834.110/chromecast/base/device_capabilities_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/device_capabilities_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,418 +0,0 @@ -// 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 "chromecast/base/device_capabilities_impl.h" - -#include - -#include - -#include "base/containers/contains.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/json/json_writer.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/not_fatal_until.h" -#include "base/strings/string_util.h" -#include "base/task/single_thread_task_runner.h" -#include "base/values.h" - -namespace chromecast { - -namespace { - -const char kPathSeparator = '.'; - -// Determines if a key passed to Register() is valid. No path separators can -// be present in the key and it must not be empty. -bool IsValidRegisterKey(const std::string& key) { - return !key.empty() && !base::Contains(key, kPathSeparator); -} - -// Determines if a path is valid. This is true if there are no empty keys -// anywhere in the path (ex: .foo, foo., foo..bar are all invalid). -bool IsValidPath(const std::string& path) { - return !path.empty() && *path.begin() != kPathSeparator && - *path.rbegin() != kPathSeparator && - path.find("..") == std::string::npos; -} - -// Given a path, gets the first key present in the path (ex: for path "foo.bar" -// return "foo"). -std::string GetFirstKey(const std::string& path) { - std::size_t length_to_first_separator = path.find(kPathSeparator); - return (length_to_first_separator == std::string::npos) - ? path - : path.substr(0, length_to_first_separator); -} - -} // namespace - -// static Default Capability Keys -const char DeviceCapabilities::kKeyAssistantSupported[] = "assistant_supported"; -const char DeviceCapabilities::kKeyBluetoothSupported[] = "bluetooth_supported"; -const char DeviceCapabilities::kKeyDisplaySupported[] = "display_supported"; -const char DeviceCapabilities::kKeyHiResAudioSupported[] = - "hi_res_audio_supported"; - -// static -std::unique_ptr DeviceCapabilities::Create() { - return base::WrapUnique(new DeviceCapabilitiesImpl); -} - -// static -std::unique_ptr DeviceCapabilities::CreateForTesting() { - DeviceCapabilities* capabilities = new DeviceCapabilitiesImpl; - capabilities->SetCapability(kKeyBluetoothSupported, base::Value(false)); - capabilities->SetCapability(kKeyDisplaySupported, base::Value(true)); - capabilities->SetCapability(kKeyHiResAudioSupported, base::Value(false)); - capabilities->SetCapability(kKeyAssistantSupported, base::Value(true)); - return base::WrapUnique(capabilities); -} - -scoped_refptr DeviceCapabilities::CreateData() { - return base::WrapRefCounted(new Data); -} - -scoped_refptr DeviceCapabilities::CreateData( - base::Value::Dict dictionary) { - return base::WrapRefCounted(new Data(std::move(dictionary))); -} - -DeviceCapabilities::Validator::Validator(DeviceCapabilities* capabilities) - : capabilities_(capabilities) { - DCHECK(capabilities); -} - -void DeviceCapabilities::Validator::SetPublicValidatedValue( - const std::string& path, - base::Value new_value) const { - capabilities_->SetPublicValidatedValue(path, std::move(new_value)); -} - -void DeviceCapabilities::Validator::SetPrivateValidatedValue( - const std::string& path, - base::Value new_value) const { - capabilities_->SetPrivateValidatedValue(path, std::move(new_value)); -} - -DeviceCapabilities::Data::Data() { - base::JSONWriter::Write(dictionary_, &json_string_); -} - -DeviceCapabilities::Data::Data(base::Value::Dict dictionary) - : dictionary_(std::move(dictionary)) { - base::JSONWriter::Write(dictionary_, &json_string_); -} - -DeviceCapabilitiesImpl::Data::~Data() {} - -DeviceCapabilitiesImpl::ValidatorInfo::ValidatorInfo(Validator* validator) - : validator_(validator), - task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()) { - DCHECK(validator_); - DCHECK(task_runner_.get()); -} - -DeviceCapabilitiesImpl::ValidatorInfo::~ValidatorInfo() { - // Check that ValidatorInfo is being destroyed on the same thread that it was - // constructed on. - DCHECK(task_runner_->BelongsToCurrentThread()); -} - -void DeviceCapabilitiesImpl::ValidatorInfo::Validate( - const std::string& path, - base::Value proposed_value) const { - // Check that we are running Validate on the same thread that ValidatorInfo - // was constructed on. - DCHECK(task_runner_->BelongsToCurrentThread()); - validator_->Validate(path, std::move(proposed_value)); -} - -DeviceCapabilitiesImpl::DeviceCapabilitiesImpl() - : all_data_(CreateData()), - public_data_(CreateData()), - task_runner_for_writes_( - base::SingleThreadTaskRunner::GetCurrentDefault()), - observer_list_(new base::ObserverListThreadSafe) { - DCHECK(task_runner_for_writes_.get()); -} - -DeviceCapabilitiesImpl::~DeviceCapabilitiesImpl() { - // Make sure that any registered Validators have unregistered at this point - DCHECK(validator_map_.empty()) - << "Some validators weren't properly unregistered: " << [this] { - std::vector keys; - for (const auto& pair : validator_map_) { - keys.push_back(pair.first); - } - return base::JoinString(keys, ", "); - }(); - // Make sure that all observers have been removed at this point - observer_list_->AssertEmpty(); -} - -void DeviceCapabilitiesImpl::Register(const std::string& key, - Validator* validator) { - DCHECK(IsValidRegisterKey(key)); - DCHECK(validator); - - base::AutoLock auto_lock(validation_lock_); - // Check that a validator has not already been registered for this key - DCHECK_EQ(0u, validator_map_.count(key)); - validator_map_[key] = std::make_unique(validator); -} - -void DeviceCapabilitiesImpl::Unregister(const std::string& key, - const Validator* validator) { - base::AutoLock auto_lock(validation_lock_); - auto validator_it = validator_map_.find(key); - CHECK(validator_it != validator_map_.end(), base::NotFatalUntil::M130); - // Check that validator being unregistered matches the original for |key|. - // This prevents managers from accidentally unregistering incorrect - // validators. - DCHECK_EQ(validator, validator_it->second->validator()); - // Check that validator is unregistering on same thread that it was - // registered on - DCHECK(validator_it->second->task_runner()->BelongsToCurrentThread()); - validator_map_.erase(validator_it); -} - -DeviceCapabilities::Validator* DeviceCapabilitiesImpl::GetValidator( - const std::string& key) const { - base::AutoLock auto_lock(validation_lock_); - auto validator_it = validator_map_.find(key); - return validator_it == validator_map_.end() - ? nullptr - : validator_it->second->validator(); -} - -bool DeviceCapabilitiesImpl::BluetoothSupported() const { - scoped_refptr data_ref = GetAllData(); - auto bluetooth_supported = - data_ref->dictionary().FindBool(kKeyBluetoothSupported); - DCHECK(bluetooth_supported); - return *bluetooth_supported; -} - -bool DeviceCapabilitiesImpl::DisplaySupported() const { - scoped_refptr data_ref = GetAllData(); - auto display_supported = - data_ref->dictionary().FindBool(kKeyDisplaySupported); - DCHECK(display_supported); - return *display_supported; -} - -bool DeviceCapabilitiesImpl::HiResAudioSupported() const { - scoped_refptr data_ref = GetAllData(); - auto hi_res_audio_supported = - data_ref->dictionary().FindBool(kKeyHiResAudioSupported); - DCHECK(hi_res_audio_supported); - return *hi_res_audio_supported; -} - -bool DeviceCapabilitiesImpl::AssistantSupported() const { - scoped_refptr data_ref = GetAllData(); - auto assistant_supported = - data_ref->dictionary().FindBool(kKeyAssistantSupported); - DCHECK(assistant_supported); - return *assistant_supported; -} - -base::Value DeviceCapabilitiesImpl::GetCapability( - const std::string& path) const { - scoped_refptr data_ref = GetAllData(); - const base::Value* value = data_ref->dictionary().FindByDottedPath(path); - return value ? value->Clone() : base::Value(); -} - -scoped_refptr DeviceCapabilitiesImpl::GetAllData() - const { - // Need to acquire lock here when copy constructing all_data_ otherwise we - // could concurrently be writing to scoped_refptr in SetPublicValidatedValue() - // or SetPrivateValidatedValue(), which could cause a bad scoped_refptr read. - base::AutoLock auto_lock(data_lock_); - return all_data_; -} - -scoped_refptr DeviceCapabilitiesImpl::GetPublicData() - const { - // Need to acquire lock here when copy constructing public_data_ otherwise we - // could concurrently be writing to scoped_refptr in SetPublicValidatedValue() - // or SetPrivateValidatedValue(), which could cause a bad scoped_refptr read. - base::AutoLock auto_lock(data_lock_); - return public_data_; -} - -void DeviceCapabilitiesImpl::SetCapability(const std::string& path, - base::Value proposed_value) { - if (!IsValidPath(path)) { - LOG(DFATAL) << "Invalid capability path encountered for SetCapability()"; - return; - } - - { - base::AutoLock auto_lock(validation_lock_); - // Check for Validator registered under first key per the Register() - // interface. - auto validator_it = validator_map_.find(GetFirstKey(path)); - if (validator_it != validator_map_.end()) { - // We do not want to post a task directly for the Validator's Validate() - // method here because if another thread is in the middle of unregistering - // that Validator, there will be an outstanding call to Validate() that - // occurs after it has unregistered. Since ValidatorInfo gets destroyed - // in Unregister() on same thread that validation should run on, we can - // post a task to the Validator's thread with weak_ptr. This way, if the - // Validator gets unregistered, the call to Validate will get skipped. - validator_it->second->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&ValidatorInfo::Validate, - validator_it->second->AsWeakPtr(), path, - std::move(proposed_value))); - return; - } - } - // Since we are done checking for a registered Validator at this point, we - // can release the lock. All further member access will be for capabilities. - // By default, a capability without a validator will be public. - SetPublicValidatedValue(path, std::move(proposed_value)); -} - -void DeviceCapabilitiesImpl::MergeDictionary(const base::Value::Dict& dict) { - for (const auto [key, value] : dict) { - SetCapability(key, value.Clone()); - } -} - -void DeviceCapabilitiesImpl::AddCapabilitiesObserver(Observer* observer) { - DCHECK(observer); - observer_list_->AddObserver(observer); -} - -void DeviceCapabilitiesImpl::RemoveCapabilitiesObserver(Observer* observer) { - DCHECK(observer); - observer_list_->RemoveObserver(observer); -} - -void DeviceCapabilitiesImpl::SetPublicValidatedValue(const std::string& path, - base::Value new_value) { - // All internal writes/modifications of capabilities must occur on same - // thread to avoid race conditions. - if (!task_runner_for_writes_->BelongsToCurrentThread()) { - task_runner_for_writes_->PostTask( - FROM_HERE, - base::BindOnce(&DeviceCapabilitiesImpl::SetPublicValidatedValue, - base::Unretained(this), path, std::move(new_value))); - return; - } - - DCHECK(IsValidPath(path)); - - // If the capability exists, it must be public (present in all_data_ and - // public_data_). We cannot change the privacy of an already existing - // capability. - bool is_private = all_data_->dictionary().Find(path) && - !public_data_->dictionary().Find(path); - if (is_private) { - NOTREACHED() << "Cannot make a private capability '" << path << "' public."; - } - - // We don't need to acquire lock here when reading public_data_ because we - // know that all writes to public_data_ must occur serially on thread that - // we're on. - const base::Value* cur_value = - public_data_->dictionary().FindByDottedPath(path); - bool capability_unchanged = cur_value && *cur_value == new_value; - if (capability_unchanged) { - DVLOG(1) << "Ignoring unchanged public capability: " << path; - return; - } - - // In this sequence, we create deep copies for both dictionaries, modify the - // copies, and then do a pointer swap. We do this to have minimal time spent - // in the data_lock_. If we were to lock and modify the capabilities - // dictionary directly, there may be expensive writes that block other - // threads. - scoped_refptr new_public_data = GenerateDataWithNewValue( - public_data_->dictionary(), path, new_value.Clone()); - scoped_refptr new_data = GenerateDataWithNewValue( - all_data_->dictionary(), path, std::move(new_value)); - - { - base::AutoLock auto_lock(data_lock_); - // Using swap instead of assignment operator here because it's a little - // faster. Avoids an extra call to AddRef()/Release(). - public_data_.swap(new_public_data); - all_data_.swap(new_data); - } - - // Even though ObserverListThreadSafe notifications are always asynchronous - // (posts task even if to same thread), no locks should be held at this point - // in the code. This is just to be safe that no deadlocks occur if Observers - // call DeviceCapabilities methods in OnCapabilitiesChanged(). - observer_list_->Notify(FROM_HERE, &Observer::OnCapabilitiesChanged, path); -} - -void DeviceCapabilitiesImpl::SetPrivateValidatedValue(const std::string& path, - base::Value new_value) { - // All internal writes/modifications of capabilities must occur on same - // thread to avoid race conditions. - if (!task_runner_for_writes_->BelongsToCurrentThread()) { - task_runner_for_writes_->PostTask( - FROM_HERE, - base::BindOnce(&DeviceCapabilitiesImpl::SetPrivateValidatedValue, - base::Unretained(this), path, std::move(new_value))); - return; - } - - DCHECK(IsValidPath(path)); - - // If the capability exists, it must be private (present in all_data_ only). - // We cannot change the privacy of an already existing capability. - const auto* is_public = public_data_->dictionary().Find(path); - if (is_public) { - NOTREACHED() << "Cannot make a public capability '" << path << "' private."; - } - - // We don't need to acquire lock here when reading all_data_ because we know - // that all writes to all_data_ must occur serially on thread that we're on. - const base::Value* cur_value = all_data_->dictionary().FindByDottedPath(path); - bool capability_unchanged = cur_value && *cur_value == new_value; - if (capability_unchanged) { - DVLOG(1) << "Ignoring unchanged capability: " << path; - return; - } - - // In this sequence, we create a deep copy, modify the deep copy, and then - // do a pointer swap. We do this to have minimal time spent in the - // data_lock_. If we were to lock and modify the capabilities - // dictionary directly, there may be expensive writes that block other - // threads. - scoped_refptr new_data = GenerateDataWithNewValue( - all_data_->dictionary(), path, std::move(new_value)); - - { - base::AutoLock auto_lock(data_lock_); - // Using swap instead of assignment operator here because it's a little - // faster. Avoids an extra call to AddRef()/Release(). - all_data_.swap(new_data); - } - - // Even though ObserverListThreadSafe notifications are always asynchronous - // (posts task even if to same thread), no locks should be held at this point - // in the code. This is just to be safe that no deadlocks occur if Observers - // call DeviceCapabilities methods in OnCapabilitiesChanged(). - observer_list_->Notify(FROM_HERE, &Observer::OnCapabilitiesChanged, path); -} - -scoped_refptr -DeviceCapabilitiesImpl::GenerateDataWithNewValue(const base::Value::Dict& dict, - const std::string& path, - base::Value new_value) { - base::Value::Dict dict_deep_copy(dict.Clone()); - dict_deep_copy.SetByDottedPath(path, std::move(new_value)); - return CreateData(std::move(dict_deep_copy)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/device_capabilities_impl.h chromium-132.0.6834.159/chromecast/base/device_capabilities_impl.h --- chromium-132.0.6834.110/chromecast/base/device_capabilities_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/device_capabilities_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,123 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_DEVICE_CAPABILITIES_IMPL_H_ -#define CHROMECAST_BASE_DEVICE_CAPABILITIES_IMPL_H_ - -#include -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list_threadsafe.h" -#include "base/synchronization/lock.h" -#include "base/values.h" -#include "chromecast/base/device_capabilities.h" - -namespace base { -class SingleThreadTaskRunner; -} - -namespace chromecast { - -class DeviceCapabilitiesImpl : public DeviceCapabilities { - public: - DeviceCapabilitiesImpl(const DeviceCapabilitiesImpl&) = delete; - DeviceCapabilitiesImpl& operator=(const DeviceCapabilitiesImpl&) = delete; - - ~DeviceCapabilitiesImpl() override; - - // DeviceCapabilities implementation: - void Register(const std::string& key, Validator* validator) override; - void Unregister(const std::string& key, const Validator* validator) override; - Validator* GetValidator(const std::string& key) const override; - bool AssistantSupported() const override; - bool BluetoothSupported() const override; - bool DisplaySupported() const override; - bool HiResAudioSupported() const override; - base::Value GetCapability(const std::string& path) const override; - scoped_refptr GetAllData() const override; - scoped_refptr GetPublicData() const override; - void SetCapability(const std::string& path, - base::Value proposed_value) override; - void MergeDictionary(const base::Value::Dict& dict) override; - void AddCapabilitiesObserver(Observer* observer) override; - void RemoveCapabilitiesObserver(Observer* observer) override; - - private: - class ValidatorInfo final { - public: - explicit ValidatorInfo(Validator* validator); - - ValidatorInfo(const ValidatorInfo&) = delete; - ValidatorInfo& operator=(const ValidatorInfo&) = delete; - - ~ValidatorInfo(); - - Validator* validator() const { return validator_; } - - scoped_refptr task_runner() const { - return task_runner_; - } - - void Validate(const std::string& path, base::Value proposed_value) const; - - base::WeakPtr AsWeakPtr() { - return weak_ptr_factory_.GetWeakPtr(); - } - - private: - const raw_ptr validator_; - // TaskRunner of thread that validator_ was registered on - const scoped_refptr task_runner_; - - base::WeakPtrFactory weak_ptr_factory_{this}; - }; - - // For DeviceCapabilitiesImpl() - friend class DeviceCapabilities; - - // Map from capability key to corresponding ValidatorInfo. Gets updated - // in Register()/Unregister(). - using ValidatorMap = - std::unordered_map>; - - // Internal constructor used by static DeviceCapabilities::Create*() methods. - DeviceCapabilitiesImpl(); - - void SetPublicValidatedValue(const std::string& path, - base::Value new_value) override; - void SetPrivateValidatedValue(const std::string& path, - base::Value new_value) override; - void SetValidatedValueInternal(const std::string& path, - base::Value new_value); - - scoped_refptr GenerateDataWithNewValue(const base::Value::Dict& dict, - const std::string& path, - base::Value new_value); - - // Lock for reading/writing all_data_ or public_data_ pointers - mutable base::Lock data_lock_; - // Lock for reading/writing validator_map_ - mutable base::Lock validation_lock_; - - // Contains all public and private capabilities. - scoped_refptr all_data_; - // Contains only public capabilities. All capabilities in public_data_ are - // present and duplicated in all_data_. This duplication allows callers to - // quickly query public capabilities without having build a new data - // dictionary. - scoped_refptr public_data_; - // TaskRunner for capability writes. All internal writes to data_ must occur - // on task_runner_for_writes_'s thread. - const scoped_refptr task_runner_for_writes_; - - ValidatorMap validator_map_; - const scoped_refptr> observer_list_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_DEVICE_CAPABILITIES_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/device_capabilities_impl_unittest.cc chromium-132.0.6834.159/chromecast/base/device_capabilities_impl_unittest.cc --- chromium-132.0.6834.110/chromecast/base/device_capabilities_impl_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/device_capabilities_impl_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,649 +0,0 @@ -// 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 "chromecast/base/device_capabilities_impl.h" - -#include -#include - -#include "base/json/json_reader.h" -#include "base/json/json_writer.h" -#include "base/memory/ptr_util.h" -#include "base/memory/raw_ptr.h" -#include "base/message_loop/message_pump_type.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/values.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -namespace { - -const char kSampleDictionaryCapability[] = - "{" - " \"dummy_field_bool\": true," - " \"dummy_field_int\": 99" - "}"; - -void GetSampleDefaultCapability(std::string* key, base::Value* init_value); -void TestBasicOperations(DeviceCapabilities* capabilities); - -// Simple capability manager that implements the Validator interface. Either -// accepts or rejects all proposed changes based on |accept_changes| constructor -// argument. -class FakeCapabilityManagerSimple : public DeviceCapabilities::Validator { - public: - // Registers itself as Validator in constructor. If init_value is not null, - // the capability gets initialized to that value. Else capability remains - // untouched. - FakeCapabilityManagerSimple(DeviceCapabilities* capabilities, - const std::string& key, - base::Value init_value, - bool accept_changes, - bool validate_private) - : DeviceCapabilities::Validator(capabilities), - key_(key), - accept_changes_(accept_changes), - validate_private_(validate_private) { - capabilities->Register(key, this); - if (!init_value.is_none()) { - if (validate_private_) { - SetPrivateValidatedValue(key, std::move(init_value)); - } else { - SetPublicValidatedValue(key, std::move(init_value)); - } - } - } - - // Unregisters itself as Validator. - ~FakeCapabilityManagerSimple() override { - capabilities()->Unregister(key_, this); - } - - void Validate(const std::string& path, base::Value proposed_value) override { - ASSERT_EQ(path.find(key_), 0ul); - if (!accept_changes_) - return; - if (validate_private_) { - SetPrivateValidatedValue(path, std::move(proposed_value)); - } else { - SetPublicValidatedValue(path, std::move(proposed_value)); - } - } - - private: - const std::string key_; - const bool accept_changes_; - const bool validate_private_; -}; - -// Used to test that capabilities/validator can be read and written in -// Validate() without encountering deadlocks/unexpected behavior. -class FakeCapabilityManagerComplex : public DeviceCapabilities::Validator { - public: - FakeCapabilityManagerComplex(DeviceCapabilities* capabilities, - const std::string& key) - : DeviceCapabilities::Validator(capabilities), key_(key) { - capabilities->Register(key, this); - } - - // Unregisters itself as Validator. - ~FakeCapabilityManagerComplex() override { - capabilities()->Unregister(key_, this); - } - - // Runs TestBasicOperations(). - void Validate(const std::string& path, base::Value proposed_value) override { - TestBasicOperations(capabilities()); - } - - private: - const std::string key_; -}; - -// Used to test that capabilities/validators can be read and written in -// OnCapabilitiesChanged() without encountering deadlocks/unexpected behavior. -class FakeCapabilitiesObserver : public DeviceCapabilities::Observer { - public: - explicit FakeCapabilitiesObserver(DeviceCapabilities* capabilities) - : capabilities_(capabilities), removed_as_observer(false) { - capabilities_->AddCapabilitiesObserver(this); - } - - ~FakeCapabilitiesObserver() override { - if (!removed_as_observer) - capabilities_->RemoveCapabilitiesObserver(this); - } - - // Runs TestBasicOperations(). - void OnCapabilitiesChanged(const std::string& path) override { - TestBasicOperations(capabilities_); - // To prevent infinite loop of SetCapability() -> OnCapabilitiesChanged() - // -> SetCapability() -> OnCapabilitiesChanged() etc. - capabilities_->RemoveCapabilitiesObserver(this); - removed_as_observer = true; - } - - private: - const raw_ptr capabilities_; - bool removed_as_observer; -}; - -// Used to test that OnCapabilitiesChanged() is called when capabilities are -// modified -class MockCapabilitiesObserver : public DeviceCapabilities::Observer { - public: - MockCapabilitiesObserver() {} - - MockCapabilitiesObserver(const MockCapabilitiesObserver&) = delete; - MockCapabilitiesObserver& operator=(const MockCapabilitiesObserver&) = delete; - - ~MockCapabilitiesObserver() override {} - - MOCK_METHOD1(OnCapabilitiesChanged, void(const std::string& path)); -}; - -// Test fixtures needs an example default capability to test DeviceCapabilities -// methods. Gets a sample key and initial value. -void GetSampleDefaultCapability(std::string* key, base::Value* init_value) { - DCHECK(key); - DCHECK(init_value); - *key = DeviceCapabilities::kKeyBluetoothSupported; - *init_value = base::Value(true); -} - -// For test fixtures that test dynamic capabilities, gets a sample key -// and initial value. -void GetSampleDynamicCapability(std::string* key, base::Value* init_value) { - DCHECK(key); - DCHECK(init_value); - *key = "dummy_dynamic_key"; - *init_value = base::Value(99); -} - -// Gets a value for sample default capability different from |init_value| -// returned in GetSampleDefaultCapability(). Must be of same type as -// |init_value| of course. -base::Value GetSampleDefaultCapabilityNewValue() { - return base::Value(false); -} - -// Gets a value for sample dynamic capability different from |init_value| -// returned in GetSampleDynamicCapability(). Must be of same type as -// |init_value| of course. -base::Value GetSampleDynamicCapabilityNewValue() { - return base::Value(100); -} - -// Tests that |json| string matches contents of a DictionaryValue with one entry -// specified by |key| and |value|. -bool JsonStringEquals(const std::string& json, - const std::string& key, - const base::Value& value) { - return base::WriteJson(base::Value::Dict().Set(key, value.Clone())) == json; -} - -// The function runs through the set of basic operations of DeviceCapabilities. -// Register validator for sample default capability, reads capability, writes -// capability, and unregister validator. After it has completed, use -// AssertBasicOperationsSuccessful() to ensure that all operations completed -// successfully. Sample default capability should not be added or registered in -// class before this function is called. -void TestBasicOperations(DeviceCapabilities* capabilities) { - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - - ASSERT_TRUE(capabilities->GetCapability(key).is_none()); - ASSERT_FALSE(capabilities->GetValidator(key)); - - // Register and write capability - FakeCapabilityManagerSimple* manager(new FakeCapabilityManagerSimple( - capabilities, key, init_value.Clone(), true, false)); - // Read Validator - EXPECT_EQ(capabilities->GetValidator(key), manager); - // Read Capability - EXPECT_EQ(capabilities->GetCapability(key), init_value); - // Unregister - delete manager; - - // Write capability again. Provides way of checking that this function - // ran and was successful. - base::Value new_value = GetSampleDefaultCapabilityNewValue(); - capabilities->SetCapability(key, std::move(new_value)); -} - -// See TestBasicOperations() comment. -void AssertBasicOperationsSuccessful(const DeviceCapabilities* capabilities) { - base::RunLoop().RunUntilIdle(); - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - base::Value value = capabilities->GetCapability(key); - base::Value new_value = GetSampleDefaultCapabilityNewValue(); - EXPECT_EQ(value, new_value); -} - -} // namespace - -class DeviceCapabilitiesImplTest : public ::testing::Test { - protected: - void SetUp() override { - capabilities_ = DeviceCapabilities::Create(); - mock_capabilities_observer_.reset(new MockCapabilitiesObserver()); - capabilities_->AddCapabilitiesObserver(mock_capabilities_observer_.get()); - - // We set the default gmock expected calls to any so that tests must - // 'opt in' to checking the calls rather than 'opt out'. This avoids having - // to add explicit calls in test cases that don't care in order to prevent - // lots of useless mock warnings. - EXPECT_CALL(*mock_capabilities_observer_, OnCapabilitiesChanged(testing::_)) - .Times(testing::AnyNumber()); - } - - void TearDown() override { - capabilities_->RemoveCapabilitiesObserver( - mock_capabilities_observer_.get()); - mock_capabilities_observer_.reset(); - capabilities_.reset(); - } - - DeviceCapabilities* capabilities() const { return capabilities_.get(); } - - MockCapabilitiesObserver* capabilities_observer() const { - return mock_capabilities_observer_.get(); - } - - private: - base::test::SingleThreadTaskEnvironment task_environment_; - std::unique_ptr capabilities_; - std::unique_ptr mock_capabilities_observer_; -}; - -// Tests that class is in correct state after Create(). -TEST_F(DeviceCapabilitiesImplTest, Create) { - std::string empty_dict_string; - base::JSONWriter::Write(base::Value(base::Value::Type::DICT), - &empty_dict_string); - EXPECT_EQ(capabilities()->GetAllData()->json_string(), empty_dict_string); - EXPECT_TRUE(capabilities()->GetAllData()->dictionary().empty()); -} - -// Tests Register() of a default capability. -TEST_F(DeviceCapabilitiesImplTest, Register) { - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - - EXPECT_CALL(*capabilities_observer(), OnCapabilitiesChanged(key)).Times(0); - FakeCapabilityManagerSimple manager(capabilities(), key, base::Value(), true, - false); - - EXPECT_EQ(capabilities()->GetValidator(key), &manager); - std::string empty_dict_string; - base::JSONWriter::Write(base::Value(base::Value::Type::DICT), - &empty_dict_string); - EXPECT_EQ(capabilities()->GetAllData()->json_string(), empty_dict_string); - EXPECT_TRUE(capabilities()->GetCapability(key).is_none()); -} - -// Tests Unregister() of a default capability. -TEST_F(DeviceCapabilitiesImplTest, Unregister) { - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - - EXPECT_CALL(*capabilities_observer(), OnCapabilitiesChanged(key)).Times(0); - FakeCapabilityManagerSimple* manager = new FakeCapabilityManagerSimple( - capabilities(), key, base::Value(), true, false); - - delete manager; - - EXPECT_FALSE(capabilities()->GetValidator(key)); - std::string empty_dict_string; - base::JSONWriter::Write(base::Value(base::Value::Type::DICT), - &empty_dict_string); - EXPECT_EQ(capabilities()->GetAllData()->json_string(), empty_dict_string); - EXPECT_TRUE(capabilities()->GetCapability(key).is_none()); -} - -// Tests GetCapability() and updating the value through SetCapability(). -TEST_F(DeviceCapabilitiesImplTest, GetCapabilityAndSetCapability) { - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - FakeCapabilityManagerSimple manager(capabilities(), key, init_value.Clone(), - true, false); - - EXPECT_EQ(capabilities()->GetCapability(key), init_value); - - base::Value new_value = GetSampleDefaultCapabilityNewValue(); - capabilities()->SetCapability(key, new_value.Clone()); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(capabilities()->GetCapability(key), new_value); -} - -// Tests BluetoothSupported() and updating this value through SetCapability(). -TEST_F(DeviceCapabilitiesImplTest, BluetoothSupportedAndSetCapability) { - FakeCapabilityManagerSimple manager( - capabilities(), DeviceCapabilities::kKeyBluetoothSupported, - base::Value(true), true, false); - - EXPECT_TRUE(capabilities()->BluetoothSupported()); - capabilities()->SetCapability(DeviceCapabilities::kKeyBluetoothSupported, - base::Value(false)); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(capabilities()->BluetoothSupported()); -} - -// Tests DisplaySupported() and updating this value through SetCapability(). -TEST_F(DeviceCapabilitiesImplTest, DisplaySupportedAndSetCapability) { - FakeCapabilityManagerSimple manager(capabilities(), - DeviceCapabilities::kKeyDisplaySupported, - base::Value(true), true, false); - - EXPECT_TRUE(capabilities()->DisplaySupported()); - capabilities()->SetCapability(DeviceCapabilities::kKeyDisplaySupported, - base::Value(false)); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(capabilities()->DisplaySupported()); -} - -// Tests HiResAudioSupported() and updating this value through SetCapability() -TEST_F(DeviceCapabilitiesImplTest, HiResAudioSupportedAndSetCapability) { - FakeCapabilityManagerSimple manager( - capabilities(), DeviceCapabilities::kKeyHiResAudioSupported, - base::Value(true), true, false); - - EXPECT_TRUE(capabilities()->HiResAudioSupported()); - capabilities()->SetCapability(DeviceCapabilities::kKeyHiResAudioSupported, - base::Value(false)); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(capabilities()->HiResAudioSupported()); -} - -// Tests AssistantSupported() and updating this value through SetCapability() -TEST_F(DeviceCapabilitiesImplTest, AssistantSupportedAndSetCapability) { - FakeCapabilityManagerSimple manager( - capabilities(), DeviceCapabilities::kKeyAssistantSupported, - base::Value(true), true, false); - - EXPECT_TRUE(capabilities()->AssistantSupported()); - capabilities()->SetCapability(DeviceCapabilities::kKeyAssistantSupported, - base::Value(false)); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(capabilities()->AssistantSupported()); -} - -// Tests SetCapability() for a default capability when the capability's manager -// rejects the proposed change. -TEST_F(DeviceCapabilitiesImplTest, SetCapabilityInvalid) { - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - FakeCapabilityManagerSimple manager(capabilities(), key, init_value.Clone(), - false, false); - - capabilities()->SetCapability(key, GetSampleDefaultCapabilityNewValue()); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(capabilities()->GetCapability(key), init_value); -} - -// Test that SetCapability() updates the capabilities string correctly -TEST_F(DeviceCapabilitiesImplTest, SetCapabilityUpdatesString) { - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - FakeCapabilityManagerSimple manager(capabilities(), key, init_value.Clone(), - true, false); - - EXPECT_TRUE(JsonStringEquals(capabilities()->GetAllData()->json_string(), key, - init_value)); - - base::Value new_value = GetSampleDefaultCapabilityNewValue(); - capabilities()->SetCapability(key, new_value.Clone()); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(JsonStringEquals(capabilities()->GetAllData()->json_string(), key, - new_value)); -} - -// Tests that GetPublicData() does not include private capabilities -TEST_F(DeviceCapabilitiesImplTest, SetPublicPrivateCapabilities) { - std::string key_private = "private"; - std::string key_public = "public"; - base::Value init_value(true); - - // Dictionary of only public values. - base::Value::Dict public_dict; - public_dict.Set(key_public, init_value.Clone()); - // Dictionary of public and private values. - base::Value::Dict full_dict; - full_dict.Set(key_public, init_value.Clone()); - full_dict.Set(key_private, init_value.Clone()); - - FakeCapabilityManagerSimple public_manager(capabilities(), key_public, - init_value.Clone(), true, false); - FakeCapabilityManagerSimple private_manager(capabilities(), key_private, - init_value.Clone(), true, true); - - EXPECT_EQ(capabilities()->GetAllData()->dictionary(), full_dict); - EXPECT_EQ(capabilities()->GetPublicData()->dictionary(), public_dict); -} - -// Tests that SetCapability() defaults to making a capability public -TEST_F(DeviceCapabilitiesImplTest, NoValidatorDefaultsToPublicCapability) { - std::string key_private = "private"; - std::string key_public = "public"; - base::Value init_value(true); - - // Dictionary of only public values. - base::Value::Dict public_dict; - public_dict.Set(key_public, init_value.Clone()); - // Dictionary of public and private values. - base::Value::Dict full_dict; - full_dict.Set(key_public, init_value.Clone()); - full_dict.Set(key_private, init_value.Clone()); - - // We will not create a validator for the public capability; instead we will - // set the capability directly. It will be registered as a public capability. - capabilities()->SetCapability(key_public, init_value.Clone()); - - FakeCapabilityManagerSimple private_manager(capabilities(), key_private, - init_value.Clone(), true, true); - - EXPECT_EQ(capabilities()->GetAllData()->dictionary(), full_dict); - EXPECT_EQ(capabilities()->GetPublicData()->dictionary(), public_dict); -} - -// Test that SetCapability() notifies Observers when the capability's value -// changes -TEST_F(DeviceCapabilitiesImplTest, SetCapabilityNotifiesObservers) { - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - - EXPECT_CALL(*capabilities_observer(), OnCapabilitiesChanged(key)).Times(3); - - // 1st call (register) - FakeCapabilityManagerSimple manager(capabilities(), key, init_value.Clone(), - true, false); - - // 2nd call - capabilities()->SetCapability(key, GetSampleDefaultCapabilityNewValue()); - - // Observer should not get called when value does not change - capabilities()->SetCapability(key, GetSampleDefaultCapabilityNewValue()); - - // 3rd call - capabilities()->SetCapability(key, std::move(init_value)); - base::RunLoop().RunUntilIdle(); -} - -// Test that SetCapability() notifies Observers when a private capability's -// value changes -TEST_F(DeviceCapabilitiesImplTest, SetPrivateCapabilityNotifiesObservers) { - std::string key; - base::Value init_value; - GetSampleDefaultCapability(&key, &init_value); - - EXPECT_CALL(*capabilities_observer(), OnCapabilitiesChanged(key)).Times(3); - - // 1st call (register), this manager validates and sets the capability - // privately. - FakeCapabilityManagerSimple manager(capabilities(), key, init_value.Clone(), - true, true); - - // 2nd call - capabilities()->SetCapability(key, GetSampleDefaultCapabilityNewValue()); - - // Observer should not get called when value does not change - capabilities()->SetCapability(key, GetSampleDefaultCapabilityNewValue()); - - // 3rd call - capabilities()->SetCapability(key, std::move(init_value)); - base::RunLoop().RunUntilIdle(); -} - -// Test adding dynamic capabilities -TEST_F(DeviceCapabilitiesImplTest, SetCapabilityDynamic) { - std::string key; - base::Value init_value; - GetSampleDynamicCapability(&key, &init_value); - - ASSERT_TRUE(capabilities()->GetCapability(key).is_none()); - capabilities()->SetCapability(key, init_value.Clone()); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(capabilities()->GetCapability(key), init_value); - EXPECT_TRUE(JsonStringEquals(capabilities()->GetAllData()->json_string(), key, - init_value)); - - base::Value new_value = GetSampleDynamicCapabilityNewValue(); - capabilities()->SetCapability(key, new_value.Clone()); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(capabilities()->GetCapability(key), new_value); - EXPECT_TRUE(JsonStringEquals(capabilities()->GetAllData()->json_string(), key, - new_value)); -} - -// Tests that SetCapability() works with expanded paths when there is a -// capability of type DictionaryValue. -TEST_F(DeviceCapabilitiesImplTest, SetCapabilityDictionary) { - std::string key("dummy_dictionary_key"); - auto init_value = base::JSONReader::Read(kSampleDictionaryCapability); - ASSERT_TRUE(init_value); - FakeCapabilityManagerSimple manager(capabilities(), key, - std::move(*init_value), true, false); - - capabilities()->SetCapability("dummy_dictionary_key.dummy_field_bool", - base::Value(false)); - base::RunLoop().RunUntilIdle(); - base::Value value = - capabilities()->GetCapability("dummy_dictionary_key.dummy_field_bool"); - ASSERT_TRUE(value.is_bool()); - EXPECT_FALSE(value.GetBool()); - - capabilities()->SetCapability("dummy_dictionary_key.dummy_field_int", - base::Value(100)); - base::RunLoop().RunUntilIdle(); - value = capabilities()->GetCapability("dummy_dictionary_key.dummy_field_int"); - ASSERT_TRUE(value.is_int()); - EXPECT_EQ(value.GetInt(), 100); -} - -// Tests that SetCapability() works with expanded paths when there is a -// capability of type DictionaryValue and invalid changes are proposed. -TEST_F(DeviceCapabilitiesImplTest, SetCapabilityDictionaryInvalid) { - std::string key("dummy_dictionary_key"); - auto init_value = base::JSONReader::Read(kSampleDictionaryCapability); - ASSERT_TRUE(init_value); - FakeCapabilityManagerSimple manager(capabilities(), key, - std::move(*init_value), false, false); - - capabilities()->SetCapability("dummy_dictionary_key.dummy_field_bool", - base::Value(false)); - base::RunLoop().RunUntilIdle(); - base::Value value = - capabilities()->GetCapability("dummy_dictionary_key.dummy_field_bool"); - ASSERT_TRUE(value.is_bool()); - EXPECT_TRUE(value.GetBool()); - - capabilities()->SetCapability("dummy_dictionary_key.dummy_field_int", - base::Value(100)); - base::RunLoop().RunUntilIdle(); - value = capabilities()->GetCapability("dummy_dictionary_key.dummy_field_int"); - ASSERT_TRUE(value.is_int()); - EXPECT_EQ(value.GetInt(), 99); -} - -// Test MergeDictionary. -TEST_F(DeviceCapabilitiesImplTest, MergeDictionary) { - std::optional deserialized_value = - base::JSONReader::ReadDict(kSampleDictionaryCapability); - ASSERT_TRUE(deserialized_value); - - capabilities()->MergeDictionary(*deserialized_value); - base::RunLoop().RunUntilIdle(); - - // First make sure that capabilities get created if they do not exist - base::Value value = capabilities()->GetCapability("dummy_field_bool"); - ASSERT_TRUE(value.is_bool()); - EXPECT_TRUE(value.GetBool()); - - value = capabilities()->GetCapability("dummy_field_int"); - ASSERT_TRUE(value.is_int()); - EXPECT_EQ(value.GetInt(), 99); - - // Now just update one of the fields. Make sure the updated value is changed - // in DeviceCapabilities and the other field remains untouched. - deserialized_value->Set("dummy_field_int", 100); - ASSERT_TRUE(deserialized_value->Remove("dummy_field_bool")); - - capabilities()->MergeDictionary(*deserialized_value); - base::RunLoop().RunUntilIdle(); - - value = capabilities()->GetCapability("dummy_field_bool"); - ASSERT_TRUE(value.is_bool()); - EXPECT_TRUE(value.GetBool()); - - value = capabilities()->GetCapability("dummy_field_int"); - ASSERT_TRUE(value.is_int()); - EXPECT_EQ(value.GetInt(), 100); -} - -// Tests that it is safe to call DeviceCapabilities methods in -// an Observer's OnCapabilitiesChanged() implementation safely with correct -// behavior and without deadlocking. -TEST_F(DeviceCapabilitiesImplTest, OnCapabilitiesChangedSafe) { - FakeCapabilitiesObserver observer(capabilities()); - - // Trigger FakeCapabilitiesObserver::OnCapabilitiesChanged() - capabilities()->SetCapability("dummy_trigger_key", base::Value(true)); - base::RunLoop().RunUntilIdle(); - - // Check that FakeCapabilitiesObserver::OnCapabilitiesChanged() ran and that - // behavior was successful - AssertBasicOperationsSuccessful(capabilities()); -} - -// Tests that it is safe to call DeviceCapabilities methods in a Validator's -// Validate() implementation safely with correct behavior and without -// deadlocking. -TEST_F(DeviceCapabilitiesImplTest, ValidateSafe) { - FakeCapabilityManagerComplex manager(capabilities(), "dummy_validate_key"); - - // Trigger FakeCapabilityManagerComplex::Validate() - capabilities()->SetCapability("dummy_validate_key", base::Value(true)); - base::RunLoop().RunUntilIdle(); - - // Check that FakeCapabilityManagerComplex::Validate() ran and that behavior - // was successful - AssertBasicOperationsSuccessful(capabilities()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/error_codes.cc chromium-132.0.6834.159/chromecast/base/error_codes.cc --- chromium-132.0.6834.110/chromecast/base/error_codes.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/error_codes.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -// 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 "chromecast/base/error_codes.h" - -#include -#include - -#include - -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "chromecast/base/path_utils.h" - -namespace chromecast { - -namespace { - -const char kInitialErrorFile[] = "initial_error"; - -base::FilePath GetInitialErrorFilePath() { - return GetHomePathASCII(kInitialErrorFile); -} - -} // namespace - -ErrorCode GetInitialErrorCode() { - std::string initial_error_code_str; - if (!base::ReadFileToString(GetInitialErrorFilePath(), - &initial_error_code_str)) { - return NO_ERROR; - } - - int initial_error_code = 0; - if (base::StringToInt(initial_error_code_str, &initial_error_code) && - initial_error_code >= NO_ERROR && initial_error_code <= ERROR_UNKNOWN) { - DVLOG(1) << "Initial error from " << GetInitialErrorFilePath().value() - << ": " << initial_error_code; - return static_cast(initial_error_code); - } - - LOG(ERROR) << "Unknown initial error code: " << initial_error_code_str; - return NO_ERROR; -} - -bool SetInitialErrorCode(ErrorCode initial_error_code) { - // Note: Do not use Chromium IO methods in this function. When cast_shell - // crashes, this function can be called by any thread. - const std::string error_file_path = GetInitialErrorFilePath().value(); - - if (initial_error_code > NO_ERROR && initial_error_code <= ERROR_UNKNOWN) { - const std::string initial_error_code_str( - base::NumberToString(initial_error_code)); - int fd = creat(error_file_path.c_str(), 0640); - if (fd < 0) { - PLOG(ERROR) << "Could not open error code file"; - return false; - } - - int written = - write(fd, initial_error_code_str.data(), initial_error_code_str.size()); - - if (written != static_cast(initial_error_code_str.size())) { - PLOG(ERROR) << "Could not write error code to file: written=" << written - << ", expected=" << initial_error_code_str.size(); - close(fd); - return false; - } - - close(fd); - return true; - } - - // Remove initial error file if no error. - if (unlink(error_file_path.c_str()) == 0 || errno == ENOENT) - return true; - - PLOG(ERROR) << "Failed to remove error file"; - return false; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/error_codes.h chromium-132.0.6834.159/chromecast/base/error_codes.h --- chromium-132.0.6834.110/chromecast/base/error_codes.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/error_codes.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_ERROR_CODES_H_ -#define CHROMECAST_BASE_ERROR_CODES_H_ - -namespace chromecast { - -enum ErrorCode { - NO_ERROR = 0, - - // web_content [1, 9999] - ERROR_WEB_CONTENT_RENDER_VIEW_GONE = 1, - ERROR_WEB_CONTENT_NAME_NOT_RESOLVED, - ERROR_WEB_CONTENT_INTERNET_DISCONNECTED, - - // reboot [10000, 19999] - // The following error codes do not reset the volume when the page is - // launched. Add codes that do not reset the volume before ERROR_REBOOT_NOW. - ERROR_REBOOT_NOW = 10000, - ERROR_REBOOT_FDR, - ERROR_REBOOT_OTA, - ERROR_REBOOT_IDLE, - // Chromecast WebUI uses 19999 for END_OF_REBOOT_SECTION, so reserve it here. - END_OF_REBOOT_SECTION = 19999, - - // misc [20000, 29999] - ERROR_ABORTED = 20000, - ERROR_LOST_PEER_CONNECTION = 20001, - - ERROR_UNKNOWN = 30000, -}; - -// Gets the error code for the first idle screen. -ErrorCode GetInitialErrorCode(); - -// Sets the error code for the first idle screen. Returns true if set -// successfully. -bool SetInitialErrorCode(ErrorCode initial_error_code); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_ERROR_CODES_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/error_codes_unittest.cc chromium-132.0.6834.159/chromecast/base/error_codes_unittest.cc --- chromium-132.0.6834.110/chromecast/base/error_codes_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/error_codes_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -// 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 "chromecast/base/error_codes.h" - -#include - -#include "base/base_paths.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/test/scoped_path_override.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -class ErrorCodesTest : public testing::Test { - protected: - ErrorCodesTest() {} - ~ErrorCodesTest() override {} - - void SetUp() override { - // Set up a temporary directory which will be used as our fake home dir. - ASSERT_TRUE(fake_home_dir_.CreateUniqueTempDir()); - path_override_.reset( - new base::ScopedPathOverride(base::DIR_HOME, fake_home_dir_.GetPath())); - } - - base::FilePath home_path() const { return fake_home_dir_.GetPath(); } - - private: - base::ScopedTempDir fake_home_dir_; - std::unique_ptr path_override_; -}; - -TEST_F(ErrorCodesTest, GetInitialErrorCodeReturnsNoErrorIfMissingFile) { - EXPECT_EQ(NO_ERROR, GetInitialErrorCode()); -} - -TEST_F(ErrorCodesTest, SetInitialErrorCodeSucceedsWithNoError) { - ASSERT_TRUE(SetInitialErrorCode(NO_ERROR)); - - // File should not be written. - ASSERT_FALSE(base::PathExists(home_path().Append("initial_error"))); - EXPECT_EQ(NO_ERROR, GetInitialErrorCode()); -} - -TEST_F(ErrorCodesTest, SetInitialErrorCodeSucceedsWithValidErrors) { - // Write initial error and read it from the file. - EXPECT_TRUE(SetInitialErrorCode(ERROR_WEB_CONTENT_RENDER_VIEW_GONE)); - EXPECT_TRUE(base::PathExists(home_path().Append("initial_error"))); - EXPECT_EQ(ERROR_WEB_CONTENT_RENDER_VIEW_GONE, GetInitialErrorCode()); - - // File should be updated with most recent error. - EXPECT_TRUE(SetInitialErrorCode(ERROR_UNKNOWN)); - EXPECT_TRUE(base::PathExists(home_path().Append("initial_error"))); - EXPECT_EQ(ERROR_UNKNOWN, GetInitialErrorCode()); - - // File should be updated with most recent error. - EXPECT_TRUE(SetInitialErrorCode(ERROR_WEB_CONTENT_NAME_NOT_RESOLVED)); - EXPECT_TRUE(base::PathExists(home_path().Append("initial_error"))); - EXPECT_EQ(ERROR_WEB_CONTENT_NAME_NOT_RESOLVED, GetInitialErrorCode()); - - // File should be removed after writing NO_ERROR. - EXPECT_TRUE(SetInitialErrorCode(NO_ERROR)); - EXPECT_FALSE(base::PathExists(home_path().Append("initial_error"))); - EXPECT_EQ(NO_ERROR, GetInitialErrorCode()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/hash_util.cc chromium-132.0.6834.159/chromecast/base/hash_util.cc --- chromium-132.0.6834.110/chromecast/base/hash_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/hash_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,149 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/hash_util.h" - -#include -#include - -#include "base/check_op.h" -#include "base/hash/sha1.h" -#include "base/logging.h" -#include "base/notreached.h" -#include "base/stl_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "chromecast/base/legacy_app_id_mapper.h" -#include "chromecast/base/version.h" - -namespace chromecast { - -namespace { - -const size_t kAppIdV2StrLen = 8; - -} // namespace - -uint64_t HashToUInt64(const std::string& value) { - uint64_t output; - const std::string sha1hash = base::SHA1HashString(value); - DCHECK_GE(sha1hash.size(), sizeof(output)); - memcpy(&output, sha1hash.data(), sizeof(output)); - return output; -} - -uint32_t HashToUInt32(const std::string& value) { - uint32_t output; - const std::string sha1hash = base::SHA1HashString(value); - DCHECK_GE(sha1hash.size(), sizeof(output)); - memcpy(&output, sha1hash.data(), sizeof(output)); - return output; -} - -uint64_t HashGUID64(const std::string& guid) { - std::string hex; - base::RemoveChars(guid, "-", &hex); - uint64_t output; - DCHECK_EQ(hex.size(), 32u); - if (base::HexStringToUInt64(hex.substr(0, 16), &output)) - return output; - NOTREACHED(); -} - -uint32_t HashAppId32(const std::string& app_id) { - uint32_t output; - if (app_id.size() == kAppIdV2StrLen && - base::HexStringToUInt(app_id, &output)) { - return output; - } - - return MapLegacyAppId(app_id); -} - -uint64_t HashCastBuildNumber64(const std::string& build_number) { - uint64_t return_value = 0; - std::vector tokens(base::SplitString( - build_number, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)); - const size_t tsize = tokens.size(); - if (tsize < 1 || tsize > 4) - return static_cast(-1); - - int bits = 64 / tsize; - // special case for 3-tuple to make hex look nicer. - if (tsize == 3) - bits = 16; - - for (size_t i = 0; i < tsize; ++i) { - // special case for the last token of 3-tuple. - if (tsize == 3 && i == 2) - bits = 32; - return_value <<= bits; - unsigned value = 0; - if (!base::StringToUint(tokens[i], &value)) - return static_cast(-1); - if (bits != 64) // avoid overflow - value &= (static_cast(1) << bits) - 1; - return_value |= value; - } - return return_value; -} - -uint64_t HashSessionId64(const std::string& session_id) { - return HashGUID64(session_id); -} - -uint64_t HashSdkVersion64(const std::string& sdk_version) { - if (sdk_version.empty()) - return 0; - - // Sdk version is usually in "X.Y.Z(.minor)" format. - // Following code is a little bit relaxed to accept all sub-fields optional. - uint64_t return_value = 0; - std::vector tokens(base::SplitString( - sdk_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)); - for (size_t i = 0; i < 4; ++i) { - return_value <<= 16; - if (tokens.size() > i) { - unsigned value = 0; - if (base::StringToUint(tokens[i], &value)) { - return_value |= value & 0xFFFF; - } else { - LOG_IF(ERROR, !CAST_IS_DEBUG_BUILD()) - << "Sdk version " << sdk_version << " is not in correct format."; - return static_cast(-1); - } - } - } - return return_value; -} - -uint32_t HashSocketId32(const std::string& socket_id) { - uint32_t output; - // socket id is usually just numerical. - if (base::StringToUint(socket_id, &output)) { - return output; - } else { // CastControlSocket and unittests. - return HashToUInt32(socket_id); - } -} - -uint32_t HashConnectionId32(const std::string& connection_id) { - return HashToUInt32(connection_id); -} - -uint64_t HashAndroidBuildNumber64(const std::string& build_id) { - if (build_id.length() == 0) { - return static_cast(-1); - } - - uint64_t value = 0; - for (const char& c : build_id.substr(0, sizeof(value) / sizeof(char))) { - value <<= CHAR_BIT; - value += c; - } - return value; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/hash_util.h chromium-132.0.6834.159/chromecast/base/hash_util.h --- chromium-132.0.6834.110/chromecast/base/hash_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/hash_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_HASH_UTIL_H_ -#define CHROMECAST_BASE_HASH_UTIL_H_ - -#include - -#include - -namespace chromecast { - -// These are utils to hash strings to uma proto integers. - -// Common utils to hash strings. -uint64_t HashToUInt64(const std::string& value); -uint32_t HashToUInt32(const std::string& value); -uint64_t HashGUID64(const std::string& guid); - -// Common utils to hash cast-related ids. -uint32_t HashAppId32(const std::string& app_id); -uint64_t HashCastBuildNumber64(const std::string& build_number); -uint64_t HashSessionId64(const std::string& session_id); -uint64_t HashSdkVersion64(const std::string& sdk_version); -uint32_t HashSocketId32(const std::string& socket_id); -uint32_t HashConnectionId32(const std::string& connection_id); - -// Encodes the first 8 characters build_id into a uint64 -uint64_t HashAndroidBuildNumber64(const std::string& build_id); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_HASH_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/hash_util_test.cc chromium-132.0.6834.159/chromecast/base/hash_util_test.cc --- chromium-132.0.6834.110/chromecast/base/hash_util_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/hash_util_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/hash_util.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace receiver { - -TEST(UmaHashUtilTest, HashCastBuildNumber64) { - EXPECT_EQ(0xffffffffffffffffU, HashCastBuildNumber64("")); - - EXPECT_EQ(1234567890U, HashCastBuildNumber64("1234567890")); - - EXPECT_EQ(0x0000000200000001U, HashCastBuildNumber64("2.1")); - - EXPECT_EQ(0x0002000000010000U, HashCastBuildNumber64("2.0.65536")); - - EXPECT_EQ(0x00020000007b03e7U, HashCastBuildNumber64("2.0.123.999")); - - EXPECT_EQ(0xffffffffffffffffU, HashCastBuildNumber64("2.na.123.invalid")); - - EXPECT_EQ(0xffffffffffffffffU, HashCastBuildNumber64("invalid")); -} - -TEST(UmaHashUtilTest, HashSdkVersion64) { - EXPECT_EQ(0UL, HashSdkVersion64("")); - - EXPECT_EQ(0x00020000007b0000U, HashSdkVersion64("2.0.123")); - - EXPECT_EQ(0x00020000007b03e7U, HashSdkVersion64("2.0.123.999")); - - EXPECT_EQ(0xffffffffffffffffU, HashSdkVersion64("2.na.123.invalid")); - - EXPECT_EQ(0xffffffffffffffffU, HashSdkVersion64("invalid")); -} - -TEST(UmaHashUtilTest, HashAndroidBuildNumber64) { - EXPECT_EQ(0x00000000004E5943U, HashAndroidBuildNumber64("NYC")); - - EXPECT_EQ(0x00004E554632364EU, HashAndroidBuildNumber64("NUF26N")); - - EXPECT_EQ(0x00004e524439304dU, HashAndroidBuildNumber64("NRD90M")); - - EXPECT_EQ(0x4d4d423239562e53U, HashAndroidBuildNumber64("MMB29V.S39")); - - EXPECT_EQ(0x4f5052312e313730U, HashAndroidBuildNumber64("OPR1.170508.001")); - - EXPECT_EQ(0x00004d4153544552U, HashAndroidBuildNumber64("MASTER")); - - EXPECT_EQ(0x00696e76616c6964U, HashAndroidBuildNumber64("invalid")); - - EXPECT_EQ(0xffffffffffffffffU, HashAndroidBuildNumber64("")); -} - -} // namespace receiver -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/init_command_line_shlib.cc chromium-132.0.6834.159/chromecast/base/init_command_line_shlib.cc --- chromium-132.0.6834.110/chromecast/base/init_command_line_shlib.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/init_command_line_shlib.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/init_command_line_shlib.h" - -#include "base/command_line.h" -#include "base/logging.h" -#include "chromecast/chromecast_buildflags.h" - -namespace chromecast { - - -void InitCommandLineShlib(const std::vector& argv) { - if (base::CommandLine::InitializedForCurrentProcess()) - return; - - base::CommandLine::Init(0, nullptr); - base::CommandLine::ForCurrentProcess()->InitFromArgv(argv); - - logging::InitLogging(logging::LoggingSettings()); -#if BUILDFLAG(IS_CAST_DESKTOP_BUILD) - logging::SetLogItems(true, true, true, false); -#else - // Timestamp available through logcat -v time. - logging::SetLogItems(true, true, false, false); -#endif // BUILDFLAG(IS_CAST_DESKTOP_BUILD) -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/init_command_line_shlib.h chromium-132.0.6834.159/chromecast/base/init_command_line_shlib.h --- chromium-132.0.6834.110/chromecast/base/init_command_line_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/init_command_line_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_INIT_COMMAND_LINE_SHLIB_H_ -#define CHROMECAST_BASE_INIT_COMMAND_LINE_SHLIB_H_ - -#include -#include - -namespace chromecast { - -// A utility function which initializes command line flags and logging. It is -// intended to be called at the entry point of a shared library. -// -// When doing a component build, calls to this function will be a no-op. -// cast_shell will initialize the single global instance of base::CommandLine, -// which lives in libbase.so. For a non-component build, each shared lib will -// statically link its own instance of base::CommandLine, and will initialize -// it here on the initial call. Every subsequent call from within the same -// library will be a no-op. -// -// THREAD SAFTEY: Accessing the CommandLine instance for this process is -// technically not threadsafe when using the component build. However, the -// instance is initialized on the main thread before any other threads are -// started (see content/app/content_main_runner_impl.cc), so accessing this -// instance on those threads for read-operations is safe in practice. -void InitCommandLineShlib(const std::vector& argv); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_INIT_COMMAND_LINE_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/java/OWNERS chromium-132.0.6834.159/chromecast/base/java/OWNERS --- chromium-132.0.6834.110/chromecast/base/java/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/java/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -sanfin@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/base/legacy_app_id_mapper.h chromium-132.0.6834.159/chromecast/base/legacy_app_id_mapper.h --- chromium-132.0.6834.110/chromecast/base/legacy_app_id_mapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/legacy_app_id_mapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_LEGACY_APP_ID_MAPPER_H_ -#define CHROMECAST_BASE_LEGACY_APP_ID_MAPPER_H_ - -#include - -#include - -namespace chromecast { - -// Calculates the AppID associated with |id| and returns it, or -// |kAppUnknownFallback| if no such AppID exists. -uint32_t MapLegacyAppId(const std::string& id); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_LEGACY_APP_ID_MAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/legacy_app_id_mapper_dummy.cc chromium-132.0.6834.159/chromecast/base/legacy_app_id_mapper_dummy.cc --- chromium-132.0.6834.110/chromecast/base/legacy_app_id_mapper_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/legacy_app_id_mapper_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/legacy_app_id_mapper.h" - -namespace chromecast { -namespace { - -// The AppID that should be returned for an unknown |id| by the below function. -constexpr uint32_t kAppUnknownFallback = 0x0; - -} // namespace - -uint32_t MapLegacyAppId(const std::string& id) { - return kAppUnknownFallback; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/metrics/cast_histograms.h chromium-132.0.6834.159/chromecast/base/metrics/cast_histograms.h --- chromium-132.0.6834.110/chromecast/base/metrics/cast_histograms.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/metrics/cast_histograms.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_METRICS_CAST_HISTOGRAMS_H_ -#define CHROMECAST_BASE_METRICS_CAST_HISTOGRAMS_H_ - -#include "base/metrics/histogram.h" - -// STATIC_HISTOGRAM_POINTER_BLOCK only calls histogram_factory_get_invocation -// at the first time and uses the cached histogram_pointer for subsequent calls -// through base::subtle::Release_Store() and base::subtle::Acquire_Load(). -// If the histogram name changes between subsequent calls, use this non-cached -// version that always calls histogram_factory_get_invocation. -#define STATIC_HISTOGRAM_POINTER_BLOCK_NO_CACHE( \ - constant_histogram_name, histogram_add_method_invocation, \ - histogram_factory_get_invocation) \ - do { \ - base::HistogramBase* histogram_pointer = histogram_factory_get_invocation; \ - if (DCHECK_IS_ON()) \ - histogram_pointer->CheckName(constant_histogram_name); \ - histogram_pointer->histogram_add_method_invocation; \ - } while (0) - -#define UMA_HISTOGRAM_CUSTOM_TIMES_NO_CACHE(name, sample, min, max, \ - bucket_count) \ - STATIC_HISTOGRAM_POINTER_BLOCK_NO_CACHE( \ - name, AddTimeMillisecondsGranularity(sample), \ - base::Histogram::FactoryTimeGet( \ - name, min, max, bucket_count, \ - base::Histogram::kUmaTargetedHistogramFlag)) - -#define UMA_HISTOGRAM_CUSTOM_COUNTS_NO_CACHE(name, sample, min, max, \ - bucket_count, count) \ - STATIC_HISTOGRAM_POINTER_BLOCK_NO_CACHE(name, AddCount(sample, count), \ - base::Histogram::FactoryGet(name, min, max, bucket_count, \ - base::HistogramBase::kUmaTargetedHistogramFlag)) - -#define UMA_HISTOGRAM_ENUMERATION_NO_CACHE(name, sample, boundary_value) \ - STATIC_HISTOGRAM_POINTER_BLOCK_NO_CACHE(name, Add(sample), \ - base::LinearHistogram::FactoryGet(name, 1, boundary_value, \ - boundary_value + 1, base::Histogram::kUmaTargetedHistogramFlag)) - -#endif // CHROMECAST_BASE_METRICS_CAST_HISTOGRAMS_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/metrics/cast_metrics_helper.cc chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper.cc --- chromium-132.0.6834.110/chromecast/base/metrics/cast_metrics_helper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,360 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/metrics/cast_metrics_helper.h" - -#include -#include - -#include "base/containers/contains.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/json/json_writer.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/metrics/histogram.h" -#include "base/metrics/user_metrics.h" -#include "base/no_destructor.h" -#include "base/strings/string_split.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/tick_clock.h" -#include "chromecast/base/metrics/cast_histograms.h" -#include "chromecast/base/metrics/grouped_histogram.h" - -namespace chromecast { -namespace metrics { - -// A useful macro to make sure current member function runs on the valid thread. -#define MAKE_SURE_SEQUENCE(callback, ...) \ - if (!task_runner_->RunsTasksInCurrentSequence()) { \ - task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&CastMetricsHelper::callback, \ - base::Unretained(this), ##__VA_ARGS__)); \ - return; \ - } - -namespace { - -const char kMetricsNameAppInfoDelimiter = '#'; - -constexpr base::TimeDelta kAppLoadTimeout = base::Minutes(5); - -} // namespace - -// NOTE(gfhuang): This is a hacky way to encode/decode app infos into a -// string. Mainly because it's hard to add another metrics serialization type -// into components/metrics/serialization/. -// static -bool CastMetricsHelper::DecodeAppInfoFromMetricsName( - const std::string& metrics_name, - std::string* action_name, - std::string* app_id, - std::string* session_id, - std::string* sdk_version) { - DCHECK(action_name); - DCHECK(app_id); - DCHECK(session_id); - DCHECK(sdk_version); - - if (!base::Contains(metrics_name, kMetricsNameAppInfoDelimiter)) { - return false; - } - - std::vector tokens = base::SplitString( - metrics_name, std::string(1, kMetricsNameAppInfoDelimiter), - base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - DCHECK_EQ(tokens.size(), 4u); - // The order of tokens should match EncodeAppInfoIntoMetricsName(). - *action_name = tokens[0]; - *app_id = tokens[1]; - *session_id = tokens[2]; - *sdk_version = tokens[3]; - return true; -} - -// static -std::string CastMetricsHelper::EncodeAppInfoIntoMetricsName( - const std::string& action_name, - const std::string& app_id, - const std::string& session_id, - const std::string& sdk_version) { - std::string result(action_name); - result.push_back(kMetricsNameAppInfoDelimiter); - result.append(app_id); - result.push_back(kMetricsNameAppInfoDelimiter); - result.append(session_id); - result.push_back(kMetricsNameAppInfoDelimiter); - result.append(sdk_version); - return result; -} - -// static -CastMetricsHelper* CastMetricsHelper::GetInstance() { - static base::NoDestructor instance; - return instance.get(); -} - -CastMetricsHelper::CastMetricsHelper( - scoped_refptr task_runner, - const base::TickClock* tick_clock) - : task_runner_(std::move(task_runner)), - tick_clock_(tick_clock), - metrics_sink_(nullptr), - logged_first_audio_(false), - record_action_callback_( - base::BindRepeating(&base::RecordComputedAction)) { - DCHECK(task_runner_); -} - -CastMetricsHelper::~CastMetricsHelper() {} - -void CastMetricsHelper::DidStartLoad(const std::string& app_id) { - MAKE_SURE_SEQUENCE(DidStartLoad, app_id); - const base::TimeTicks now = Now(); - - // Remove start times for apps that never became the current app. - for (auto it = app_load_start_times_.cbegin(); - it != app_load_start_times_.cend();) { - if (now - it->second >= kAppLoadTimeout) { - it = app_load_start_times_.erase(it); - } else { - ++it; - } - } - - app_load_start_times_[app_id] = now; -} - -void CastMetricsHelper::DidCompleteLoad(const std::string& app_id, - const std::string& session_id) { - MAKE_SURE_SEQUENCE(DidCompleteLoad, app_id, session_id); - auto it = app_load_start_times_.find(app_id); - if (it == app_load_start_times_.end()) { - LOG(ERROR) << "No start time for app: app_id=" << app_id; - return; - } - app_id_ = app_id; - session_id_ = session_id; - app_start_time_ = it->second; - app_load_start_times_.erase(it); - logged_first_audio_ = false; - TagAppStartForGroupedHistograms(app_id_); - sdk_version_.clear(); -} - -void CastMetricsHelper::UpdateSDKInfo(const std::string& sdk_version) { - MAKE_SURE_SEQUENCE(UpdateSDKInfo, sdk_version); - sdk_version_ = sdk_version; -} - -void CastMetricsHelper::LogMediaPlay() { - MAKE_SURE_SEQUENCE(LogMediaPlay); - RecordSimpleAction(EncodeAppInfoIntoMetricsName( - "MediaPlay", - app_id_, - session_id_, - sdk_version_)); -} - -void CastMetricsHelper::LogMediaPause() { - MAKE_SURE_SEQUENCE(LogMediaPause); - RecordSimpleAction(EncodeAppInfoIntoMetricsName( - "MediaPause", - app_id_, - session_id_, - sdk_version_)); -} - -void CastMetricsHelper::LogTimeToFirstPaint() { - MAKE_SURE_SEQUENCE(LogTimeToFirstPaint); - if (app_id_.empty()) - return; - base::TimeDelta launch_time = Now() - app_start_time_; - const std::string uma_name(GetMetricsNameWithAppName("Startup", - "TimeToFirstPaint")); - LogMediumTimeHistogramEvent(uma_name, launch_time); - LOG(INFO) << uma_name << " is " << launch_time.InSecondsF() << " seconds."; -} - -void CastMetricsHelper::LogTimeToFirstAudio() { - MAKE_SURE_SEQUENCE(LogTimeToFirstAudio); - if (logged_first_audio_) - return; - if (app_id_.empty()) - return; - base::TimeDelta time_to_first_audio = Now() - app_start_time_; - const std::string uma_name( - GetMetricsNameWithAppName("Startup", "TimeToFirstAudio")); - LogMediumTimeHistogramEvent(uma_name, time_to_first_audio); - LOG(INFO) << uma_name << " is " << time_to_first_audio.InSecondsF() - << " seconds."; - logged_first_audio_ = true; -} - -void CastMetricsHelper::LogTimeToBufferAv(BufferingType buffering_type, - base::TimeDelta time) { - MAKE_SURE_SEQUENCE(LogTimeToBufferAv, buffering_type, time); - if (time.is_negative()) { - LOG(WARNING) << "Negative time"; - return; - } - - const std::string uma_name(GetMetricsNameWithAppName( - "Media", - (buffering_type == kInitialBuffering ? "TimeToBufferAv" : - buffering_type == kBufferingAfterUnderrun ? - "TimeToBufferAvAfterUnderrun" : - buffering_type == kAbortedBuffering ? "TimeToBufferAvAfterAbort" : ""))); - - // Histogram from 250ms to 30s with 50 buckets. - // The ratio between 2 consecutive buckets is: - // exp( (ln(30000) - ln(250)) / 50 ) = 1.1 - LogTimeHistogramEvent(uma_name, time, base::Milliseconds(250), - base::Milliseconds(30000), 50); -} - -std::string CastMetricsHelper::GetMetricsNameWithAppName( - const std::string& prefix, - const std::string& suffix) const { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - std::string metrics_name(prefix); - if (!app_id_.empty()) { - if (!metrics_name.empty()) - metrics_name.push_back('.'); - metrics_name.append(app_id_); - } - if (!suffix.empty()) { - if (!metrics_name.empty()) - metrics_name.push_back('.'); - metrics_name.append(suffix); - } - return metrics_name; -} - -void CastMetricsHelper::SetMetricsSink(MetricsSink* delegate) { - MAKE_SURE_SEQUENCE(SetMetricsSink, delegate); - metrics_sink_ = delegate; -} - -void CastMetricsHelper::SetRecordActionCallback(RecordActionCallback callback) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - record_action_callback_ = std::move(callback); -} - -void CastMetricsHelper::SetDummySessionIdForTesting() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - session_id_ = "00000000-0000-0000-0000-000000000000"; -} - -void CastMetricsHelper::RecordSimpleAction(const std::string& action) { - MAKE_SURE_SEQUENCE(RecordSimpleAction, action); - - if (metrics_sink_) { - metrics_sink_->OnAction(action); - } else { - record_action_callback_.Run(action); - } -} - -void CastMetricsHelper::LogEnumerationHistogramEvent( - const std::string& name, int value, int num_buckets) { - MAKE_SURE_SEQUENCE(LogEnumerationHistogramEvent, name, value, num_buckets); - - if (metrics_sink_) { - metrics_sink_->OnEnumerationEvent(name, value, num_buckets); - } else { - UMA_HISTOGRAM_ENUMERATION_NO_CACHE(name, value, num_buckets); - } -} - -void CastMetricsHelper::LogTimeHistogramEvent(const std::string& name, - base::TimeDelta value, - base::TimeDelta min, - base::TimeDelta max, - int num_buckets) { - MAKE_SURE_SEQUENCE(LogTimeHistogramEvent, name, value, min, max, num_buckets); - - if (metrics_sink_) { - metrics_sink_->OnTimeEvent(name, value, min, max, num_buckets); - } else { - UMA_HISTOGRAM_CUSTOM_TIMES_NO_CACHE(name, value, min, max, num_buckets); - } -} - -void CastMetricsHelper::LogMediumTimeHistogramEvent(const std::string& name, - base::TimeDelta value) { - // Follow UMA_HISTOGRAM_MEDIUM_TIMES definition. - LogTimeHistogramEvent(name, value, base::Milliseconds(10), base::Minutes(3), - 50); -} - -base::Value::Dict CastMetricsHelper::CreateEventBase(const std::string& name) { - base::Value::Dict cast_event; - cast_event.Set("name", name); - const double time = (Now() - base::TimeTicks()).InMicrosecondsF(); - cast_event.Set("time", time); - return cast_event; -} - -void CastMetricsHelper::RecordEventWithValue(const std::string& event, - int value) { - base::Value::Dict cast_event = CreateEventBase(event); - cast_event.Set("value", value); - std::string message; - base::JSONWriter::Write(cast_event, &message); - RecordSimpleAction(message); -} - -void CastMetricsHelper::RecordApplicationEvent(const std::string& event) { - RecordApplicationEvent(app_id_, session_id_, sdk_version_, event); -} - -void CastMetricsHelper::RecordApplicationEvent(const std::string& app_id, - const std::string& session_id, - const std::string& sdk_version, - const std::string& event) { - base::Value::Dict cast_event = CreateEventBase(event); - cast_event.Set("app_id", app_id); - cast_event.Set("session_id", session_id); - cast_event.Set("sdk_version", sdk_version); - std::string message; - base::JSONWriter::Write(cast_event, &message); - RecordSimpleAction(message); -} - -void CastMetricsHelper::RecordApplicationEventWithValue( - const std::string& event, - int value) { - base::Value::Dict cast_event = CreateEventBase(event); - cast_event.Set("app_id", app_id_); - cast_event.Set("session_id", session_id_); - cast_event.Set("sdk_version", sdk_version_); - cast_event.Set("value", value); - std::string message; - base::JSONWriter::Write(cast_event, &message); - RecordSimpleAction(message); -} - -void CastMetricsHelper::RecordApplicationEventWithValue( - const std::string& app_id, - const std::string& session_id, - const std::string& sdk_version, - const std::string& event, - int value) { - base::Value::Dict cast_event = CreateEventBase(event); - cast_event.Set("app_id", app_id); - cast_event.Set("session_id", session_id); - cast_event.Set("sdk_version", sdk_version); - cast_event.Set("value", value); - std::string message; - base::JSONWriter::Write(cast_event, &message); - RecordSimpleAction(message); -} - -base::TimeTicks CastMetricsHelper::Now() { - return tick_clock_ ? tick_clock_->NowTicks() : base::TimeTicks::Now(); -} - -} // namespace metrics -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/metrics/cast_metrics_helper.h chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper.h --- chromium-132.0.6834.110/chromecast/base/metrics/cast_metrics_helper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,197 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_METRICS_CAST_METRICS_HELPER_H_ -#define CHROMECAST_BASE_METRICS_CAST_METRICS_HELPER_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/functional/callback.h" -#include "base/memory/raw_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/no_destructor.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "base/values.h" - -namespace base { -class SequencedTaskRunner; -class TickClock; -} // namespace base - -namespace chromecast { -namespace metrics { - -// Helper class for tracking complex metrics. This particularly includes -// playback metrics that span events across time, such as "time from app launch -// to video being rendered." -// Currently, browser startup code should instantiate this once; it can be -// accessed thereafter through GetInstance. It's not deleted since it may be -// called during teardown of other global objects. -// TODO(halliwell,guohuideng): convert to mojo service, eliminate singleton -// pattern. -class CastMetricsHelper { - public: - enum BufferingType { - kInitialBuffering, - kBufferingAfterUnderrun, - kAbortedBuffering, - }; - - using RecordActionCallback = - base::RepeatingCallback; - - class MetricsSink { - public: - virtual ~MetricsSink() = default; - - virtual void OnAction(const std::string& action) = 0; - virtual void OnEnumerationEvent(const std::string& name, - int value, int num_buckets) = 0; - virtual void OnTimeEvent(const std::string& name, - base::TimeDelta value, - base::TimeDelta min, - base::TimeDelta max, - int num_buckets) = 0; - }; - - // Decodes action_name/app_id/session_id/sdk_version from metrics name. - // Return false if the metrics name is not generated from - // EncodeAppInfoIntoMetricsName() with correct format. - static bool DecodeAppInfoFromMetricsName( - const std::string& metrics_name, - std::string* action_name, - std::string* app_id, - std::string* session_id, - std::string* sdk_version); - - static CastMetricsHelper* GetInstance(); - - CastMetricsHelper(const CastMetricsHelper&) = delete; - CastMetricsHelper& operator=(const CastMetricsHelper&) = delete; - - // This records the startup time of an app load (note: another app - // may be running and still collecting metrics). - virtual void DidStartLoad(const std::string& app_id); - // This function marks the completion of a successful app load. It switches - // metric collection to this app. - virtual void DidCompleteLoad(const std::string& app_id, - const std::string& session_id); - // This function updates the sdk version of the current active application - virtual void UpdateSDKInfo(const std::string& sdk_version); - - // Logs UMA record for media play/pause user actions. - virtual void LogMediaPlay(); - virtual void LogMediaPause(); - - // Logs a simple UMA user action. - // This is used as an in-place replacement of content::RecordComputedAction(). - virtual void RecordSimpleAction(const std::string& action); - - // Logs a generic event. - virtual void RecordEventWithValue(const std::string& action, int value); - - // Logs application specific events. - virtual void RecordApplicationEvent(const std::string& event); - virtual void RecordApplicationEvent(const std::string& app_id, - const std::string& session_id, - const std::string& sdk_version, - const std::string& event); - virtual void RecordApplicationEventWithValue(const std::string& event, - int value); - virtual void RecordApplicationEventWithValue(const std::string& app_id, - const std::string& session_id, - const std::string& sdk_version, - const std::string& event, - int value); - - // Logs UMA record of the time the app made its first paint. - virtual void LogTimeToFirstPaint(); - - // Logs UMA record of the time the app pushed its first audio frame. - virtual void LogTimeToFirstAudio(); - - // Logs UMA record of the time needed to re-buffer A/V. - virtual void LogTimeToBufferAv(BufferingType buffering_type, - base::TimeDelta time); - - // Returns metrics name with app name between prefix and suffix. - virtual std::string GetMetricsNameWithAppName( - const std::string& prefix, - const std::string& suffix) const; - - // Provides a MetricsSink instance to delegate UMA event logging. - // Once the delegate interface is set, CastMetricsHelper will not log UMA - // events internally unless SetMetricsSink(NULL) is called. - // CastMetricsHelper can only hold one MetricsSink instance. - // Caller retains ownership of MetricsSink. - virtual void SetMetricsSink(MetricsSink* delegate); - - // Sets a default callback to record user action when MetricsSink is not set. - // This function could be called multiple times (in unittests), and - // CastMetricsHelper only honors the last one. - virtual void SetRecordActionCallback(RecordActionCallback callback); - - // Sets an all-0's session ID for running browser tests. - void SetDummySessionIdForTesting(); - - private: - static std::string EncodeAppInfoIntoMetricsName( - const std::string& action_name, - const std::string& app_id, - const std::string& session_id, - const std::string& sdk_version); - - friend class base::NoDestructor; - friend class CastMetricsHelperTest; - friend class MockCastMetricsHelper; - - // |tick_clock| just provided for unit test to construct; normally it should - // be nullptr when accessed through GetInstance. - CastMetricsHelper(scoped_refptr task_runner = - base::SequencedTaskRunner::GetCurrentDefault(), - const base::TickClock* tick_clock = nullptr); - virtual ~CastMetricsHelper(); - - void LogEnumerationHistogramEvent(const std::string& name, - int value, int num_buckets); - void LogTimeHistogramEvent(const std::string& name, - base::TimeDelta value, - base::TimeDelta min, - base::TimeDelta max, - int num_buckets); - void LogMediumTimeHistogramEvent(const std::string& name, - base::TimeDelta value); - base::Value::Dict CreateEventBase(const std::string& name); - base::TimeTicks Now(); - - const scoped_refptr task_runner_; - const raw_ptr tick_clock_; - - // Start times for loading the next apps. - base::flat_map - app_load_start_times_; - - // Start time for the currently running app. - base::TimeTicks app_start_time_; - - // Currently running app id. Used to construct histogram name. - std::string app_id_; - std::string session_id_; - std::string sdk_version_; - - raw_ptr metrics_sink_; - - bool logged_first_audio_; - - // Default RecordAction callback when metrics_sink_ is not set. - RecordActionCallback record_action_callback_; -}; - -} // namespace metrics -} // namespace chromecast - -#endif // CHROMECAST_BASE_METRICS_CAST_METRICS_HELPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/metrics/cast_metrics_helper_unittest.cc chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper_unittest.cc --- chromium-132.0.6834.110/chromecast/base/metrics/cast_metrics_helper_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/metrics/cast_metrics_helper_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,191 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/metrics/cast_metrics_helper.h" - -#include -#include - -#include "base/json/json_reader.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "base/values.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::AllOf; -using ::testing::HasSubstr; -using ::testing::SaveArg; -using ::testing::_; - -namespace chromecast { -namespace metrics { - -namespace { - -constexpr char kAppId1[] = "APP_ID_1"; -constexpr char kAppId2[] = "APP_ID_2"; -constexpr char kAppId3[] = "APP_ID_3"; -constexpr char kEvent[] = "EVENT"; -constexpr char kSdkVersion[] = "SDK_VERSION"; -constexpr char kSessionId1[] = "SESSION_ID_1"; -constexpr char kSessionId2[] = "SESSION_ID_2"; -constexpr char kSessionId3[] = "SESSION_ID_3"; -constexpr int kValue = 123; - -constexpr base::TimeDelta kAppLoadTimeout = base::Minutes(5); - -MATCHER_P2(HasDouble, key, value, "") { - const std::optional v = base::JSONReader::Read(arg); - if (!v || !v->is_dict()) { - return false; - } - - const base::Value::Dict& dict = v->GetDict(); - return dict.FindDouble(key) == value; -} - -MATCHER_P2(HasInt, key, value, "") { - const std::optional v = base::JSONReader::Read(arg); - if (!v || !v->is_dict()) { - return false; - } - - const base::Value::Dict& dict = v->GetDict(); - return dict.FindInt(key) == value; -} - -MATCHER_P2(HasString, key, value, "") { - const std::optional v = base::JSONReader::Read(arg); - if (!v || !v->is_dict()) { - return false; - } - - const base::Value::Dict& dict = v->GetDict(); - const std::string* stored_value = dict.FindString(key); - return stored_value && (*stored_value == value); -} - -} // namespace - -class MockMetricsSink : public CastMetricsHelper::MetricsSink { - public: - MOCK_METHOD1(OnAction, void(const std::string&)); - MOCK_METHOD3(OnEnumerationEvent, void(const std::string&, int, int)); - MOCK_METHOD5(OnTimeEvent, - void(const std::string&, - base::TimeDelta, - base::TimeDelta, - base::TimeDelta, - int)); -}; - -class CastMetricsHelperTest : public ::testing::Test { - public: - CastMetricsHelperTest() - : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME), - metrics_helper_(task_environment_.GetMainThreadTaskRunner(), - task_environment_.GetMockTickClock()) { - metrics_helper_.SetMetricsSink(&metrics_sink_); - } - - base::test::TaskEnvironment task_environment_; - MockMetricsSink metrics_sink_; - CastMetricsHelper metrics_helper_; -}; - -TEST_F(CastMetricsHelperTest, RecordEventWithValue) { - const auto expected_time = task_environment_.NowTicks(); - - EXPECT_CALL( - metrics_sink_, - OnAction( - AllOf(HasString("name", kEvent), - HasDouble("time", - (expected_time - base::TimeTicks()).InMicroseconds()), - HasInt("value", kValue)))); - metrics_helper_.RecordApplicationEventWithValue(kEvent, kValue); -} - -TEST_F(CastMetricsHelperTest, RecordApplicationEvent) { - metrics_helper_.DidStartLoad(kAppId1); - metrics_helper_.DidCompleteLoad(kAppId1, kSessionId1); - metrics_helper_.UpdateSDKInfo(kSdkVersion); - - const auto expected_time = task_environment_.NowTicks(); - - EXPECT_CALL( - metrics_sink_, - OnAction(AllOf( - HasString("name", kEvent), - HasDouble("time", - (expected_time - base::TimeTicks()).InMicroseconds()), - HasString("app_id", kAppId1), HasString("session_id", kSessionId1), - HasString("sdk_version", kSdkVersion)))); - metrics_helper_.RecordApplicationEvent(kEvent); -} - -TEST_F(CastMetricsHelperTest, RecordApplicationEventWithValue) { - metrics_helper_.DidStartLoad(kAppId1); - metrics_helper_.DidCompleteLoad(kAppId1, kSessionId1); - metrics_helper_.UpdateSDKInfo(kSdkVersion); - - const auto expected_time = task_environment_.NowTicks(); - - EXPECT_CALL( - metrics_sink_, - OnAction(AllOf( - HasString("name", kEvent), - HasDouble("time", - (expected_time - base::TimeTicks()).InMicroseconds()), - HasString("app_id", kAppId1), HasString("session_id", kSessionId1), - HasString("sdk_version", kSdkVersion), HasInt("value", kValue)))); - metrics_helper_.RecordApplicationEventWithValue(kEvent, kValue); -} - -TEST_F(CastMetricsHelperTest, LogTimeToFirstPaint) { - metrics_helper_.DidStartLoad(kAppId1); - metrics_helper_.DidCompleteLoad(kAppId1, kSessionId1); - - constexpr base::TimeDelta kTimeToFirstPaint = base::Seconds(5); - task_environment_.FastForwardBy(kTimeToFirstPaint); - - EXPECT_CALL(metrics_sink_, OnTimeEvent(AllOf(HasSubstr(kAppId1), - HasSubstr("TimeToFirstPaint")), - kTimeToFirstPaint, _, _, _)); - metrics_helper_.LogTimeToFirstPaint(); -} - -TEST_F(CastMetricsHelperTest, LogTimeToFirstAudio) { - metrics_helper_.DidStartLoad(kAppId1); - metrics_helper_.DidCompleteLoad(kAppId1, kSessionId1); - - constexpr base::TimeDelta kTimeToFirstAudio = base::Seconds(5); - task_environment_.FastForwardBy(kTimeToFirstAudio); - - EXPECT_CALL(metrics_sink_, OnTimeEvent(AllOf(HasSubstr(kAppId1), - HasSubstr("TimeToFirstAudio")), - kTimeToFirstAudio, _, _, _)); - metrics_helper_.LogTimeToFirstAudio(); -} - -TEST_F(CastMetricsHelperTest, MultipleApps) { - metrics_helper_.DidStartLoad(kAppId1); - task_environment_.FastForwardBy(kAppLoadTimeout); - metrics_helper_.DidStartLoad(kAppId2); - metrics_helper_.DidStartLoad(kAppId3); - metrics_helper_.DidCompleteLoad(kAppId3, kSessionId3); - // kAppId2 should become the current app. - metrics_helper_.DidCompleteLoad(kAppId2, kSessionId2); - // kAppId1 should not become the current app because it timed out. - metrics_helper_.DidCompleteLoad(kAppId1, kSessionId1); - - EXPECT_CALL(metrics_sink_, - OnAction(AllOf(HasString("app_id", kAppId2), - HasString("session_id", kSessionId2)))); - metrics_helper_.RecordApplicationEvent(kEvent); -} - -} // namespace metrics -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/metrics/grouped_histogram.cc chromium-132.0.6834.159/chromecast/base/metrics/grouped_histogram.cc --- chromium-132.0.6834.110/chromecast/base/metrics/grouped_histogram.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/metrics/grouped_histogram.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,190 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/metrics/grouped_histogram.h" - -#include -#include - -#include - -#include "base/check_op.h" -#include "base/metrics/histogram.h" -#include "base/metrics/statistics_recorder.h" -#include "base/no_destructor.h" -#include "base/strings/stringprintf.h" -#include "base/synchronization/lock.h" -#include "base/time/time.h" - -namespace chromecast { -namespace metrics { - -namespace { - -const char kAppNameErrorNoApp[] = "ERROR_NO_APP_REGISTERED"; - -// Current app name guarded by lock. -struct CurrentAppNameWithLock { - base::Lock lock; - std::string app_name; -}; - -CurrentAppNameWithLock& GetCurrentApp() { - static base::NoDestructor current_app; - return *current_app; -} - -std::string GetAppName() { - base::AutoLock lock(GetCurrentApp().lock); - const std::string& app_name = GetCurrentApp().app_name; - return app_name.empty() ? kAppNameErrorNoApp : app_name; -} - -struct HistogramArgs { - const char* name; - int minimum; - int maximum; - size_t bucket_count; -}; - -// List of metrics to collect using a GroupedHistogram. -// -// When adding more Histograms to this list, find the source of the -// Histogram and look for the construction arguments it uses to add it in. -const HistogramArgs kHistogramsToGroup[] = { - { - "DNS.TotalTime", - 1, - 1000 * 60 * 60, - 100, - }, - { - "Net.DNS_Resolution_And_TCP_Connection_Latency2", - 1, - 1000 * 60 * 10, - 100, - }, - { - "Net.SSL_Connection_Latency2", - 1, - 1000 * 60, - 100, - }, - { - "Net.TCP_Connection_Latency", - 1, - 1000 * 60 * 10, - 100, - }, - { - "Net.HttpJob.TotalTime", - 1, - 1000 * 10, - 50, - }, -}; - -// This class is used to override a Histogram to generate per-app metrics. -// It intercepts calls to Add() for a given metric and generates new metrics -// of the form ".". -class GroupedHistogram : public base::Histogram { - public: - // TODO(crbug.com/40824087): min/max parameters are redundant with "ranges" - // and can probably be removed. - GroupedHistogram(const char* metric_to_override, - Sample minimum, - Sample maximum, - const base::BucketRanges* ranges) - : Histogram(metric_to_override, ranges), - minimum_(minimum), - maximum_(maximum), - bucket_count_(ranges->bucket_count()) {} - - GroupedHistogram(const GroupedHistogram&) = delete; - GroupedHistogram& operator=(const GroupedHistogram&) = delete; - - ~GroupedHistogram() override { - } - - // base::Histogram implementation: - void Add(Sample value) override { - Histogram::Add(value); - - // Note: This is very inefficient. Fetching the app name (which has a lock) - // plus doing a search by name with FactoryGet (which also has a lock) makes - // incrementing a metric relatively slow. - std::string name( - base::StringPrintf("%s.%s", histogram_name(), GetAppName().c_str())); - HistogramBase* grouped_histogram = - base::Histogram::FactoryGet(name, - minimum_, - maximum_, - bucket_count_, - flags()); - DCHECK(grouped_histogram); - grouped_histogram->Add(value); - } - - private: - // Saved construction arguments for reconstructing the Histogram later (with - // a suffixed app name). - Sample minimum_; - Sample maximum_; - uint32_t bucket_count_; -}; - -// Registers a GroupedHistogram with StatisticsRecorder. Must be called -// before any Histogram of the same name has been used. -// It acts similarly to Histogram::FactoryGet but checks that -// the histogram is being newly created and does not already exist. -void PreregisterHistogram(const char* name, - GroupedHistogram::Sample minimum, - GroupedHistogram::Sample maximum, - size_t bucket_count, - int32_t flags) { - std::string_view name_piece(name); - - DCHECK(base::Histogram::InspectConstructionArguments( - name_piece, &minimum, &maximum, &bucket_count)); - DCHECK(!base::StatisticsRecorder::FindHistogram(name_piece)) - << "Failed to preregister " << name << ", Histogram already exists."; - - // To avoid racy destruction at shutdown, the following will be leaked. - base::BucketRanges* ranges = new base::BucketRanges(bucket_count + 1); - base::Histogram::InitializeBucketRanges(minimum, maximum, ranges); - const base::BucketRanges* registered_ranges = - base::StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges); - - GroupedHistogram* tentative_histogram = - new GroupedHistogram(name, minimum, maximum, registered_ranges); - - tentative_histogram->SetFlags(flags); - base::HistogramBase* histogram = - base::StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram); - - DCHECK_EQ(histogram, tentative_histogram); - DCHECK_EQ(base::HISTOGRAM, histogram->GetHistogramType()); - DCHECK(histogram->HasConstructionArguments(minimum, maximum, bucket_count)); -} - -} // namespace - -void PreregisterAllGroupedHistograms() { - for (size_t i = 0; i < std::size(kHistogramsToGroup); ++i) { - PreregisterHistogram( - kHistogramsToGroup[i].name, - kHistogramsToGroup[i].minimum, - kHistogramsToGroup[i].maximum, - kHistogramsToGroup[i].bucket_count, - base::HistogramBase::kUmaTargetedHistogramFlag); - } -} - -void TagAppStartForGroupedHistograms(const std::string& app_name) { - base::AutoLock lock(GetCurrentApp().lock); - GetCurrentApp().app_name = app_name; -} - -} // namespace metrics -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/metrics/grouped_histogram.h chromium-132.0.6834.159/chromecast/base/metrics/grouped_histogram.h --- chromium-132.0.6834.110/chromecast/base/metrics/grouped_histogram.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/metrics/grouped_histogram.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_METRICS_GROUPED_HISTOGRAM_H_ -#define CHROMECAST_BASE_METRICS_GROUPED_HISTOGRAM_H_ - -#include - -namespace chromecast { -namespace metrics { - -// Registers a predefined list of histograms to be collected per-app. Must be -// called before any histograms of the same name are used or registration will -// fail. -void PreregisterAllGroupedHistograms(); - -// Sets the current app name to be used for subsequent grouped histogram -// samples (a new metric is generated with the app name as a suffix). -void TagAppStartForGroupedHistograms(const std::string& app_name); - -} // namespace metrics -} // namespace chromecast - -#endif // CHROMECAST_BASE_METRICS_GROUPED_HISTOGRAM_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/metrics/mock_cast_metrics_helper.cc chromium-132.0.6834.159/chromecast/base/metrics/mock_cast_metrics_helper.cc --- chromium-132.0.6834.110/chromecast/base/metrics/mock_cast_metrics_helper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/metrics/mock_cast_metrics_helper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/metrics/mock_cast_metrics_helper.h" - -namespace chromecast { -namespace metrics { - -MockCastMetricsHelper::MockCastMetricsHelper() : CastMetricsHelper() {} - -MockCastMetricsHelper::~MockCastMetricsHelper() = default; - -} // namespace metrics -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/metrics/mock_cast_metrics_helper.h chromium-132.0.6834.159/chromecast/base/metrics/mock_cast_metrics_helper.h --- chromium-132.0.6834.110/chromecast/base/metrics/mock_cast_metrics_helper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/metrics/mock_cast_metrics_helper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_METRICS_MOCK_CAST_METRICS_HELPER_H_ -#define CHROMECAST_BASE_METRICS_MOCK_CAST_METRICS_HELPER_H_ - -#include - -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace metrics { - -class MockCastMetricsHelper : public CastMetricsHelper { - public: - MockCastMetricsHelper(); - - MockCastMetricsHelper(const MockCastMetricsHelper&) = delete; - MockCastMetricsHelper& operator=(const MockCastMetricsHelper&) = delete; - - ~MockCastMetricsHelper() override; - - MOCK_METHOD2(UpdateCurrentAppInfo, - void(const std::string& app_id, const std::string& session_id)); - MOCK_METHOD1(UpdateSDKInfo, void(const std::string& sdk_version)); - MOCK_METHOD0(LogMediaPlay, void()); - MOCK_METHOD0(LogMediaPause, void()); - MOCK_METHOD1(RecordSimpleAction, void(const std::string& action)); - MOCK_METHOD2(RecordEventWithValue, - void(const std::string& action, int value)); - MOCK_METHOD1(RecordApplicationEvent, void(const std::string& event)); - MOCK_METHOD2(RecordApplicationEventWithValue, - void(const std::string& event, int value)); - MOCK_METHOD0(LogTimeToFirstPaint, void()); - MOCK_METHOD0(LogTimeToFirstAudio, void()); - MOCK_METHOD2(LogTimeToBufferAv, - void(BufferingType buffering_type, base::TimeDelta time)); - MOCK_CONST_METHOD2(GetMetricsNameWithAppName, - std::string(const std::string& prefix, - const std::string& suffix)); - MOCK_METHOD1(SetMetricsSink, void(MetricsSink* delegate)); - MOCK_METHOD1(SetRecordActionCallback, void(RecordActionCallback callback)); -}; - -} // namespace metrics -} // namespace chromecast - -#endif // CHROMECAST_BASE_METRICS_MOCK_CAST_METRICS_HELPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/observer.h chromium-132.0.6834.159/chromecast/base/observer.h --- chromium-132.0.6834.110/chromecast/base/observer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/observer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,431 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Safe Observer/Observable implementation. -// -// When using ObserverListThreadSafe, we were running into issues since there -// was no synchronization between getting the existing value, and registering -// as an observer. See go/cast-platform-design-synchronized-value for more -// details. -// -// To fix this issue, and to make observing values safer and simpler in general, -// use the Observable/Observer pattern in this file. When you have a value that -// other code wants to observe (ie, get the value of and receive any changes), -// wrap that value in an Observable. The value type T must be copyable and -// copy-assignable. The Observable must be constructed with the initial observed -// value, and the value may be updated at any time from any thread by calling -// SetValue(). You can also get the value using GetValue(); but note that this -// is not threadsafe (the value is returned without locking), so the caller must -// ensure safety by other means. Calling GetValueThreadSafe() is threadsafe but -// involves a mutex lock. -// -// Code that wants to observe the value calls Observe() on it at any point when -// the value is alive. Note that Observe() may be called safely from any thread. -// Observe() returns an Observer instance, which MUST be used and destroyed -// only on the thread that called Observe(). The Observer initially contains the -// value that the Observable had when Observe() was called, and that value will -// be updated asynchronously whenever the Observable's SetValue() method is -// is called. NOTE: the initial value of the Observer is the value known to the -// thread that created the Observer at the time; there may be an updated value -// from the Observable that hasn't been handled by the Observer's thread yet. -// -// The Observer's view of the observed value is returned by GetValue(); this is -// a low-cost call since there is no locking (the value is updated on the thread -// that constructed the Observer). Note that Observers are always updated -// asynchronously with PostTask(), even if they belong to the same thread that -// calls SetValue(). All Observers on the same thread have the same consistent -// view of the observed value. -// -// Observers may be copied freely; the copy also observes the original -// Observable, and belongs to the thread that created the copy. Copying is safe -// even when the original Observable has been destroyed. -// -// Code may register a callback that is called whenever an Observer's value is -// updated, by calling SetOnUpdateCallback(). If you get an Observer by calling -// Observe() and then immediately call SetOnUpdateCallback() to register a -// a callback, you are guaranteed to get every value of the Observable starting -// from when you called Observe() - you get the initial value by calling -// GetValue() on the returned Observer, and any subsequent updates will trigger -// the callback so you can call GetValue() to get the new value. You will not -// receive any extra callbacks (exactly one callback per value update). -// -// Note that Observers are not default-constructible, since there is no way to -// construct it in a default state. In cases where you need to instantiate an -// Observer after your constructor, you can use a std::unique_ptr -// instead, and initialize it when needed. -// -// Example usage: -// -// class MediaManager { -// public: -// MediaManager() : volume_(0.0f) {} -// -// Observer ObserveVolume() { return volume_.Observe(); } -// -// // ... other methods ... -// -// private: -// // Assume this is called from some other internal code when the volume is -// // updated. -// void OnUpdateVolume(float new_volume) { -// volume_.SetValue(new_volume); // All observers will get the new value. -// } -// -// Observable volume_; -// } -// -// class VolumeFeedbackManager { -// public: -// VolumeFeedbackManager(MediaManager* media_manager) -// : volume_observer_(media_manager->ObserveVolume()) { -// volume_observer_.SetOnUpdateCallback( -// base::BindRepeating(&VolumeFeedbackManager::OnVolumeChanged, -// base::Unretained(this))); -// } -// -// private: -// void OnVolumeChanged() { -// ShowVolumeFeedback(volume_observer_.GetValue()); -// } -// -// void ShowVolumeFeedback(float volume) { -// // ... some implementation ... -// } -// }; -// - -#ifndef CHROMECAST_BASE_OBSERVER_H_ -#define CHROMECAST_BASE_OBSERVER_H_ - -#include -#include - -#include -#include -#include - -#include "base/check_op.h" -#include "base/containers/contains.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/location.h" -#include "base/memory/raw_ref.h" -#include "base/memory/ref_counted.h" -#include "base/notreached.h" -#include "base/sequence_checker.h" -#include "base/synchronization/lock.h" -#include "base/task/sequenced_task_runner.h" - -namespace chromecast { - -namespace subtle { -template -class ObservableInternals; -} // namespace subtle - -template -class Observable; - -template -class Observer { - public: - Observer(const Observer& other); - - Observer& operator=(const Observer&) = delete; - - ~Observer(); - - void SetOnUpdateCallback(base::RepeatingClosure callback) { - on_update_callback_ = std::move(callback); - } - - const T& GetValue() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return *value_; - } - - private: - friend class subtle::ObservableInternals; - friend class Observable; - - explicit Observer(scoped_refptr> internals); - - void OnUpdate(); - - const scoped_refptr> internals_; - // Note: value_ is a const ref to the value copy for this sequence, stored in - // SequenceOwnedInfo. - const raw_ref value_; - base::RepeatingClosure on_update_callback_; - SEQUENCE_CHECKER(sequence_checker_); -}; - -template -class Observable { - static_assert(std::is_copy_constructible::value, - "Observable values must be copyable"); - static_assert(std::is_copy_assignable::value, - "Observable values must be copy-assignable"); - - public: - explicit Observable(const T& initial_value); - - Observable(const Observable&) = delete; - Observable& operator=(const Observable&) = delete; - - Observer Observe(); - - void SetValue(const T& new_value); - const T& GetValue() const; // NOT threadsafe! - T GetValueThreadSafe() const; - - private: - // By using a refcounted object to store the value and observer list, we can - // avoid tying the lifetime of Observable to its Observers or vice versa. - const scoped_refptr> internals_; -}; - -namespace subtle { - -template -class ObservableInternals - : public base::RefCountedThreadSafe> { - public: - explicit ObservableInternals(const T& initial_value) - : value_(initial_value) {} - - ObservableInternals(const ObservableInternals&) = delete; - ObservableInternals& operator=(const ObservableInternals&) = delete; - - void SetValue(const T& new_value) { - base::AutoLock lock(lock_); - value_ = new_value; - - for (auto& item : per_sequence_) { - item.SetValue(new_value); - } - } - - const T& GetValue() const { return value_; } - - T GetValueThreadSafe() const { - base::AutoLock lock(lock_); - return value_; - } - - const T& AddObserver(Observer* observer) { - DCHECK(observer); - DCHECK(base::SequencedTaskRunner::HasCurrentDefault()); - auto task_runner = base::SequencedTaskRunner::GetCurrentDefault(); - - base::AutoLock lock(lock_); - auto it = per_sequence_.begin(); - while (it != per_sequence_.end() && it->task_runner() != task_runner) { - ++it; - } - if (it == per_sequence_.end()) { - per_sequence_.emplace_back(std::move(task_runner), value_); - it = --per_sequence_.end(); - } - it->AddObserver(observer); - return it->value(); - } - - void RemoveObserver(Observer* observer) { - DCHECK(observer); - DCHECK(base::SequencedTaskRunner::HasCurrentDefault()); - auto task_runner = base::SequencedTaskRunner::GetCurrentDefault(); - - base::AutoLock lock(lock_); - for (size_t i = 0; i < per_sequence_.size(); ++i) { - if (per_sequence_[i].task_runner() == task_runner) { - per_sequence_[i].RemoveObserver(observer); - - if (per_sequence_[i].Empty()) { - per_sequence_[i].Swap(per_sequence_.back()); - per_sequence_.pop_back(); - } - return; - } - } - - NOTREACHED() << "Tried to remove observer from unknown task runner"; - } - - private: - // Information owned by a particular sequence. Must be only accessed on that - // sequence, and must be deleted by posting a task to that sequence. - // This class MUST NOT contain a scoped_refptr to the task_runner, since if it - // did, there would be a reference cycle during cleanup, when the task to - // Destroy() is posted. - class SequenceOwnedInfo { - public: - explicit SequenceOwnedInfo(const T& value) : value_(value) {} - - SequenceOwnedInfo(const SequenceOwnedInfo&) = delete; - SequenceOwnedInfo& operator=(const SequenceOwnedInfo&) = delete; - - const T& value() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return value_; - } - - void AddObserver(Observer* observer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(observer); - DCHECK(!base::Contains(observers_, observer)); - observers_.push_back(observer); - } - - void RemoveObserver(Observer* observer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(observer); - DCHECK(base::Contains(observers_, observer)); - observers_.erase( - std::remove(observers_.begin(), observers_.end(), observer), - observers_.end()); - } - - bool Empty() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return observers_.empty(); - } - - void SetValue(const T& value) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - value_ = value; - for (auto* obs : observers_) { - obs->OnUpdate(); - } - } - - static void Destroy(std::unique_ptr self) { - // The unique_ptr deletes automatically. - } - - private: - std::vector*> observers_; - T value_; - SEQUENCE_CHECKER(sequence_checker_); - }; - - class PerSequenceInfo { - public: - PerSequenceInfo(scoped_refptr task_runner, - const T& value) - : task_runner_(std::move(task_runner)), - owned_info_(std::make_unique(value)) {} - - PerSequenceInfo(PerSequenceInfo&& other) = default; - - ~PerSequenceInfo() { - if (!owned_info_) { - // Members have been moved out via move constructor. - return; - } - - DCHECK(Empty()); - // Must post a task to delete the owned info, since there may still be a - // pending task to call SequenceOwnedInfo::SetValue(). - // Use manual PostNonNestableTask(), since DeleteSoon() does not - // guarantee deletion. - task_runner_->PostNonNestableTask( - FROM_HERE, - base::BindOnce(&SequenceOwnedInfo::Destroy, std::move(owned_info_))); - } - - const T& value() const { return owned_info_->value(); } - - const base::SequencedTaskRunner* task_runner() const { - return task_runner_.get(); - } - - void AddObserver(Observer* observer) { - owned_info_->AddObserver(observer); - } - - void RemoveObserver(Observer* observer) { - owned_info_->RemoveObserver(observer); - } - - bool Empty() const { return owned_info_->Empty(); } - - void Swap(PerSequenceInfo& other) { - std::swap(task_runner_, other.task_runner_); - std::swap(owned_info_, other.owned_info_); - } - - void SetValue(const T& value) { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&SequenceOwnedInfo::SetValue, - base::Unretained(owned_info_.get()), value)); - } - - private: - // Operations on |owned_info| do not need to be synchronized with a lock, - // since all operations must occur on |task_runner|. - scoped_refptr task_runner_; - std::unique_ptr owned_info_; - }; - - friend class base::RefCountedThreadSafe; - ~ObservableInternals() {} - - mutable base::Lock lock_; - T value_; - std::vector per_sequence_; -}; - -} // namespace subtle - -template -Observer::Observer(scoped_refptr> internals) - : internals_(std::move(internals)), value_(internals_->AddObserver(this)) {} - -template -Observer::Observer(const Observer& other) : Observer(other.internals_) {} - -template -Observer::~Observer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - internals_->RemoveObserver(this); -} - -template -void Observer::OnUpdate() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (on_update_callback_) { - on_update_callback_.Run(); - } -} - -template -Observable::Observable(const T& initial_value) - : internals_(base::WrapRefCounted( - new subtle::ObservableInternals(initial_value))) {} - -template -Observer Observable::Observe() { - return Observer(internals_); -} - -template -void Observable::SetValue(const T& new_value) { - internals_->SetValue(new_value); -} - -template -const T& Observable::GetValue() const { - return internals_->GetValue(); -} - -template -T Observable::GetValueThreadSafe() const { - return internals_->GetValueThreadSafe(); -} - -} // namespace chromecast - -#endif // CHROMECAST_BASE_OBSERVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/observer_unittest.cc chromium-132.0.6834.159/chromecast/base/observer_unittest.cc --- chromium-132.0.6834.110/chromecast/base/observer_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/observer_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,352 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/run_loop.h" -#include "base/synchronization/waitable_event.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "chromecast/base/observer.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -class ObserverTest : public ::testing::Test { - protected: - base::test::SingleThreadTaskEnvironment task_environment_; -}; - -struct NoDefaultConstructor { - NoDefaultConstructor(int v) : value(v) {} - - int value; -}; - -class ThreadedObservable { - public: - ThreadedObservable() : thread_("ThreadedObservable"), value_(0) { - thread_.Start(); - } - - ThreadedObservable(const ThreadedObservable&) = delete; - ThreadedObservable& operator=(const ThreadedObservable&) = delete; - - Observer Observe() { return value_.Observe(); } - - void SetValue(int value) { - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&ThreadedObservable::SetValueOnThread, - base::Unretained(this), value)); - } - - private: - void SetValueOnThread(int value) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - value_.SetValue(value); - } - - base::Thread thread_; - Observable value_; -}; - -class ThreadedObserver { - public: - ThreadedObserver() - : thread_("ThreadedObserver"), - observing_(base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED) { - thread_.Start(); - } - - ThreadedObserver(const ThreadedObserver&) = delete; - ThreadedObserver& operator=(const ThreadedObserver&) = delete; - - ~ThreadedObserver() { - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&ThreadedObserver::DestroyOnThread, - base::Unretained(this))); - thread_.Stop(); - } - - void Observe(Observable* observable) { - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&ThreadedObserver::ObserveOnThread, - base::Unretained(this), observable)); - observing_.Wait(); - } - - void CheckValue(int value) { - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&ThreadedObserver::CheckValueOnThread, - base::Unretained(this), value)); - } - - private: - void ObserveOnThread(Observable* observable) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - observer_ = std::make_unique>(observable->Observe()); - observing_.Signal(); - } - - void CheckValueOnThread(int value) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - EXPECT_EQ(value, observer_->GetValue()); - } - - void DestroyOnThread() { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - observer_.reset(); - } - - base::Thread thread_; - std::unique_ptr> observer_; - base::WaitableEvent observing_; -}; - -void RunCallback(std::function callback) { - callback(); -} - -TEST_F(ObserverTest, SimpleValue) { - Observable original(0); - Observer observer = original.Observe(); - - EXPECT_EQ(0, observer.GetValue()); - - original.SetValue(1); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, observer.GetValue()); -} - -TEST_F(ObserverTest, MultipleObservers) { - Observable original(0); - Observer observer1 = original.Observe(); - Observer observer2 = observer1; - - EXPECT_EQ(0, observer1.GetValue()); - EXPECT_EQ(0, observer2.GetValue()); - - original.SetValue(1); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, observer1.GetValue()); - EXPECT_EQ(1, observer2.GetValue()); -} - -TEST_F(ObserverTest, NoDefaultConstructor) { - Observable original(0); - Observer observer = original.Observe(); - - EXPECT_EQ(0, observer.GetValue().value); - - original.SetValue(1); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, observer.GetValue().value); -} - -TEST_F(ObserverTest, NoMissingEvents) { - Observable original(0); - Observer observer = original.Observe(); - original.SetValue(1); - - std::vector event_values; - std::function callback = [&]() { - event_values.push_back(observer.GetValue()); - }; - observer.SetOnUpdateCallback(base::BindRepeating(&RunCallback, callback)); - - EXPECT_EQ(0, observer.GetValue()); - - original.SetValue(2); - base::RunLoop().RunUntilIdle(); - original.SetValue(3); - original.SetValue(4); - base::RunLoop().RunUntilIdle(); - - ASSERT_EQ(4u, event_values.size()); - EXPECT_EQ(1, event_values[0]); - EXPECT_EQ(2, event_values[1]); - EXPECT_EQ(3, event_values[2]); - EXPECT_EQ(4, event_values[3]); - - EXPECT_EQ(4, observer.GetValue()); -} - -TEST_F(ObserverTest, NoExtraEventsAfterChange) { - Observable original(0); - original.SetValue(1); - - Observer observer = original.Observe(); - EXPECT_EQ(1, observer.GetValue()); - - std::vector event_values; - std::function callback = [&]() { - event_values.push_back(observer.GetValue()); - }; - observer.SetOnUpdateCallback(base::BindRepeating(&RunCallback, callback)); - - // Propagate the SetValue event; the observer shouldn't get it since it - // started observing after SetValue(). - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, observer.GetValue()); - EXPECT_EQ(0u, event_values.size()); -} - -TEST_F(ObserverTest, NoExtraEventsBetweenChanges) { - Observable original(0); - original.SetValue(1); - - Observer observer = original.Observe(); - EXPECT_EQ(1, observer.GetValue()); - - original.SetValue(2); - - std::vector event_values; - std::function callback = [&]() { - event_values.push_back(observer.GetValue()); - }; - observer.SetOnUpdateCallback(base::BindRepeating(&RunCallback, callback)); - - // Propagate the SetValue events; the observer should only get the second - // event, corresponding to the SetValue after the observer was created. - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(2, observer.GetValue()); - ASSERT_EQ(1u, event_values.size()); - EXPECT_EQ(2, event_values[0]); -} - -TEST_F(ObserverTest, NoExtraEventsForCopy) { - Observable original(0); - original.SetValue(1); - - Observer observer1 = original.Observe(); - EXPECT_EQ(1, observer1.GetValue()); - - original.SetValue(2); - - Observer observer2 = observer1; - // All observers on the same thread observe the same value. The update hasn't - // propagated yet. - EXPECT_EQ(1, observer2.GetValue()); - - std::vector event_values1; - std::function callback1 = [&]() { - event_values1.push_back(observer1.GetValue()); - }; - observer1.SetOnUpdateCallback(base::BindRepeating(&RunCallback, callback1)); - - std::vector event_values2; - std::function callback2 = [&]() { - event_values2.push_back(observer2.GetValue()); - }; - observer2.SetOnUpdateCallback(base::BindRepeating(&RunCallback, callback2)); - - // Propagate the SetValue events; each observer should get just one callback - // for the new value. - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(2, observer1.GetValue()); - EXPECT_EQ(2, observer2.GetValue()); - - ASSERT_EQ(1u, event_values1.size()); - EXPECT_EQ(2, event_values1[0]); - - ASSERT_EQ(1u, event_values2.size()); - EXPECT_EQ(2, event_values2[0]); -} - -TEST_F(ObserverTest, SetCallbackTwice) { - Observable original(0); - original.SetValue(1); - - Observer observer = original.Observe(); - EXPECT_EQ(1, observer.GetValue()); - - original.SetValue(2); - - std::vector event_values1; - std::function callback1 = [&]() { - event_values1.push_back(observer.GetValue()); - }; - observer.SetOnUpdateCallback(base::BindRepeating(&RunCallback, callback1)); - - std::vector event_values2; - std::function callback2 = [&]() { - event_values2.push_back(observer.GetValue()); - }; - observer.SetOnUpdateCallback(base::BindRepeating(&RunCallback, callback2)); - - // Propagate the SetValue events; only the second callback should be run. - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(2, observer.GetValue()); - EXPECT_EQ(0u, event_values1.size()); - ASSERT_EQ(1u, event_values2.size()); - EXPECT_EQ(2, event_values2[0]); -} - -TEST_F(ObserverTest, ObserverOutlivesObservable) { - auto original = std::make_unique>(0); - Observer observer1 = original->Observe(); - - EXPECT_EQ(0, observer1.GetValue()); - - original->SetValue(1); - original.reset(); - - Observer observer2 = observer1; - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(1, observer1.GetValue()); - EXPECT_EQ(1, observer2.GetValue()); -} - -TEST_F(ObserverTest, ObserverOnDifferentThread) { - auto original = std::make_unique(); - Observer observer = original->Observe(); - EXPECT_EQ(0, observer.GetValue()); - - std::vector event_values; - std::function callback = [&]() { - event_values.push_back(observer.GetValue()); - }; - observer.SetOnUpdateCallback(base::BindRepeating(&RunCallback, callback)); - - original->SetValue(1); - original->SetValue(2); - original.reset(); - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(2, observer.GetValue()); - ASSERT_EQ(2u, event_values.size()); - EXPECT_EQ(1, event_values[0]); - EXPECT_EQ(2, event_values[1]); -} - -TEST_F(ObserverTest, ObserveOnManyThreads) { - auto original = std::make_unique>(0); - std::vector> observers; - for (int i = 0; i < 20; ++i) { - observers.push_back(std::make_unique()); - observers.back()->Observe(original.get()); - } - - original->SetValue(1); - original.reset(); - - base::RunLoop().RunUntilIdle(); - for (auto& observer : observers) { - observer->CheckValue(1); - } - - // Deleting the observers should check the expectations, since all posted - // tasks on their internal threads will run. - observers.clear(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/path_utils.cc chromium-132.0.6834.159/chromecast/base/path_utils.cc --- chromium-132.0.6834.110/chromecast/base/path_utils.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/path_utils.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// 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 "chromecast/base/path_utils.h" - -#include "base/logging.h" -#include "base/path_service.h" - -namespace chromecast { - -namespace { - -base::FilePath GetPath(base::BasePathKey default_dir_key, - const base::FilePath& path) { - if (path.IsAbsolute()) - return path; - - base::FilePath default_dir; - if (!base::PathService::Get(default_dir_key, &default_dir)) - LOG(DFATAL) << "Cannot get default dir: " << default_dir_key; - - base::FilePath adjusted_path(default_dir.Append(path)); - DVLOG(1) << "Path adjusted from " << path.value() << " to " - << adjusted_path.value(); - return adjusted_path; -} - -} // namespace - -base::FilePath GetHomePath(const base::FilePath& path) { - return GetPath(base::DIR_HOME, path); -} - -base::FilePath GetHomePathASCII(const std::string& path) { - return GetHomePath(base::FilePath(path)); -} - -base::FilePath GetBinPath(const base::FilePath& path) { - return GetPath(base::DIR_EXE, path); -} - -base::FilePath GetBinPathASCII(const std::string& path) { - return GetBinPath(base::FilePath(path)); -} - -base::FilePath GetTmpPath(const base::FilePath& path) { - return GetPath(base::DIR_TEMP, path); -} - -base::FilePath GetTmpPathASCII(const std::string& path) { - return GetTmpPath(base::FilePath(path)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/path_utils.h chromium-132.0.6834.159/chromecast/base/path_utils.h --- chromium-132.0.6834.110/chromecast/base/path_utils.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/path_utils.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_PATH_UTILS_H_ -#define CHROMECAST_BASE_PATH_UTILS_H_ - -#include - -#include "base/files/file_path.h" - -namespace chromecast { - -// If |path| is relative, returns the path created by prepending HOME directory -// to |path| (e.g. {HOME}/|path|). If |path| is absolute, returns |path|. -base::FilePath GetHomePath(const base::FilePath& path); -base::FilePath GetHomePathASCII(const std::string& path); - -// If |path| is relative, returns the path created by prepending BIN directory -// to |path| (e.g. {BIN}/|path|). If |path| is absolute, returns |path|. -base::FilePath GetBinPath(const base::FilePath& path); -base::FilePath GetBinPathASCII(const std::string& path); - -// If |path| is relative, returns the path created by prepending TMP directory -// to |path| (e.g. {TMP}/|path|). If |path| is absolute, returns |path|. -base::FilePath GetTmpPath(const base::FilePath& path); -base::FilePath GetTmpPathASCII(const std::string& path); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_PATH_UTILS_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/path_utils_unittest.cc chromium-132.0.6834.159/chromecast/base/path_utils_unittest.cc --- chromium-132.0.6834.110/chromecast/base/path_utils_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/path_utils_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// 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 "base/files/file_path.h" -#include "base/path_service.h" -#include "chromecast/base/path_utils.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { -const char kTestRelPath[] = "rel/path"; -const char kTestAbsPath[] = "/abs/path/to/dir"; - -std::string GetTestString(int base_dir_key) { - base::FilePath basedir; - EXPECT_TRUE(base::PathService::Get(base_dir_key, &basedir)); - return basedir.value() + "/" + kTestRelPath; -} - -} // namespace - -TEST(PathUtilsTest, GetHomePath) { - // Test with relative path. - std::string expected = GetTestString(base::DIR_HOME); - base::FilePath actual = GetHomePath(base::FilePath(kTestRelPath)); - EXPECT_EQ(expected, actual.value()); - - // Test with absolute path. - actual = GetHomePath(base::FilePath(kTestAbsPath)); - EXPECT_EQ(kTestAbsPath, actual.value()); -} - -TEST(PathUtilsTest, GetBinPath) { - // Test with relative path. - std::string expected = GetTestString(base::DIR_EXE); - base::FilePath actual = GetBinPath(base::FilePath(kTestRelPath)); - EXPECT_EQ(expected, actual.value()); - - // Test with absolute path. - actual = GetBinPath(base::FilePath(kTestAbsPath)); - EXPECT_EQ(kTestAbsPath, actual.value()); -} - -TEST(PathUtilsTest, GetTmpPath) { - // Test with relative path. - std::string expected = GetTestString(base::DIR_TEMP); - base::FilePath actual = GetTmpPath(base::FilePath(kTestRelPath)); - EXPECT_EQ(expected, actual.value()); - - // Test with absolute path. - actual = GetTmpPath(base::FilePath(kTestAbsPath)); - EXPECT_EQ(kTestAbsPath, actual.value()); -} - -} // chromecast \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/base/pref_names.cc chromium-132.0.6834.159/chromecast/base/pref_names.cc --- chromium-132.0.6834.110/chromecast/base/pref_names.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/pref_names.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/pref_names.h" - -namespace chromecast { -namespace prefs { - -// List of experiments enabled by DCS. For metrics purposes only. -const char kActiveDCSExperiments[] = "experiments.ids"; - -// Dictionary of remotely-enabled features from the latest DCS config fetch. -const char kLatestDCSFeatures[] = "experiments.features"; - -// Boolean that specifies whether or not the client_id has been regenerated -// due to bug b/9487011. -const char kMetricsIsNewClientID[] = "user_experience_metrics.is_new_client_id"; - -// Whether or not to report metrics and crashes. -const char kOptInStats[] = "opt-in.stats"; - -// Whether or not TOS has been accepted by user. -const char kTosAccepted[] = "tos-accepted"; - -// Total number of kernel crashes since the last report. -const char kStabilityKernelCrashCount[] = - "user_experience_metrics.stability.kernel_crash_count"; - -// Total number of external user process crashes since the last report. -const char kStabilityOtherUserCrashCount[] = - "user_experience_metrics.stability.other_user_crash_count"; - -// Total number of unclean system shutdowns since the last report. -const char kStabilitySystemUncleanShutdownCount[] = - "user_experience_metrics.stability.system_unclean_shutdowns"; - -// Current web color scheme. See blink::PreferredColorScheme. -const char kWebColorScheme[] = "web-color-scheme"; - -} // namespace prefs -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/pref_names.h chromium-132.0.6834.159/chromecast/base/pref_names.h --- chromium-132.0.6834.110/chromecast/base/pref_names.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/pref_names.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_PREF_NAMES_H_ -#define CHROMECAST_BASE_PREF_NAMES_H_ - -namespace chromecast { -namespace prefs { - -extern const char kActiveDCSExperiments[]; -extern const char kLatestDCSFeatures[]; -extern const char kMetricsIsNewClientID[]; -extern const char kOptInStats[]; -extern const char kTosAccepted[]; -extern const char kStabilityKernelCrashCount[]; -extern const char kStabilityOtherUserCrashCount[]; -extern const char kStabilitySystemUncleanShutdownCount[]; -extern const char kWebColorScheme[]; - -} // namespace prefs -} // namespace chromecast - -#endif // CHROMECAST_BASE_PREF_NAMES_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/process_types.h chromium-132.0.6834.159/chromecast/base/process_types.h --- chromium-132.0.6834.110/chromecast/base/process_types.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/process_types.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_PROCESS_TYPES_H_ -#define CHROMECAST_BASE_PROCESS_TYPES_H_ - -namespace chromecast { - -enum class ProcessType { - kCastBrowser, - kCastService, -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_PROCESS_TYPES_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/process_utils.cc chromium-132.0.6834.159/chromecast/base/process_utils.cc --- chromium-132.0.6834.110/chromecast/base/process_utils.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/process_utils.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// 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 "chromecast/base/process_utils.h" - -#include -#include -#include - -#include "base/logging.h" -#include "base/posix/safe_strerror.h" -#include "base/strings/string_util.h" - -namespace chromecast { - -bool GetAppOutput(const std::vector& argv, std::string* output) { - DCHECK(output); - - // Join the args into one string, creating the command. - std::string command = base::JoinString(argv, " "); - - // Open the process. - FILE* fp = popen(command.c_str(), "r"); - if (!fp) { - PLOG(ERROR) << "popen (" << command << ") failed"; - return false; - } - - // Fill |output| with the stdout from the process. - output->clear(); - while (!feof(fp)) { - char buffer[256]; - size_t bytes_read = fread(buffer, 1, sizeof(buffer), fp); - if (bytes_read <= 0) - break; - output->append(buffer, bytes_read); - } - - // pclose() function waits for the associated process to terminate and returns - // the exit status. - return (pclose(fp) == 0); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/process_utils.h chromium-132.0.6834.159/chromecast/base/process_utils.h --- chromium-132.0.6834.110/chromecast/base/process_utils.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/process_utils.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_PROCESS_UTILS_H_ -#define CHROMECAST_BASE_PROCESS_UTILS_H_ - -#include -#include - -namespace chromecast { - -// Executes application, for which arguments are specified by |argv| and wait -// for it to exit. Stores the output (stdout) in |output|. Returns true on -// success. -// TODO(slan): Replace uses of this with base::GetAppOutput when crbug/493711 is -// resolved. -bool GetAppOutput(const std::vector& argv, std::string* output); - -} // namespace chromecast - -#endif // CHROMECAST_BASE_PROCESS_UTILS_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/process_utils_unittest.cc chromium-132.0.6834.159/chromecast/base/process_utils_unittest.cc --- chromium-132.0.6834.110/chromecast/base/process_utils_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/process_utils_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -// 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 "chromecast/base/process_utils.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -// Verify that a simple process works as expected. -TEST(ProcessUtilsTest, SimpleProcess) { - // Create a simple command. - std::vector args; - args.push_back("echo"); - args.push_back("Hello World"); - - // Execute the command and collect the output. - std::string stdout_result; - ASSERT_TRUE(GetAppOutput(args, &stdout_result)); - - // Echo will append a newline to the stdout. - EXPECT_EQ("Hello World\n", stdout_result); -} - -// Verify that false is returned for an invalid command. -TEST(ProcessUtilsTest, InvalidCommand) { - // Create a command which is not valid. - std::vector args; - args.push_back("invalid_command"); - - // The command should not run. - std::string stdout_result; - ASSERT_FALSE(GetAppOutput(args, &stdout_result)); - ASSERT_TRUE(stdout_result.empty()); -} - -// Verify that false is returned when a command an error code. -TEST(ProcessUtilsTest, ProcessReturnsError) { - // Create a simple command. - std::vector args; - args.push_back("cd"); - args.push_back("path/to/invalid/directory"); - args.push_back("2>&1"); // Pipe the stderr into stdout. - - // Execute the command and collect the output. Verify that the output of the - // process is collected, even when the process returns an error code. - std::string stderr_result; - ASSERT_FALSE(GetAppOutput(args, &stderr_result)); - ASSERT_FALSE(stderr_result.empty()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/reactive_java.md chromium-132.0.6834.159/chromecast/base/reactive_java.md --- chromium-132.0.6834.110/chromecast/base/reactive_java.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/reactive_java.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,1293 +0,0 @@ -# Reactive Android Java programming - -[TOC] - -## Introduction - -**Ever notice how Android methods often come in pairs?** For every `onCreate()`, -there is an `onDestroy()`, for every `onStart()`, there is an `onStop()`. The -Android SDK commonly asks clients to register callbacks or extend base classes -that override pairs of methods that correspond to *reversible changes in state*. - -*State* is often expressed in Java code as *mutable variables*. A state changes -when you assign a new value to the variable. If a variable can be one value at -some points and another value at other points, that means there are two states -that the variable can have. Everything that interacts with that variable needs -to work correctly for each state the variable can be in. For example, if an -instance variable is `null` in a class's constructor, and set to a value by some -method in that class, then *every* method that tries to call a method on that -variable needs to check whether the value of the variable is null before -handling it, because there is no guarantee which state the variable is in. You -will see a lot of code that looks like this when using this pattern for -representing state: - -```java -if (mFoo != null) { - mFoo.doSomething(); -} -``` - -Additionally, mutator methods may need to check the state at runtime. For -example, lazy initialization often looks like this: - -```java -if (mFoo == null) { - mFoo = new Foo(...); -} -``` - -This is not bad in and of itself, if the states are well-defined and it's easy -to reason about the set of possible states by looking at the code. However, it -very, very quickly becomes difficult to reason about states when there are any -of the following: - -* **Multiple methods that can mutate state**. For example, a hypothetical - `Connection` class that reads and writes data over a socket might disconnect - on a socket error from any `read()` or `write()` call. That means that - before any `read()` or `write()` call, the state must be checked. (Real Java - objects will often use `Exception`s to short-circuit code blocks that enter - an exceptional state). -* **Methods that throw a runtime error** or have **undefined behavior when in - a certain state**. For example, a class with an `initialize()` method may - have methods that should only be called after `initialize()`, but the - compiler will not be able to check whether `initialize()` has been called. - This includes every method that has an `assert` statement on a mutable - instance variable. -* Multiple **states that interact with each other**. The number of states that - independently-mutable variables can take is the *product* of the number of - states of each of the variables. Often, variables are not strictly - independent (e.g. the only method that mutates a certain variable also - mutates another), so some states might be unreachable. However, it's **not - possible for the compiler to tell you which states are reachable** when - you're using mutable instance variables, so you have to figure that out - yourself! This makes it hard to exhaustively come up with unittest cases. - -## Motivating Example - -Consider this seemingly-simple task: you have two variables, `mA` and `mB`, each -of which could be either `null` or some real value of types `A` and `B`, -respectively. Furthermore, you want to initialize a new variable, `mC` of type -`C`, when the values of `mA` and `mB` are non-null, perhaps because the `C` -constructor takes an `A` and a `B`. Finally, if `mA` or `mB` becomes null again -after creating `mC`, reset `mC` to `null`. Also, you need to invoke a `close()` -method on `mC` whenever `mC` is reset. And if `mA` or `mB` changes while `mC` -exists, you need to call `mC.close()` and re-create `mC` with the new `mA` and -`mB`. - -```java -class MyClass { - private A mA = null; - private B mB = null; - private C mC = null; - - public void setA(A a) { - mA = a; - recalculateC(); - } - - public void setB(B b) { - mB = b; - recalculateC(); - } - - private void recalculateC() { - // This method is always called when A or B changes, so if C exists, it - // must first be reset. - if (mC != null) { - mC.close(); - mC = null; - } - if (mA != null && mB != null) { - mC = new C(mA, mB); - } - } -} -``` - -This may be fine on its own. But chances are, you will want to do something with -`mC` outside these methods. Every read will have to null-check, there's an -**undocumented but critical requirement** that every write to `mA` and `mB` is -done through `setA()` and `setB()`, and that `recalculateC()` is only called -when `mA` or `mB` is mutating, or else it will implicitly close. - -These undocumented dependencies can only be protected against regression by -testing. The compiler will not tell you if you made a mistake, so there must be -unittests covering every possible state change. And in this case, we have two -variables, each with two states that each have two possible state transitions, -so **8 test cases are needed to cover everything**. And this is the **simplest** -case of composing **two** independent nullable mutable variables. - -Meanwhile, if you use the `Observable`s framework: - -```java - -class MyClass { - private final Controller mA = new Controller<>(); - private final Controller mb = new Controller<>(); - - { - mA.and(mB).subscribe(Both.adapt(C::new)); - } - - public void setA(A a) { - mA.set(a); - } - - public void setB(B b) { - mB.set(b); - } -} -``` - -In the instance initializer, we set up a simple state machine with two -`Controller`s, which correspond to the mutable instance variables from the -previous example, and an event that observes the state of the `Controller`s and -invokes some logic on certain state changes. - -The `and()` call composes the `mA` and `mB`, returning a new `Observable` that -is only activated when *both* sources are activated, and then deactivated if -*either* source is deactivated. `mA` and `mB` are activated or deactivated by -`set()` and `reset()` calls, respectively. The `set()` method deactivates the -state if the argument is `null` (the `reset()` method can also be used to -deactivate the state). - -The `subscribe()` call makes it so that when the composed `Observable` formed by -`mA.and(mB)` is activated, a new `C` object will be created. When deactivated, -that `C` object's `close()` method will be called. - -This really does cover all the cases we need. If multiple `set*()` calls are -made, an implicit `reset()` call will be made to the relevant `Controller` and -the `C` object associated with the first scope will be `close()`d. - -What's better about this? First, notice we **don't need mutable variables**. -Both `Controller` objects are `final`, and are never `null`. We don't at any -point need to know what state the object is in inside any method -implementations; the `Controller`s and the pipeline set up by the `and()` and -`subscribe()` calls handle that for you. - -Second, notice how the concerns of mutating and reacting to state are **cleanly -separated**. The mutator methods `setA()` and `setB()` are concerned only with -their respective `Controller`s, and the lifetime of the `C` object is managed in -one place in the instance initializer. - -Finally, the relationship between the `A`, `B`, and `C` objects is -**self-documenting**. In the first approach with mutable variables, to -understand that the lifetime of `C` is associated with the intersection of the -lifetimes of `A` and `B`, one has to examine both setters and trace through -`recalculateC()` from the perspective of both of its call sites. In the second -approach, using `Controller`s, the relationship between `A`, `B`, and `C` is -expressed holistically in one line. - -## Observables and Observers - -Think of an `Observable` as a *container*, with one very important feature: the -ability to register **observers** that will be notified when the contents of the -container change. The contents of the container at a given time is the *state* -of the `Observable`. The `Observable` base class alone does not expose any state -mutators, but it provides ways to register events that will be invoked when -state changes. - -All state transitions of an `Observable` is either an *activation* or a -*deactivation*. An activation refers to putting some data into the container, -and a deactivation represents removing some data from the container. The data -that is contained in an `Observable` is thus called **activation data**. - -To register events that should be invoked on these state transitions, we -**subscribe** observers. An `Observer` works by opening a `Scope` when an -activation occurs. If a deactivation occurs, the `Scope` opened by the -`Observer` will be closed. The name **scope** comes from how its lifetime is the -time that the activation data exists within the `Observable`, similar to how -variables are *in scope* when using -[RAII](https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) in -languages like C++. - -The one-to-one mapping of activations in an `Observable` to opened `Scopes` for -each subscribed `Observer` affords many useful properties. Foremost among these -is that the `Scope` can capture the data it is associated with as an *immutable* -variable: the activation data is the same when it is deactivated as when it was -activated. It also ensures that every deactivation requires an activation to -have occurred first (since you cannot `close()` an object that hasn't been -constructed). The implications of these properties will be explored further in -later sections. - -### Registering subscriptions with Observables - -To subscribe an `Observer` to an `Observable`, we call `subscribe()` -on the `Observable`. The `subscribe()` method takes a single argument, an -`Observer`, which has an `open()` method that returns a `Scope`. The -`Observer`'s `open()` method is called when the `Observable` activates, -and the resulting `Scope`'s `close()` method is called when the `Observable` -deactivates. - -Lambda syntax can be used to easily construct `Observer` objects without -much boilerplate. For instance, if we want to simply log the transitions of an -`Observable`, we might do it like this: - -```java -void logStateTransitions(Observable observable) { - observable.subscribe(x -> { - Log.d(TAG, "activated"); - return () -> Log.d(TAG, "deactivated"); - }); -}; -``` - -This is equivalent to the following, much more verbose version: - -```java -void logStateTransitions(Observable observable) { - observable.subscribe(new Observer() { - @Override - public Scope create(Object x) { - Log.d(TAG, "activated"); - return new Scope() { - @Override - public void close() { - Log.d(TAG, "deactivated"); - } - }; - } - }); -} -``` - -As you can see, the version that uses lambdas is much more readable, as long as -you understand what an `Observer` is. It can help to think of the `return () ->` -as a separator between what happens when the data is activated and what happens -when the data is deactivated. - -Either way, when `logStateTransitions()` is called on an `Observable`, -`"activated"` will be printed to the log when that `Observable` is activated, -and `"deactivated"` will be printed to the log when that `Observable` is -deactivated. - -Though the above `Observer` does not use the `x` parameter, normally -`Observer` implementations will use the data that `open()` is given, so -that the behavior of the scope can depend on what data the `Observable` is -activated with. - -Say we have an `Observable` and we want to log the data it is activated -with: - -```java -void logStateTransitionsWithData(Observable observable) { - observable.subscribe((String s) -> { - Log.d(TAG, "activated with data: %s", s); - return () -> Log.d(TAG, "deactivated"); - }); -} -``` - -### Mutating state with Controllers - -The `Observable` interface does not provide any way to directly change the state -of the `Observable`. However, subclasses of `Observable` exist that do provide -mutators. The `Controller` class provides `set()` and `reset()`. - -`Controller`s are basically nullable, mutable variables that let you register -callbacks, through the `Observable` interface, that are run when the variable -changes. - -With this in mind, the `set()` method on `Controller` is like setting a mutable -variable to a value. The `reset()` method is like setting the mutable variable -to `null`. - -Here are some guarantees that `Controller`s provide: - -* Start out in the *deactivated* state. -* If the parameter of `set()` is non-`null`, it enters the *activated* state. -* If the parameter of `set()` is `null`, it enters the *deactivated* state. -* If in the activated state, `reset()` and `set(null)` enter the *deactivated* - state. -* If already in the deactivated state, `reset()` and `set(null)` do nothing. -* If in the activated state with data `data1`, `set(data2)` no-ops if - `data1.equals(data2)`. -* If in the activated state, and the new data is not `equal()` to the current - data, `set()` implicitly deactivates and reactivates with the new data. - -As corollaries, any registered `Observer` objects will: - -* have their `open()` methods invoked *exactly once* for each non-`null` - `set()` call -* have their resulting `Scope`s `close()`d *exactly once* when `reset()` or - `set()` to `null` -* always clean up scopes from previous activations when new activations occur - -This means this: - -```java -void helloGoodbye(Controller message) { - message.set("hello"); - message.set("goodbye"); - message.set(null); -} -``` - -has the same behavior as this: - -```java -void helloGoodbye(Controller message) { - message.set("hello"); - message.reset(); - message.set("goodbye"); - message.reset(); -} -``` - -Essentially, a `Controller` adapts two states with two possible actions each: - -* `deactivated`: `set`, `reset` -* `activated`: `set`, `reset` - -into a well-defined state machine with two states and two transitions: - -* `deactivated`: `set` -* `activated`: `reset` - -... by dropping redundant `reset()` calls and inserting implicit `reset()` calls -between contiguous `set()` calls. This cuts the number of state transitions you -need to worry about in half! - -Since `Controller`s implement `Observable`, you can register `Observer` -objects with `subscribe()` the same way as in the previous section, or inject a -`Controller` into any method that takes an `Observable` of the same parametric -type. - -Remember that an `Observable` can be thought of as a *container* of data. In -this frame of mind, a `Controller` is a container of *one or zero* instances of -some data type. - -### Observables without data - -The state of a `Controller` is isomorphic to that of a nullable `T` variable -for all types `T`. But there are many cases where what we really want is a -representation of a boolean state: on or off, active or inactive, and don't need -any activation data. - -For these cases, the `org.chromium.chromecast.base.Unit` class is used to denote -the fact that there is no data associated with the controller. The `Unit` type -is inspired by the type of the same name in many functional programming -languages, and represents a type with only one possible instance (aka -`Singleton`). - -To make a controller without data, you can therefore use `Controller`. -Since `Unit` means "no data," and there's only one way to get a `Unit` instance -(through the `Unit.unit()` method), this maps correctly to the concept of a -mutable boolean value. - -Note that because the instance of `Unit` equals itself, calling `set()` on a -`Controller` when it is already activated will no-op, making the behavior -of `set(Unit.unit())` and `reset()` symmetric. - -Example: - -```java -{ - Controller onOrOff = new Controller<>(); - onOrOff.subscribe(x -> { - Log.d(TAG, "on"); - return () -> Log.d(TAG, "off"); - }); - onOrOff.set(Unit.unit()); // Turns on. - onOrOff.set(Unit.unit()); // Does nothing because it's already on. - onOrOff.reset(); // Turns off. - onOrOff.reset(); // Does nothing because it's already off. -} -``` - -It's common for observers and APIs that refer to `Observable`s with no data to -use `Observable` in their interface. This is an easy way to make an -`Observable`'s data "opaque" to observers, even when the data are not `Unit`. - -```java -{ - Controller foos = new Controller<>(); - // Subscribers to opaqueFoos will get notified of state changes, but will - // not be able to access the data through the Foo interface. - Observable opaqueFoos = foos; - // The observer can use methods like toString() that exist on all Objects, - // but cannot use Foo's API. - subscribe(opaqueFoos, x -> { - Log.d(TAG, "got Foo: %s", x.toString()); - return () -> Log.d(TAG, "lost Foo: %s", x.toString()); - }); -} -``` - -### Composing Observables with `and()` - -In the motivating example, we wanted to invoke a callback once *two* independent -`Observable`s have been activated. - -Let's say we have a set of states: - -* `A` -* `not A` - -With the transitions `not A` **<->** `A`. - -And introduce another set of states: - -* `B` -* `not B` - -With the transitions `not B` **<->** `B`. - -We can then describe the *combinations* of those state spaces with four states: - -* `neither` -* `just A` -* `just B` -* `A and B` - -...and eight transitions: - -* `neither` **<->** `just A` -* `neither` **<->** `just B` -* `just A` **<->** `A and B` -* `just B` **<->** `A and B` - -The `Observable` interface gives us a convenient way to get the `(A and B)` -state with a simple call: - -```java -public void logWhenBoth(Observable observableA, Observable observableB) { - observableA.and(observableB).subscribe(...); -} -``` - -The `and()` method takes the calling `Observable` and the given other -`Observable` and returns a new `Observable` that is only activated when *both* -input `Observable`s are activated. - -One way to think about it is that the `and()` call collapses the three states -`(neither)`, `(just A)`, and `(just B)` into one *deactivated* state, and -treats the state `both` as *activated*. For observers of the `and()`-composition -of states, one needs only worry about the two states, *deactivated* and -*activated*, same as with any other observer. - -So how do we get the data in the `subscribe()` call? Let's say we want to log -when both `Observable`s are activated: - -```java -public void logWhenBoth(Observable observableA, Observable observableB) { - observableA.and(observableB).subscribe((Both data) -> { - A a = data.first; - B b = data.second; - Log.d(TAG, "both activated: a=" + a + ", b=" + b); - return () -> Log.d(TAG, "deactivated"); - }); -} -``` - -The type of the activation data for an `and()`-composed `Observable` is `Both`. -The `Both` type has two generic parameters, and `first` and `second` public -fields to access the data it encapsulates. It is essentially a trick to box -multiple values into a single object, so we only ever need `Observer` -interfaces that take a single argument. - -Since the `and()` method returns an `Observable`, the result can itself call -`and()`, whose result can itself call `and()`, ad infinitum: - -```java - observableA.and(observableB).and(observableC).and(observableD)... -``` - -But beware, as the associated type of the `Observable` gets uglier and uglier: - -```java - a.and(b).and(c).and(d).subscribe((Both, C>, D> data) -> { - A aData = data.first.first.first; - B bData = data.first.first.second; - C cData = data.first.second; - D dData = data.second; - Log.d(TAG, "a=%s, b=%s, c=%s, d=%s", aData, bData, cData, dData); - return () -> Log.d(TAG, "exit"); - }); -``` - -One one hand, it's kind of neat that you can do that at all. But it does come at -a cost to readability. The compiler can catch you if you mess up the -`first.first.second` chains if the types are different, but it is regrettable -that this much work is required to read the compound data. Some methods for -alleviating this are described below. - -### Imposing order dependency with `andThen()` - -The composition of state spaces `stateA.and(stateB)` doesn't care if `stateA` or -`stateB` was activated first, so it can be activated by either activating -`stateA` and then `stateB`, or by activating `stateB` and then `stateA`. - -This means the state `(A and B)`, extracted by the `and()` method on -`Observable`, is too ambiguous for knowing the *order* of activation. If we want -to know whether `A` was activated before `B`, we must *partition* the state -`(A and B)` into `(A and then B)` and `(B and then A)`. The time-dependent state -space for two boolean variables looks like this, with five states: - -* `neither` -* `just A` -* `just B` -* `A and then B` -* `B and then A` - -...and ten transitions: - -* `neither` **<->** `just A` -* `neither` **<->** `just B` -* `just A` **<->** `A and then B` -* `just B` **<->** `B and then A` -* `A and then B` **-->** `just B` -* `B and then A` **-->** `just A` - -Calling `stateA.andThen(stateB)` returns an `Observable` representing the -`(A and then B)` state from above. The resulting `Observable` will only activate -on the transition between `(just A)` and `(A and then B)`, and will not activate -on the transition between `(just B)` and `(B and then A)`. - -### Subscriptions as Scopes - -Sometimes you might want to only `subscribe()` to an `Observable` for a limited -time, for instance, until some other `Observable` is activated. So how do you -remove an observer? - -The `subscribe()` method returns a `Subscription`, which, when `close()`d, will -unregister the `Observer` registered in the `subscribe()` call. To `subscribe()` -for a limited time, simply store the `Subscription` somewhere, and call -`close()` on it when you're done. - -```java - private final Observable mMessages = ...; - private final List mLog = ...; - private Subscription mSubscription = null; - - public void startRecording() { - if (mObserver != null) stopRecording(); - mObserver = mMessages.subscribe(Observers.onEnter(mLog::add)); - } - - public void stopRecording() { - if (mSubscription == null) return; - mSubscription.close(); - } -``` - -... wait a minute, are those `null`-checks? And a *mutable variable*? I thought -this framework was supposed to get rid of those! - -And indeed we can! Since `mObserver` is a `Subscription`, which is a kind of -`Scope`, that means we can use it in another `subscribe()` call! - -```java - private final Observable mMessages = ...; - private final List mLog = ...; - private final Controller mRecordingState = ...; - - { - // When mRecordingState is activated, an Observer is registered to - // mMessages. - mRecordingState.subscribe(x -> { - // When mRecordingState is deactivated, the Subscription is closed, - // so new messages will stop being added to the log. - return mMessages.subscribe(Observers.onEnter(mLog::add)); - }); - } - - public void startRecording() { - mRecordingState.set(Unit.unit()); - } - - public void stopRecording() { - mRecordingState.reset(); - } -``` - -Now we have removed the mutable variable and delegated all management of state -to `Observable`s. - -But wait, we could have done the same thing with `and()`: - -```java - { - mRecordingState.and(mMessages).subscribe(Observers.onEnter( - (Both data) -> mLog.add(data.second))); - } -``` - -But here we can see the drawbacks of that approach. We need to deconstruct the -`Both` object. Though the below section shows a way to circumvent that when only -using a single `and()` call, it gets much harder to work with longer chains of -`and()`-composed `Observable`s. - -Recall that deconstructing larger `Both` trees is ugly: - -```java - stateA.and(stateB).and(stateC).and(stateD).subscribe(data -> { - A a = data.first.first.first; - B b = data.first.first.second; - C c = data.first.second; - D d = data.second; - ... - }); -``` - -If we only care about registering a `Scope` for when all four `Observable`s are -activated, then we can use nested `subscribe()` calls instead: - -```java - stateA.subscribe(a -> stateB.subscribe(b -> stateC.subscribe(c -> stateD.subscribe(d -> { - ... - })))); -``` - -This is called **subscription-currying**, and is a useful alternative to `and()` -calls when registering `Observer` objects for the intersection of many -`Observable`s. - -To show why this works, let's simplify to just this: - -```java - stateA.subscribe(a -> stateB.subscribe(b -> ...)); -``` - -Notice that: - -* We do not `subscribe` to `stateB` until `stateA` is activated. -* If `stateB` is already activated when an `Observer` is subscribed to it, the - observer will be notified of the data immediately. -* While `stateA` is activated, the `Observer` subscribed to `stateB` will open - and close its scopes normally as `stateB` mutates. -* If `stateA` is deactivated, the `Subscription` to `stateB` is closed. Closing - a `Subscription` also closes the `Scope`s from the `Observer`. - -In other words, the inner `Observer` is only opened if *both* `stateA` and -`stateB` are activated, and that `Observer`'s `Scope` will be closed if *either* -`stateA` or `stateB` is deactivated. This is the same as the `and()` operator! - -This even works for `Observable`s that have multiple activations. Each -activation of `stateA` will produce a unique `Subscription` to `stateB`, so this -pattern can be compared to a nested `for` loop -- one that operates reactively -whenever the states update! More precisely, there will be a 1:1 mapping of the -Cartesian product of activations of `stateA` and `stateB` and `Scopes` from the -inner `Observer` subscribed to `stateB`. - -One should use the `and()` operator when more operations like `map()` and -`filter()` are needed on the resulting `Observable`, but subscription-currying -can be used in some other situations as an alternative in situations where -dealing with `Both` objects becomes cumbersome. It is generally recommended to -prefer the `and()` operator if all else is equal, because it's easier to add -more operators to the pipeline later on if needed. - -An alternative to using `and()` in situations that call for `map()` and -`filter()` on the result is to use `flatMap()`-currying: - -```java - stateA.flatMap(a -> stateB.flatMap(b -> Observable.just(new C(a, b)))) - .filter(c -> isValid(c)) - .subscribe(d -> ...); -``` - -### Increase readability for Observers with wrapper methods - -The `Observers` class contains several helper methods to increase the -fluency and readability of common cases that `Observer` objects might be -used for. - -#### Use onOpen() and onClose() to observe only one kind of transition - -Every `Observer` returns a `Scope`, but sometimes clients do not care about -when the state deactivates, only when it activates. It's possible to create a -`Observer` with lambda syntax to do the job like this: - -```java -{ - observable.subscribe((String data) -> { - Log.d(TAG, "activated: data=" + data); - return () -> {}; - }); -} -``` - -The `return () -> {};` statement in the lambda corresponds to having no -side-effects to handle the destructor, but this is not very readable. - -To make intentions clearer, the `onOpen()` method can wrap any `Consumer` of -the activation data's type: - -```java -{ - // Without data. - observable.subscribe(Observer.onOpen(x -> Log.d(TAG, "activated"))); - // With data. - observable.subscribe(Observer.onOpen((String data) -> { - Log.d(TAG, "activated: data=" + data); - })); -} -``` - -Likewise, `onClose()` is used the same way to transform any `Consumer` of the -activation data's type into a `Observer` that only has side effects when the -`Observable` is deactivated. - -#### Deconstructing Both objects - -When you use the `and()` method on `Observable` to create an `Observable`, -recall that the `Observer` passed to `subscribe()` must look like this: - -```java -{ - observableA.and(observableB).subscribe((Both data) -> { - A a = data.first; - B b = data.second; - Log.d(TAG, "on enter: a = " + a + "; b = " + b); - return () -> Log.d(TAG, "on exit: a = " + a + "; b = " + b); - }); -} -``` - -`Observers` provides a helper method to turn any function that takes two -arguments and returns a `Scope` into a `Observer`, which deconstructs -the `Both` object for you and passes the constituent parts into the function. - -Using `Both.adapt()`, we can rewrite the above like this: - -```java -{ - observableA.and(observableB).subscribe(Both.adapt((A a, B b) -> { - Log.d(TAG, "on enter: a = " + a + "; b = " + b); - return () -> Log.d(TAG, "on exit: a = " + a + "; b = " + b); - })); -} -``` - -When using `onEnter()` or `onExit()`, which take `Consumer`s of the data type, -it can be useful to use `Both.adapt` on a `BiConsumer` to turn it into a -`Consumer`. - -```java -{ - // Before: - Observable> both = observableA.and(observableB); - both.subscribe(Observers.onEnter((Both data) -> { - Log.d(TAG, "on enter: a = " + data.first + "; b = " + data.second); - })); - both.subscribe(Observers.onExit((Both data) -> { - Log.d(TAG, "on exit: a = " + data.first + "; b = " + data.second); - })); - // After: - both.subscribe(Observers.onEnter(Both.adapt((A a, B b) -> { - Log.d(TAG, "on enter: a = " + a + "; b = " + b); - }))); - both.subscribe(Observers.onExit(Both.adapt((A a, B b) -> { - Log.d(TAG, "on exit: a = " + a + "; b = " + b); - }))); -} -``` - -The `Both.adapt()` helpers are also able to turn `BiFunction`s into -`Function` objects and `BiPredicate`s into `Predicate` objects, -which makes them useful when using `map()` and `filter()` operators on -`Observable` objects. - -```java -{ - both.map(Both.adapt((A a, B b) -> { - return new ThingBuilder().setA(a).setB(b).build(); - })); - both.filter(Both.adapt((A a, B b) -> a.contains(b))); -} -``` - -## Data flow - -There are numerous instances where one may want to take the activation data of -some `Observable` and use it to set the state of a `Controller`, and reset that -`Controller` when the `Observable` is deactivated. A shortcut to doing this -without having to instantiate any `Controller` is provided with the `map()` -method in the `Observable` interface. - -For example, we might have an `Activity` that overrides `onNewIntent()`, and -extracts some data from the `Intent` it receives. We might want to register -observers on the extracted data rather than the `Intent` itself, as some work -needs to be done to unparcel the data we care about from the `Intent`. - -```java -public class MyActivity extends Activity { - private final Controller mIntentState = new Controller<>(); - - { - Observable uriState = mIntentState.map(Intent::getData); - Observable instanceIdState = uriState.map(Uri::getPath); - ... - } - - public void onCreate() { - super.onCreate(); - mIntentState.set(getIntent()); - } - - public void onNewIntent(Intent intent) { - super.onNewIntent(intent); - mIntentState.set(intent); - } -} -``` - -The `map()` method takes any function on the `Observable`'s activation data and -creates a new `Observable` of the result of that function applied to the -original `Observable`'s activation data. So the activation lifetime of -`uriState` and `instanceIdState` are the same as `mIntentState` in this example. - -The instance initializer can then call `subscribe()` on `uriState` or -`instanceIdState` to register callbacks for when we get a new URI or instance -ID, and the process of extracting the URI from the `Intent` and the instance ID -from the `Uri` is delegated to methods with no side-effects. - -### Handling null - -If a function provided to a `map()` method returns `null`, then the resulting -`Observable` will be put in a deactivated state, even if the source `Observable` -is activated. This can be used to **filter** invalid data from `Observable`s in -the pipeline: - -```java -{ - mIntentState.map(Intent::getExtras) - .map((Bundle bundle) -> bundle.getString(INTENT_EXTRA_FOO)) - .subscribe((String foo) -> ...); -} -``` - -The `bundle.getString()` call might return `null` if the source `Intent` does -not have the correct extra data field set. When this happens, the resulting -`Observable` simply does not activate, so the `Observer` registered in the -`subscribe()` call does not need to worry that `foo` might be `null`. - -### Filtering data - -One may wish to construct an `Observable` that is only activated if some -*predicate* on some other `Observable`'s activation data is true. This is easily -done using the `filter()` method on `Observable`. - -This example will only log `"Got FOO intent"` if `mIntentState` was `set()` with -an `Intent` with action `"org.my.app.action.FOO"`: - -```java -{ - String ACTION_FOO = "org.my.app.action.FOO"; - mIntentState.map(Intent::getAction) - .filter(ACTION_FOO::equals) - .subscribe(Observers.onEnter(action -> { - Log.d(TAG, "Got FOO intent"); - })); -} -``` - -Since `Observable#filter()` takes any `Predicate`, which is a functional -interface whose method takes a `T` and returns a `boolean`, the parameter can be -an instance of a class that implements `Predicate`: - -```java - class InRangePredicate implements Predicate { - private final int mMin; - private final int mMax; - - private InRangePredicate(int min, int max) { - mMin = min; - mMax = max; - } - - @Override - public boolean test(Integer value) { - return mMin <= value && value <= mMax; - } - } - - InRangePredicate inRange(int min, int max) { - return new InRangePredicate(min, max); - } - - Controller hasIntState = new Controller<>(); - Observable hasValidIntState = hasIntState.filter(inRange(0, 10)); -``` - -... or a method reference for a method that takes the activation data and -returns a boolean: - -```java - class Util { - static boolean inRange(int i) { - return 0 <= i && i <= 10; - } - } - Controller hasIntState = new Controller<>(); - Observable hasValidIntState = hasIntState.filter(Util::inRange); -``` - -... or a lambda that takes the activation data and returns a boolean: - -```java - Controller hasIntState = new Controller<>(); - Observable hasValidIntState = - hasIntState.filter(i -> 0 <= i && i <= 10); -``` - -## Tips and best practices - -### Construct the pipeline before modifying it - -Consider this code: - -```java - Controller c = new Controller<>(); - c.set("hi"); - c.reset(); - c.subscribe(Observers.onEnter(s -> Log.d(TAG, s))); -``` - -Will the callback registered in the `subscribe()` call get fired? It turns out -that it will not, since `c` is deactivated when `subscribe()` is called. But if -the `subscribe()` call is made before the `set()` call, then the callback is -fired. - -Sometimes this is what you want, but it's best to avoid any ambiguity like this. -Generally, `Observable` methods like `subscribe()` should be called before any -`Controller` methods. A couple of things that one can do to help with this: - -* Instantiate `Controller` objects in field initializers, not the constructor. -* Set up the pipeline (`subscribe()`, `and()`, `map()`, etc.) in an instance - initializer. This is run before anything else when creating an instance, - including the constructor, and is the same regardless of which constructor - is being used. This also removes the potential of accidentally depending on - constructor parameters or mutable instance variables in the pipeline, which - can be dangerous compared to adapting them to `Observable`s. -* In the instance initializer, `Observable`s composed from other `Observable`s - can usually be local variables rather than instance variables. This prevents - code outside the initializer from `subscribe()`ing these `Observable`s after - the instance has been initialized. -* Do not call `Controller` mutator methods (`set()` or `reset()`) inside the - instance initializer. They may be called in the constructor or any instance - methods. -* Alternatively, the concerns of creating the pipeline and adapting function - calls to state changes of `Controller`s can be separated by using a factory - function. - -### Manipulating state inside observers - -What happens here? - -```java - Controller c = new Controller<>(); - c.subscribe(x -> { - Log.d(TAG, "enter"); - c.reset(); - return () -> Log.d(TAG, "exit"); - }); - c.set("ding"); -``` - -Here, we `reset()` the same `Controller` in an activation observer for that very -`Controller`! - -This is in fact safe, though there should be few places you need to do something -like this. Currently, `Controller`s notify all observers synchronously on the -thread that `set()` or `reset()` was called in (so they are not thread safe), -but if an observer calls `set()` or `reset()` again while observers are still -being notified, the `set()` or `reset()` call gets queued and handled only after -all observers have been notified. This allows a deterministic and unastonishing -order of execution for the above example: the log will show "enter", followed -immediately by "exit". - -We call this property *re-entrancy safety*. `Controller`s are *re-entrant-safe*. -What this guarantees is that all observers are notified of all changes, and any -observer that imposes its own change (including indirect changes) will not have -that change take effect until all observers are notified of the current change. - -Note that if you `set()` a controller with a value that is never `null` inside -an activation handler, **you will get an infinite loop**. - -```java - Controller c = new Controller<>(); - c.subscribe(Observers.onEnter(x -> c.set(x + 1))); // Danger! - c.set(0); // Infinite loop! -``` - -Whenever the `Controller` is set with a value, the observing scope immediately -sets it with a new value, recurring infinitely. - -It's possible to still be safe if you can guarantee that `set()` isn't called or -`set(null)` is called in some base case for all recursive stacks of activation -handlers, but if you do that, it's *your* job to solve the halting problem. - -It is good practice to avoid calling `set()` or `reset()` on `Controller`s -inside `Observer` event handlers altogether, but there are many safe ways -that are useful. - -### Testing - -One of the most important aspects of using `Observable`s is that they are very -testable. Although `Observer`s themselves are not pure-functional (i.e. they -tend to mutate program state), this is done in such a way that the mutations in -the form of state transitions in `Observable`s are easy to track, and therefore -easy to test. - -If you write a class that implements `Observable` or returns an `Observable` in -one of its methods, it's easy to test the events it emits by using the -`ReactiveRecorder` test utility module. This class, which is only allowed in -tests, provides a fluent interface for describing the expected output of an -`Observable`. - -To use this in your tests, add `//chromecast/base:cast_base_test_utils_java` to -your JUnit test target's GN `deps`. - -As an example, imagine we want to test a class called `FlipFlop`, which -implements `Observable` and changes from deactivated to activated every time its -`flip` method is called. The tests might look like this: - -```java -import org.chromium.chromecast.base.ReactiveRecorder; -... // other imports -public class FlipFlopTest { - @Test - public void testStartsDeactivated() { - FlipFlop f = new FlipFlop(); - ReactiveRecorder recorder = ReactiveRecorder.record(f); - // No events should be emitted. - recorder.verify().end(); - } - - @Test - public void testFlipOnceActivatesObserver() { - FlipFlop f = new FlipFlop(); - ReactiveRecorder recorder = ReactiveRecorder.record(f); - f.flip(); - // A single activation should have been emitted. - recorder.verify().opened(Unit.unit()).end(); - } - - @Test - public void testFlipTwiceActivatesThenDeactivates() { - FlipFlop f = new FlipFlop(); - ReactiveRecorder recorder = ReactiveRecorder.record(f); - f.flip(); - f.flip(); - // Expect an activation followed by a deactivation. - recorder.verify().opened(Unit.unit()).closed(Unit.unit()).end(); - } -} -``` - -The `ReactiveRecorder` class works by calling `subscribe()` on the given -`Observable` and storing the activations and deactivations it observes in a -list. The `verify()` method opens a domain-specific language for performing -assertions on the activation data, using `opened()` and `closed()` to check -which data has been activated and deactivated. The transitions recorded must -occur in the same order as the `opened()` and `closed()` calls to pass the test. -The `end()` method asserts that no more transitions occurred. - -You can test behaviors that should occur when closing a `subscribe()` scope by -calling `recorder.unsubscribe()`. For example, every `Observable` implementation -should close all existing `Scopes` emitted from an `Observer` when that -`Observer`'s `subscribe()` scope is closed: - -```java - @Test - public void testUnsubscribeCloses() { - FlipFlop f = new FlipFlop(); - ReactiveRecorder recorder = ReactiveRecorder.record(f); - f.flip(); - // Clear the record; we don't care about the activation from flip(). - recorder.reset(); - recorder.unsubscribe(); - // Unsubscribing should implicitly close the scope. - recorder.verify().closed(Unit.unit()).end(); - } -``` - -Once a `ReactiveRecorder` unsubscribes, it will not get any new events from the -`Observable` it was recording. - -### Debugging - -Sometimes, particularly in long chains of `and()` or `andThen()` or `map()` or -`filter()`, you might get confused about the ultimate state of the system in -some circumstances. When confused about these complex `Observable`s, it's often -helpful to use the `debug()` operator: - -```java - // Before - foos.andThen(bars).subscribe(...); - // After - foos.debug(msg -> Log.d(TAG, "foos: %s", msg)) - .andThen(bars.debug(msg -> Log.d(TAG, "bars: %s", msg))) - .debug(msg -> Log.d(TAG, "foosAndThenBars: %s", msg)) - .subscribe(...); -``` - -The `debug()` operator doesn't by itself log anything; you need to give it a -`Consumer` that logs the debug messages it generates. This makes the -file/line number information in the log is more helpful, as it indicates which -file you're debugging, rather than the body of the `debug()` operator itself. - -The messages in question will show when `Observer`s subscribe and unsubscribe, -and whenever data are added or removed from the `Observable`. The `debug()` -operator will call the `toString()` method on all data to format messages about -state transitions. - -## When to use Observables - -`Observable`s and `Controller`s are intended to succinctly adapt common Android -SDK method pairs, whether they're callbacks for entering and exiting a state, or -mutators to perform state changes, into a common pattern that better separates -concerns and is composable. - -### Replace mutable, nullable variables - -Every mutable, nullable variable is a variable that you constantly have to -null-check before using. A `Controller` can be used to refactor these variables -into a `final` `Controller`. - -The important insight is that you tend to only read a variable when state -changes, either after the variable itself is known to change, or when some other -state changes. - -First, let's consider an Activity that registers a `BroadcastReceiver` in -`onStart()` and unregisters the `BroadcastReceiver` in `onStop()`. - -We will ignore for now that Android tries to guarantee that pathological call -sequences like multiple `onStart()`s in a row or an `onStop()` before the first -`onStart()` will not occur, because these guarantees are not known to the Java -compiler and similar guarantees can't be relied on for all events. - -```java -class MyActivity extends Activity { - private BroadcastReceiver mReceiver = null; - - @Override - public void onStart() { - super.onStart(); - if (mReceiver != null) - unregisterReceiver(mReceiver); - mReceiver = new BroadcastReceiver(...); - registerReceiver(mReceiver); - } - - @Override - public void onStop() { - if (mReceiver != null) - unregisterReceiver(mReceiver); - mReceiver = null; - super.onStop(); - } -} -``` - -Without the assumption that Android will call `onStart()` and `onStop()` in -reasonable orders, we need to check the state of the `mReceiver` variable each -time before it is used. And making that assumption is prone to backfiring, as -it's a recipe for `NullPointerException`s, `IllegalStateException`s, and other -horrors in general practice. - -Here's the refactored version that uses a `Controller`: - -```java -class MyActivity extends Activity { - private final Controller mStartedState = new Controller<>(); - - { - mStartedState.subscribe(x -> { - final BroadcastReceiver receiver = new BroadcastReceiver(...); - registerReceiver(receiver); - return () -> unregisterReceiver(receiver); - }); - } - - @Override - public void onStart() { - super.onStart(); - mStartedState.set(Unit.unit()); - } - - @Override - public void onStop() { - mStartedState.reset(); - super.onStop(); - } -} -``` - -The refactored version better separates concerns. `BroadcastReceiver` -registration and unregistration is handled in a small area of the code, rather -than spread throughout the class, and the `BroadcastReceiver` doesn't need to be -stored in a mutable variable. *No code outside the scope in which the -`BroadcastReceiver` object is relevant can touch it*, and the `onStart()` and -`onStop()` methods have no logic except toggling the `Controller` that -represents whether the `Activity` is started. Best of all, there are no `null` -checks, and no need for any. - -### Asynchronous initialization - -Some methods run asynchronously and take a callback that is run when the work is -complete. We can `set()` `Controller`s in such callbacks to adapt this pattern -to `Observable`s, which can be used to create asynchronous initialization -pipelines. - -This example shows how one can link up the outputs of multiple asynchronous -functions that use the callback-passing style using `Controller`s, and -encapsulating the complicated setup into a single function that returns an -`Observable`. - -```java -public class AsyncExample { - private static final String TAG = "AsyncExample"; - - // Adapts the callback-style asynchronous Baz function to an Observable. - // Shows how a - public static Observable createBazDefault() { - // Begin constructing a Foo. - Controller fooState = new Controller<>(); - // Set the fooState controller when created, reset on errors. - Foo.createAsync(fooState::set, fooState::reset); - // Bar requires Foo to initialize. - Controller barState = new Controller<>(); - fooState.subscribe((Foo foo) -> { - Bar.createAsync(foo, barState::set); - // If fooState is reset, then barState is also reset. - return barState::reset; - }); - // Baz requires Foo and Bar to initialize. - Controller bazState = new Controller<>(); - fooState.and(barState).subscribe(Observers.both((Foo foo, Bar bar) -> { - Baz.createAsync(foo, bar, bazState::set); - // If fooState or barState is reset, then bazState is also reset. - return bazState::reset; - })); - return bazState; - } - - public static void demo() { - Observable bazState = createBazDefault(); - bazState.subscribe(Observers.onEnter((Baz baz) -> { - // This runs when the full initialization pipeline is complete. - Log.d(TAG, "Baz created!"); - })); - } - - public static class Foo { - static void createAsync(Consumer callback, Runnable onError) {...} - } - - public static class Bar { - static void createAsync(Foo foo, Consumer callback) {...} - } - - public static class Baz { - static void createAsync(Foo foo, Bar bar, Consumer callback) {...} - } -} -``` - -This way, `Observable`s can be used similarly to `Promise`s, where a callback -handling the underlying value can be registered before the underlying value is -available. But unlike `Promise`s, `Observable`s provide a way to also handle -teardowns, and to transitively tear down everything down stream when something -is torn down. diff -Nru chromium-132.0.6834.110/chromecast/base/scoped_temp_file.cc chromium-132.0.6834.159/chromecast/base/scoped_temp_file.cc --- chromium-132.0.6834.110/chromecast/base/scoped_temp_file.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/scoped_temp_file.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -// 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 "chromecast/base/scoped_temp_file.h" -#include "base/check.h" -#include "base/files/file_util.h" - -namespace chromecast { - -ScopedTempFile::ScopedTempFile() { - CHECK(base::CreateTemporaryFile(&path_)); -} - -ScopedTempFile::~ScopedTempFile() { - if (FileExists()) { - CHECK(base::DeleteFile(path_)); - } -} - -bool ScopedTempFile::FileExists() const { - return base::PathExists(path_); -} - -bool ScopedTempFile::Write(const std::string& str) { - CHECK(FileExists()); - return base::WriteFile(path_, str); -} - -std::string ScopedTempFile::Read() const { - CHECK(FileExists()); - std::string result; - CHECK(ReadFileToString(path_, &result)); - return result; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/scoped_temp_file.h chromium-132.0.6834.159/chromecast/base/scoped_temp_file.h --- chromium-132.0.6834.110/chromecast/base/scoped_temp_file.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/scoped_temp_file.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_SCOPED_TEMP_FILE_H_ -#define CHROMECAST_BASE_SCOPED_TEMP_FILE_H_ - -#include - -#include "base/files/file_path.h" - -namespace chromecast { - -// Creates a temporary file that is deleted when this object is destroyed, -// unless the underlying file has been moved or deleted. -// Warning: This class uses CHECKs, and should only be used for testing. -class ScopedTempFile { - public: - ScopedTempFile(); - - ScopedTempFile(const ScopedTempFile&) = delete; - ScopedTempFile& operator=(const ScopedTempFile&) = delete; - - ~ScopedTempFile(); - - // Return the path to the temporary file. Note that if the underlying file has - // been moved or deleted, this will still return the original path. - base::FilePath path() const { return path_; } - - // Returns true if the underlying file exists, false otherwise. This will - // return false, for example, if the file has been moved or deleted. - bool FileExists() const; - - // Write the contents of |str| to the file. Returns the whether all the - // contents were written to the file. CHECKs that FileExists() returns true. - bool Write(const std::string& str); - - // Read the file and return the contents. CHECKs that FileExists() returns - // true. - std::string Read() const; - - private: - base::FilePath path_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_SCOPED_TEMP_FILE_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/statistics/weighted_mean.cc chromium-132.0.6834.159/chromecast/base/statistics/weighted_mean.cc --- chromium-132.0.6834.110/chromecast/base/statistics/weighted_mean.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/statistics/weighted_mean.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/statistics/weighted_mean.h" - -#include - -namespace chromecast { - -WeightedMean::WeightedMean() = default; - -void WeightedMean::Reset() { - weighted_mean_ = 0.0; - variance_sum_ = 0.0; - sum_weights_ = 0.0; - sum_squared_weights_ = 0.0; -} - -void WeightedMean::AddDelta(double delta, double weight) { - double old_sum_weights = sum_weights_; - sum_weights_ += weight; - // Use std::abs() to handle negative weights (ie, removing a sample). - sum_squared_weights_ += weight * std::abs(weight); - if (sum_weights_ == 0) { - weighted_mean_ = 0; - variance_sum_ = 0; - } else { - double mean_change = delta * weight / sum_weights_; - weighted_mean_ += mean_change; - variance_sum_ += old_sum_weights * delta * mean_change; - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/statistics/weighted_mean.h chromium-132.0.6834.159/chromecast/base/statistics/weighted_mean.h --- chromium-132.0.6834.110/chromecast/base/statistics/weighted_mean.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/statistics/weighted_mean.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_STATISTICS_WEIGHTED_MEAN_H_ -#define CHROMECAST_BASE_STATISTICS_WEIGHTED_MEAN_H_ - -#include - -namespace chromecast { - -// Calculates the weighted mean (and variance) of a set of values. Values can be -// added to or removed from the mean. -class WeightedMean { - public: - WeightedMean(); - - double weighted_mean() const { return weighted_mean_; } - // The weighted variance should be calculated as variance_sum()/sum_weights(). - double variance_sum() const { return variance_sum_; } - double sum_weights() const { return sum_weights_; } - double sum_squared_weights() const { return sum_squared_weights_; } - - // Adds |value| to the mean if |weight| is positive. Removes |value| from - // the mean if |weight| is negative. Has no effect if |weight| is 0. - template - void AddSample(T value, double weight) { - AddDelta(value - weighted_mean_, weight); - } - - // Resets to initial state. - void Reset(); - - private: - void AddDelta(double delta, double weight); - - double weighted_mean_ = 0.0; - double variance_sum_ = 0.0; - double sum_weights_ = 0.0; - double sum_squared_weights_ = 0.0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_STATISTICS_WEIGHTED_MEAN_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_average.cc chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average.cc --- chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_average.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/statistics/weighted_moving_average.h" - -#include - -#include "base/check_op.h" - -namespace chromecast { - -WeightedMovingAverage::WeightedMovingAverage(int64_t max_x_range) - : max_x_range_(max_x_range) { - DCHECK_GE(max_x_range_, 0); -} - -WeightedMovingAverage::~WeightedMovingAverage() {} - -void WeightedMovingAverage::AddSample(int64_t x, int64_t y, double weight) { - DCHECK_GE(weight, 0); - if (!samples_.empty()) - DCHECK_GE(x, samples_.back().x); - - Sample sample = {x, y, weight}; - samples_.push_back(sample); - mean_.AddSample(y, weight); - - // Remove old samples. - while (x - samples_.front().x > max_x_range_) { - const Sample& old_sample = samples_.front(); - mean_.AddSample(old_sample.y, -old_sample.weight); - samples_.pop_front(); - } - DCHECK(!samples_.empty()); -} - -bool WeightedMovingAverage::Average(int64_t* average, double* error) const { - if (samples_.empty() || mean_.sum_weights() == 0) - return false; - - *average = static_cast(round(mean_.weighted_mean())); - - const double effective_sample_size = - mean_.sum_weights() * mean_.sum_weights() / mean_.sum_squared_weights(); - const double variance = mean_.variance_sum() / mean_.sum_weights(); - *error = sqrt(variance / effective_sample_size); - return true; -} - -void WeightedMovingAverage::Clear() { - samples_.clear(); - mean_ = WeightedMean(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_average.h chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average.h --- chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_average.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_AVERAGE_H_ -#define CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_AVERAGE_H_ - -#include -#include - -#include "chromecast/base/statistics/weighted_mean.h" - -namespace chromecast { - -// Calculates the weighted moving average of recent points. The points -// do not need to be evenly distributed on the X axis, but the X coordinate -// is assumed to be generally increasing. -// -// Whenever a new sample is added using AddSample(), old samples whose -// x coordinates are farther than |max_x_range_| from the new sample's -// x coordinate will be removed from the average. Note that |max_x_range_| -// must be non-negative. -class WeightedMovingAverage { - public: - explicit WeightedMovingAverage(int64_t max_x_range); - - WeightedMovingAverage(const WeightedMovingAverage&) = delete; - WeightedMovingAverage& operator=(const WeightedMovingAverage&) = delete; - - ~WeightedMovingAverage(); - - int64_t max_x_range() const { return max_x_range_; } - // Returns the current number of samples that are in the weighted average. - size_t num_samples() const { return samples_.size(); } - - // Adds an (x, y) sample with the provided weight to the average. - // |weight| should be non-negative. - void AddSample(int64_t x, int64_t y, double weight); - - // Gets the current average and standard error. - // Returns |true| if the average exists, |false| otherwise. If the average - // does not exist, |average| and |error| are not modified. - bool Average(int64_t* average, double* error) const; - - // Clears all current samples from the moving average. - void Clear(); - - private: - struct Sample { - int64_t x; - int64_t y; - double weight; - }; - - const int64_t max_x_range_; - std::deque samples_; - WeightedMean mean_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_AVERAGE_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_average_unittest.cc chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average_unittest.cc --- chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_average_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_average_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include "chromecast/base/statistics/weighted_moving_average.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -TEST(WeightedMovingAverageTest, NoSamples) { - WeightedMovingAverage averager(0); - - int64_t avg = 12345; - double error = 12345.0; - EXPECT_FALSE(averager.Average(&avg, &error)); - EXPECT_EQ(12345, avg); - EXPECT_EQ(12345.0, error); -} - -TEST(WeightedMovingAverageTest, ZeroWeight) { - WeightedMovingAverage averager(0); - for (int s = 1; s <= 5; ++s) - averager.AddSample(0, s, 0.0); - - int64_t avg = 12345; - double error = 12345.0; - EXPECT_FALSE(averager.Average(&avg, &error)); - EXPECT_EQ(12345, avg); - EXPECT_EQ(12345.0, error); -} - -TEST(WeightedMovingAverageTest, AverageOneValue) { - int64_t value = 1; - - WeightedMovingAverage averager(0); - averager.AddSample(0, value, 1.0); - - int64_t avg = 0; - double error = 1.0; - EXPECT_TRUE(averager.Average(&avg, &error)); - EXPECT_EQ(value, avg); - EXPECT_EQ(0.0, error); -} - -TEST(WeightedMovingAverageTest, AverageSeveralUnweightedValues) { - WeightedMovingAverage averager(0); - for (int s = 1; s <= 5; ++s) - averager.AddSample(0, s, 1.0); - - int64_t avg = 0; - double error = 0; - EXPECT_TRUE(averager.Average(&avg, &error)); - EXPECT_EQ(3, avg); - EXPECT_NEAR(sqrt(2) / sqrt(5), error, 1e-9); -} - -TEST(WeightedMovingAverageTest, Clear) { - WeightedMovingAverage averager(0); - for (int s = 1; s <= 5; ++s) - averager.AddSample(0, s, 1.0); - - int64_t avg = 0; - double error = 0; - EXPECT_TRUE(averager.Average(&avg, &error)); - EXPECT_EQ(3, avg); - EXPECT_NEAR(sqrt(2) / sqrt(5), error, 1e-9); - - averager.Clear(); - EXPECT_FALSE(averager.Average(&avg, &error)); - - for (int s = 1; s <= 5; ++s) - averager.AddSample(0, s, 1.0); - - avg = 0; - error = 0; - EXPECT_TRUE(averager.Average(&avg, &error)); - EXPECT_EQ(3, avg); - EXPECT_NEAR(sqrt(2) / sqrt(5), error, 1e-9); -} - -TEST(WeightedMovingAverageTest, AverageSeveralWeightedValues) { - WeightedMovingAverage averager(0); - averager.AddSample(0, 1, 2.0); - averager.AddSample(0, 2, 1.0); - averager.AddSample(0, 3, 0.0); - averager.AddSample(0, 4, 1.0); - averager.AddSample(0, 5, 2.0); - - int64_t avg = 0; - double error = 0; - EXPECT_TRUE(averager.Average(&avg, &error)); - EXPECT_EQ(3, avg); - // ^2 / - double effective_sample_size = 36.0 / 10.0; - EXPECT_NEAR(sqrt(3) / sqrt(effective_sample_size), error, 1e-9); -} - -TEST(WeightedMovingAverageTest, DropOldValues) { - WeightedMovingAverage averager(1); - for (int s = 0; s < 10; ++s) - averager.AddSample(s, 100, 5.0); - - averager.AddSample(10, 1, 1.0); - averager.AddSample(11, 3, 1.0); - - int64_t avg = 0; - double error = 0; - EXPECT_TRUE(averager.Average(&avg, &error)); - EXPECT_EQ(2, avg); - EXPECT_DOUBLE_EQ(1.0 / sqrt(2), error); -} - -TEST(WeightedMovingAverageTest, DropOldValuesUneven) { - WeightedMovingAverage averager(5); - for (int s = 0; s < 10; ++s) - averager.AddSample(s * s, 100, 5.0); - - averager.AddSample(100, 1, 1.0); - averager.AddSample(105, 3, 1.0); - - int64_t avg = 0; - double error = 0; - EXPECT_TRUE(averager.Average(&avg, &error)); - EXPECT_EQ(2, avg); - EXPECT_DOUBLE_EQ(1.0 / sqrt(2), error); -} - -TEST(WeightedMovingAverageTest, DropOldValuesByAddingZeroWeightValues) { - WeightedMovingAverage averager(5); - for (int s = 0; s < 10; ++s) - averager.AddSample(s, 1, 5.0); - - // Adding values with weight 0 still drops old values. - for (int s = 11; s < 15; ++s) - averager.AddSample(s, 100, 0.0); - - averager.AddSample(15, 10, 1.0); - - int64_t avg = 0; - double error = 0; - EXPECT_TRUE(averager.Average(&avg, &error)); - EXPECT_EQ(10, avg); - EXPECT_DOUBLE_EQ(0.0, error); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_linear_regression.cc chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression.cc --- chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_linear_regression.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,120 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/statistics/weighted_moving_linear_regression.h" - -#include -#include - -#include "base/check_op.h" -#include "base/logging.h" - -namespace chromecast { - -WeightedMovingLinearRegression::WeightedMovingLinearRegression( - int64_t max_x_range) - : max_x_range_(max_x_range) { - DCHECK_GE(max_x_range_, 0); -} - -WeightedMovingLinearRegression::~WeightedMovingLinearRegression() = default; - -void WeightedMovingLinearRegression::Reserve(int count) { - Sample sample = {0, 0, 0}; - samples_.insert(samples_.end(), count, sample); - samples_.erase(samples_.end() - count, samples_.end()); -} - -void WeightedMovingLinearRegression::Reset() { - x_mean_.Reset(); - y_mean_.Reset(); - covariance_ = 0.0; - samples_.clear(); - slope_ = 0.0; - slope_variance_ = 0.0; - intercept_variance_ = 0.0; - - has_estimate_ = false; -} - -void WeightedMovingLinearRegression::AddSample(int64_t x, - int64_t y, - double weight) { - DCHECK_GE(weight, 0); - if (!samples_.empty()) - DCHECK_GE(x, samples_.back().x); - - UpdateSet(x, y, weight); - Sample sample = {x, y, weight}; - samples_.push_back(sample); - - // Remove old samples. - while (x - samples_.front().x > max_x_range_) { - const Sample& old_sample = samples_.front(); - UpdateSet(old_sample.x, old_sample.y, -old_sample.weight); - samples_.pop_front(); - } - DCHECK(!samples_.empty()); - - if (samples_.size() <= 2 || x_mean_.sum_weights() == 0 || - x_mean_.variance_sum() == 0) { - has_estimate_ = false; - return; - } - - slope_ = covariance_ / x_mean_.variance_sum(); - - double residual_sum_squares = - (covariance_ * covariance_) / x_mean_.variance_sum(); - double mean_squared_error = - (y_mean_.variance_sum() - residual_sum_squares) / (samples_.size() - 2); - - slope_variance_ = std::max(0.0, mean_squared_error / x_mean_.variance_sum()); - intercept_variance_ = std::max( - 0.0, (slope_variance_ * x_mean_.variance_sum()) / x_mean_.sum_weights()); - - has_estimate_ = true; -} - -bool WeightedMovingLinearRegression::EstimateY(int64_t x, - int64_t* y, - double* error) const { - if (!has_estimate_) - return false; - - double x_diff = x - x_mean_.weighted_mean(); - double y_estimate = y_mean_.weighted_mean() + (slope_ * x_diff); - - *y = static_cast(round(y_estimate)); - *error = sqrt(intercept_variance_ + (slope_variance_ * x_diff * x_diff)); - return true; -} - -bool WeightedMovingLinearRegression::EstimateSlope(double* slope, - double* error) const { - if (!has_estimate_) - return false; - - *slope = slope_; - *error = sqrt(slope_variance_); - return true; -} - -void WeightedMovingLinearRegression::UpdateSet(int64_t x, - int64_t y, - double weight) { - double old_y_mean = y_mean_.weighted_mean(); - x_mean_.AddSample(x, weight); - y_mean_.AddSample(y, weight); - covariance_ += weight * (x - x_mean_.weighted_mean()) * (y - old_y_mean); -} - -void WeightedMovingLinearRegression::DumpSamples() const { - for (auto sample : samples_) { - LOG(INFO) << "x, y, weight: " << sample.x << " " << sample.y << " " - << sample.weight; - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_linear_regression.h chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression.h --- chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_linear_regression.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,93 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_LINEAR_REGRESSION_H_ -#define CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_LINEAR_REGRESSION_H_ - -#include -#include - -#include "chromecast/base/statistics/weighted_mean.h" - -namespace chromecast { - -// Performs linear regression over a set of weighted (x, y) samples. -// Calculates a weighted moving average over a set of weighted (x, y) points. -// The points do not need to be evenly distributed on the X axis, but the -// X coordinate is assumed to be generally increasing. -// -// Whenever a new sample is added using AddSample(), old samples whose -// x coordinates are farther than |max_x_range_| from the new sample's -// x coordinate will be removed from the regression. Note that |max_x_range_| -// must be non-negative. -class WeightedMovingLinearRegression { - public: - struct Sample { - int64_t x; - int64_t y; - double weight; - }; - - explicit WeightedMovingLinearRegression(int64_t max_x_range); - - WeightedMovingLinearRegression(const WeightedMovingLinearRegression&) = - delete; - WeightedMovingLinearRegression& operator=( - const WeightedMovingLinearRegression&) = delete; - - ~WeightedMovingLinearRegression(); - - // Returns the current number of samples that are in the regression. - size_t num_samples() const { return samples_.size(); } - - // Adds a weighted (x, y) sample to the set. Note that |weight| - // should be positive. - void AddSample(int64_t x, int64_t y, double weight); - - // Gets a y value estimate from the linear regression: y = a*x + b, where - // a and b are the slope and intercept estimates from the regression. The - // standard error of the resulting y estimate is also provided. - // Returns false if the y value cannot be estimated, in which case y and - // |error| are not modified. Returns true otherwise. - bool EstimateY(int64_t x, int64_t* y, double* error) const; - - // Gets the current estimated slope and slope error from the linear - // regression. Returns false if the slope cannot be estimated, in which - // case |slope| and |error| are not modified. Returns true otherwise. - bool EstimateSlope(double* slope, double* error) const; - - // Dumps samples currently in the linear regression. - void DumpSamples() const; - - // Returns a const reference to the samples currently captured. Very - // useful for debugging. - const std::deque& samples() { return samples_; } - - // Reserves space for |count| samples, to reduce memory allocation during use. - void Reserve(int count); - - // Resets to initial state. - void Reset(); - - private: - // Adds (x, y) to the set if |weight| is positive; removes (x, y) from the - // set if |weight| is negative. - void UpdateSet(int64_t x, int64_t y, double weight); - - const int64_t max_x_range_; - WeightedMean x_mean_; - WeightedMean y_mean_; - double covariance_ = 0.0; - std::deque samples_; - - double slope_ = 0.0; - double slope_variance_ = 0.0; - double intercept_variance_ = 0.0; - - bool has_estimate_ = false; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_LINEAR_REGRESSION_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_linear_regression_unittest.cc chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression_unittest.cc --- chromium-132.0.6834.110/chromecast/base/statistics/weighted_moving_linear_regression_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/statistics/weighted_moving_linear_regression_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,155 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/statistics/weighted_moving_linear_regression.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -TEST(WeightedMovingLinearRegressionTest, NotEnoughSamples) { - for (int num_samples = 0; num_samples <= 2; ++num_samples) { - WeightedMovingLinearRegression linear(1e6); - for (int s = 0; s < num_samples; ++s) - linear.AddSample(s, s, 1.0); - - int64_t y = 12345; - double error = 12345.0; - EXPECT_FALSE(linear.EstimateY(0, &y, &error)); - EXPECT_EQ(12345, y); - EXPECT_EQ(12345.0, error); - - double slope = 12345.0; - EXPECT_FALSE(linear.EstimateSlope(&slope, &error)); - EXPECT_EQ(12345.0, slope); - EXPECT_EQ(12345.0, error); - } -} - -TEST(WeightedMovingLinearRegressionTest, NoXVariance) { - WeightedMovingLinearRegression linear(1e6); - for (int s = 0; s < 10; ++s) - linear.AddSample(0, s, 1.0); - - int64_t y = 12345; - double error = 12345.0; - EXPECT_FALSE(linear.EstimateY(0, &y, &error)); - EXPECT_EQ(12345, y); - EXPECT_EQ(12345.0, error); - - double slope = 12345.0; - EXPECT_FALSE(linear.EstimateSlope(&slope, &error)); - EXPECT_EQ(12345.0, slope); - EXPECT_EQ(12345.0, error); -} - -TEST(WeightedMovingLinearRegressionTest, ZeroWeight) { - WeightedMovingLinearRegression linear(1e6); - for (int s = 0; s < 10; ++s) - linear.AddSample(s, s, 0.0); - - int64_t y = 12345; - double error = 12345.0; - EXPECT_FALSE(linear.EstimateY(0, &y, &error)); - EXPECT_EQ(12345, y); - EXPECT_EQ(12345.0, error); - - double slope = 12345.0; - EXPECT_FALSE(linear.EstimateSlope(&slope, &error)); - EXPECT_EQ(12345.0, slope); - EXPECT_EQ(12345.0, error); -} - -TEST(WeightedMovingLinearRegressionTest, SimpleLine) { - WeightedMovingLinearRegression linear(1e6); - for (int s = 0; s < 3; ++s) - linear.AddSample(s, s, 1.0); - - int64_t y; - double error; - EXPECT_TRUE(linear.EstimateY(20, &y, &error)); - EXPECT_EQ(20, y); - EXPECT_DOUBLE_EQ(0.0, error); - - double slope; - EXPECT_TRUE(linear.EstimateSlope(&slope, &error)); - EXPECT_DOUBLE_EQ(1.0, slope); - EXPECT_DOUBLE_EQ(0.0, error); -} - -TEST(WeightedMovingLinearRegressionTest, SimpleLineHighX) { - WeightedMovingLinearRegression linear(1e6); - for (int s = 0; s < 10; ++s) - linear.AddSample(1000000000 + s, s, 1.0); - - int64_t y; - double error; - EXPECT_TRUE(linear.EstimateY(0, &y, &error)); - EXPECT_EQ(-1000000000, y); - EXPECT_DOUBLE_EQ(0.0, error); - - EXPECT_TRUE(linear.EstimateY(1000000020, &y, &error)); - EXPECT_EQ(20, y); - EXPECT_DOUBLE_EQ(0.0, error); - - double slope; - EXPECT_TRUE(linear.EstimateSlope(&slope, &error)); - EXPECT_DOUBLE_EQ(1.0, slope); - EXPECT_DOUBLE_EQ(0.0, error); -} - -TEST(WeightedMovingLinearRegressionTest, Weighted) { - WeightedMovingLinearRegression linear(1e6); - // Add some weight 1.0 points on the line y = x/2, and some weight 2.0 points - // on the line y = x/2 + 4.5. - for (int s = 0; s < 1000; ++s) { - linear.AddSample(2 * s, s, 1.0); - linear.AddSample(2 * s + 1, s + 5, 2.0); - } - - // The resulting estimate should be y = x/2 + 3. - int64_t y; - double error; - EXPECT_TRUE(linear.EstimateY(20, &y, &error)); - EXPECT_EQ(13, y); - - EXPECT_TRUE(linear.EstimateY(-20, &y, &error)); - EXPECT_EQ(-7, y); - EXPECT_NEAR(0.0, error, 0.1); - - double slope; - EXPECT_TRUE(linear.EstimateSlope(&slope, &error)); - EXPECT_NEAR(0.5, slope, 0.001); - EXPECT_NEAR(0.0, error, 0.001); -} - -TEST(WeightedMovingLinearRegressionTest, DropOldSamples) { - WeightedMovingLinearRegression linear(1999); - // First add some points that will fall outside of the window. - for (int s = -1000; s < 0; ++s) - linear.AddSample(s, 0, 1.0); - - // Add some weight 1.0 points on the line y = x/2, and some weight 2.0 points - // on the line y = x/2 + 4.5. - for (int s = 0; s < 1000; ++s) { - linear.AddSample(2 * s, s, 1.0); - linear.AddSample(2 * s + 1, s + 5, 2.0); - } - - // The resulting estimate should be y = x/2 + 3. - int64_t y; - double error; - EXPECT_TRUE(linear.EstimateY(20, &y, &error)); - EXPECT_EQ(13, y); - - EXPECT_TRUE(linear.EstimateY(-20, &y, &error)); - EXPECT_EQ(-7, y); - EXPECT_NEAR(0.0, error, 0.1); - - double slope; - EXPECT_TRUE(linear.EstimateSlope(&slope, &error)); - EXPECT_NEAR(0.5, slope, 0.001); - EXPECT_NEAR(0.0, error, 0.001); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/system_time_change_notifier.cc chromium-132.0.6834.159/chromecast/base/system_time_change_notifier.cc --- chromium-132.0.6834.110/chromecast/base/system_time_change_notifier.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/system_time_change_notifier.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -// 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 "chromecast/base/system_time_change_notifier.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/task/sequenced_task_runner.h" - -namespace chromecast { - -namespace { - -// Limits for periodic system time monitoring. -const int kLimitForMonitorPer1Sec = 60; // 1 minute -const int kLimitForMonitorPer10Sec = 600; // 10 minutes - -} // namespace - -SystemTimeChangeNotifier::SystemTimeChangeNotifier() - : observer_list_(new base::ObserverListThreadSafe()) {} - -SystemTimeChangeNotifier::~SystemTimeChangeNotifier() = default; - -void SystemTimeChangeNotifier::AddObserver(Observer* observer) { - observer_list_->AddObserver(observer); -} - -void SystemTimeChangeNotifier::RemoveObserver(Observer* observer) { - observer_list_->RemoveObserver(observer); -} - -void SystemTimeChangeNotifier::NotifySystemTimeChanged() { - observer_list_->Notify(FROM_HERE, &Observer::OnSystemTimeChanged); -} - -SystemTimeChangeNotifierPeriodicMonitor:: -SystemTimeChangeNotifierPeriodicMonitor( - const scoped_refptr& task_runner) - : task_runner_(task_runner), - weak_factory_(this) { - DCHECK(task_runner_); - base::Time now = Now(); - ResetTimeAndLimits(now); - ScheduleNextMonitor(now); -} - -SystemTimeChangeNotifierPeriodicMonitor:: - ~SystemTimeChangeNotifierPeriodicMonitor() = default; - -void SystemTimeChangeNotifierPeriodicMonitor::ResetTimeAndLimits( - base::Time now) { - // ScheduleNextMonitor() will adjust actual expected_system_time. - expected_system_time_ = now; - monitoring_limit_time_1sec_ = now + base::Seconds(kLimitForMonitorPer1Sec); - monitoring_limit_time_10sec_ = - monitoring_limit_time_1sec_ + base::Seconds(kLimitForMonitorPer10Sec); -} - -void SystemTimeChangeNotifierPeriodicMonitor::ScheduleNextMonitor( - base::Time now) { - base::TimeDelta next_checking_interval = - now <= monitoring_limit_time_1sec_ - ? base::Seconds(1) - : now <= monitoring_limit_time_10sec_ ? base::Seconds(10) - : base::Minutes(10); - // Adjusting expected_system_time based on now cannot detect continuous system - // time drift (false negative), but tolerates task delay (false positive). - // Task delay is expected more than system time drift. - expected_system_time_ = now + next_checking_interval; - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce(&SystemTimeChangeNotifierPeriodicMonitor::CheckSystemTime, - weak_factory_.GetWeakPtr()), - next_checking_interval); -} - -void SystemTimeChangeNotifierPeriodicMonitor::CheckSystemTime() { - base::Time now = Now(); - const base::TimeDelta kInterval10Seconds(base::Seconds(10)); - if (now < expected_system_time_ - kInterval10Seconds || - now > expected_system_time_ + kInterval10Seconds) { // Time changed! - ResetTimeAndLimits(now); - NotifySystemTimeChanged(); - } - ScheduleNextMonitor(now); -} - -base::Time SystemTimeChangeNotifierPeriodicMonitor::Now() const { - if (!fake_now_.is_null()) - return fake_now_; - return base::Time::Now(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/system_time_change_notifier.h chromium-132.0.6834.159/chromecast/base/system_time_change_notifier.h --- chromium-132.0.6834.110/chromecast/base/system_time_change_notifier.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/system_time_change_notifier.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_SYSTEM_TIME_CHANGE_NOTIFIER_H_ -#define CHROMECAST_BASE_SYSTEM_TIME_CHANGE_NOTIFIER_H_ - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list_threadsafe.h" -#include "base/time/time.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace chromecast { - -// Abstract class to notify system time changes. -class SystemTimeChangeNotifier { - public: - class Observer { - public: - // Called when current system time has changed. - virtual void OnSystemTimeChanged() = 0; - - protected: - virtual ~Observer() {} - }; - - SystemTimeChangeNotifier(const SystemTimeChangeNotifier&) = delete; - SystemTimeChangeNotifier& operator=(const SystemTimeChangeNotifier&) = delete; - - virtual ~SystemTimeChangeNotifier(); - - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - protected: - SystemTimeChangeNotifier(); - - // Implementations are expected to call this to notify system time changes. - void NotifySystemTimeChanged(); - - private: - scoped_refptr> observer_list_; -}; - -// Default implementation of SystemTimeChangeNotifier for most platform. -// It monitors system time changes periodically and notifies if the current -// system time is different from the expected one by more than 10 seconds. -// After reboot or system time has changed, it checks for time changes every -// second for first 1 minute. Then, checks every 10 seconds for next 10 minutes. -// Then, checks every 10 minutes. -class SystemTimeChangeNotifierPeriodicMonitor - : public SystemTimeChangeNotifier { - public: - explicit SystemTimeChangeNotifierPeriodicMonitor( - const scoped_refptr& task_runner); - - SystemTimeChangeNotifierPeriodicMonitor( - const SystemTimeChangeNotifierPeriodicMonitor&) = delete; - SystemTimeChangeNotifierPeriodicMonitor& operator=( - const SystemTimeChangeNotifierPeriodicMonitor&) = delete; - - ~SystemTimeChangeNotifierPeriodicMonitor() override; - - // For unittests. - void set_fake_now_for_testing(base::Time now) { fake_now_ = now; } - - private: - // Helper functions to monitor system time changes. - void ResetTimeAndLimits(base::Time now); - void ScheduleNextMonitor(base::Time now); - void CheckSystemTime(); - - // Returns base::Time::Now() unless fake_now is set. - base::Time Now() const; - - const scoped_refptr task_runner_; - - base::Time expected_system_time_; - base::Time monitoring_limit_time_1sec_; - base::Time monitoring_limit_time_10sec_; - - base::Time fake_now_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_SYSTEM_TIME_CHANGE_NOTIFIER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/system_time_change_notifier_unittest.cc chromium-132.0.6834.159/chromecast/base/system_time_change_notifier_unittest.cc --- chromium-132.0.6834.110/chromecast/base/system_time_change_notifier_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/system_time_change_notifier_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,213 +0,0 @@ -// 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 "chromecast/base/system_time_change_notifier.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/run_loop.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -namespace { - -class SequencedTaskRunnerNoDelay : public base::SequencedTaskRunner { - public: - SequencedTaskRunnerNoDelay() {} - - SequencedTaskRunnerNoDelay(const SequencedTaskRunnerNoDelay&) = delete; - SequencedTaskRunnerNoDelay& operator=(const SequencedTaskRunnerNoDelay&) = - delete; - - // base::SequencedTaskRunner implementation: - bool PostDelayedTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta delay) override { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - from_here, std::move(task)); - return true; - } - - bool PostNonNestableDelayedTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta delay) override { - return true; - } - - bool RunsTasksInCurrentSequence() const override { return true; } - - private: - ~SequencedTaskRunnerNoDelay() override {} -}; - -class TimeChangeObserver : public SystemTimeChangeNotifier::Observer { - public: - TimeChangeObserver() : num_time_changed_(0) {} - - TimeChangeObserver(const TimeChangeObserver&) = delete; - TimeChangeObserver& operator=(const TimeChangeObserver&) = delete; - - ~TimeChangeObserver() override {} - - // SystemTimeChangeNotifier::Observer implementation: - void OnSystemTimeChanged() override { ++num_time_changed_; } - - int num_time_changed() const { return num_time_changed_; } - - private: - int num_time_changed_; -}; - -} // namespace - -class SystemTimeChangeNotifierTest : public testing::Test { - protected: - void SetUp() override { - notifier_.reset(new SystemTimeChangeNotifierPeriodicMonitor( - new SequencedTaskRunnerNoDelay())); - - observer_.reset(new TimeChangeObserver); - notifier_->AddObserver(observer_.get()); - } - - // Runs pending tasks. It doesn't run tasks schedule after this call. - void RunPendingTasks() { - base::RunLoop run_loop; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, run_loop.QuitClosure()); - run_loop.Run(); - } - - base::test::SingleThreadTaskEnvironment task_environment_; - std::unique_ptr notifier_; - std::unique_ptr observer_; -}; - -TEST_F(SystemTimeChangeNotifierTest, NotChanged) { - EXPECT_EQ(0, observer_->num_time_changed()); - - // Not changed. - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); -} - -TEST_F(SystemTimeChangeNotifierTest, TimeChangedForwardLessThan10Seconds) { - base::Time now = base::Time::Now(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change NOT detected. - notifier_->set_fake_now_for_testing(now + base::Seconds(4)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); -} - -TEST_F(SystemTimeChangeNotifierTest, TimeChangedBackwardLessThan10Seconds) { - base::Time now = base::Time::Now(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change NOT detected. - notifier_->set_fake_now_for_testing(now - base::Seconds(4)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); -} - -TEST_F(SystemTimeChangeNotifierTest, TimeChangedForwardMoreThan10Seconds) { - base::Time now = base::Time::Now(); - EXPECT_EQ(0, observer_->num_time_changed()); - - notifier_->set_fake_now_for_testing(now + base::Seconds(40)); - RunPendingTasks(); - // Still 0 since observe callback is running in next run loop. - EXPECT_EQ(0, observer_->num_time_changed()); - RunPendingTasks(); - // Time change detected. - EXPECT_EQ(1, observer_->num_time_changed()); -} - -TEST_F(SystemTimeChangeNotifierTest, TimeChangedBackwardMoreThan10Seconds) { - base::Time now = base::Time::Now(); - EXPECT_EQ(0, observer_->num_time_changed()); - - notifier_->set_fake_now_for_testing(now - base::Seconds(40)); - RunPendingTasks(); - // Still 0 since observe callback is running in next run loop. - EXPECT_EQ(0, observer_->num_time_changed()); - RunPendingTasks(); - // Time change detected. - EXPECT_EQ(1, observer_->num_time_changed()); -} - -TEST_F(SystemTimeChangeNotifierTest, CannotDetectTimeDriftForward) { - base::Time now = base::Time::Now(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change NOT detected. Expected = now + 1, actual = now + 4. - notifier_->set_fake_now_for_testing(now + base::Seconds(4)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change NOT detected. Expected = now + 4 + 1, actual = now + 8. - notifier_->set_fake_now_for_testing(now + base::Seconds(8)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change NOT detected. Expected = now + 8 + 1, actual = now + 12. - notifier_->set_fake_now_for_testing(now + base::Seconds(12)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change detected. Expected = now + 12 + 1, actual = now + 16. - notifier_->set_fake_now_for_testing(now + base::Seconds(16)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change detected. Expected = now + 16 + 1, actual = now + 20. - notifier_->set_fake_now_for_testing(now + base::Seconds(20)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); -} - -TEST_F(SystemTimeChangeNotifierTest, CannotDetectTTimeDriftBackward) { - base::Time now = base::Time::Now(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change NOT detected. Expected = now + 1, actual = now - 4. - notifier_->set_fake_now_for_testing(now - base::Seconds(4)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change NOT detected. Expected = now - 4 + 1, actual = now - 8. - notifier_->set_fake_now_for_testing(now - base::Seconds(8)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change detected. Expected = now - 8 + 1, actual = now - 12. - notifier_->set_fake_now_for_testing(now - base::Seconds(12)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change detected. Expected = now - 12 + 1, actual = now - 16. - notifier_->set_fake_now_for_testing(now - base::Seconds(16)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); - - // Time change detected. Expected = now - 20 + 1, actual = now - 20. - notifier_->set_fake_now_for_testing(now - base::Seconds(20)); - RunPendingTasks(); - EXPECT_EQ(0, observer_->num_time_changed()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/task_runner_impl.cc chromium-132.0.6834.159/chromecast/base/task_runner_impl.cc --- chromium-132.0.6834.110/chromecast/base/task_runner_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/task_runner_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// 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 "chromecast/base/task_runner_impl.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" - -namespace chromecast { - -TaskRunnerImpl::TaskRunnerImpl() - : TaskRunnerImpl(base::SingleThreadTaskRunner::GetCurrentDefault()) {} - -TaskRunnerImpl::TaskRunnerImpl( - scoped_refptr runner) - : runner_(std::move(runner)) { - DCHECK(runner_.get()); -} - -TaskRunnerImpl::~TaskRunnerImpl() {} - -bool TaskRunnerImpl::PostTask(Task* task, uint64_t delay_milliseconds) { - DCHECK(task); - // TODO(halliwell): FROM_HERE is misleading, we should consider a macro for - // vendor backends to send the callsite info. - return runner_->PostDelayedTask(FROM_HERE, - base::BindOnce(&Task::Run, base::Owned(task)), - base::Milliseconds(delay_milliseconds)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/task_runner_impl.h chromium-132.0.6834.159/chromecast/base/task_runner_impl.h --- chromium-132.0.6834.110/chromecast/base/task_runner_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/task_runner_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BASE_TASK_RUNNER_IMPL_H_ -#define CHROMECAST_BASE_TASK_RUNNER_IMPL_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/public/task_runner.h" - -namespace base { -class SingleThreadTaskRunner; -} - -namespace chromecast { - -// Implementation of public TaskRunner interface that just calls -// base::SingleThreadTaskRunner::CurrentDefaultHandle at construction time and -// uses it to post. -class TaskRunnerImpl : public TaskRunner { - public: - TaskRunnerImpl(); - explicit TaskRunnerImpl(scoped_refptr runner); - - TaskRunnerImpl(const TaskRunnerImpl&) = delete; - TaskRunnerImpl& operator=(const TaskRunnerImpl&) = delete; - - ~TaskRunnerImpl() override; - - bool PostTask(Task* task, uint64_t delay_milliseconds) override; - - const scoped_refptr& runner() const { - return runner_; - } - - private: - const scoped_refptr runner_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_TASK_RUNNER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/thread_health_checker.cc chromium-132.0.6834.159/chromecast/base/thread_health_checker.cc --- chromium-132.0.6834.110/chromecast/base/thread_health_checker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/thread_health_checker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/thread_health_checker.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/memory/ref_counted.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner.h" -#include "base/threading/thread_checker.h" -#include "base/timer/timer.h" -#include "chromecast/base/bind_to_task_runner.h" - -namespace chromecast { - -ThreadHealthChecker::Internal::Internal( - scoped_refptr patient_task_runner, - scoped_refptr doctor_task_runner, - base::TimeDelta interval, - base::TimeDelta timeout, - base::RepeatingClosure on_failure) - : patient_task_runner_(std::move(patient_task_runner)), - doctor_task_runner_(std::move(doctor_task_runner)), - interval_(interval), - timeout_(timeout), - on_failure_(std::move(on_failure)) { - DCHECK(patient_task_runner_); - DCHECK(doctor_task_runner_); -} - -ThreadHealthChecker::Internal::~Internal() {} - -void ThreadHealthChecker::Internal::StartHealthCheck() { - DCHECK(doctor_task_runner_->RunsTasksInCurrentSequence()); - DETACH_FROM_THREAD(thread_checker_); - ok_timer_ = std::make_unique(); - failure_timer_ = std::make_unique(); - ScheduleHealthCheck(); -} - -void ThreadHealthChecker::Internal::StopHealthCheck() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(ok_timer_); - DCHECK(failure_timer_); - ok_timer_->Stop(); - failure_timer_->Stop(); -} - -void ThreadHealthChecker::Internal::ScheduleHealthCheck() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - ok_timer_->Start(FROM_HERE, interval_, this, - &ThreadHealthChecker::Internal::CheckThreadHealth); -} - -void ThreadHealthChecker::Internal::CheckThreadHealth() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(!failure_timer_->IsRunning()); - patient_task_runner_->PostTask( - FROM_HERE, BindToCurrentThread(base::BindOnce( - &ThreadHealthChecker::Internal::ThreadOk, this))); - failure_timer_->Start(FROM_HERE, timeout_, this, - &ThreadHealthChecker::Internal::ThreadTimeout); -} - -void ThreadHealthChecker::Internal::ThreadOk() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - failure_timer_->Stop(); - ScheduleHealthCheck(); -} - -void ThreadHealthChecker::Internal::ThreadTimeout() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - on_failure_.Run(); - ScheduleHealthCheck(); -} - -// The public ThreadHealthChecker owns a ref-counted reference to an Internal -// object which does the heavy lifting. -ThreadHealthChecker::ThreadHealthChecker( - scoped_refptr patient_task_runner, - scoped_refptr doctor_task_runner, - base::TimeDelta interval, - base::TimeDelta timeout, - base::RepeatingClosure on_failure) - : doctor_task_runner_(doctor_task_runner), - internal_(base::MakeRefCounted( - patient_task_runner, - doctor_task_runner, - interval, - timeout, - std::move(on_failure))) { - doctor_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&ThreadHealthChecker::Internal::StartHealthCheck, - internal_)); -} - -// When the public ThreadHealthChecker is destroyed, the reference to the -// Internal representation is freed, but if there are any pending tasks on the -// doctor thread that partially own Internal, they will be run asynchronously -// before the Internal object is destroyed and the health check stops. -ThreadHealthChecker::~ThreadHealthChecker() { - doctor_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&ThreadHealthChecker::Internal::StopHealthCheck, - internal_)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/thread_health_checker.h chromium-132.0.6834.159/chromecast/base/thread_health_checker.h --- chromium-132.0.6834.110/chromecast/base/thread_health_checker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/thread_health_checker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BASE_THREAD_HEALTH_CHECKER_H_ -#define CHROMECAST_BASE_THREAD_HEALTH_CHECKER_H_ - -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" - -namespace base { -class OneShotTimer; -class SequencedTaskRunner; -class TaskRunner; -} // namespace base - -namespace chromecast { -// A class used to periodically check the responsiveness of a thread. -// -// The class takes two task runners, a "patient", and a "doctor". The doctor -// task runner will post a "sentinel" task to the patient and verify that it -// gets run within a certain response time, determined by |timeout|. -// If the task is not run in time, then the patient fails the health checkup and -// |on_failure| is invoked. -// -// The thread health is checked periodically, with the length between one check -// and the next determined by |interval|, and the amount of time allowed for the -// sentinel task to complete determined by |timeout|. -class ThreadHealthChecker { - public: - ThreadHealthChecker( - scoped_refptr patient_task_runner, - scoped_refptr doctor_task_runner, - base::TimeDelta interval, - base::TimeDelta timeout, - base::RepeatingClosure on_failure); - - ThreadHealthChecker(const ThreadHealthChecker&) = delete; - ThreadHealthChecker& operator=(const ThreadHealthChecker&) = delete; - - ~ThreadHealthChecker(); - - private: - class Internal : public base::RefCountedThreadSafe { - public: - Internal(scoped_refptr patient_task_runner, - scoped_refptr doctor_task_runner, - base::TimeDelta interval, - base::TimeDelta timeout, - base::RepeatingClosure on_failure); - void StartHealthCheck(); - void StopHealthCheck(); - - private: - friend class base::RefCountedThreadSafe; - ~Internal(); - void ScheduleHealthCheck(); - void CheckThreadHealth(); - void ThreadOk(); - void ThreadTimeout(); - - scoped_refptr patient_task_runner_; - scoped_refptr doctor_task_runner_; - base::TimeDelta interval_; - base::TimeDelta timeout_; - std::unique_ptr ok_timer_; - std::unique_ptr failure_timer_; - base::RepeatingClosure on_failure_; - THREAD_CHECKER(thread_checker_); - }; - - scoped_refptr doctor_task_runner_; - scoped_refptr internal_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BASE_THREAD_HEALTH_CHECKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/base/thread_health_checker_unittest.cc chromium-132.0.6834.159/chromecast/base/thread_health_checker_unittest.cc --- chromium-132.0.6834.110/chromecast/base/thread_health_checker_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/thread_health_checker_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/base/thread_health_checker.h" - -#include "base/functional/bind.h" -#include "base/memory/ref_counted.h" -#include "base/synchronization/waitable_event.h" -#include "base/test/test_mock_time_task_runner.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -namespace { -const base::TimeDelta kInterval = base::Seconds(3); -const base::TimeDelta kTimeout = base::Seconds(2); -} // namespace - -class ThreadHealthCheckerTest : public ::testing::Test { - protected: - ThreadHealthCheckerTest() - : patient_(base::MakeRefCounted()), - doctor_(base::MakeRefCounted()), - event_(base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED) {} - - ~ThreadHealthCheckerTest() override {} - - scoped_refptr patient_; - scoped_refptr doctor_; - base::WaitableEvent event_; -}; - -#define CREATE_THREAD_HEALTH_CHECKER(name) \ - ThreadHealthChecker name(patient_, doctor_, kInterval, kTimeout, \ - base::BindRepeating(&base::WaitableEvent::Signal, \ - base::Unretained(&event_))) - -TEST_F(ThreadHealthCheckerTest, FiresTimeoutWhenTaskRunnerDoesNotFlush) { - CREATE_THREAD_HEALTH_CHECKER(thc); - // Do not flush the patient, so that the health check sentinel task won't run. - doctor_->FastForwardBy(base::Seconds(6)); - EXPECT_TRUE(event_.IsSignaled()); -} - -TEST_F(ThreadHealthCheckerTest, DoesNotFireTimeoutWhenTaskRunnerFlushesInTime) { - CREATE_THREAD_HEALTH_CHECKER(thc); - // Advance the doctor by enough time to post the health check, but not to time - // out. - doctor_->FastForwardBy(base::Seconds(4)); - // Advance the patient to let the sentinel task run. - patient_->FastForwardBy(base::Seconds(4)); - // Advance the doctor by enough time such that the sentinel not running would - // cause the failure callback to run. - doctor_->FastForwardBy(base::Seconds(2)); - EXPECT_FALSE(event_.IsSignaled()); -} - -TEST_F(ThreadHealthCheckerTest, FiresTimeoutWhenTaskRunnerFlushesTooLate) { - CREATE_THREAD_HEALTH_CHECKER(thc); - // Advance the doctor before the patient, to simulate a task in the patient - // that takes too long. - doctor_->FastForwardBy(base::Seconds(6)); - patient_->FastForwardBy(base::Seconds(6)); - // Flush the task runner so the health check sentinel task is run. - EXPECT_TRUE(event_.IsSignaled()); -} - -TEST_F(ThreadHealthCheckerTest, FiresTimeoutOnLaterIteration) { - CREATE_THREAD_HEALTH_CHECKER(thc); - // Advance the doctor enough to start the check. - doctor_->FastForwardBy(base::Seconds(4)); - // Advance the patient enough to run the task. - patient_->FastForwardBy(base::Seconds(4)); - // Advance the doctor enough to start the check again. - doctor_->FastForwardBy(base::Seconds(4)); - EXPECT_FALSE(event_.IsSignaled()); - // Advance the doctor enough for the timeout from the second check to fire. - doctor_->FastForwardBy(base::Seconds(2)); - EXPECT_TRUE(event_.IsSignaled()); -} - -TEST_F(ThreadHealthCheckerTest, NoCrashWhenDestroyed) { - { - CREATE_THREAD_HEALTH_CHECKER(thc); - doctor_->RunUntilIdle(); - } - doctor_->RunUntilIdle(); -} - -TEST_F(ThreadHealthCheckerTest, DropPendingEventsAfterDestruction) { - { - CREATE_THREAD_HEALTH_CHECKER(thc); - // Fast forward by enough time to have scheduled a health check. - doctor_->FastForwardBy(base::Seconds(4)); - EXPECT_FALSE(event_.IsSignaled()); - } - // Fast forward by enough time for the health check to have executed. - // However, we want all pending events to be dropped after the destructor is - // called, so the event should not be signalled. - doctor_->FastForwardBy(base::Seconds(2)); - EXPECT_FALSE(event_.IsSignaled()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/base/version.h.in chromium-132.0.6834.159/chromecast/base/version.h.in --- chromium-132.0.6834.110/chromecast/base/version.h.in 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/base/version.h.in 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// version.h is generated from version.h.in. Edit the source! - -#ifndef CHROMECAST_BASE_VERSION_INFO_H_ -#define CHROMECAST_BASE_VERSION_INFO_H_ - -#define PRODUCT_VERSION "@VERSION_FULL@" -#define CAST_BUILD_INCREMENTAL "@CAST_BUILD_INCREMENTAL@" -#define CAST_BUILD_RELEASE "@CAST_BUILD_RELEASE@" -#define CAST_BUILD_REVISION "@CAST_BUILD_RELEASE@.@CAST_BUILD_INCREMENTAL@" -#define CAST_IS_DEBUG_BUILD() @CAST_IS_DEBUG_BUILD@ -#define CAST_PRODUCT_TYPE @CAST_PRODUCT_TYPE@ - -#endif // CHROMECAST_BASE_VERSION_INFO_H_ diff -Nru chromium-132.0.6834.110/chromecast/bindings/DEPS chromium-132.0.6834.159/chromecast/bindings/DEPS --- chromium-132.0.6834.110/chromecast/bindings/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -include_rules = [ - "+chromecast/browser", - "+components/cast/api_bindings", - "+components/cast/message_port", - "+components/cast/named_message_port_connector", - "+components/on_load_script_injector/browser", - "+content/public/common", - "+content/public/test", - "+mojo/public", - "+net/test", - "+ui/base/resource", -] - -specific_include_rules = { - "bindings_manager_fuchsia\..*": [ - "+fuchsia_web/runners/cast/fidl/fidl/hlcpp/chromium/cast/cpp/fidl.h", - ], -} diff -Nru chromium-132.0.6834.110/chromecast/bindings/OWNERS chromium-132.0.6834.159/chromecast/bindings/OWNERS --- chromium-132.0.6834.110/chromecast/bindings/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -lijiawei@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/bindings/bindings_manager.h chromium-132.0.6834.159/chromecast/bindings/bindings_manager.h --- chromium-132.0.6834.110/chromecast/bindings/bindings_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/bindings_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BINDINGS_BINDINGS_MANAGER_H_ -#define CHROMECAST_BINDINGS_BINDINGS_MANAGER_H_ - -#include "components/cast/api_bindings/manager.h" - -namespace chromecast { -namespace bindings { - -// TODO(crbug.com/40139651): Remove this alias when all callers are migrated to -// use cast_api_bindings::Manager directly. -class BindingsManager : public cast_api_bindings::Manager {}; - -} // namespace bindings -} // namespace chromecast - -#endif // CHROMECAST_BINDINGS_BINDINGS_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/bindings/bindings_manager_cast.cc chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast.cc --- chromium-132.0.6834.110/chromecast/bindings/bindings_manager_cast.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/bindings/bindings_manager_cast.h" - -#include -#include -#include -#include - -#include "base/functional/bind.h" -#include "components/cast/message_port/cast/message_port_cast.h" - -namespace chromecast { -namespace bindings { - -BindingsManagerCast::BindingsManagerCast() = default; - -BindingsManagerCast::~BindingsManagerCast() = default; - -mojo::PendingRemote BindingsManagerCast::CreateRemote() { - DCHECK(!receiver_.is_bound()); - - mojo::PendingRemote pending_remote = - receiver_.BindNewPipeAndPassRemote(); - receiver_.set_disconnect_handler(base::BindOnce( - &BindingsManagerCast::OnClientDisconnected, base::Unretained(this))); - - return pending_remote; -} - -void BindingsManagerCast::AddBinding(std::string_view binding_name, - std::string_view binding_script) { - std::pair new_entry = {std::string(binding_name), - std::string(binding_script)}; - for (auto it = bindings_.begin(); it != bindings_.end(); ++it) { - if (it->first == new_entry.first) { - *it = std::move(new_entry); - return; - } - } - - bindings_.emplace_back(std::move(new_entry)); -} - -void BindingsManagerCast::OnClientDisconnected() { - receiver_.reset(); -} - -void BindingsManagerCast::GetAll(GetAllCallback callback) { - std::vector bindings_vector; - for (const auto& entry : bindings_) { - bindings_vector.emplace_back( - chromecast::mojom::ApiBinding::New(entry.second)); - } - std::move(callback).Run(std::move(bindings_vector)); -} - -void BindingsManagerCast::Connect(const std::string& port_name, - blink::MessagePortDescriptor port) { - OnPortConnected(port_name, - cast_api_bindings::MessagePortCast::Create(std::move(port))); -} - -} // namespace bindings -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/bindings/bindings_manager_cast.h chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast.h --- chromium-132.0.6834.110/chromecast/bindings/bindings_manager_cast.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BINDINGS_BINDINGS_MANAGER_CAST_H_ -#define CHROMECAST_BINDINGS_BINDINGS_MANAGER_CAST_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "chromecast/bindings/bindings_manager.h" -#include "chromecast/bindings/public/mojom/api_bindings.mojom.h" -#include "components/cast/api_bindings/manager.h" -#include "mojo/public/cpp/bindings/receiver.h" - -namespace chromecast { -namespace bindings { - -// Implements the CastOS BindingsManager. -class BindingsManagerCast : public BindingsManager, - public chromecast::mojom::ApiBindings { - public: - // |cast_web_contents|: Used to inject bindings scripts into document early. - // Must outlive |this|. - BindingsManagerCast(); - ~BindingsManagerCast() override; - - BindingsManagerCast(const BindingsManagerCast&) = delete; - void operator=(const BindingsManagerCast&) = delete; - - // Creates an mojo::PendingRemote, binds it to |this| and returns it. - // At most one bound remote can exist at the same time. - mojo::PendingRemote CreateRemote(); - - // BindingsManager implementation. - void AddBinding(std::string_view binding_name, - std::string_view binding_script) override; - - private: - void OnClientDisconnected(); - - // chromecast::mojom::ApiBindings implementation. - void GetAll(GetAllCallback callback) override; - void Connect(const std::string& port_name, - blink::MessagePortDescriptor port) override; - - // Stores all bindings, keyed on the string-based IDs provided by the - // ApiBindings interface. Bindings are stored in the order they are added - // because evaluation order matters when one depends on another. - std::list> bindings_; - - mojo::Receiver receiver_{this}; -}; - -} // namespace bindings -} // namespace chromecast - -#endif // CHROMECAST_BINDINGS_BINDINGS_MANAGER_CAST_H_ diff -Nru chromium-132.0.6834.110/chromecast/bindings/bindings_manager_cast_browsertest.cc chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast_browsertest.cc --- chromium-132.0.6834.110/chromecast/bindings/bindings_manager_cast_browsertest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/bindings_manager_cast_browsertest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,280 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BINDINGS_BINDINGS_MANAGER_CAST_BROWSERTEST_H_ -#define CHROMECAST_BINDINGS_BINDINGS_MANAGER_CAST_BROWSERTEST_H_ - -#include "chromecast/bindings/bindings_manager_cast.h" - -#include -#include -#include - -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/memory/weak_ptr.h" -#include "base/path_service.h" -#include "base/run_loop.h" -#include "base/strings/utf_string_conversions.h" -#include "base/test/bind.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/bindings/public/mojom/api_bindings.mojom.h" -#include "chromecast/browser/cast_browser_context.h" -#include "chromecast/browser/cast_browser_process.h" -#include "chromecast/browser/cast_web_contents_impl.h" -#include "chromecast/browser/cast_web_contents_observer.h" -#include "chromecast/browser/test/cast_browser_test.h" -#include "components/cast/message_port/test_message_port_receiver.h" -#include "content/public/common/content_switches.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_base.h" -#include "content/public/test/browser_test_utils.h" -#include "mojo/public/cpp/bindings/connector.h" -#include "mojo/public/cpp/bindings/message.h" -#include "mojo/public/cpp/system/message_pipe.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -using ::testing::_; -using ::testing::Expectation; -using ::testing::InSequence; -using ::testing::Mock; -using ::testing::NiceMock; - -namespace content { -class WebContents; -} // namespace content - -namespace chromecast { - -namespace { - -const base::FilePath::CharType kTestDataPath[] = - FILE_PATH_LITERAL("chromecast/bindings/testdata"); - -base::FilePath GetTestDataPath() { - return base::FilePath(kTestDataPath); -} - -base::FilePath GetTestDataFilePath(const std::string& name) { - base::FilePath file_path; - CHECK(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &file_path)); - return file_path.Append(GetTestDataPath()).AppendASCII(name); -} - -class TitleChangeObserver : public CastWebContentsObserver { - public: - TitleChangeObserver() = default; - - TitleChangeObserver(const TitleChangeObserver&) = delete; - TitleChangeObserver& operator=(const TitleChangeObserver&) = delete; - - ~TitleChangeObserver() override = default; - - // Spins a Runloop until the title of the page matches the |expected_title| - // that have been set. - void RunUntilTitleEquals(std::string_view expected_title) { - expected_title_ = std::string(expected_title); - // Spin the runloop until the expected conditions are met. - if (current_title_ != expected_title_) { - expected_title_ = std::string(expected_title); - base::RunLoop run_loop; - quit_closure_ = run_loop.QuitClosure(); - run_loop.Run(); - } - } - - // CastWebContentsObserver implementation: - void UpdateTitle(const std::string& title) override { - // Resumes execution of RunUntilTitleEquals() if |title| matches - // expectations. - current_title_ = title; - if (!quit_closure_.is_null() && current_title_ == expected_title_) { - std::move(quit_closure_).Run(); - } - } - - private: - std::string current_title_; - std::string expected_title_; - - base::OnceClosure quit_closure_; -}; - -// ============================================================================= -// Mocks -// ============================================================================= -class MockWebContentsDelegate : public content::WebContentsDelegate { - public: - MockWebContentsDelegate() = default; - - MockWebContentsDelegate(const MockWebContentsDelegate&) = delete; - MockWebContentsDelegate& operator=(const MockWebContentsDelegate&) = delete; - - ~MockWebContentsDelegate() override = default; - - MOCK_METHOD1(CloseContents, void(content::WebContents* source)); -}; - -} // namespace - -// ============================================================================= -// Test class -// ============================================================================= -class BindingsManagerCastBrowserTest : public shell::CastBrowserTest { - protected: - void PreRunTestOnMainThread() override { - // Pump startup related events. - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::RunLoop().RunUntilIdle(); - - metrics::CastMetricsHelper::GetInstance()->SetDummySessionIdForTesting(); - content::WebContents::CreateParams create_params( - shell::CastBrowserProcess::GetInstance()->browser_context(), nullptr); - web_contents_ = content::WebContents::Create(create_params); - web_contents_->SetDelegate(&mock_wc_delegate_); - - // CastWebContents::Delegate must be set for receiving PageStateChanged - // event. - mojom::CastWebViewParamsPtr params = mojom::CastWebViewParams::New(); - params->is_root_window = true; - - cast_web_contents_ = std::make_unique( - web_contents_.get(), std::move(params)); - title_change_observer_.Observe(cast_web_contents_.get()); - bindings_manager_ = std::make_unique(); - cast_web_contents_->ConnectToBindingsService( - bindings_manager_->CreateRemote()); - } - - void PostRunTestOnMainThread() override { - cast_web_contents_.reset(); - web_contents_.reset(); - bindings_manager_.reset(); - } - - void StartTestServer() { - ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); - embedded_test_server()->StartAcceptingConnections(); - } - - NiceMock mock_wc_delegate_; - TitleChangeObserver title_change_observer_; - std::unique_ptr web_contents_; - std::unique_ptr cast_web_contents_; - - std::unique_ptr bindings_manager_; -}; - -// Handles connected ports from the NamedMessagePortConnector and -// provides a convenience methods for waiting for and then returning the port -// synchronously. -class MessagePortConnectionHandler { - public: - MessagePortConnectionHandler() {} - ~MessagePortConnectionHandler() {} - - cast_api_bindings::Manager::MessagePortConnectedHandler GetConnectCallback() { - return base::BindRepeating(&MessagePortConnectionHandler::OnConnect, - base::Unretained(this)); - } - - std::unique_ptr RunUntilPortConnected() { - base::RunLoop run_loop; - on_port_connected_ = run_loop.QuitClosure(); - run_loop.Run(); - return std::move(port_); - } - - private: - void OnConnect(std::unique_ptr port) { - DCHECK(on_port_connected_); - - port_ = std::move(port); - std::move(on_port_connected_).Run(); - } - - base::OnceClosure on_port_connected_; - std::unique_ptr port_; -}; - -// ============================================================================= -// Test cases -// ============================================================================= -IN_PROC_BROWSER_TEST_F(BindingsManagerCastBrowserTest, EndToEnd) { - // =========================================================================== - // Test: Load BindingsManagerCast, ensure binding backend can receive a port - // via BindingsManagerCast and the port is good to use. - // Step 1: Create a TestBindingBackend object. TestBindingBackend will - // register a PortHandler to BindingsManagerCast. - // Step 2: Attach |bindings_manager_cast_| to |cast_web_contents_|, port - // connector binding should be injected into |cast_web_contents_|. - // Step 3: Load the test page, expected behaviours include: - // - BindingsManagerCast posts one end of MessagePort to the page. - // NamedMessagePort binding should be able to forward ports to native. - // - BindingManagerCast should successfully route a connected MessagePort to - // TestBindingBackend. This port is created by test page "connector.html". - // Step 4: Verify that messages that are sent through the port are cached - // before the port is not routed to native. And make sure TestBindingBackend - // could use the |bindings_manager_cast_| provided port to send & receive - // messages. Note: Messages should arrive in order. - // =========================================================================== - GURL test_url = - content::GetFileUrlWithQuery(GetTestDataFilePath("connector.html"), ""); - - MessagePortConnectionHandler connect_handler; - bindings_manager_->RegisterPortHandler("hello", - connect_handler.GetConnectCallback()); - - // Load test page. - constexpr char kTestPageTitle[] = "bindings"; - cast_web_contents_->LoadUrl(test_url); - title_change_observer_.RunUntilTitleEquals(kTestPageTitle); - - auto message_port = connect_handler.RunUntilPortConnected(); - cast_api_bindings::TestMessagePortReceiver receiver; - message_port->SetReceiver(&receiver); - - message_port->PostMessage("ping"); - - // Test that message are received in order. - receiver.RunUntilMessageCountEqual(3); - EXPECT_EQ(receiver.buffer()[0].first, "early 1"); - EXPECT_EQ(receiver.buffer()[1].first, "early 2"); - EXPECT_EQ(receiver.buffer()[2].first, "ack ping"); - - // Ensure that the MessagePort is dropped when navigating away. - cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL)); - receiver.RunUntilDisconnected(); - - bindings_manager_->UnregisterPortHandler("hello"); -} - -IN_PROC_BROWSER_TEST_F(BindingsManagerCastBrowserTest, OrderedBindings) { - bindings_manager_->AddBinding("foo", "bar"); - bindings_manager_->AddBinding("hello", "world"); - - // A repeated binding should have its order preserved - bindings_manager_->AddBinding("foo", "BAR"); - - std::vector received_bindings; - static_cast(bindings_manager_.get()) - ->GetAll(base::BindLambdaForTesting( - [&](std::vector bindings) { - for (auto& entry : bindings) { - received_bindings.push_back(entry->script); - } - })); - - EXPECT_EQ(2UL, received_bindings.size()); - EXPECT_EQ("BAR", received_bindings[0]); - EXPECT_EQ("world", received_bindings[1]); -} -} // namespace chromecast - -#endif // CHROMECAST_BINDINGS_BINDINGS_MANAGER_CAST_BROWSERTEST_H_ diff -Nru chromium-132.0.6834.110/chromecast/bindings/bindings_manager_fuchsia.cc chromium-132.0.6834.159/chromecast/bindings/bindings_manager_fuchsia.cc --- chromium-132.0.6834.110/chromecast/bindings/bindings_manager_fuchsia.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/bindings_manager_fuchsia.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/bindings/bindings_manager_fuchsia.h" - -#include -#include -#include -#include -#include - -#include "base/fuchsia/fuchsia_logging.h" -#include "base/fuchsia/mem_buffer_util.h" -#include "components/cast/message_port/fuchsia/message_port_fuchsia.h" - -namespace chromecast { -namespace bindings { - -BindingsManagerFuchsia::BindingsManagerFuchsia() = default; - -BindingsManagerFuchsia::~BindingsManagerFuchsia() = default; - -void BindingsManagerFuchsia::AddBinding(std::string_view binding_name, - std::string_view binding_script) { - std::pair new_entry = { - std::string(binding_name), - base::MemBufferFromString(binding_script, "cast-binding-script")}; - for (auto it = bindings_.begin(); it != bindings_.end(); ++it) { - if (it->first == new_entry.first) { - *it = std::move(new_entry); - return; - } - } - - bindings_.emplace_back(std::move(new_entry)); -} - -void BindingsManagerFuchsia::GetAll(GetAllCallback callback) { - // Build a list of binding scripts and send it to the client. - std::vector bindings_vector; - for (auto& entry : bindings_) { - chromium::cast::ApiBinding binding_cloned; - zx_status_t status; - status = entry.second.Clone(binding_cloned.mutable_before_load_script()); - ZX_CHECK(status == ZX_OK, status) << "vmo::clone"; - bindings_vector.emplace_back(std::move(binding_cloned)); - } - callback(std::move(bindings_vector)); -} - -void BindingsManagerFuchsia::Connect( - std::string port_name, - fidl::InterfaceHandle<::fuchsia::web::MessagePort> message_port) { - OnPortConnected(port_name, std::unique_ptr( - cast_api_bindings::MessagePortFuchsia::Create( - std::move(message_port)))); -} - -} // namespace bindings -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/bindings/bindings_manager_fuchsia.h chromium-132.0.6834.159/chromecast/bindings/bindings_manager_fuchsia.h --- chromium-132.0.6834.110/chromecast/bindings/bindings_manager_fuchsia.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/bindings_manager_fuchsia.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BINDINGS_BINDINGS_MANAGER_FUCHSIA_H_ -#define CHROMECAST_BINDINGS_BINDINGS_MANAGER_FUCHSIA_H_ - -#include -#include - -#include -#include -#include -#include - -#include "chromecast/bindings/bindings_manager.h" - -namespace chromecast { -namespace bindings { - -// Implements the BindingsManager as a ApiBindings FIDL service. -class BindingsManagerFuchsia : public chromium::cast::ApiBindings, - public BindingsManager { - public: - BindingsManagerFuchsia(); - - BindingsManagerFuchsia(const BindingsManagerFuchsia&) = delete; - BindingsManagerFuchsia& operator=(const BindingsManagerFuchsia&) = delete; - - ~BindingsManagerFuchsia() override; - - // BindingsManager implementation: - void AddBinding(std::string_view binding_name, - std::string_view binding_script) override; - - protected: - // chromium::cast::ApiBindings implementation: - void GetAll(GetAllCallback callback) override; - void Connect( - std::string port_name, - fidl::InterfaceHandle<::fuchsia::web::MessagePort> message_port) override; - - private: - // Stores all bindings, keyed on the string-based IDs provided by the - // ApiBindings interface. Bindings are stored in the order they are added - // because evaluation order matters when one depends on another. - std::list> bindings_; -}; - -} // namespace bindings -} // namespace chromecast - -#endif // CHROMECAST_BINDINGS_BINDINGS_MANAGER_FUCHSIA_H_ diff -Nru chromium-132.0.6834.110/chromecast/bindings/public/mojom/OWNERS chromium-132.0.6834.159/chromecast/bindings/public/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/bindings/public/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/public/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/bindings/public/mojom/api_bindings.mojom chromium-132.0.6834.159/chromecast/bindings/public/mojom/api_bindings.mojom --- chromium-132.0.6834.110/chromecast/bindings/public/mojom/api_bindings.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/public/mojom/api_bindings.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -import "third_party/blink/public/mojom/messaging/message_port_descriptor.mojom"; - -// Provides Cast platform API binding scripts and methods for connecting those -// scripts with Cast service backends. -interface ApiBindings { - // Gets the list of bindings to early-inject into the page at load time. - // The returned ApiBindings must be evaluated in order. - GetAll() => (array bindings); - - // Should be invoked when a connecting a named MessagePort to a native - // bindings backend. - // |port_name| is a string-based ID. It is used to locate corresponding - // native bindings backend. - // |port| is one end of a paired message channel. It can be deserilized - // to bind a blink::WebMessagePort to perform bi-directional communication. - Connect(string port_name, blink.mojom.MessagePortDescriptor port); -}; - -struct ApiBinding { - // Script to execute before the load of a web document. |script| uses - // UTF-8 encoding. - string script; -}; diff -Nru chromium-132.0.6834.110/chromecast/bindings/shared/proto_serializer.h chromium-132.0.6834.159/chromecast/bindings/shared/proto_serializer.h --- chromium-132.0.6834.110/chromecast/bindings/shared/proto_serializer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/bindings/shared/proto_serializer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BINDINGS_SHARED_PROTO_SERIALIZER_H_ -#define CHROMECAST_BINDINGS_SHARED_PROTO_SERIALIZER_H_ - -#include -#include - -#include "base/base64.h" - -namespace chromecast { -namespace bindings { - -template -class ProtoSerializer { - public: - ProtoSerializer() = delete; - - // Serializes |proto| to its base64 representation. Used by bindings - // frontends and backends for consistent serialization logic. - static std::string Serialize(T proto) { - std::vector encoded(proto.ByteSizeLong()); - if (encoded.empty()) { - return std::string(); - } - - CHECK(proto.SerializeWithCachedSizesToArray(&encoded[0])); - std::string ser = base::Base64Encode(encoded); - return ser; - } - - // Deserializes |base64| to its proto representation, parsed into |result|. - // Returns a value if parsing is successful; otherwise, returns false. Used - // by bindings frontends and backends for consistent serialization logic. - static std::optional Deserialize(std::string_view base64_proto) { - std::string decoded; - if (!base::Base64Decode(base64_proto, &decoded)) { - return std::nullopt; - } - - T result; - return result.ParseFromString(decoded) ? std::make_optional(result) - : std::nullopt; - } -}; - -} // namespace bindings -} // namespace chromecast - -#endif // CHROMECAST_BINDINGS_SHARED_PROTO_SERIALIZER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/DEPS chromium-132.0.6834.159/chromecast/browser/DEPS --- chromium-132.0.6834.110/chromecast/browser/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,113 +0,0 @@ -include_rules = [ - "+cc/base/switches.h", - "+chromecast/activity", - "+chromecast/bindings", - "+chromecast/bindings/public/mojom", - "+chromecast/common", - "+chromecast/common/mojom", - "+chromecast/graphics", - "+chromecast/app/grit/chromecast_settings.h", - "+chromecast/app/resources/grit/shell_resources.h", - "+chromecast/external_mojo", - "+chromecast/media", - "+chromecast/metrics", - "+chromecast/mojo", - "+chromecast/net", - "+chromecast/service", - "+chromecast/ui", - "+components/cast", - "+components/cast_receiver/browser", - "+components/cdm/browser", - "+components/crash", - "+components/download/public/common", - "+components/guest_view/browser", - "+components/heap_profiling", - "+components/input", - "+components/keyed_service", - "+components/media_control/browser", - "+components/media_control/mojom", - "+components/memory_pressure", - "+components/network_hints", - "+components/network_session_configurator/common", - "+components/on_load_script_injector/browser", - "+components/policy/core/browser", - "+components/prefs", - "+components/pref_registry", - "+components/profile_metrics", - "+components/proxy_config", - "+components/safe_search_api", - "+components/services/heap_profiling/heap_profiling_service.h", - "+components/services/heap_profiling/public/mojom", - "+components/services/heap_profiling/public/cpp/settings.h", - "+components/storage_monitor", - "+components/ui_devtools", - "+components/url_matcher", - "+components/url_rewrite/browser", - "+components/url_rewrite/common", - "+components/url_rewrite/mojom", - "+components/user_prefs", - "+components/value_store", - "+components/variations/net", - "+components/version_info", - "+components/viz/common/switches.h", - "+components/zoom", - "+content/common/net", - "+content/public/android", - "+content/public/browser", - "+content/public/common", - "+content/public/test", - "+device/bluetooth", - "+gin/v8_initializer.h", - "+gpu/command_buffer/service/gpu_switches.h", - "+media/audio", - "+media/base", - "+media/gpu", - "+media/mojo", - "+mojo/public", - "+net", - "+sandbox/policy", - "+services/cert_verifier/public/mojom", - "+services/media_session/public", - "+services/metrics/public/cpp", - "+services/network/public/cpp", - "+services/service_manager", - "+storage/browser/quota/quota_settings.h", - "+third_party/blink/public/common", - "+third_party/blink/public/mojom/autoplay", - "+third_party/blink/public/mojom/loader/resource_load_info.mojom.h", - "+third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h", - "+third_party/blink/public/mojom/mediastream/media_stream.mojom.h", - "+third_party/blink/public/mojom/messaging", - "+third_party/blink/public/mojom/speech/speech_synthesis.mojom.h", - "+third_party/blink/public/mojom/webpreferences/web_preferences.mojom.h", - "+third_party/skia/include/core/SkColor.h", - "+ui/aura", - "+ui/base", - "+ui/compositor", - "+ui/events", - "+ui/gfx", - "+ui/gl", - "+ui/display", - "+ui/ozone", - "+ui/views", - "+ui/wm", - - # TODO(sanfin): Remove this by fixing the crash handler on android. - "!chromecast/app", - - # TODO(slan): Remove this when the network service is shipped on Cast. - "+services/network", - - # TODO(guohuideng): Separate SetGeometry from VideoPlaneController, and get - # rid of the dependency on cast_renderer.h. - "+chromecast/media/service/cast_renderer.h", - - # For favicon url - "+third_party/blink/public/mojom/favicon", - - # No inclusion of WebKit from the browser, other than the ones in - # WebKit/public/{mojom,common}, or the ones that are strictly enum/POD, - # header-only types, and some selected common code. - # Needed for constants for TTS. - "+third_party/blink/public/platform/web_speech_synthesis_constants.h", -] diff -Nru chromium-132.0.6834.110/chromecast/browser/OWNERS chromium-132.0.6834.159/chromecast/browser/OWNERS --- chromium-132.0.6834.110/chromecast/browser/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -seantopping@chromium.org - -per-file cast_overlay_manifests.h=set noparent -per-file cast_overlay_manifests.h=file://ipc/SECURITY_OWNERS -per-file cast_overlay_manifests.cc=set noparent -per-file cast_overlay_manifests.cc=file://ipc/SECURITY_OWNERS -per-file cast_content_browser_client_receiver_bindings.cc=set noparent -per-file cast_content_browser_client_receiver_bindings.cc=file://ipc/SECURITY_OWNERS -per-file cast_browser_interface_binders.*=set noparent -per-file cast_browser_interface_binders.*=file://ipc/SECURITY_OWNERS -per-file service_connector.cc=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/browser/android/DEPS chromium-132.0.6834.159/chromecast/browser/android/DEPS --- chromium-132.0.6834.110/chromecast/browser/android/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -include_rules = [ - "+components/embedder_support/android", - "+components/minidump_uploader", - "+components/module_installer/android/java/src/org/chromium/components/module_installer/builder/ModuleInterface.java", - "+content/public/android", - "+jni", - "+ui/android", -] diff -Nru chromium-132.0.6834.110/chromecast/browser/android/OWNERS chromium-132.0.6834.159/chromecast/browser/android/OWNERS --- chromium-132.0.6834.110/chromecast/browser/android/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -sanfin@chromium.org -thoren@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/AndroidManifest.xml.jinja2 chromium-132.0.6834.159/chromecast/browser/android/apk/AndroidManifest.xml.jinja2 --- chromium-132.0.6834.110/chromecast/browser/android/apk/AndroidManifest.xml.jinja2 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/AndroidManifest.xml.jinja2 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {% set num_sandboxed_services = 40 %} - - - - {% for i in range(num_sandboxed_services) %} - - {% endfor %} - - {% set num_privileged_services = 5 %} - - - - {% for i in range(num_privileged_services) %} - - {% endfor %} - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/CastBrowserAndroidManifest.xml.jinja2 chromium-132.0.6834.159/chromecast/browser/android/apk/CastBrowserAndroidManifest.xml.jinja2 --- chromium-132.0.6834.110/chromecast/browser/android/apk/CastBrowserAndroidManifest.xml.jinja2 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/CastBrowserAndroidManifest.xml.jinja2 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {% set num_sandboxed_services = 40 %} - - - - {% for i in range(num_sandboxed_services) %} - - {% endfor %} - - {% set num_privileged_services = 5 %} - - - - {% for i in range(num_privileged_services) %} - - {% endfor %} - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-anydpi-v26/ic_settings_cast.xml chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-anydpi-v26/ic_settings_cast.xml --- chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-anydpi-v26/ic_settings_cast.xml 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-anydpi-v26/ic_settings_cast.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-hdpi/ic_notification_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-hdpi/ic_notification_cast.png differ Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-hdpi/ic_settings_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-hdpi/ic_settings_cast.png differ Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-mdpi/ic_notification_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-mdpi/ic_notification_cast.png differ Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-mdpi/ic_settings_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-mdpi/ic_settings_cast.png differ diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-nodpi/ic_cast_vector.xml chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-nodpi/ic_cast_vector.xml --- chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-nodpi/ic_cast_vector.xml 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-nodpi/ic_cast_vector.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ - - - - - - \ No newline at end of file Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-xhdpi/ic_notification_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xhdpi/ic_notification_cast.png differ Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-xhdpi/ic_settings_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xhdpi/ic_settings_cast.png differ Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-xxhdpi/ic_notification_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xxhdpi/ic_notification_cast.png differ Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-xxhdpi/ic_settings_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xxhdpi/ic_settings_cast.png differ Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-xxxhdpi/ic_notification_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xxxhdpi/ic_notification_cast.png differ Binary files /srv/release.debian.org/tmp/3jM8HqcW1Y/chromium-132.0.6834.110/chromecast/browser/android/apk/res/drawable-xxxhdpi/ic_settings_cast.png and /srv/release.debian.org/tmp/KMaXv81MMw/chromium-132.0.6834.159/chromecast/browser/android/apk/res/drawable-xxxhdpi/ic_settings_cast.png differ diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/res/layout/cast_web_contents_activity.xml chromium-132.0.6834.159/chromecast/browser/android/apk/res/layout/cast_web_contents_activity.xml --- chromium-132.0.6834.110/chromecast/browser/android/apk/res/layout/cast_web_contents_activity.xml 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/res/layout/cast_web_contents_activity.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ - - - - - - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/res-values/values/colors.xml chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values/colors.xml --- chromium-132.0.6834.110/chromecast/browser/android/apk/res-values/values/colors.xml 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values/colors.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ - - - #1c73e8 - \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/res-values/values/strings.xml chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values/strings.xml --- chromium-132.0.6834.110/chromecast/browser/android/apk/res-values/values/strings.xml 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values/strings.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ - - - - - - Chromecast built-in - Initialization failed. - diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/res-values/values-v17/styles.xml chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values-v17/styles.xml --- chromium-132.0.6834.110/chromecast/browser/android/apk/res-values/values-v17/styles.xml 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/res-values/values-v17/styles.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ - - - - - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/IDeviceLogsProvider.aidl chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/IDeviceLogsProvider.aidl --- chromium-132.0.6834.110/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/IDeviceLogsProvider.aidl 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/IDeviceLogsProvider.aidl 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chromecast.shell; - -/** - * Interface implemented by services provide device logs - * - * WARNING: Please read before updating this file. - * Rules for updating this file: - * - DO NOT change or remove methods that are already defined. - * - Methods must be added to the bottom of this file. - * - When adding a method, please increment the VERSION field - * defined in implementors. - * - The presence of new methods must be verified in the service - * by checking the API version via getApiVersion(). - * - * API CHANGE LOG (Update when methods are added): - * VERSION 1: Initial API version. - */ -interface IDeviceLogsProvider { - /** - * The current API version. Whenever a method is added to this file, - * please ++ this value and update the change log at the top. - */ - const int VERSION = 1; - - /** - * Filename of location of logs provided from remote service. - */ - String getLogs(); -} \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/OWNERS chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/OWNERS --- chromium-132.0.6834.110/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *.aidl=set noparent -per-file *.aidl=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/logs_provider_service.aidl chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/logs_provider_service.aidl --- chromium-132.0.6834.110/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/logs_provider_service.aidl 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/logs_provider_service.aidl 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -interface org.chromium.chromecast.shell.IDeviceLogsProvider; diff -Nru chromium-132.0.6834.110/chromecast/browser/android/cast_content_window_android.cc chromium-132.0.6834.159/chromecast/browser/android/cast_content_window_android.cc --- chromium-132.0.6834.110/chromecast/browser/android/cast_content_window_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/cast_content_window_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,145 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/android/cast_content_window_android.h" - -#include - -#include "base/android/jni_android.h" -#include "base/android/jni_string.h" -#include "base/android/scoped_java_ref.h" -#include "components/media_control/browser/media_blocker.h" -#include "content/public/browser/web_contents_observer.h" - -// Must come after all headers that specialize FromJniType() / ToJniType(). -#include "chromecast/browser/android/jni_headers/CastContentWindowAndroid_jni.h" - -namespace chromecast { - -using base::android::ConvertUTF8ToJavaString; - -namespace { - -base::android::ScopedJavaLocalRef CreateJavaWindow( - jlong native_window, - bool enable_touch_input, - bool turn_on_screen, - bool keep_screen_on, - const std::string& session_id, - const int display_id) { - JNIEnv* env = base::android::AttachCurrentThread(); - return Java_CastContentWindowAndroid_create( - env, native_window, enable_touch_input, turn_on_screen, keep_screen_on, - ConvertUTF8ToJavaString(env, session_id), static_cast(display_id)); -} - -bool ShouldRequestAudioFocus(bool is_remote_control_mode, - const media_control::MediaBlocker* media_blocker) { - if (is_remote_control_mode) { - return false; - } - if (!media_blocker) { - return true; - } - return !media_blocker->media_loading_blocked(); -} - -} // namespace - -CastContentWindowAndroid::CastContentWindowAndroid( - mojom::CastWebViewParamsPtr params) - : CastContentWindow(std::move(params)), - web_contents_attached_(false), - java_window_(CreateJavaWindow(reinterpret_cast(this), - params_->enable_touch_input, - params_->turn_on_screen, - params_->keep_screen_on, - params_->session_id, - params_->display_id)) {} - -CastContentWindowAndroid::~CastContentWindowAndroid() { - JNIEnv* env = base::android::AttachCurrentThread(); - Java_CastContentWindowAndroid_onNativeDestroyed(env, java_window_); -} - -void CastContentWindowAndroid::CreateWindow( - mojom::ZOrder /* z_order */, - VisibilityPriority visibility_priority) { - if (web_contents_attached_) { - return; - } - JNIEnv* env = base::android::AttachCurrentThread(); - - content::WebContentsObserver::Observe(cast_web_contents()->web_contents()); - - base::android::ScopedJavaLocalRef java_web_contents = - cast_web_contents()->web_contents()->GetJavaWebContents(); - - Java_CastContentWindowAndroid_createWindowForWebContents( - env, java_window_, java_web_contents, - ConvertUTF8ToJavaString(env, params_->activity_id), - ShouldRequestAudioFocus(params_->is_remote_control_mode, - cast_web_contents()->media_blocker())); - web_contents_attached_ = true; - cast_web_contents()->web_contents()->Focus(); -} - -void CastContentWindowAndroid::GrantScreenAccess() { - JNIEnv* env = base::android::AttachCurrentThread(); - Java_CastContentWindowAndroid_grantScreenAccess(env, java_window_); -} - -void CastContentWindowAndroid::RevokeScreenAccess() { - JNIEnv* env = base::android::AttachCurrentThread(); - Java_CastContentWindowAndroid_revokeScreenAccess(env, java_window_); -} - -void CastContentWindowAndroid::EnableTouchInput(bool enabled) { - JNIEnv* env = base::android::AttachCurrentThread(); - Java_CastContentWindowAndroid_enableTouchInput( - env, java_window_, static_cast(enabled)); -} - -void CastContentWindowAndroid::MediaStartedPlaying( - const content::WebContentsObserver::MediaPlayerInfo& video_type, - const content::MediaPlayerId& id) { - JNIEnv* env = base::android::AttachCurrentThread(); - if (video_type.has_video) { - Java_CastContentWindowAndroid_setAllowPictureInPicture( - env, java_window_, static_cast(true)); - } - Java_CastContentWindowAndroid_setMediaPlaying(env, java_window_, - static_cast(true)); -} - -void CastContentWindowAndroid::MediaStoppedPlaying( - const content::WebContentsObserver::MediaPlayerInfo& video_type, - const content::MediaPlayerId& id, - content::WebContentsObserver::MediaStoppedReason reason) { - JNIEnv* env = base::android::AttachCurrentThread(); - Java_CastContentWindowAndroid_setAllowPictureInPicture( - env, java_window_, static_cast(false)); - Java_CastContentWindowAndroid_setMediaPlaying(env, java_window_, - static_cast(false)); -} - -void CastContentWindowAndroid::OnActivityStopped( - JNIEnv* env, - const base::android::JavaParamRef& jcaller) { - for (auto& observer : observers_) { - observer->OnWindowDestroyed(); - } -} - -void CastContentWindowAndroid::RequestVisibility( - VisibilityPriority visibility_priority) {} - -void CastContentWindowAndroid::OnVisibilityChange( - JNIEnv* env, - const base::android::JavaParamRef& jcaller, - int visibility_type) { - NotifyVisibilityChange(static_cast(visibility_type)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/android/cast_content_window_android.h chromium-132.0.6834.159/chromecast/browser/android/cast_content_window_android.h --- chromium-132.0.6834.110/chromecast/browser/android/cast_content_window_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/cast_content_window_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_ANDROID_CAST_CONTENT_WINDOW_ANDROID_H_ -#define CHROMECAST_BROWSER_ANDROID_CAST_CONTENT_WINDOW_ANDROID_H_ - -#include - -#include "base/android/scoped_java_ref.h" -#include "chromecast/browser/cast_content_window.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_observer.h" - -namespace chromecast { - -// Android implementation of CastContentWindow, which displays WebContents in -// CastWebContentsActivity. -class CastContentWindowAndroid : public CastContentWindow, - content::WebContentsObserver { - public: - explicit CastContentWindowAndroid(mojom::CastWebViewParamsPtr params); - - CastContentWindowAndroid(const CastContentWindowAndroid&) = delete; - CastContentWindowAndroid& operator=(const CastContentWindowAndroid&) = delete; - - ~CastContentWindowAndroid() override; - - // CastContentWindow implementation: - void CreateWindow(mojom::ZOrder z_order, - VisibilityPriority visibility_priority) override; - void GrantScreenAccess() override; - void RevokeScreenAccess() override; - void EnableTouchInput(bool enabled) override; - void RequestVisibility(VisibilityPriority visibility_priority) override; - - // content::WebContentsObserver implementation - void MediaStartedPlaying( - const content::WebContentsObserver::MediaPlayerInfo& video_type, - const content::MediaPlayerId& id) override; - void MediaStoppedPlaying( - const content::WebContentsObserver::MediaPlayerInfo& video_type, - const content::MediaPlayerId& id, - content::WebContentsObserver::MediaStoppedReason reason) override; - - // Called through JNI. - void OnActivityStopped(JNIEnv* env, - const base::android::JavaParamRef& jcaller); - void OnVisibilityChange(JNIEnv* env, - const base::android::JavaParamRef& jcaller, - int visibility_type); - - private: - bool web_contents_attached_; - base::android::ScopedJavaGlobalRef java_window_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_ANDROID_CAST_CONTENT_WINDOW_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/android/cast_metrics_helper_android.cc chromium-132.0.6834.159/chromecast/browser/android/cast_metrics_helper_android.cc --- chromium-132.0.6834.110/chromecast/browser/android/cast_metrics_helper_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/cast_metrics_helper_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// 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 "chromecast/base/metrics/cast_metrics_helper.h" - -// Must come after all headers that specialize FromJniType() / ToJniType(). -#include "chromecast/browser/android/jni_headers/CastMetricsHelper_jni.h" - -namespace chromecast { -namespace shell { - -void JNI_CastMetricsHelper_LogMediaPlay(JNIEnv* env) { - metrics::CastMetricsHelper::GetInstance()->LogMediaPlay(); -} - -void JNI_CastMetricsHelper_LogMediaPause(JNIEnv* env) { - metrics::CastMetricsHelper::GetInstance()->LogMediaPause(); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/android/cast_web_service_android.cc chromium-132.0.6834.159/chromecast/browser/android/cast_web_service_android.cc --- chromium-132.0.6834.110/chromecast/browser/android/cast_web_service_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/android/cast_web_service_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_web_service.h" - -#include - -#include "chromecast/browser/android/cast_content_window_android.h" - -namespace chromecast { - -std::unique_ptr CastWebService::CreateWindow( - mojom::CastWebViewParamsPtr params) { - return std::make_unique(std::move(params)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/application_media_capabilities.cc chromium-132.0.6834.159/chromecast/browser/application_media_capabilities.cc --- chromium-132.0.6834.110/chromecast/browser/application_media_capabilities.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/application_media_capabilities.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/application_media_capabilities.h" - -#include - -#include "chromecast/base/bitstream_audio_codecs.h" - -namespace chromecast { -namespace shell { - -ApplicationMediaCapabilities::ApplicationMediaCapabilities() = default; - -ApplicationMediaCapabilities::~ApplicationMediaCapabilities() = default; - -void ApplicationMediaCapabilities::AddReceiver( - mojo::PendingReceiver receiver) { - receivers_.Add(this, std::move(receiver)); -} - -void ApplicationMediaCapabilities::SetSupportedBitstreamAudioCodecs( - const BitstreamAudioCodecsInfo& info) { - supported_bitstream_audio_codecs_info_ = info; - for (auto& observer : observers_) - observer->OnSupportedBitstreamAudioCodecsChanged(info); -} - -void ApplicationMediaCapabilities::AddObserver( - mojo::PendingRemote - observer_remote) { - mojo::Remote observer( - std::move(observer_remote)); - observer->OnSupportedBitstreamAudioCodecsChanged( - supported_bitstream_audio_codecs_info_); - observers_.Add(std::move(observer)); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/application_media_capabilities.h chromium-132.0.6834.159/chromecast/browser/application_media_capabilities.h --- chromium-132.0.6834.110/chromecast/browser/application_media_capabilities.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/application_media_capabilities.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_APPLICATION_MEDIA_CAPABILITIES_H_ -#define CHROMECAST_BROWSER_APPLICATION_MEDIA_CAPABILITIES_H_ - -#include "chromecast/common/mojom/application_media_capabilities.mojom.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "mojo/public/cpp/bindings/remote_set.h" - -namespace content { -class RenderFrameHost; -} // namespace content - -namespace chromecast { -namespace shell { - -class ApplicationMediaCapabilities - : public mojom::ApplicationMediaCapabilities { - public: - ApplicationMediaCapabilities(); - - ApplicationMediaCapabilities(const ApplicationMediaCapabilities&) = delete; - ApplicationMediaCapabilities& operator=(const ApplicationMediaCapabilities&) = - delete; - - ~ApplicationMediaCapabilities() override; - - void AddReceiver( - mojo::PendingReceiver receiver); - - void SetSupportedBitstreamAudioCodecs(const BitstreamAudioCodecsInfo& info); - - private: - // mojom::ApplicationMediaCapabilities implementation: - void AddObserver( - mojo::PendingRemote - observer_remote) override; - - mojo::ReceiverSet receivers_; - mojo::RemoteSet observers_; - BitstreamAudioCodecsInfo supported_bitstream_audio_codecs_info_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_APPLICATION_MEDIA_CAPABILITIES_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/application_media_info_manager.cc chromium-132.0.6834.159/chromecast/browser/application_media_info_manager.cc --- chromium-132.0.6834.110/chromecast/browser/application_media_info_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/application_media_info_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,110 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/application_media_info_manager.h" - -#include - -#include "base/logging.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/browser/cast_renderer_block_data.h" -#include "chromecast/browser/cast_session_id_map.h" -#include "content/public/browser/web_contents.h" - -namespace chromecast { -namespace media { -namespace { -void RunGetCastApplicationMediaInfoCallback( - ApplicationMediaInfoManager::GetCastApplicationMediaInfoCallback callback, - const std::string& session_id, - bool mixer_audio_enabled, - bool is_audio_only_session) { - std::move(callback).Run(::media::mojom::CastApplicationMediaInfo::New( - session_id, mixer_audio_enabled, is_audio_only_session)); -} -} // namespace - -void ApplicationMediaInfoManager::Create( - content::RenderFrameHost* render_frame_host, - std::string application_session_id, - bool mixer_audio_enabled, - mojo::PendingReceiver<::media::mojom::CastApplicationMediaInfoManager> - receiver) { - CHECK(render_frame_host); - // The created ApplicationMediaInfoManager will be deleted on connection - // error, or when the frame navigates away. See DocumentService for - // details. - new ApplicationMediaInfoManager(*render_frame_host, std::move(receiver), - std::move(application_session_id), - mixer_audio_enabled); -} - -ApplicationMediaInfoManager& ApplicationMediaInfoManager::CreateForTesting( - content::RenderFrameHost& render_frame_host, - std::string application_session_id, - bool mixer_audio_enabled, - mojo::PendingReceiver<::media::mojom::CastApplicationMediaInfoManager> - receiver) { - return *new ApplicationMediaInfoManager( - render_frame_host, std::move(receiver), std::move(application_session_id), - mixer_audio_enabled); -} - -ApplicationMediaInfoManager::ApplicationMediaInfoManager( - content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver<::media::mojom::CastApplicationMediaInfoManager> - receiver, - std::string application_session_id, - bool mixer_audio_enabled) - : DocumentService(render_frame_host, std::move(receiver)), - application_session_id_(std::move(application_session_id)), - mixer_audio_enabled_(mixer_audio_enabled), - renderer_blocked_(false) { - shell::CastRendererBlockData::SetApplicationMediaInfoManagerForWebContents( - content::WebContents::FromRenderFrameHost(&render_frame_host), - weak_ptr_factory_.GetWeakPtr()); -} - -ApplicationMediaInfoManager::~ApplicationMediaInfoManager() = default; - -void ApplicationMediaInfoManager::SetRendererBlock(bool renderer_blocked) { - LOG(INFO) << "Setting blocked to: " << renderer_blocked << " from " - << renderer_blocked_ - << "(Pending call set: " << (!pending_call_.is_null()) << ")"; - if (renderer_blocked_ && !renderer_blocked && pending_call_) { - shell::CastSessionIdMap::GetInstance()->IsAudioOnlySessionAsync( - application_session_id_, - base::BindOnce(&RunGetCastApplicationMediaInfoCallback, - // Move callbacks in case CanStartRenderer() is called. - std::move(pending_call_), application_session_id_, - mixer_audio_enabled_)); - pending_call_.Reset(); - } - - renderer_blocked_ = renderer_blocked; -} - -void ApplicationMediaInfoManager::GetCastApplicationMediaInfo( - GetCastApplicationMediaInfoCallback callback) { - LOG(INFO) << "GetCastApplicationMediaInfo called with blocked: " - << renderer_blocked_; - - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEventWithValue( - "Cast.Platform.CastRenderer.MediaReady", renderer_blocked_); - - if (renderer_blocked_) { - DCHECK(!pending_call_); - pending_call_ = std::move(callback); - return; - } - - shell::CastSessionIdMap::GetInstance()->IsAudioOnlySessionAsync( - application_session_id_, - base::BindOnce(&RunGetCastApplicationMediaInfoCallback, - std::move(callback), application_session_id_, - mixer_audio_enabled_)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/application_media_info_manager.h chromium-132.0.6834.159/chromecast/browser/application_media_info_manager.h --- chromium-132.0.6834.110/chromecast/browser/application_media_info_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/application_media_info_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_APPLICATION_MEDIA_INFO_MANAGER_H_ -#define CHROMECAST_BROWSER_APPLICATION_MEDIA_INFO_MANAGER_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "content/public/browser/document_service.h" -#include "media/mojo/mojom/cast_application_media_info_manager.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" - -namespace content { -class RenderFrameHost; -} // namespace content - -namespace chromecast { -namespace media { - -class ApplicationMediaInfoManagerTest; - -class ApplicationMediaInfoManager final - : public ::content::DocumentService< - ::media::mojom::CastApplicationMediaInfoManager> { - public: - static void Create( - content::RenderFrameHost* render_frame_host, - std::string application_session_id, - bool mixer_audio_enabled, - mojo::PendingReceiver<::media::mojom::CastApplicationMediaInfoManager> - receiver); - static ApplicationMediaInfoManager& CreateForTesting( - content::RenderFrameHost& render_frame_host, - std::string application_session_id, - bool mixer_audio_enabled, - mojo::PendingReceiver<::media::mojom::CastApplicationMediaInfoManager> - receiver); - - ApplicationMediaInfoManager(const ApplicationMediaInfoManager&) = delete; - ApplicationMediaInfoManager& operator=(const ApplicationMediaInfoManager&) = - delete; - - void SetRendererBlock(bool renderer_blocked); - - private: - friend ApplicationMediaInfoManagerTest; - - ApplicationMediaInfoManager( - content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver<::media::mojom::CastApplicationMediaInfoManager> - receiver, - std::string application_session_id, - bool mixer_audio_enabled); - ~ApplicationMediaInfoManager() override; - - // ::media::mojom::CastApplicationMediaInfoManager implementation: - void GetCastApplicationMediaInfo( - GetCastApplicationMediaInfoCallback callback) final; - - GetCastApplicationMediaInfoCallback pending_call_; - const std::string application_session_id_; - bool mixer_audio_enabled_; - // Flag to determine if renderer can start. - bool renderer_blocked_; - base::WeakPtrFactory weak_ptr_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_APPLICATION_MEDIA_INFO_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/application_media_info_manager_unittest.cc chromium-132.0.6834.159/chromecast/browser/application_media_info_manager_unittest.cc --- chromium-132.0.6834.110/chromecast/browser/application_media_info_manager_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/application_media_info_manager_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/application_media_info_manager.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/browser/cast_session_id_map.h" -#include "content/public/test/test_content_client_initializer.h" -#include "content/public/test/test_renderer_host.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -using ::testing::_; -using ::testing::Invoke; - -namespace { - -const char kSessionId[] = "test-session-id"; -constexpr bool kMixedAudioEnabled = true; - -} // namespace - -class ApplicationMediaInfoManagerTest - : public content::RenderViewHostTestHarness { - public: - ApplicationMediaInfoManagerTest() : started_(false) {} - ~ApplicationMediaInfoManagerTest() override {} - - void SetUp() override { - initializer_ = std::make_unique(); - content::RenderViewHostTestHarness::SetUp(); - shell::CastSessionIdMap::GetInstance( - base::SequencedTaskRunner::GetCurrentDefault().get()); - application_media_info_manager_ = - &ApplicationMediaInfoManager::CreateForTesting( - *main_rfh(), kSessionId, kMixedAudioEnabled, - application_media_info_manager_remote_ - .BindNewPipeAndPassReceiver()); - } - - void OnCastApplicationMediaInfo( - ::media::mojom::CastApplicationMediaInfoPtr ptr) { - EXPECT_EQ(ptr->application_session_id, kSessionId); - EXPECT_EQ(ptr->mixer_audio_enabled, kMixedAudioEnabled); - started_ = true; - } - - mojo::Remote<::media::mojom::CastApplicationMediaInfoManager> - application_media_info_manager_remote_; - std::unique_ptr initializer_; - // `ApplicationMediaInfoManager` is a `DocumentService` and manages its - // own lifetime. - ApplicationMediaInfoManager* application_media_info_manager_; - bool started_; -}; - -TEST_F(ApplicationMediaInfoManagerTest, NoBlock_GetMediaInfo) { - application_media_info_manager_remote_->GetCastApplicationMediaInfo( - base::BindOnce( - &ApplicationMediaInfoManagerTest::OnCastApplicationMediaInfo, - base::Unretained(this))); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(started_); -} - -TEST_F(ApplicationMediaInfoManagerTest, Block_GetMediaInfo_Unblock) { - application_media_info_manager_->SetRendererBlock(true); - base::RunLoop().RunUntilIdle(); - application_media_info_manager_remote_->GetCastApplicationMediaInfo( - base::BindOnce( - &ApplicationMediaInfoManagerTest::OnCastApplicationMediaInfo, - base::Unretained(this))); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(started_); - application_media_info_manager_->SetRendererBlock(false); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(started_); -} - -TEST_F(ApplicationMediaInfoManagerTest, Block_Unblock_GetMediaInfo) { - application_media_info_manager_->SetRendererBlock(true); - base::RunLoop().RunUntilIdle(); - application_media_info_manager_->SetRendererBlock(false); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(started_); - application_media_info_manager_remote_->GetCastApplicationMediaInfo( - base::BindOnce( - &ApplicationMediaInfoManagerTest::OnCastApplicationMediaInfo, - base::Unretained(this))); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(started_); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/audio_socket_broker.cc chromium-132.0.6834.159/chromecast/browser/audio_socket_broker.cc --- chromium-132.0.6834.110/chromecast/browser/audio_socket_broker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/audio_socket_broker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,193 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/audio_socket_broker.h" - -#include -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/posix/unix_domain_socket.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "base/timer/timer.h" -#include "chromecast/media/audio/audio_io_thread.h" -#include "chromecast/media/audio/audio_output_service/constants.h" -#include "chromecast/net/socket_util.h" -#include "mojo/public/cpp/platform/platform_handle.h" -#include "net/base/net_errors.h" -#include "net/socket/unix_domain_client_socket_posix.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr base::TimeDelta kConnectTimeout = base::Seconds(1); -constexpr char kSocketMsg[] = "socket-handle"; - -} // namespace - -// Helper class for sending the socket descriptors to the audio output service. -class AudioSocketBroker::SocketFdConnection { - public: - SocketFdConnection(AudioSocketBroker* socket_broker, - base::ScopedFD connect_socket_fd, - base::ScopedFD pending_socket_fd, - const std::string& audio_output_service_path, - base::OnceCallback connect_callback) - : socket_broker_(socket_broker), - socket_fd_(std::move(connect_socket_fd)), - pending_socket_fd_(std::move(pending_socket_fd)), - connect_callback_(std::move(connect_callback)) { - DCHECK(socket_broker_); - DCHECK(socket_fd_.is_valid()); - DCHECK(pending_socket_fd_.is_valid()); - DCHECK(connect_callback_); - connecting_socket_ = std::make_unique( - audio_output_service_path, true); - } - SocketFdConnection(const SocketFdConnection&) = delete; - SocketFdConnection& operator=(const SocketFdConnection&) = delete; - ~SocketFdConnection() = default; - - void Connect() { - DCHECK(connecting_socket_); - int result = connecting_socket_->Connect(base::BindOnce( - &SocketFdConnection::OnConnected, base::Unretained(this))); - if (result != net::ERR_IO_PENDING) { - OnConnected(result); - return; - } - - connection_timeout_.Start(FROM_HERE, kConnectTimeout, this, - &SocketFdConnection::ConnectTimeout); - } - - private: - void OnConnected(int result) { - if (result != net::OK || - !base::UnixDomainSocket::SendMsg( - connecting_socket_->ReleaseConnectedSocket(), kSocketMsg, - sizeof(kSocketMsg), {socket_fd_.get()})) { - std::move(connect_callback_).Run(base::ScopedFD()); - return; - } - connecting_socket_.reset(); - std::move(connect_callback_).Run(std::move(pending_socket_fd_)); - } - - void ConnectTimeout() { - LOG(ERROR) << "Timed out connecting to audio output service"; - OnConnected(net::ERR_TIMED_OUT); - } - - AudioSocketBroker* const socket_broker_; - base::ScopedFD socket_fd_; - base::ScopedFD pending_socket_fd_; - base::OnceCallback connect_callback_; - std::unique_ptr connecting_socket_; - base::OneShotTimer connection_timeout_; -}; - -AudioSocketBroker::PendingConnectionInfo::PendingConnectionInfo( - base::SequenceBound arg_socket_fd_connection, - GetSocketDescriptorCallback arg_callback) - : socket_fd_connection(std::move(arg_socket_fd_connection)), - callback(std::move(arg_callback)) {} - -AudioSocketBroker::PendingConnectionInfo::PendingConnectionInfo( - PendingConnectionInfo&&) = default; -AudioSocketBroker::PendingConnectionInfo& -AudioSocketBroker::PendingConnectionInfo::operator=(PendingConnectionInfo&&) = - default; - -AudioSocketBroker::PendingConnectionInfo::~PendingConnectionInfo() = default; - -void AudioSocketBroker::Create( - content::RenderFrameHost* render_frame_host, - mojo::PendingReceiver receiver) { - CHECK(render_frame_host); - // Lifecycle managed by content::DocumentService. - new AudioSocketBroker(*render_frame_host, std::move(receiver)); -} - -AudioSocketBroker& AudioSocketBroker::CreateForTesting( - content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver receiver, - const std::string& audio_output_service_path) { - return *new AudioSocketBroker(render_frame_host, std::move(receiver), - audio_output_service_path); -} - -AudioSocketBroker::AudioSocketBroker( - content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver receiver) - : AudioSocketBroker(render_frame_host, - std::move(receiver), - audio_output_service:: - kDefaultAudioOutputServiceUnixDomainSocketPath) {} - -AudioSocketBroker::AudioSocketBroker( - content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver receiver, - const std::string& audio_output_service_path) - : DocumentService(render_frame_host, std::move(receiver)), - audio_output_service_path_(audio_output_service_path), - main_task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) {} - -AudioSocketBroker::~AudioSocketBroker() = default; - -void AudioSocketBroker::GetSocketDescriptor( - GetSocketDescriptorCallback callback) { - base::ScopedFD socket_fd1, socket_fd2; - if (!CreateUnnamedSocketPair(&socket_fd1, &socket_fd2)) { - std::move(callback).Run(mojo::PlatformHandle(base::ScopedFD())); - return; - } - - // Send one socket descriptor to audio output service first, and then the - // other to the client in the renderer. - int sock_fd1 = socket_fd1.get(); - auto socket_fd_connection = base::SequenceBound( - AudioIoThread::Get()->task_runner(), this, std::move(socket_fd2), - std::move(socket_fd1), audio_output_service_path_, - base::BindPostTask( - main_task_runner_, - base::BindOnce(&AudioSocketBroker::OnSocketHandleSentToAudioService, - weak_factory_.GetWeakPtr(), sock_fd1))); - auto result = pending_connection_infos_.emplace( - sock_fd1, PendingConnectionInfo(std::move(socket_fd_connection), - std::move(callback))); - DCHECK(result.second); - result.first->second.socket_fd_connection.AsyncCall( - &SocketFdConnection::Connect); -} - -void AudioSocketBroker::OnSocketHandleSentToAudioService( - int socket_fd, - base::ScopedFD pending_socket_fd) { - DCHECK(main_task_runner_->RunsTasksInCurrentSequence()); - - auto it = pending_connection_infos_.find(socket_fd); - if (it == pending_connection_infos_.end()) { - LOG(ERROR) << "Cannot find connection: " << socket_fd; - return; - } - - DCHECK(it->second.callback); - - // Now that one descriptor is sent to the audio output service, send the other - // descriptor back to the client. - std::move(it->second.callback) - .Run(mojo::PlatformHandle(std::move(pending_socket_fd))); - pending_connection_infos_.erase(it); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/audio_socket_broker.h chromium-132.0.6834.159/chromecast/browser/audio_socket_broker.h --- chromium-132.0.6834.110/chromecast/browser/audio_socket_broker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/audio_socket_broker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,93 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_AUDIO_SOCKET_BROKER_H_ -#define CHROMECAST_BROWSER_AUDIO_SOCKET_BROKER_H_ - -#include - -#include "base/containers/flat_map.h" -#include "base/files/scoped_file.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/sequence_bound.h" -#include "chromecast/common/mojom/audio_socket.mojom.h" -#include "content/public/browser/document_service.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace net { -class UnixDomainClientSocket; -} // namespace net - -namespace chromecast { -namespace media { - -// Service hosted in the browser process to provide the descriptors of connected -// Unix Domain sockets for renderers and the audio output service. This service -// is necessary since renderers are not allowed to perform socket operations on -// some platforms (e.g. Android). -class AudioSocketBroker - : public ::content::DocumentService { - public: - static void Create(content::RenderFrameHost* render_frame_host, - mojo::PendingReceiver receiver); - static AudioSocketBroker& CreateForTesting( - content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver receiver, - const std::string& audio_output_service_path); - AudioSocketBroker(const AudioSocketBroker&) = delete; - AudioSocketBroker& operator=(const AudioSocketBroker&) = delete; - - private: - class SocketFdConnection; - - AudioSocketBroker(content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver receiver); - AudioSocketBroker(content::RenderFrameHost& render_frame_host, - mojo::PendingReceiver receiver, - const std::string& audio_output_service_path); - ~AudioSocketBroker() override; - - // Helper struct which holds the information regarding a socket pair - // in the time between sending the socket to the renderer and the audio - // service. - struct PendingConnectionInfo { - PendingConnectionInfo( - base::SequenceBound arg_socket_fd_connection, - GetSocketDescriptorCallback arg_callback); - PendingConnectionInfo(const PendingConnectionInfo&) = delete; - PendingConnectionInfo& operator=(const PendingConnectionInfo&) = delete; - PendingConnectionInfo(PendingConnectionInfo&&); - PendingConnectionInfo& operator=(PendingConnectionInfo&&); - ~PendingConnectionInfo(); - - base::SequenceBound socket_fd_connection; - GetSocketDescriptorCallback callback; - }; - - // mojom::AudioSocketBroker implementation: - void GetSocketDescriptor(GetSocketDescriptorCallback callback) override; - - // Callback triggered when the socket handle is sent to the audio output - // service. |socket_fd| is the key to |pending_connection_infos_|. - // |pending_socket_fd| is invalid when connection fails. - void OnSocketHandleSentToAudioService(int socket_fd, - base::ScopedFD pending_socket_fd); - - const std::string audio_output_service_path_; - scoped_refptr main_task_runner_; - base::flat_map - pending_connection_infos_; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_AUDIO_SOCKET_BROKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/audio_socket_broker_unittest.cc chromium-132.0.6834.159/chromecast/browser/audio_socket_broker_unittest.cc --- chromium-132.0.6834.110/chromecast/browser/audio_socket_broker_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/audio_socket_broker_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,162 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/audio_socket_broker.h" - -#include -#include - -#include -#include -#include -#include - -#include "base/files/scoped_temp_dir.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/posix/eintr_wrapper.h" -#include "base/posix/unix_domain_socket.h" -#include "base/run_loop.h" -#include "base/synchronization/waitable_event.h" -#include "base/threading/thread.h" -#include "chromecast/net/socket_util.h" -#include "content/public/test/test_content_client_initializer.h" -#include "content/public/test/test_renderer_host.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "net/base/net_errors.h" -#include "net/socket/stream_socket.h" -#include "net/socket/unix_domain_server_socket_posix.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr char kTestSocket[] = "test.socket"; -constexpr char kSocketMsg[] = "socket-handle"; -constexpr int kListenBacklog = 1; - -} // namespace - -class AudioSocketBrokerTest : public content::RenderViewHostTestHarness { - public: - AudioSocketBrokerTest() = default; - ~AudioSocketBrokerTest() override { - if (io_thread_) { - io_thread_->task_runner()->DeleteSoon(FROM_HERE, - std::move(accepted_socket_)); - io_thread_->task_runner()->DeleteSoon(FROM_HERE, - std::move(listen_socket_)); - } - } - - void SetUp() override { - ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); - socket_path_ = test_dir_.GetPath().Append(kTestSocket).value(); - initializer_ = std::make_unique(); - content::RenderViewHostTestHarness::SetUp(); - audio_socket_broker_ = &AudioSocketBroker::CreateForTesting( - *main_rfh(), audio_socket_broker_remote_.BindNewPipeAndPassReceiver(), - socket_path_); - } - - void SetupServerSocket() { - base::WaitableEvent server_setup_finished; - io_thread_ = std::make_unique("test_io_thread"); - io_thread_->StartWithOptions( - base::Thread::Options(base::MessagePumpType::IO, 0)); - io_thread_->task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&AudioSocketBrokerTest::SetupServerSocketOnIoThread, - base::Unretained(this), &server_setup_finished)); - server_setup_finished.Wait(); - } - - void SetupServerSocketOnIoThread(base::WaitableEvent* server_setup_finished) { - auto unix_socket = std::make_unique( - base::BindRepeating( - [](const net::UnixDomainServerSocket::Credentials&) { - // Always accept the connection. - return true; - }), - /*use_abstract_namespace=*/true); - int result = unix_socket->BindAndListen(socket_path_, kListenBacklog); - EXPECT_EQ(result, net::OK); - listen_socket_ = std::move(unix_socket); - listen_socket_->AcceptSocketDescriptor( - &accepted_descriptor_, - base::BindRepeating(&AudioSocketBrokerTest::OnAccept, - base::Unretained(this))); - server_setup_finished->Signal(); - } - - void OnAccept(int result) { - EXPECT_EQ(result, net::OK); - char buffer[16]; - std::vector fds; - const int flags = fcntl(accepted_descriptor_, F_GETFL); - ASSERT_NE( - HANDLE_EINTR(fcntl(accepted_descriptor_, F_SETFL, flags & ~O_NONBLOCK)), - -1); - EXPECT_EQ(static_cast(base::UnixDomainSocket::RecvMsg( - accepted_descriptor_, buffer, sizeof(buffer), &fds)), - sizeof(kSocketMsg)); - EXPECT_EQ(memcmp(buffer, kSocketMsg, sizeof(kSocketMsg)), 0); - EXPECT_THAT(fds, ::testing::SizeIs(1U)); - accepted_socket_ = AdoptUnnamedSocketHandle(std::move(fds[0])); - } - - void OnSocketDescriptor(bool expect_success, mojo::PlatformHandle handle) { - EXPECT_EQ(handle.is_valid_fd(), expect_success); - descriptor_received_ = true; - if (expect_success) { - auto stream_socket = AdoptUnnamedSocketHandle(handle.TakeFD()); - EXPECT_TRUE(stream_socket->IsConnected()); - } - run_loop_.Quit(); - } - - void RunThreadsUntilIdle() { - run_loop_.Run(); - task_environment()->RunUntilIdle(); - } - - protected: - mojo::Remote audio_socket_broker_remote_; - base::ScopedTempDir test_dir_; - std::string socket_path_; - std::unique_ptr initializer_; - // `AudioSocketBroker` is a `DocumentService` which manages its own - // lifecycle. - AudioSocketBroker* audio_socket_broker_ = nullptr; - bool descriptor_received_ = false; - base::RunLoop run_loop_; - - std::unique_ptr io_thread_; - std::unique_ptr listen_socket_; - net::SocketDescriptor accepted_descriptor_; - std::unique_ptr accepted_socket_; -}; - -TEST_F(AudioSocketBrokerTest, ValidSocketHandle) { - SetupServerSocket(); - audio_socket_broker_remote_->GetSocketDescriptor( - base::BindOnce(&AudioSocketBrokerTest::OnSocketDescriptor, - base::Unretained(this), true)); - RunThreadsUntilIdle(); - EXPECT_TRUE(descriptor_received_); -} - -TEST_F(AudioSocketBrokerTest, InvalidSocketHandle) { - audio_socket_broker_remote_->GetSocketDescriptor( - base::BindOnce(&AudioSocketBrokerTest::OnSocketDescriptor, - base::Unretained(this), false)); - RunThreadsUntilIdle(); - EXPECT_TRUE(descriptor_received_); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/bluetooth/cast_bluetooth_chooser.cc chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser.cc --- chromium-132.0.6834.110/chromecast/browser/bluetooth/cast_bluetooth_chooser.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/bluetooth/cast_bluetooth_chooser.h" - -#include "base/containers/contains.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { - -CastBluetoothChooser::CastBluetoothChooser( - content::BluetoothChooser::EventHandler event_handler, - mojo::PendingRemote pending_provider) - : event_handler_(std::move(event_handler)) { - DCHECK(event_handler_); - mojo::Remote provider( - std::move(pending_provider)); - provider->RequestDeviceAccess(receiver_.BindNewPipeAndPassRemote()); - receiver_.set_disconnect_handler(base::BindOnce( - &CastBluetoothChooser::OnClientConnectionError, base::Unretained(this))); -} - -CastBluetoothChooser::~CastBluetoothChooser() = default; - -void CastBluetoothChooser::GrantAccess(const std::string& address) { - DCHECK(event_handler_); - - if (all_devices_approved_) { - LOG(WARNING) << __func__ << " called after access granted to all devices!"; - return; - } - - if (base::Contains(available_devices_, address)) { - RunEventHandlerAndResetReceiver(content::BluetoothChooserEvent::SELECTED, - address); - return; - } - approved_devices_.insert(address); -} - -void CastBluetoothChooser::GrantAccessToAllDevices() { - DCHECK(event_handler_); - - all_devices_approved_ = true; - if (!available_devices_.empty()) { - RunEventHandlerAndResetReceiver(content::BluetoothChooserEvent::SELECTED, - *available_devices_.begin()); - } -} - -void CastBluetoothChooser::AddOrUpdateDevice(const std::string& device_id, - bool should_update_name, - const std::u16string& device_name, - bool is_gatt_connected, - bool is_paired, - int signal_strength_level) { - DCHECK(event_handler_); - - // Note: |device_id| is just a canonical Bluetooth address. - if (all_devices_approved_ || base::Contains(approved_devices_, device_id)) { - RunEventHandlerAndResetReceiver(content::BluetoothChooserEvent::SELECTED, - device_id); - return; - } - available_devices_.insert(device_id); -} - -void CastBluetoothChooser::RunEventHandlerAndResetReceiver( - content::BluetoothChooserEvent event, - std::string address) { - DCHECK(event_handler_); - std::move(event_handler_).Run(event, std::move(address)); - receiver_.reset(); -} - -void CastBluetoothChooser::OnClientConnectionError() { - // If the DeviceAccessProvider has granted access to all devices, it may - // tear down the client immediately. In this case, do not run the event - // handler, as we may have not had the opportunity to select a device. - if (!all_devices_approved_ && event_handler_) { - RunEventHandlerAndResetReceiver(content::BluetoothChooserEvent::CANCELLED, - ""); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/bluetooth/cast_bluetooth_chooser.h chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser.h --- chromium-132.0.6834.110/chromecast/browser/bluetooth/cast_bluetooth_chooser.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_BLUETOOTH_CAST_BLUETOOTH_CHOOSER_H_ -#define CHROMECAST_BROWSER_BLUETOOTH_CAST_BLUETOOTH_CHOOSER_H_ - -#include -#include - -#include "chromecast/browser/bluetooth/public/mojom/web_bluetooth.mojom.h" -#include "content/public/browser/bluetooth_chooser.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver.h" - -namespace chromecast { - -// This class requests access from a remote BluetoothDeviceAccessProvider -// implemented by the Activity's host. The host will update this client with -// whitelisted devices via GrantAccess(). Meanwhile, the WebBluetooth stack will -// add devices that match the application's filter via AddOrUpdateDevice(). The -// first device which matches both will be selected. -class CastBluetoothChooser : public content::BluetoothChooser, - public mojom::BluetoothDeviceAccessProviderClient { - public: - // |event_handler| is called when an approved device is discovered, or when - // the |provider| destroys the connection to this client. |this| may destroy - // |provider| immediately after requesting access. - CastBluetoothChooser(content::BluetoothChooser::EventHandler event_handler, - mojo::PendingRemote - pending_provider); - - CastBluetoothChooser(const CastBluetoothChooser&) = delete; - CastBluetoothChooser& operator=(const CastBluetoothChooser&) = delete; - - ~CastBluetoothChooser() override; - - private: - // mojom::BluetoothDeviceAccessProviderClient implementation: - void GrantAccess(const std::string& address) override; - void GrantAccessToAllDevices() override; - - // content::BluetoothChooser implementation: - void AddOrUpdateDevice(const std::string& device_id, - bool should_update_name, - const std::u16string& device_name, - bool is_gatt_connected, - bool is_paired, - int signal_strength_level) override; - - // Runs the event_handler and resets the client receiver. After this is - // called, this class should not be used. - void RunEventHandlerAndResetReceiver(content::BluetoothChooserEvent event, - std::string address); - - // Called when the remote connection held by |receiver_| is torn down. - void OnClientConnectionError(); - - content::BluetoothChooser::EventHandler event_handler_; - mojo::Receiver receiver_{this}; - std::unordered_set available_devices_; - std::unordered_set approved_devices_; - bool all_devices_approved_ = false; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_BLUETOOTH_CAST_BLUETOOTH_CHOOSER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/bluetooth/cast_bluetooth_chooser_unittest.cc chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser_unittest.cc --- chromium-132.0.6834.110/chromecast/browser/bluetooth/cast_bluetooth_chooser_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/bluetooth/cast_bluetooth_chooser_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,186 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/bluetooth/cast_bluetooth_chooser.h" - -#include "base/test/mock_callback.h" -#include "base/test/task_environment.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -class SimpleDeviceAccessProvider : public mojom::BluetoothDeviceAccessProvider { - public: - SimpleDeviceAccessProvider() = default; - - SimpleDeviceAccessProvider(const SimpleDeviceAccessProvider&) = delete; - SimpleDeviceAccessProvider& operator=(const SimpleDeviceAccessProvider&) = - delete; - - ~SimpleDeviceAccessProvider() override = default; - - // mojom::BluetoothDeviceAccessProvider implementation: - void RequestDeviceAccess( - mojo::PendingRemote client) - override { - DCHECK(!client_); - client_.Bind(std::move(client)); - client_.set_disconnect_handler(connection_closed_.Get()); - for (const auto& address : approved_devices_) - client_->GrantAccess(address); - } - - mojom::BluetoothDeviceAccessProviderClient* client() { - return client_ ? client_.get() : nullptr; - } - void reset_client() { return client_.reset(); } - base::MockCallback& connection_closed() { - return connection_closed_; - } - std::vector& approved_devices() { return approved_devices_; } - - private: - mojo::Remote client_; - base::MockCallback connection_closed_; - std::vector approved_devices_; -}; - -} // namespace - -using testing::AnyOf; - -class CastBluetoothChooserTest : public testing::Test { - public: - CastBluetoothChooserTest() : provider_receiver_(&provider_) { - cast_bluetooth_chooser_ = std::make_unique( - handler_.Get(), provider_receiver_.BindNewPipeAndPassRemote()); - task_environment_.RunUntilIdle(); - } - - CastBluetoothChooserTest(const CastBluetoothChooserTest&) = delete; - CastBluetoothChooserTest& operator=(const CastBluetoothChooserTest&) = delete; - - ~CastBluetoothChooserTest() override = default; - - void AddDeviceToChooser(const std::string& address) { - chooser().AddOrUpdateDevice(address, false, std::u16string(), false, false, - 0); - } - - SimpleDeviceAccessProvider& provider() { return provider_; } - content::BluetoothChooser& chooser() { return *cast_bluetooth_chooser_; } - - protected: - base::test::TaskEnvironment task_environment_; - base::MockCallback handler_; - - private: - SimpleDeviceAccessProvider provider_; - mojo::Receiver provider_receiver_; - std::unique_ptr cast_bluetooth_chooser_; -}; - -TEST_F(CastBluetoothChooserTest, GrantAccessBeforeDeviceAvailable) { - // No devices have been made available to |chooser| yet. Grant it access to a - // device. |handler| should not run yet. - EXPECT_TRUE(provider().client()); - provider().client()->GrantAccess("aa:bb:cc:dd:ee:ff"); - task_environment_.RunUntilIdle(); - - // Make some unapproved devices available. |handler| should not run yet. - AddDeviceToChooser("11:22:33:44:55:66"); - AddDeviceToChooser("99:88:77:66:55:44"); - - // Now make the approved device available. |handler| should be called. - EXPECT_CALL(handler_, Run(content::BluetoothChooserEvent::SELECTED, - "aa:bb:cc:dd:ee:ff")); - EXPECT_CALL(provider().connection_closed(), Run()); - AddDeviceToChooser("aa:bb:cc:dd:ee:ff"); - task_environment_.RunUntilIdle(); -} - -TEST_F(CastBluetoothChooserTest, DiscoverDeviceBeforeAccessGranted) { - // Make some devices available before access is granted. |handler| should not - // run yet. - AddDeviceToChooser("11:22:33:44:55:66"); - AddDeviceToChooser("aa:bb:cc:dd:ee:ff"); - AddDeviceToChooser("00:00:00:11:00:00"); - AddDeviceToChooser("99:88:77:66:55:44"); - - // Now approve one of those devices. |handler| should run. - EXPECT_CALL(handler_, Run(content::BluetoothChooserEvent::SELECTED, - "00:00:00:11:00:00")); - EXPECT_CALL(provider().connection_closed(), Run()); - provider().client()->GrantAccess("00:00:00:11:00:00"); - task_environment_.RunUntilIdle(); -} - -TEST_F(CastBluetoothChooserTest, GrantAccessToAllDevicesBeforeDiscovery) { - // Grant access to all devices. |handler| should not run until the first - // device is made available. - provider().client()->GrantAccessToAllDevices(); - task_environment_.RunUntilIdle(); - - // Now make the some device available. |handler| should be called. - EXPECT_CALL(handler_, Run(content::BluetoothChooserEvent::SELECTED, - "aa:bb:cc:dd:ee:ff")); - EXPECT_CALL(provider().connection_closed(), Run()); - AddDeviceToChooser("aa:bb:cc:dd:ee:ff"); - task_environment_.RunUntilIdle(); -} - -TEST_F(CastBluetoothChooserTest, GrantAccessToAllDevicesAfterDiscovery) { - // Make some devices available before access is granted. |handler| should not - // run yet. - AddDeviceToChooser("11:22:33:44:55:66"); - AddDeviceToChooser("aa:bb:cc:dd:ee:ff"); - AddDeviceToChooser("00:00:00:11:00:00"); - - // Now grant access to all devices. |handler| should be called with one of the - // available devices. - EXPECT_CALL(handler_, Run(content::BluetoothChooserEvent::SELECTED, - AnyOf("11:22:33:44:55:66", "aa:bb:cc:dd:ee:ff", - "00:00:00:11:00:00"))); - EXPECT_CALL(provider().connection_closed(), Run()); - provider().client()->GrantAccessToAllDevices(); - task_environment_.RunUntilIdle(); -} - -TEST_F(CastBluetoothChooserTest, TearDownClientAfterAllAccessGranted) { - // Grant access to all devices. |handler| should not run until the first - // device is made available. - provider().client()->GrantAccessToAllDevices(); - task_environment_.RunUntilIdle(); - - // Tear down the client. Now that it has granted access to the client, it does - // not need to keep a reference to it. However, the chooser should stay alive - // and wait for devices to be made available. - provider().reset_client(); - EXPECT_FALSE(provider().client()); - task_environment_.RunUntilIdle(); - - // As soon as a device is available, run the handler. - EXPECT_CALL(handler_, Run(content::BluetoothChooserEvent::SELECTED, - "aa:bb:cc:dd:ee:ff")); - AddDeviceToChooser("aa:bb:cc:dd:ee:ff"); -} - -TEST_F(CastBluetoothChooserTest, TearDownClientBeforeApprovedDeviceDiscovered) { - // Make some devices available before access is granted. |handler| should not - // run yet. - AddDeviceToChooser("11:22:33:44:55:66"); - AddDeviceToChooser("aa:bb:cc:dd:ee:ff"); - - // Tear the client down before any access is granted. |handler| should run, - // but with content::BluetoothChooserEvent::CANCELLED. - EXPECT_CALL(handler_, Run(content::BluetoothChooserEvent::CANCELLED, "")); - provider().reset_client(); - EXPECT_FALSE(provider().client()); - task_environment_.RunUntilIdle(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/bluetooth/public/mojom/OWNERS chromium-132.0.6834.159/chromecast/browser/bluetooth/public/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/browser/bluetooth/public/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/bluetooth/public/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/browser/bluetooth/public/mojom/web_bluetooth.mojom chromium-132.0.6834.159/chromecast/browser/bluetooth/public/mojom/web_bluetooth.mojom --- chromium-132.0.6834.110/chromecast/browser/bluetooth/public/mojom/web_bluetooth.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/bluetooth/public/mojom/web_bluetooth.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -// When WebBluetooth is enabled for a Cast Activity, this interface must be -// provided by the Activity's host, which may be running in a remote service. -// This interface is responsible for granting the Activity access to Bluetooth -// devices. -interface BluetoothDeviceAccessProvider { - // Request that the host begin granting |client| access to approved devices. - RequestDeviceAccess( - pending_remote client); -}; - -// The client for BluetoothDeviceAccessProvider, provided by the Activity, -// and passed to the host via RequestDeviceAccess(). -interface BluetoothDeviceAccessProviderClient { - // Grant the Activity access to the device at |address|. This is a Bluetooth - // mac address in canonical format. This method may be invoked multiple times, - // or zero times, during this object's lifetime. - GrantAccess(string address); - - // Grant the Activity access to any device discovered by the WebBluetooth - // stack. GrantAccess() will not be called on this interface after this method - // is called. - GrantAccessToAllDevices(); -}; \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_context.cc chromium-132.0.6834.159/chromecast/browser/cast_browser_context.cc --- chromium-132.0.6834.110/chromecast/browser/cast_browser_context.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_context.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,145 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_browser_context.h" - -#include -#include - -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/path_service.h" -#include "build/build_config.h" -#include "chromecast/base/cast_paths.h" -#include "chromecast/browser/cast_download_manager_delegate.h" -#include "chromecast/browser/cast_permission_manager.h" -#include "components/keyed_service/core/simple_key_map.h" -#include "components/profile_metrics/browser_profile_type.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/storage_partition.h" -#include "content/public/common/content_switches.h" - -namespace chromecast { -namespace shell { - -namespace { -const void* const kDownloadManagerDelegateKey = &kDownloadManagerDelegateKey; -} // namespace - -CastBrowserContext::CastBrowserContext() { - profile_metrics::SetBrowserProfileType( - this, profile_metrics::BrowserProfileType::kRegular); - InitWhileIOAllowed(); - simple_factory_key_ = - std::make_unique(GetPath(), IsOffTheRecord()); - SimpleKeyMap::GetInstance()->Associate(this, simple_factory_key_.get()); -} - -CastBrowserContext::~CastBrowserContext() { - SimpleKeyMap::GetInstance()->Dissociate(this); - NotifyWillBeDestroyed(); - ShutdownStoragePartitions(); -} - -void CastBrowserContext::InitWhileIOAllowed() { -#if BUILDFLAG(IS_ANDROID) - CHECK(base::PathService::Get(base::DIR_ANDROID_APP_DATA, &path_)); - path_ = path_.Append(FILE_PATH_LITERAL("cast_shell")); - - if (!base::PathExists(path_)) - base::CreateDirectory(path_); -#else - // Chromecast doesn't support user profiles nor does it have - // incognito mode. This means that all of the persistent - // data (currently only cookies and local storage) will be - // shared in a single location as defined here. - CHECK(base::PathService::Get(DIR_CAST_HOME, &path_)); -#endif // BUILDFLAG(IS_ANDROID) -} - -std::unique_ptr -CastBrowserContext::CreateZoomLevelDelegate( - const base::FilePath& partition_path) { - return nullptr; -} - -base::FilePath CastBrowserContext::GetPath() { - return path_; -} - -bool CastBrowserContext::IsOffTheRecord() { - return false; -} - -content::DownloadManagerDelegate* -CastBrowserContext::GetDownloadManagerDelegate() { - if (!GetUserData(kDownloadManagerDelegateKey)) { - SetUserData(kDownloadManagerDelegateKey, - std::make_unique()); - } - return static_cast( - GetUserData(kDownloadManagerDelegateKey)); -} - -content::BrowserPluginGuestManager* CastBrowserContext::GetGuestManager() { - return nullptr; -} - -storage::SpecialStoragePolicy* CastBrowserContext::GetSpecialStoragePolicy() { - return nullptr; -} - -content::PlatformNotificationService* -CastBrowserContext::GetPlatformNotificationService() { - return nullptr; -} - -content::PushMessagingService* CastBrowserContext::GetPushMessagingService() { - return nullptr; -} - -content::StorageNotificationService* -CastBrowserContext::GetStorageNotificationService() { - return nullptr; -} - -content::SSLHostStateDelegate* CastBrowserContext::GetSSLHostStateDelegate() { - return nullptr; -} - -content::PermissionControllerDelegate* -CastBrowserContext::GetPermissionControllerDelegate() { - if (!permission_manager_.get()) - permission_manager_.reset(new CastPermissionManager()); - return permission_manager_.get(); -} - -content::ClientHintsControllerDelegate* -CastBrowserContext::GetClientHintsControllerDelegate() { - return nullptr; -} - -content::BackgroundFetchDelegate* -CastBrowserContext::GetBackgroundFetchDelegate() { - return nullptr; -} - -content::BackgroundSyncController* -CastBrowserContext::GetBackgroundSyncController() { - return nullptr; -} - -content::BrowsingDataRemoverDelegate* -CastBrowserContext::GetBrowsingDataRemoverDelegate() { - return nullptr; -} - -content::ReduceAcceptLanguageControllerDelegate* -CastBrowserContext::GetReduceAcceptLanguageControllerDelegate() { - return nullptr; -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_context.h chromium-132.0.6834.159/chromecast/browser/cast_browser_context.h --- chromium-132.0.6834.110/chromecast/browser/cast_browser_context.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_context.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_BROWSER_CONTEXT_H_ -#define CHROMECAST_BROWSER_CAST_BROWSER_CONTEXT_H_ - -#include - -#include "base/files/file_path.h" -#include "components/keyed_service/core/simple_factory_key.h" -#include "content/public/browser/browser_context.h" - -namespace chromecast { -namespace shell { - -// Chromecast does not currently support multiple profiles. So there is a -// single BrowserContext for all chromecast renderers. -// There is no support for PartitionStorage. -class CastBrowserContext final : public content::BrowserContext { - public: - CastBrowserContext(); - - CastBrowserContext(const CastBrowserContext&) = delete; - CastBrowserContext& operator=(const CastBrowserContext&) = delete; - - ~CastBrowserContext() override; - - // BrowserContext implementation: - std::unique_ptr CreateZoomLevelDelegate( - const base::FilePath& partition_path) override; - base::FilePath GetPath() override; - bool IsOffTheRecord() override; - content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; - content::BrowserPluginGuestManager* GetGuestManager() override; - storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override; - content::PlatformNotificationService* GetPlatformNotificationService() - override; - content::PushMessagingService* GetPushMessagingService() override; - content::StorageNotificationService* GetStorageNotificationService() override; - content::SSLHostStateDelegate* GetSSLHostStateDelegate() override; - content::PermissionControllerDelegate* GetPermissionControllerDelegate() - override; - content::ClientHintsControllerDelegate* GetClientHintsControllerDelegate() - override; - content::BackgroundFetchDelegate* GetBackgroundFetchDelegate() override; - content::BackgroundSyncController* GetBackgroundSyncController() override; - content::BrowsingDataRemoverDelegate* GetBrowsingDataRemoverDelegate() - override; - content::ReduceAcceptLanguageControllerDelegate* - GetReduceAcceptLanguageControllerDelegate() override; - - private: - // Performs initialization of the CastBrowserContext while IO is still - // allowed on the current thread. - void InitWhileIOAllowed(); - - base::FilePath path_; - std::unique_ptr permission_manager_; - std::unique_ptr simple_factory_key_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_BROWSER_CONTEXT_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_interface_binders.cc chromium-132.0.6834.159/chromecast/browser/cast_browser_interface_binders.cc --- chromium-132.0.6834.110/chromecast/browser/cast_browser_interface_binders.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_interface_binders.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,139 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_browser_interface_binders.h" - -#include "base/functional/bind.h" -#include "chromecast/browser/application_media_capabilities.h" -#include "chromecast/browser/application_media_info_manager.h" -#include "chromecast/browser/audio_socket_broker.h" -#include "chromecast/browser/cast_navigation_ui_data.h" -#include "chromecast/browser/cast_web_contents.h" -#include "chromecast/common/mojom/activity_window.mojom.h" -#include "chromecast/common/mojom/application_media_capabilities.mojom.h" -#include "chromecast/common/mojom/assistant_messenger.mojom.h" -#include "chromecast/common/mojom/audio_socket.mojom.h" -#include "chromecast/common/mojom/cast_demo.mojom.h" -#include "chromecast/common/mojom/gesture.mojom.h" -#include "chromecast/common/mojom/settings_ui.mojom.h" -#include "components/network_hints/browser/simple_network_hints_handler_impl.h" -#include "components/network_hints/common/network_hints.mojom.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/web_contents.h" -#include "media/mojo/mojom/cast_application_media_info_manager.mojom.h" -#include "media/mojo/mojom/remoting.mojom.h" - -namespace chromecast { -namespace shell { - -namespace { - -void BindNetworkHintsHandler( - content::RenderFrameHost* frame_host, - mojo::PendingReceiver receiver) { - network_hints::SimpleNetworkHintsHandlerImpl::Create(frame_host, - std::move(receiver)); -} - -template -void BindFromCastWebContents(content::RenderFrameHost* frame_host, - mojo::PendingReceiver receiver) { - auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host); - if (!web_contents) - return; - auto* cast_web_contents = CastWebContents::FromWebContents(web_contents); - if (!cast_web_contents) - return; - mojo::GenericPendingReceiver generic_receiver(std::move(receiver)); - cast_web_contents->TryBindReceiver(generic_receiver); -} - -void BindApplicationMediaInfoManager( - content::RenderFrameHost* frame_host, - mojo::PendingReceiver<::media::mojom::CastApplicationMediaInfoManager> - receiver) { - auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host); - if (!web_contents) { - return; - } - auto application_session_id = - CastNavigationUIData::GetSessionIdForWebContents(web_contents); - media::ApplicationMediaInfoManager::Create( - frame_host, std::move(application_session_id), - /*mixer_audio_enabled=*/false, std::move(receiver)); -} - -void BindAudioSocketBroker( - content::RenderFrameHost* frame_host, - mojo::PendingReceiver<::chromecast::mojom::AudioSocketBroker> receiver) { - media::AudioSocketBroker::Create(frame_host, std::move(receiver)); -} - -// Some Cast internals still dynamically set up interface binders after -// frame host initialization. This is used to generically forward incoming -// interface receivers to those objects until they can be reworked as static -// registrations below. -bool HandleGenericReceiver(content::RenderFrameHost* frame_host, - mojo::GenericPendingReceiver& receiver) { - // All of the following error scenarios will intentionally crash the render - // process as a security precaution. On Cast, the errors below are generally - // safe since the interface endpoints don't expose sensitive functionality. - // TODO(b/185843831): Just return true in all cases to prevent the crash. - auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host); - if (!web_contents) { - LOG(ERROR) << "Could not find target WebContents for receiver."; - return false; - } - - // Only WebContents created for Cast Webviews will have a CastWebContents - // object associated with them. We ignore these requests for any other - // WebContents. - auto* cast_web_contents = CastWebContents::FromWebContents(web_contents); - if (!cast_web_contents) { - LOG(ERROR) << "Could not find target CastWebContents for receiver."; - return false; - } - - if (!cast_web_contents->TryBindReceiver(receiver)) { - LOG(ERROR) << "Attempt to bind receiver to CastWebContents failed."; - return false; - } - - return true; -} - -} // namespace - -void PopulateCastFrameBinders( - content::RenderFrameHost* render_frame_host, - mojo::BinderMapWithContext* binder_map) { - binder_map->Add( - base::BindRepeating(&BindNetworkHintsHandler)); - binder_map->Add<::media::mojom::CastApplicationMediaInfoManager>( - base::BindRepeating(&BindApplicationMediaInfoManager)); - binder_map->Add<::chromecast::mojom::AudioSocketBroker>( - base::BindRepeating(&BindAudioSocketBroker)); - - binder_map->Add(base::BindRepeating( - &BindFromCastWebContents)); - binder_map->Add<::media::mojom::Remotee>( - base::BindRepeating(&BindFromCastWebContents<::media::mojom::Remotee>)); - binder_map->Add<::chromecast::mojom::ActivityWindow>(base::BindRepeating( - &BindFromCastWebContents<::chromecast::mojom::ActivityWindow>)); - binder_map->Add< - ::chromecast::mojom::AssistantMessageService>(base::BindRepeating( - &BindFromCastWebContents<::chromecast::mojom::AssistantMessageService>)); - binder_map->Add<::chromecast::mojom::GestureSource>(base::BindRepeating( - &BindFromCastWebContents<::chromecast::mojom::GestureSource>)); - binder_map->Add<::chromecast::mojom::SettingsPlatform>(base::BindRepeating( - &BindFromCastWebContents<::chromecast::mojom::SettingsPlatform>)); - binder_map->Add( - base::BindRepeating(&BindFromCastWebContents)); - - binder_map->SetDefaultBinderDeprecated( - base::BindRepeating(&HandleGenericReceiver)); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_interface_binders.h chromium-132.0.6834.159/chromecast/browser/cast_browser_interface_binders.h --- chromium-132.0.6834.110/chromecast/browser/cast_browser_interface_binders.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_interface_binders.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_BROWSER_INTERFACE_BINDERS_H_ -#define CHROMECAST_BROWSER_CAST_BROWSER_INTERFACE_BINDERS_H_ - -#include "mojo/public/cpp/bindings/binder_map.h" - -namespace content { -class RenderFrameHost; -} - -namespace chromecast { -namespace shell { - -void PopulateCastFrameBinders( - content::RenderFrameHost* render_frame_host, - mojo::BinderMapWithContext* binder_map); - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_BROWSER_INTERFACE_BINDERS_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_main_parts.cc chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts.cc --- chromium-132.0.6834.110/chromecast/browser/cast_browser_main_parts.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,774 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_browser_main_parts.h" - -#include -#include - -#include -#include -#include - -#include "base/check.h" -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/memory/memory_pressure_monitor.h" -#include "base/memory/ptr_util.h" -#include "base/path_service.h" -#include "base/run_loop.h" -#include "base/strings/string_split.h" -#include "base/task/current_thread.h" -#include "base/task/single_thread_task_runner.h" -#include "base/task/thread_pool.h" -#include "base/threading/thread.h" -#include "build/build_config.h" -#include "cc/base/switches.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "chromecast/base/cast_constants.h" -#include "chromecast/base/cast_paths.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/base/metrics/grouped_histogram.h" -#include "chromecast/base/version.h" -#include "chromecast/browser/cast_browser_context.h" -#include "chromecast/browser/cast_browser_process.h" -#include "chromecast/browser/cast_content_browser_client.h" -#include "chromecast/browser/cast_feature_list_creator.h" -#include "chromecast/browser/cast_feature_update_observer.h" -#include "chromecast/browser/cast_system_memory_pressure_evaluator.h" -#include "chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.h" -#include "chromecast/browser/cast_web_service.h" -#include "chromecast/browser/devtools/remote_debugging_server.h" -#include "chromecast/browser/media/media_caps_impl.h" -#include "chromecast/browser/media/supported_codec_finder.h" -#include "chromecast/browser/metrics/cast_browser_metrics.h" -#include "chromecast/browser/metrics/metrics_helper_impl.h" -#include "chromecast/browser/mojom/cast_web_service.mojom.h" -#include "chromecast/browser/service_connector.h" -#include "chromecast/browser/service_manager_connection.h" -#include "chromecast/browser/service_manager_context.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/common/mojom/constants.mojom.h" -#include "chromecast/external_mojo/broker_service/broker_service.h" -#include "chromecast/external_mojo/external_service_support/external_connector.h" -#include "chromecast/external_mojo/external_service_support/external_service.h" -#include "chromecast/external_mojo/public/cpp/common.h" -#include "chromecast/graphics/cast_window_manager.h" -#include "chromecast/media/base/key_systems_common.h" -#include "chromecast/media/base/video_plane_controller.h" -#include "chromecast/media/common/media_pipeline_backend_manager.h" -#include "chromecast/media/common/media_resource_tracker.h" -#include "chromecast/metrics/cast_metrics_service_client.h" -#include "chromecast/net/connectivity_checker.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/service/cast_service.h" -#include "chromecast/ui/display_settings_manager_impl.h" -#include "components/heap_profiling/multi_process/client_connection_manager.h" -#include "components/heap_profiling/multi_process/supervisor.h" -#include "components/input/switches.h" -#include "components/memory_pressure/multi_source_memory_pressure_monitor.h" -#include "components/prefs/pref_service.h" -#include "components/viz/common/switches.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/child_process_security_policy.h" -#include "content/public/browser/network_service_instance.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/storage_partition.h" -#include "content/public/common/content_features.h" -#include "content/public/common/content_switches.h" -#include "content/public/common/result_codes.h" -#include "gpu/command_buffer/service/gpu_switches.h" -#include "media/base/media.h" -#include "media/base/media_switches.h" -#include "net/base/network_change_notifier.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" -#include "ui/base/ui_base_switches.h" -#include "ui/gl/gl_switches.h" - -#if BUILDFLAG(IS_OZONE) -#include "ui/ozone/public/ozone_platform.h" -#endif // BUILDFLAG(IS_OZONE) - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -#include -#include -#include -#include "ui/gfx/linux/fontconfig_util.h" -#endif - -#if BUILDFLAG(IS_ANDROID) -#include "components/crash/content/browser/child_exit_observer_android.h" -#include "components/crash/content/browser/child_process_crash_observer_android.h" -#include "net/android/network_change_notifier_factory_android.h" -#elif BUILDFLAG(IS_FUCHSIA) -#include "chromecast/net/network_change_notifier_factory_fuchsia.h" -#else -#include "chromecast/net/network_change_notifier_factory_cast.h" -#endif - -#if BUILDFLAG(IS_FUCHSIA) -#include "chromecast/net/fake_connectivity_checker.h" -#endif - -#if defined(USE_AURA) -// gn check ignored on OverlayManagerCast as it's not a public ozone -// header, but is exported to allow injecting the overlay-composited -// callback. -#include "chromecast/browser/cast_display_configurator.h" // nogncheck -#include "chromecast/browser/devtools/cast_ui_devtools.h" -#include "chromecast/graphics/cast_screen.h" -#include "chromecast/graphics/cast_window_manager_aura.h" -#include "chromecast/media/service/cast_renderer.h" // nogncheck -#if !BUILDFLAG(IS_FUCHSIA) -#include "components/ui_devtools/devtools_server.h" // nogncheck -#include "components/ui_devtools/switches.h" // nogncheck -#endif -#include "ui/display/screen.h" -#include "ui/views/views_delegate.h" // nogncheck -#else -#include "chromecast/graphics/cast_window_manager_default.h" // nogncheck -#endif - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) -#include "device/bluetooth/cast/bluetooth_adapter_cast.h" -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - -#if !BUILDFLAG(IS_FUCHSIA) -#include "chromecast/base/cast_sys_info_util.h" -#include "chromecast/public/cast_sys_info.h" -#endif // !BUILDFLAG(IS_FUCHSIA) - -namespace { - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) -int kSignalsToRunClosure[] = { - SIGTERM, - SIGINT, -}; -// Closure to run on SIGTERM and SIGINT. -base::OnceClosure* g_signal_closure = nullptr; -base::PlatformThreadId g_main_thread_id; - -void RunClosureOnSignal(int signum) { - if (base::PlatformThread::CurrentId() != g_main_thread_id) { - RAW_LOG(INFO, "Received signal on non-main thread\n"); - return; - } - - char message[48] = "Received close signal: "; - strncat(message, strsignal(signum), sizeof(message) - strlen(message) - 1); - RAW_LOG(INFO, message); - - DCHECK(g_signal_closure); - if (*g_signal_closure) - std::move(*g_signal_closure).Run(); -} - -void RegisterClosureOnSignal(base::OnceClosure closure) { - DCHECK(!g_signal_closure); - DCHECK(closure); - DCHECK_GT(std::size(kSignalsToRunClosure), 0U); - - // Memory leak on purpose, since |g_signal_closure| should live until - // process exit. - g_signal_closure = new base::OnceClosure(std::move(closure)); - g_main_thread_id = base::PlatformThread::CurrentId(); - - struct sigaction sa_new; - memset(&sa_new, 0, sizeof(sa_new)); - sa_new.sa_handler = RunClosureOnSignal; - sigfillset(&sa_new.sa_mask); - sa_new.sa_flags = SA_RESTART; - - for (int sig : kSignalsToRunClosure) { - struct sigaction sa_old; - if (sigaction(sig, &sa_new, &sa_old) == -1) { - NOTREACHED(); - } else { - DCHECK_EQ(sa_old.sa_handler, SIG_DFL); - } - } - - // Get the first signal to exit when the parent process dies. - prctl(PR_SET_PDEATHSIG, kSignalsToRunClosure[0]); -} - -const int kKillOnAlarmTimeoutSec = 5; // 5 seconds - -void KillOnAlarm(int signum) { - LOG(ERROR) << "Got alarm signal for termination: " << signum; - raise(SIGKILL); -} - -void RegisterKillOnAlarm(int timeout_seconds) { - struct sigaction sa_new; - memset(&sa_new, 0, sizeof(sa_new)); - sa_new.sa_handler = KillOnAlarm; - sigfillset(&sa_new.sa_mask); - sa_new.sa_flags = SA_RESTART; - - struct sigaction sa_old; - if (sigaction(SIGALRM, &sa_new, &sa_old) == -1) { - NOTREACHED(); - } else { - DCHECK_EQ(sa_old.sa_handler, SIG_DFL); - } - - if (alarm(timeout_seconds) > 0) - NOTREACHED() << "Previous alarm() was cancelled"; -} - -void DeregisterKillOnAlarm() { - // Explicitly cancel any outstanding alarm() calls. - alarm(0); - - struct sigaction sa_new; - memset(&sa_new, 0, sizeof(sa_new)); - sa_new.sa_handler = SIG_DFL; - sigfillset(&sa_new.sa_mask); - sa_new.sa_flags = SA_RESTART; - - struct sigaction sa_old; - if (sigaction(SIGALRM, &sa_new, &sa_old) == -1) { - NOTREACHED(); - } else { - DCHECK_EQ(sa_old.sa_handler, KillOnAlarm); - } -} - -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - -std::unique_ptr -CreateClientConnectionManager( - base::WeakPtr controller_weak_ptr, - heap_profiling::Mode mode) { - return std::make_unique( - std::move(controller_weak_ptr), mode); -} - -#if defined(USE_AURA) - -// Provide a basic implementation. No need to override anything since we're not -// planning on customizing any behavior at this point. -class CastViewsDelegate : public views::ViewsDelegate { - public: - CastViewsDelegate() = default; - - CastViewsDelegate(const CastViewsDelegate&) = delete; - CastViewsDelegate& operator=(const CastViewsDelegate&) = delete; - - ~CastViewsDelegate() override = default; -}; - -#endif // defined(USE_AURA) - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - -base::FilePath GetApplicationFontsDir() { - std::unique_ptr env(base::Environment::Create()); - std::string fontconfig_sysroot; - if (env->GetVar("FONTCONFIG_SYSROOT", &fontconfig_sysroot)) { - // Running with hermetic fontconfig; using the full path will not work. - // Assume the root is base::DIR_ASSETS as set by - // test_fonts::SetUpFontconfig(). - return base::FilePath("/fonts"); - } else { - base::FilePath dir_assets; - base::PathService::Get(base::DIR_ASSETS, &dir_assets); - return dir_assets.Append("fonts"); - } -} - -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - -} // namespace - -namespace chromecast { -namespace shell { - -namespace { - -struct DefaultCommandLineSwitch { - const char* const switch_name; - const char* const switch_value; -}; - -const DefaultCommandLineSwitch kDefaultSwitches[] = { -#if !BUILDFLAG(IS_ANDROID) - // GPU shader disk cache disabling is largely to conserve disk space. - {switches::kDisableGpuShaderDiskCache, ""}, -#endif -#if BUILDFLAG(IS_CAST_AUDIO_ONLY) - {switches::kDisableGpu, ""}, - {switches::kDisableSoftwareRasterizer, ""}, - {switches::kDisableGpuCompositing, ""}, -#if BUILDFLAG(IS_ANDROID) - {switches::kDisableFrameRateLimit, ""}, - {switches::kDisableGLDrawingForTests, ""}, - {switches::kDisableThreadedAnimation, ""}, -#endif // BUILDFLAG(IS_ANDROID) -#endif // BUILDFLAG(IS_CAST_AUDIO_ONLY) -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -#if defined(ARCH_CPU_X86_FAMILY) - // This is needed for now to enable the x11 Ozone platform to work with - // current Linux/NVidia OpenGL drivers. - {switches::kIgnoreGpuBlocklist, ""}, -#elif defined(ARCH_CPU_ARM_FAMILY) -#if !BUILDFLAG(IS_CAST_AUDIO_ONLY) - {switches::kEnableHardwareOverlays, "cast"}, -#endif -#endif -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - // It's better to start GPU process on demand. For example, for TV platforms - // cast starts in background and can't render until TV switches to cast - // input. - {switches::kDisableGpuEarlyInit, ""}, - // Enable navigator.connection API. - // TODO(derekjchow): Remove this switch when enabled by default. - {switches::kEnableNetworkInformationDownlinkMax, ""}, - // TODO(halliwell): Revert after fix for b/63101386. - {switches::kDisallowNonExactResourceReuse, ""}, - // Disable pinch zoom gesture. - {input::switches::kDisablePinch, ""}, -}; - -void AddDefaultCommandLineSwitches(base::CommandLine* command_line) { - std::string default_command_line_flags_string = - BUILDFLAG(DEFAULT_COMMAND_LINE_FLAGS); - std::vector default_command_line_flags_list = - base::SplitString(default_command_line_flags_string, ",", - base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - for (auto default_command_line_flag : default_command_line_flags_list) { - std::vector default_command_line_flag_content = - base::SplitString(default_command_line_flag, "=", base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - if (default_command_line_flag_content.size() == 2 && - !command_line->HasSwitch(default_command_line_flag_content[0])) { - DVLOG(2) << "Set default command line switch '" - << default_command_line_flag_content[0] << "' = '" - << default_command_line_flag_content[1] << "'"; - command_line->AppendSwitchASCII(default_command_line_flag_content[0], - default_command_line_flag_content[1]); - } - } - - for (const auto& default_switch : kDefaultSwitches) { - // Don't override existing command line switch values with these defaults. - // This could occur primarily (or only) on Android, where the command line - // is initialized in Java first. - std::string name(default_switch.switch_name); - if (!command_line->HasSwitch(name)) { - std::string value(default_switch.switch_value); - DVLOG(2) << "Set default switch '" << name << "' = '" << value << "'"; - command_line->AppendSwitchASCII(name, value); - } else { - DVLOG(2) << "Skip setting default switch '" << name << "', already set"; - } - } -} - -} // namespace - -CastBrowserMainParts::CastBrowserMainParts( - CastContentBrowserClient* cast_content_browser_client) - : cast_browser_process_(new CastBrowserProcess()), - cast_content_browser_client_(cast_content_browser_client), - media_caps_(std::make_unique()), - metrics_helper_(std::make_unique()) { - DCHECK(cast_content_browser_client); - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - AddDefaultCommandLineSwitches(command_line); - - service_manager_context_ = std::make_unique( - cast_content_browser_client_, content::GetUIThreadTaskRunner({})); - ServiceManagerConnection::GetForProcess()->Start(); -} - -CastBrowserMainParts::~CastBrowserMainParts() { - if (cast_content_browser_client_->GetMediaTaskRunner() && - media_pipeline_backend_manager_) { - // Make sure that media_pipeline_backend_manager_ is destroyed after any - // pending media thread tasks. The CastAudioOutputStream implementation - // calls into media_pipeline_backend_manager_ when the stream is closed; - // therefore, we must be sure that all CastAudioOutputStreams are gone - // before destroying media_pipeline_backend_manager_. This is guaranteed - // once the AudioManager is destroyed; the AudioManager destruction is - // posted to the media thread in the BrowserMainLoop destructor, just before - // the BrowserMainParts are destroyed (ie, here). Therefore, if we delete - // the media_pipeline_backend_manager_ using DeleteSoon on the media thread, - // it is guaranteed that the AudioManager and all AudioOutputStreams have - // been destroyed before media_pipeline_backend_manager_ is destroyed. - cast_content_browser_client_->GetMediaTaskRunner()->DeleteSoon( - FROM_HERE, media_pipeline_backend_manager_.release()); - } -} - -media::MediaPipelineBackendManager* -CastBrowserMainParts::media_pipeline_backend_manager() { - if (!media_pipeline_backend_manager_) { - media_pipeline_backend_manager_ = - std::make_unique( - cast_content_browser_client_->GetMediaTaskRunner(), - cast_content_browser_client_->media_resource_tracker()); - } - return media_pipeline_backend_manager_.get(); -} - -media::MediaCapsImpl* CastBrowserMainParts::media_caps() { - return media_caps_.get(); -} - -metrics::MetricsHelperImpl* CastBrowserMainParts::metrics_helper() { - return metrics_helper_.get(); -} - -content::BrowserContext* CastBrowserMainParts::browser_context() { - return cast_browser_process_->browser_context(); -} - -external_mojo::BrokerService* CastBrowserMainParts::broker_service() { - CHECK(broker_service_); - return broker_service_.get(); -} - -external_service_support::ExternalConnector* CastBrowserMainParts::connector() { - CHECK(connector_); - return connector_.get(); -} - -external_service_support::ExternalConnector* -CastBrowserMainParts::media_connector() { - CHECK(media_connector_); - return media_connector_.get(); -} - -CastWebService* CastBrowserMainParts::web_service() { - return web_service_.get(); -} - -void CastBrowserMainParts::PreCreateMainMessageLoop() { - // GroupedHistograms needs to be initialized before any threads are created - // to prevent race conditions between calls to Preregister and those threads - // attempting to collect metrics. - // This call must also be before NetworkChangeNotifier, as it generates - // Net/DNS metrics. - metrics::PreregisterAllGroupedHistograms(); - -#if BUILDFLAG(IS_ANDROID) - net::NetworkChangeNotifier::SetFactory( - new net::NetworkChangeNotifierFactoryAndroid()); -#elif BUILDFLAG(IS_FUCHSIA) - net::NetworkChangeNotifier::SetFactory( - new NetworkChangeNotifierFactoryFuchsia()); -#else - net::NetworkChangeNotifier::SetFactory( - new NetworkChangeNotifierFactoryCast()); -#endif -} - -void CastBrowserMainParts::PostCreateMainMessageLoop() { - // Ensure CastMetricsHelper initialized on UI thread. - metrics::CastMetricsHelper::GetInstance(); - -#if BUILDFLAG(IS_OZONE) - // Pass the UI task runner to the ozone platform. - CHECK(base::SingleThreadTaskRunner::HasCurrentDefault()); - ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( - base::DoNothing(), base::SingleThreadTaskRunner::GetCurrentDefault()); -#endif // BUILDFLAG(IS_OZONE) -} - -void CastBrowserMainParts::ToolkitInitialized() { -#if defined(USE_AURA) - // Needs to be initialize before any UI is created. - if (!views::ViewsDelegate::GetInstance()) - views_delegate_ = std::make_unique(); -#endif // defined(USE_AURA) - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - base::FilePath dir_font = GetApplicationFontsDir(); - const FcChar8* dir_font_char8 = - reinterpret_cast(dir_font.value().data()); - if (!FcConfigAppFontAddDir(gfx::GetGlobalFontConfig(), dir_font_char8)) { - LOG(ERROR) << "Cannot load fonts from " << dir_font_char8; - } -#endif -} - -int CastBrowserMainParts::PreCreateThreads() { -#if BUILDFLAG(IS_ANDROID) - child_exit_observer_ = std::make_unique(); - child_exit_observer_->RegisterClient( - std::make_unique()); -#endif - - service_connector_ = cast_content_browser_client_->CreateServiceConnector(); - - cast_browser_process_->SetPrefService( - cast_content_browser_client_->GetCastFeatureListCreator() - ->TakePrefService()); - -#if defined(USE_AURA) - cast_screen_ = std::make_unique(); - cast_browser_process_->SetCastScreen(cast_screen_.get()); - DCHECK(!display::Screen::GetScreen()); - display::Screen::SetScreenInstance(cast_screen_.get()); - cast_browser_process_->SetDisplayConfigurator( - std::make_unique(cast_screen_.get())); -#endif // defined(USE_AURA) - - content::ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme( - kChromeResourceScheme); - return 0; -} - -void CastBrowserMainParts::PostCreateThreads() { - if (GetSwitchValueBoolean(switches::kInProcessBroker, true)) { - auto* service_manager_connector = - ServiceManagerConnection::GetForProcess()->GetConnector(); - broker_service_ = std::make_unique( - service_manager_connector); - connector_ = external_service_support::ExternalConnector::Create( - broker_service_->CreateConnector()); - } else { - connector_ = external_service_support::ExternalConnector::Create( - external_mojo::GetBrokerPath()); - } - media_connector_ = connector_->Clone(); - browser_service_ = - std::make_unique(); - heap_profiling::Supervisor* supervisor = - heap_profiling::Supervisor::GetInstance(); - supervisor->SetClientConnectionManagerConstructor( - &CreateClientConnectionManager); - supervisor->Start(base::NullCallback()); -} - -int CastBrowserMainParts::PreMainMessageLoopRun() { -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - // static_cast is safe because this is the only implementation of - // MemoryPressureMonitor. - auto* monitor = - static_cast( - base::MemoryPressureMonitor::Get()); - // |monitor| may be nullptr in browser tests. - if (monitor) { - monitor->SetSystemEvaluator( - std::make_unique( - monitor->CreateVoter())); - } - - // base::Unretained() is safe because the browser client will outlive any - // component in the browser; this factory method will not be called after - // the browser starts to tear down. - device::BluetoothAdapterCast::SetFactory(base::BindRepeating( - &CastContentBrowserClient::CreateBluetoothAdapter, - base::Unretained(cast_browser_process_->browser_client()))); -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - - cast_content_browser_client_->SetPersistentCookieAccessSettings( - cast_browser_process_->pref_service()); - - cast_browser_process_->SetBrowserContext( - std::make_unique()); - - cast_browser_process_->SetConnectivityChecker(ConnectivityChecker::Create( - content::GetIOThreadTaskRunner({}), - cast_browser_process_->browser_context() - ->GetDefaultStoragePartition() - ->GetURLLoaderFactoryForBrowserProcessIOThread(), - content::GetNetworkConnectionTracker())); - - cast_browser_process_->SetMetricsServiceClient( - std::make_unique( - cast_browser_process_->browser_client(), - cast_browser_process_->pref_service(), - cast_browser_process_->browser_context() - ->GetDefaultStoragePartition() - ->GetURLLoaderFactoryForBrowserProcess())); - cast_browser_process_->SetRemoteDebuggingServer( - std::make_unique( - cast_browser_process_->browser_client() - ->EnableRemoteDebuggingImmediately())); - -#if defined(USE_AURA) && !BUILDFLAG(IS_CAST_AUDIO_ONLY) - // TODO(halliwell) move audio builds to use ozone_platform_cast, then can - // simplify this by removing IS_CAST_AUDIO_ONLY condition. Should then also - // assert(ozone_platform_cast) in BUILD.gn where it depends on //ui/ozone. - gfx::Size display_size = - display::Screen::GetScreen()->GetPrimaryDisplay().GetSizeInPixel(); - video_plane_controller_.reset(new media::VideoPlaneController( - Size(display_size.width(), display_size.height()), - cast_content_browser_client_->GetMediaTaskRunner())); - media::CastRenderer::SetOverlayCompositedCallback(BindToCurrentThread( - base::BindRepeating(&media::VideoPlaneController::SetGeometry, - base::Unretained(video_plane_controller_.get())))); -#endif - -#if defined(USE_AURA) - -#if !BUILDFLAG(IS_FUCHSIA) - // Start UI devtools if this is a dev device or explicitly enabled. - // Note that this must happen before the window tree host is created by the - // window manager. - auto build_type = CreateSysInfo()->GetBuildType(); - if (CAST_IS_DEBUG_BUILD() || build_type == CastSysInfo::BUILD_ENG || - ::ui_devtools::UiDevToolsServer::IsUiDevToolsEnabled( - ::ui_devtools::switches::kEnableUiDevTools)) { - // Starts the UI Devtools server for browser Aura UI - ui_devtools_ = - std::make_unique(content::GetIOThreadTaskRunner({})); - } -#endif - - window_manager_ = std::make_unique( - CAST_IS_DEBUG_BUILD() || - GetSwitchValueBoolean(switches::kEnableInput, false)); - window_manager_->Setup(); - - display_change_observer_ = std::make_unique( - cast_browser_process_->display_configurator(), window_manager_.get()); - -#else // defined(USE_AURA) - window_manager_ = std::make_unique(); -#endif // defined(USE_AURA) - - cast_content_browser_client_->media_resource_tracker()->InitializeMediaLib(); - ::media::InitializeMediaLibrary(); - // Query the supported codec/profile/levels asynchronously after initializing - // the media library. This query can block and cause App Not Responding (ANR) - // errors if CPU resources are tight during browser initialization. - cast_content_browser_client_->GetMediaTaskRunner() - ->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce( - &media::SupportedCodecFinder::FindSupportedCodecProfileLevels), - base::BindOnce(&CastBrowserMainParts::AddSupportedCodecProfileLevels, - weak_factory_.GetWeakPtr())); - - display_settings_manager_ = std::make_unique( - window_manager_.get(), -#if defined(USE_AURA) - cast_browser_process_->display_configurator() -#else - nullptr -#endif // defined(USE_AURA) - ); - - web_service_ = std::make_unique( - cast_browser_process_->browser_context(), window_manager_.get()); - browser_service_->AddInterface<::chromecast::mojom::CastWebService>( - web_service_.get()); - connector()->RegisterService(::chromecast::mojom::kCastBrowserServiceName, - browser_service_.get()); - - cast_browser_process_->SetCastService( - cast_browser_process_->browser_client()->CreateCastService( - cast_browser_process_->browser_context(), nullptr, - cast_browser_process_->pref_service(), video_plane_controller_.get(), - window_manager_.get(), web_service_.get(), - display_settings_manager_.get())); - cast_browser_process_->cast_service()->Initialize(); - - // Initializing metrics service and network delegates must happen after cast - // service is initialized because CastMetricsServiceClient, - // CastURLLoaderThrottle and CastNetworkDelegate may use components - // initialized by cast service. - cast_browser_process_->cast_browser_metrics()->Initialize(); - cast_content_browser_client_->InitializeURLLoaderThrottleDelegate(); - - cast_content_browser_client_->CreateGeneralAudienceBrowsingService(); - - // Disable RenderFrameHost's Javascript injection restrictions so that the - // Cast Web Service can implement its own JS injection policy at a higher - // level. - content::RenderFrameHost::AllowInjectingJavaScript(); - - cast_browser_process_->cast_service()->Start(); - - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kUseCastBrowserPrefConfig)) { - feature_update_observer_ = std::make_unique( - connector(), cast_browser_process_->pref_service()); - } - - return content::RESULT_CODE_NORMAL_EXIT; -} - -void CastBrowserMainParts::WillRunMainMessageLoop( - std::unique_ptr& run_loop) { -#if BUILDFLAG(IS_ANDROID) - // Android does not use native main MessageLoop. - NOTREACHED(); -#elif !BUILDFLAG(IS_FUCHSIA) - // Fuchsia doesn't have signals. - RegisterClosureOnSignal(run_loop->QuitClosure()); -#endif // !BUILDFLAG(IS_FUCHSIA) -} - -void CastBrowserMainParts::PostMainMessageLoopRun() { -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - // Once the main loop has stopped running, we give the browser process a few - // seconds to stop cast service and finalize all resources. If a hang occurs - // and cast services refuse to terminate successfully, then we SIGKILL the - // current process to avoid indefinite hangs. - // - // TODO(sergeyu): Fuchsia doesn't implement POSIX signals. Implement a - // different shutdown watchdog mechanism. - RegisterKillOnAlarm(kKillOnAlarmTimeoutSec); -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - - cast_browser_process_->cast_service()->Stop(); - -#if BUILDFLAG(IS_ANDROID) - // Android does not use native main MessageLoop. - NOTREACHED(); -#else -#if defined(USE_AURA) - // Reset display change observer here to ensure it is deleted before - // display_configurator since display_configurator is deleted when - // `cast_browser_process_` is reset below. - display_change_observer_.reset(); -#endif - - cast_browser_process_->cast_service()->Finalize(); - cast_browser_process_->cast_browser_metrics()->Finalize(); - cast_browser_process_.reset(); - - window_manager_.reset(); -#if defined(USE_AURA) - display::Screen::SetScreenInstance(nullptr); - cast_screen_.reset(); -#endif - -#if !BUILDFLAG(IS_FUCHSIA) - DeregisterKillOnAlarm(); -#endif // !BUILDFLAG(IS_FUCHSIA) - - service_manager_context_.reset(); -#endif -} - -void CastBrowserMainParts::PostDestroyThreads() { -#if !BUILDFLAG(IS_ANDROID) - cast_content_browser_client_->ResetMediaResourceTracker(); -#endif // !BUILDFLAG(IS_ANDROID) -} - -void CastBrowserMainParts::AddSupportedCodecProfileLevels( - base::span codec_profile_levels) { - LOG(INFO) << "Adding " << codec_profile_levels.size() - << " supported codec profiles/levels"; - for (const auto& cpl : codec_profile_levels) { - media_caps_->AddSupportedCodecProfileLevel(cpl); - } -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_main_parts.h chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts.h --- chromium-132.0.6834.110/chromecast/browser/cast_browser_main_parts.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,168 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_BROWSER_MAIN_PARTS_H_ -#define CHROMECAST_BROWSER_CAST_BROWSER_MAIN_PARTS_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "build/build_config.h" -#include "build/buildflag.h" -#include "chromecast/browser/display_configurator_observer.h" -#include "chromecast/chromecast_buildflags.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_main_parts.h" - -#if BUILDFLAG(IS_ANDROID) -#include "base/timer/timer.h" -#endif - -class PrefService; - -#if BUILDFLAG(IS_ANDROID) -namespace crash_reporter { -class ChildExitObserver; -} // namespace crash_reporter -#endif // BUILDFLAG(IS_ANDROID) - -#if defined(USE_AURA) -namespace views { -class ViewsDelegate; -} // namespace views -#endif // defined(USE_AURA) - -namespace chromecast { -class CastFeatureUpdateObserver; -class CastWebService; -class DisplaySettingsManager; -class ServiceConnector; -class ServiceManagerContext; - -#if defined(USE_AURA) -class CastWindowManagerAura; -class CastScreen; -namespace shell { -class CastUIDevTools; -} // namespace shell -#else -class CastWindowManager; -#endif // #if defined(USE_AURA) - -namespace external_mojo { -class BrokerService; -} // namespace external_mojo - -namespace external_service_support { -class ExternalConnector; -class ExternalService; -} // namespace external_service_support - -namespace media { -struct CodecProfileLevel; -class MediaCapsImpl; -class MediaPipelineBackendManager; -class VideoPlaneController; -} // namespace media - -namespace metrics { -class MetricsHelperImpl; -} // namespace metrics - -namespace shell { -class CastBrowserProcess; -class CastContentBrowserClient; - -class CastBrowserMainParts : public content::BrowserMainParts { - public: - // Creates an implementation of CastBrowserMainParts. Platform should - // link in an implementation as needed. - static std::unique_ptr Create( - CastContentBrowserClient* cast_content_browser_client); - - // This class does not take ownership of |url_request_content_factory|. - explicit CastBrowserMainParts( - CastContentBrowserClient* cast_content_browser_client); - - CastBrowserMainParts(const CastBrowserMainParts&) = delete; - CastBrowserMainParts& operator=(const CastBrowserMainParts&) = delete; - - ~CastBrowserMainParts() override; - - media::MediaPipelineBackendManager* media_pipeline_backend_manager(); - media::MediaCapsImpl* media_caps(); - metrics::MetricsHelperImpl* metrics_helper(); - content::BrowserContext* browser_context(); - external_mojo::BrokerService* broker_service(); - external_service_support::ExternalConnector* connector(); - external_service_support::ExternalConnector* media_connector(); - CastWebService* web_service(); - - // content::BrowserMainParts implementation: - void PreCreateMainMessageLoop() override; - void PostCreateMainMessageLoop() override; - void ToolkitInitialized() override; - int PreCreateThreads() override; - void PostCreateThreads() override; - int PreMainMessageLoopRun() override; - void WillRunMainMessageLoop( - std::unique_ptr& run_loop) override; - void PostMainMessageLoopRun() override; - void PostDestroyThreads() override; - - private: - void AddSupportedCodecProfileLevels( - base::span codec_profile_levels); - - std::unique_ptr cast_browser_process_; - // Caches a pointer of the CastContentBrowserClient. - CastContentBrowserClient* const cast_content_browser_client_ = nullptr; - std::unique_ptr service_manager_context_; - std::unique_ptr video_plane_controller_; - std::unique_ptr media_caps_; - std::unique_ptr metrics_helper_; - std::unique_ptr service_connector_; - - // Created in CastBrowserMainParts::PostCreateThreads(): - std::unique_ptr broker_service_; - std::unique_ptr browser_service_; - // ExternalConnectors should be destroyed before registered services. - std::unique_ptr connector_; - // ExternalConnector for running on the media task runner. - std::unique_ptr media_connector_; - -#if defined(USE_AURA) - std::unique_ptr views_delegate_; - std::unique_ptr cast_screen_; - std::unique_ptr window_manager_; - std::unique_ptr display_change_observer_; -#else - std::unique_ptr window_manager_; -#endif // defined(USE_AURA) - std::unique_ptr web_service_; - std::unique_ptr display_settings_manager_; - -#if BUILDFLAG(IS_ANDROID) - std::unique_ptr child_exit_observer_; -#endif - - // Tracks all media pipeline backends. - std::unique_ptr - media_pipeline_backend_manager_; - - std::unique_ptr feature_update_observer_; - -#if defined(USE_AURA) && !BUILDFLAG(IS_FUCHSIA) - // Only used when running with --enable-ui-devtools. - std::unique_ptr ui_devtools_; -#endif // defined(USE_AURA) && !BUILDFLAG(IS_FUCHSIA) - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_BROWSER_MAIN_PARTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_main_parts_simple.cc chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts_simple.cc --- chromium-132.0.6834.110/chromecast/browser/cast_browser_main_parts_simple.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_main_parts_simple.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_browser_main_parts.h" - -namespace chromecast { -namespace shell { - -// static -std::unique_ptr CastBrowserMainParts::Create( - CastContentBrowserClient* cast_content_browser_client) { - return std::make_unique(cast_content_browser_client); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_process.cc chromium-132.0.6834.159/chromecast/browser/cast_browser_process.cc --- chromium-132.0.6834.110/chromecast/browser/cast_browser_process.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_process.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,120 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_browser_process.h" - -#include - -#include "base/check_op.h" -#include "build/build_config.h" -#include "chromecast/browser/cast_browser_context.h" -#include "chromecast/browser/cast_content_browser_client.h" -#include "chromecast/browser/cast_network_contexts.h" -#include "chromecast/browser/cast_web_service.h" -#include "chromecast/browser/devtools/remote_debugging_server.h" -#include "chromecast/browser/metrics/cast_browser_metrics.h" -#include "chromecast/metrics/cast_metrics_service_client.h" -#include "chromecast/net/connectivity_checker.h" -#include "chromecast/service/cast_service.h" -#include "components/prefs/pref_service.h" - -#if defined(USE_AURA) - -#include "chromecast/browser/cast_display_configurator.h" // nogncheck -#include "chromecast/graphics/cast_screen.h" -#endif // defined(USE_AURA) - -namespace chromecast { -namespace shell { - -namespace { -CastBrowserProcess* g_instance = NULL; -} // namespace - -// static -CastBrowserProcess* CastBrowserProcess::GetInstance() { - DCHECK(g_instance); - return g_instance; -} - -CastBrowserProcess::CastBrowserProcess() { - DCHECK(!g_instance); - g_instance = this; -} - -CastBrowserProcess::~CastBrowserProcess() { - DCHECK_EQ(g_instance, this); - - // TODO(halliwell): investigate having the state that's owned in - // CastContentBrowserClient (and its internal derived class) be owned in - // another class that's destructed by this point. - if (cast_content_browser_client_) { - cast_content_browser_client_->cast_network_contexts() - ->OnPrefServiceShutdown(); - } - - if (pref_service_) - pref_service_->CommitPendingWrite(); - g_instance = NULL; -} - -void CastBrowserProcess::SetBrowserContext( - std::unique_ptr browser_context) { - DCHECK(!browser_context_); - browser_context_.swap(browser_context); -} - -void CastBrowserProcess::SetCastContentBrowserClient( - CastContentBrowserClient* cast_content_browser_client) { - DCHECK(!cast_content_browser_client_); - cast_content_browser_client_ = cast_content_browser_client; -} - -void CastBrowserProcess::SetCastService( - std::unique_ptr cast_service) { - DCHECK(!cast_service_); - cast_service_.swap(cast_service); -} - -#if defined(USE_AURA) -void CastBrowserProcess::SetCastScreen(CastScreen* cast_screen) { - DCHECK(!cast_screen_); - cast_screen_ = cast_screen; -} - -void CastBrowserProcess::SetDisplayConfigurator( - std::unique_ptr display_configurator) { - DCHECK(!display_configurator_); - display_configurator_ = std::move(display_configurator); -} - -#endif // defined(USE_AURA) - -void CastBrowserProcess::SetMetricsServiceClient( - std::unique_ptr metrics_service_client) { - DCHECK(!cast_browser_metrics_); - cast_browser_metrics_ = std::make_unique( - std::move(metrics_service_client)); -} - -void CastBrowserProcess::SetPrefService( - std::unique_ptr pref_service) { - DCHECK(!pref_service_); - pref_service_.swap(pref_service); -} - -void CastBrowserProcess::SetRemoteDebuggingServer( - std::unique_ptr remote_debugging_server) { - DCHECK(!remote_debugging_server_); - remote_debugging_server_.swap(remote_debugging_server); -} - -void CastBrowserProcess::SetConnectivityChecker( - scoped_refptr connectivity_checker) { - DCHECK(!connectivity_checker_); - connectivity_checker_.swap(connectivity_checker); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_browser_process.h chromium-132.0.6834.159/chromecast/browser/cast_browser_process.h --- chromium-132.0.6834.110/chromecast/browser/cast_browser_process.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_browser_process.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_BROWSER_PROCESS_H_ -#define CHROMECAST_BROWSER_CAST_BROWSER_PROCESS_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "build/build_config.h" -#include "chromecast/chromecast_buildflags.h" - -class PrefService; - -namespace chromecast { -class CastService; -class CastScreen; -class CastWindowManager; -class ConnectivityChecker; - -namespace metrics { -class CastMetricsServiceClient; -class CastBrowserMetrics; -} // namespace metrics - -namespace shell { - -class CastBrowserContext; -class CastContentBrowserClient; -class CastDisplayConfigurator; -class RemoteDebuggingServer; - -class CastBrowserProcess { - public: - // Gets the global instance of CastBrowserProcess. Does not create lazily and - // assumes the instance already exists. - static CastBrowserProcess* GetInstance(); - - CastBrowserProcess(); - - CastBrowserProcess(const CastBrowserProcess&) = delete; - CastBrowserProcess& operator=(const CastBrowserProcess&) = delete; - - virtual ~CastBrowserProcess(); - - void PreMainMessageLoopRun(CastWindowManager* window_manager); - - void SetBrowserContext(std::unique_ptr browser_context); - void SetCastContentBrowserClient(CastContentBrowserClient* browser_client); - void SetCastService(std::unique_ptr cast_service); - -#if defined(USE_AURA) - void SetCastScreen(CastScreen* cast_screen); - void SetDisplayConfigurator( - std::unique_ptr display_configurator); -#endif // defined(USE_AURA) - void SetMetricsServiceClient( - std::unique_ptr - metrics_service_client); - void SetPrefService(std::unique_ptr pref_service); - void SetRemoteDebuggingServer( - std::unique_ptr remote_debugging_server); - void SetConnectivityChecker( - scoped_refptr connectivity_checker); - - CastContentBrowserClient* browser_client() const { - return cast_content_browser_client_; - } - CastBrowserContext* browser_context() const { return browser_context_.get(); } - CastService* cast_service() const { return cast_service_.get(); } -#if defined(USE_AURA) - CastScreen* cast_screen() const { return cast_screen_; } - CastDisplayConfigurator* display_configurator() const { - return display_configurator_.get(); - } -#endif // defined(USE_AURA) - metrics::CastBrowserMetrics* cast_browser_metrics() const { - return cast_browser_metrics_.get(); - } - PrefService* pref_service() const { return pref_service_.get(); } - ConnectivityChecker* connectivity_checker() const { - return connectivity_checker_.get(); - } - RemoteDebuggingServer* remote_debugging_server() const { - return remote_debugging_server_.get(); - } - - private: - // Note: The following objects should be declared in the same order as they - // are set in CastBrowserMainParts. - - // Created just after CastBrowserMainParts ctor: - CastContentBrowserClient* cast_content_browser_client_ = nullptr; - - // Created in CastBrowserMainParts::PreCreateThreads: - std::unique_ptr pref_service_; -#if defined(USE_AURA) - CastScreen* cast_screen_ = nullptr; - std::unique_ptr display_configurator_; -#endif // defined(USE_AURA) - - // Created in CastBrowserMainParts::PreMainMessageLoopRun: - std::unique_ptr browser_context_; - scoped_refptr connectivity_checker_; - std::unique_ptr cast_browser_metrics_; - std::unique_ptr remote_debugging_server_; - - // Note: CastService must be destroyed before others. - std::unique_ptr cast_service_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_BROWSER_PROCESS_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_browser_client.cc chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client.cc --- chromium-132.0.6834.110/chromecast/browser/cast_content_browser_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,911 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_content_browser_client.h" - -#include - -#include -#include - -#include "base/base_switches.h" -#include "base/command_line.h" -#include "base/feature_list.h" -#include "base/files/scoped_file.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/i18n/rtl.h" -#include "base/logging.h" -#include "base/message_loop/message_pump_type.h" -#include "base/path_service.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/unguessable_token.h" -#include "build/build_config.h" -#include "chromecast/base/cast_constants.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/base/cast_paths.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/pref_names.h" -#include "chromecast/browser/application_media_info_manager.h" -#include "chromecast/browser/cast_browser_context.h" -#include "chromecast/browser/cast_browser_main_parts.h" -#include "chromecast/browser/cast_browser_process.h" -#include "chromecast/browser/cast_feature_list_creator.h" -#include "chromecast/browser/cast_http_user_agent_settings.h" -#include "chromecast/browser/cast_navigation_ui_data.h" -#include "chromecast/browser/cast_network_contexts.h" -#include "chromecast/browser/cast_overlay_manifests.h" -#include "chromecast/browser/cast_session_id_map.h" -#include "chromecast/browser/cast_web_contents.h" -#include "chromecast/browser/cast_web_preferences.h" -#include "chromecast/browser/cast_web_service.h" -#include "chromecast/browser/default_navigation_throttle.h" -#include "chromecast/browser/devtools/cast_devtools_manager_delegate.h" -#include "chromecast/browser/general_audience_browsing_navigation_throttle.h" -#include "chromecast/browser/general_audience_browsing_service.h" -#include "chromecast/browser/media/media_caps_impl.h" -#include "chromecast/browser/service/cast_service_simple.h" -#include "chromecast/browser/service_connector.h" -#include "chromecast/browser/service_manager_connection.h" -#include "chromecast/browser/service_manager_context.h" -#include "chromecast/common/cors_exempt_headers.h" -#include "chromecast/common/global_descriptors.h" -#include "chromecast/common/user_agent.h" -#include "chromecast/external_mojo/broker_service/broker_service.h" -#include "chromecast/media/audio/cast_audio_manager.h" -#include "chromecast/media/cdm/cast_cdm_factory.h" -#include "chromecast/media/cdm/cast_cdm_origin_provider.h" -#include "chromecast/media/cma/backend/cma_backend_factory_impl.h" -#include "chromecast/media/common/media_pipeline_backend_manager.h" -#include "chromecast/media/common/media_resource_tracker.h" -#include "chromecast/media/service/cast_renderer.h" -#include "chromecast/media/service/mojom/video_geometry_setter.mojom.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "components/prefs/pref_service.h" -#include "components/url_rewrite/browser/url_request_rewrite_rules_manager.h" -#include "components/url_rewrite/common/url_loader_throttle.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/certificate_request_result_type.h" -#include "content/public/browser/client_certificate_delegate.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/browser/navigation_ui_data.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/browser/site_instance.h" -#include "content/public/browser/storage_partition.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_ui_url_loader_factory.h" -#include "content/public/common/content_descriptors.h" -#include "content/public/common/content_features.h" -#include "content/public/common/content_switches.h" -#include "content/public/common/url_constants.h" -#include "media/audio/audio_thread_impl.h" -#include "media/base/media_switches.h" -#include "media/gpu/buildflags.h" -#include "media/mojo/services/mojo_renderer_service.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "net/cert/x509_certificate.h" -#include "net/ssl/ssl_cert_request_info.h" -#include "net/ssl/ssl_private_key.h" -#include "net/url_request/url_request_context_getter.h" -#include "services/network/public/cpp/network_switches.h" -#include "third_party/blink/public/common/features.h" -#include "third_party/blink/public/common/web_preferences/web_preferences.h" -#include "ui/display/display.h" -#include "ui/display/screen.h" -#include "ui/gl/gl_switches.h" - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) -#include "components/crash/content/browser/crash_handler_host_linux.h" -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || - // BUILDFLAG(IS_ANDROID) - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -#include "components/crash/core/app/breakpad_linux.h" -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - -#if BUILDFLAG(IS_ANDROID) -#include "base/android/build_info.h" -#include "chromecast/media/audio/cast_audio_manager_android.h" // nogncheck -#include "components/crash/core/app/crashpad.h" -#include "media/audio/android/audio_manager_android.h" -#include "media/audio/audio_features.h" -#else -#include "chromecast/browser/memory_pressure_controller_impl.h" -#endif // BUILDFLAG(IS_ANDROID) - -#if defined(USE_ALSA) -#include "chromecast/media/audio/cast_audio_manager_alsa.h" // nogncheck -#endif // defined(USE_ALSA) - -#if BUILDFLAG(ENABLE_CAST_RENDERER) -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/service/video_geometry_setter_service.h" -#endif // BUILDFLAG(ENABLE_CAST_RENDERER) - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) -#include "device/bluetooth/cast/bluetooth_adapter_cast.h" -#endif - -namespace chromecast { -namespace shell { - -CastContentBrowserClient::CastContentBrowserClient( - CastFeatureListCreator* cast_feature_list_creator) - : -#if BUILDFLAG(ENABLE_CAST_RENDERER) - video_geometry_setter_service_( - std::unique_ptr( - nullptr, - base::OnTaskRunnerDeleter(nullptr))), -#endif // BUILDFLAG(ENABLE_CAST_RENDERER) - cast_browser_main_parts_(nullptr), - cast_network_contexts_( - std::make_unique(GetCorsExemptHeadersList())), - cast_feature_list_creator_(cast_feature_list_creator) { - std::vector extra_enable_features = { - &::media::kInternalMediaSession, - &features::kNetworkServiceInProcess, -#if BUILDFLAG(USE_V4L2_CODEC) - // Enable accelerated video decode if v4l2 codec is supported. - &::media::kAcceleratedVideoDecodeLinux, -#endif // BUILDFLAG(USE_V4L2_CODEC) - }; - - std::vector extra_disable_features; - -#if BUILDFLAG(IS_ANDROID) - extra_enable_features.push_back( - &::media::kUseTaskRunnerForMojoAudioDecoderService); - - if (base::android::BuildInfo::GetInstance()->is_tv()) { - // Use the software decoder provided by MediaCodec instead of the built in - // software decoder. This can improve av sync quality. - extra_enable_features.push_back(&::media::kAllowMediaCodecSoftwareDecoder); - // For ATV HDMI dongle devices, it's hard to get an accurate audio latency. - // The OpenSL ES output path has a way to adjust the audio timestamp by - // querying AudioManager.getOutputLatency. Based on the experiment, this - // combination has a better av sync performance compared to the AAudio path - // on ATV devices. - extra_enable_features.push_back(&::media::kUseAudioLatencyFromHAL); - extra_disable_features.push_back(&::features::kUseAAudioDriver); - } -#endif - - cast_feature_list_creator_->SetExtraEnableFeatures(extra_enable_features); - cast_feature_list_creator_->SetExtraDisableFeatures(extra_disable_features); -} - -CastContentBrowserClient::~CastContentBrowserClient() { - DCHECK(!media_resource_tracker_) - << "ResetMediaResourceTracker was not called"; - cast_network_contexts_.reset(); -} - -std::unique_ptr -CastContentBrowserClient::CreateServiceConnector() { - return std::make_unique(); -} - -std::unique_ptr CastContentBrowserClient::CreateCastService( - content::BrowserContext* browser_context, - CastSystemMemoryPressureEvaluatorAdjuster* - cast_system_memory_pressure_evaluator_adjuster, - PrefService* pref_service, - media::VideoPlaneController* video_plane_controller, - CastWindowManager* window_manager, - CastWebService* web_service, - DisplaySettingsManager* display_settings_manager) { - return std::make_unique(web_service); -} - -media::VideoModeSwitcher* CastContentBrowserClient::GetVideoModeSwitcher() { - return nullptr; -} - -void CastContentBrowserClient::InitializeURLLoaderThrottleDelegate() {} - -void CastContentBrowserClient::SetPersistentCookieAccessSettings( - PrefService* pref_service) {} - -scoped_refptr -CastContentBrowserClient::GetMediaTaskRunner() { - if (!media_thread_) { - media_thread_.reset(new base::Thread("CastMediaThread")); - base::Thread::Options options; - // We need the media thread to be IO-capable to use the mixer service. - options.message_pump_type = base::MessagePumpType::IO; - options.thread_type = base::ThreadType::kRealtimeAudio; - CHECK(media_thread_->StartWithOptions(std::move(options))); - // Start the media_resource_tracker as soon as the media thread is created. - // There are services that run on the media thread that depend on it, - // and we want to initialize it with the correct task runner before any - // tasks that might use it are posted to the media thread. - media_resource_tracker_ = new media::MediaResourceTracker( - base::SingleThreadTaskRunner::GetCurrentDefault(), - media_thread_->task_runner()); - } - return media_thread_->task_runner(); -} - -media::VideoResolutionPolicy* -CastContentBrowserClient::GetVideoResolutionPolicy() { - return nullptr; -} - -media::CmaBackendFactory* CastContentBrowserClient::GetCmaBackendFactory() { - DCHECK(GetMediaTaskRunner()->BelongsToCurrentThread()); - if (!cma_backend_factory_) { - cma_backend_factory_ = std::make_unique( - media_pipeline_backend_manager()); - } - return cma_backend_factory_.get(); -} - -media::MediaResourceTracker* -CastContentBrowserClient::media_resource_tracker() { - DCHECK(media_thread_); - return media_resource_tracker_; -} - -void CastContentBrowserClient::ResetMediaResourceTracker() { - media_resource_tracker_->FinalizeAndDestroy(); - media_resource_tracker_ = nullptr; -} - -media::MediaPipelineBackendManager* -CastContentBrowserClient::media_pipeline_backend_manager() { - DCHECK(cast_browser_main_parts_); - return cast_browser_main_parts_->media_pipeline_backend_manager(); -} - -std::unique_ptr<::media::AudioManager> -CastContentBrowserClient::CreateAudioManager( - ::media::AudioLogFactory* audio_log_factory) { - // Create the audio thread and initialize the CastSessionIdMap. We need to - // initialize the CastSessionIdMap as soon as possible, so that the task - // runner gets set before any calls to it. - auto audio_thread = std::make_unique<::media::AudioThreadImpl>(); - auto* cast_session_id_map = - shell::CastSessionIdMap::GetInstance(audio_thread->GetTaskRunner()); - -#if defined(USE_ALSA) - return std::make_unique( - std::move(audio_thread), audio_log_factory, cast_session_id_map, - base::BindRepeating(&CastContentBrowserClient::GetCmaBackendFactory, - base::Unretained(this)), - content::GetUIThreadTaskRunner({}), GetMediaTaskRunner(), - /* use_mixer= */ false); -#elif BUILDFLAG(IS_ANDROID) - if (base::FeatureList::IsEnabled(kEnableChromeAudioManagerAndroid)) { - LOG(INFO) << "Use AudioManagerAndroid instead of CastAudioManagerAndroid."; - return std::make_unique<::media::AudioManagerAndroid>( - std::move(audio_thread), audio_log_factory); - } - - return std::make_unique( - std::move(audio_thread), audio_log_factory, cast_session_id_map, - base::BindRepeating(&CastContentBrowserClient::GetCmaBackendFactory, - base::Unretained(this)), - GetMediaTaskRunner()); -#else - return std::make_unique( - std::move(audio_thread), audio_log_factory, cast_session_id_map, - base::BindRepeating(&CastContentBrowserClient::GetCmaBackendFactory, - base::Unretained(this)), - content::GetUIThreadTaskRunner({}), GetMediaTaskRunner(), - /* use_mixer= */ false); -#endif -} - -bool CastContentBrowserClient::OverridesAudioManager() { - return true; -} - -std::unique_ptr<::media::CdmFactory> CastContentBrowserClient::CreateCdmFactory( - ::media::mojom::FrameInterfaceFactory* frame_interfaces) { - url::Origin cdm_origin; - if (!CastCdmOriginProvider::GetCdmOrigin(frame_interfaces, &cdm_origin)) { - return nullptr; - } - - return std::make_unique( - GetMediaTaskRunner(), cdm_origin, media_resource_tracker()); -} - -media::MediaCapsImpl* CastContentBrowserClient::media_caps() { - DCHECK(cast_browser_main_parts_); - return cast_browser_main_parts_->media_caps(); -} - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) -scoped_refptr -CastContentBrowserClient::CreateBluetoothAdapter() { - NOTREACHED() << "Bluetooth Adapter is not supported!"; -} -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - -void CastContentBrowserClient::SetMetricsClientId( - const std::string& client_id) {} - -void CastContentBrowserClient::RegisterMetricsProviders( - ::metrics::MetricsService* metrics_service) {} - -bool CastContentBrowserClient::EnableRemoteDebuggingImmediately() { - return true; -} - -std::vector CastContentBrowserClient::GetStartupServices() { - return { -#if BUILDFLAG(ENABLE_EXTERNAL_MOJO_SERVICES) - external_mojo::BrokerService::kServiceName -#endif - }; -} - -std::unique_ptr -CastContentBrowserClient::CreateBrowserMainParts( - bool /* is_integration_test */) { - DCHECK(!cast_browser_main_parts_); - - auto main_parts = CastBrowserMainParts::Create(this); - - cast_browser_main_parts_ = main_parts.get(); - CastBrowserProcess::GetInstance()->SetCastContentBrowserClient(this); - - return main_parts; -} - -bool CastContentBrowserClient::IsHandledURL(const GURL& url) { - if (!url.is_valid()) { - return false; - } - - static const char* const kProtocolList[] = { - content::kChromeUIScheme, content::kChromeDevToolsScheme, - kChromeResourceScheme, url::kBlobScheme, - url::kDataScheme, url::kFileSystemScheme, - }; - - const std::string& scheme = url.scheme(); - for (size_t i = 0; i < std::size(kProtocolList); ++i) { - if (scheme == kProtocolList[i]) { - return true; - } - } - - if (scheme == url::kFileScheme) { - return base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableLocalFileAccesses); - } - - return false; -} - -void CastContentBrowserClient::AppendExtraCommandLineSwitches( - base::CommandLine* command_line, - int child_process_id) { - std::string process_type = - command_line->GetSwitchValueNative(switches::kProcessType); - base::CommandLine* browser_command_line = - base::CommandLine::ForCurrentProcess(); - -#if !BUILDFLAG(IS_FUCHSIA) -#if BUILDFLAG(IS_ANDROID) - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableCrashReporter)) { - command_line->AppendSwitch(switches::kEnableCrashReporter); - } -#else - // IsCrashReporterEnabled() is set when InitCrashReporter() is called, and - // controlled by GetBreakpadClient()->EnableBreakpadForProcess(), therefore - // it's ok to add switch to every process here. - if (breakpad::IsCrashReporterEnabled()) { - command_line->AppendSwitch(switches::kEnableCrashReporter); - } -#endif // BUILDFLAG(IS_ANDROID) -#endif // !BUILDFLAG(IS_FUCHSIA) - - // Command-line for different processes. - if (process_type == switches::kRendererProcess) { - // Any browser command-line switches that should be propagated to - // the renderer go here. - static const char* const kForwardSwitches[] = { - switches::kCastAppBackgroundColor, - switches::kForceMediaResolutionHeight, - switches::kForceMediaResolutionWidth, - network::switches::kUnsafelyTreatInsecureOriginAsSecure}; - command_line->CopySwitchesFrom(*browser_command_line, kForwardSwitches); - } else if (process_type == switches::kUtilityProcess) { - if (browser_command_line->HasSwitch(switches::kAudioOutputChannels)) { - command_line->AppendSwitchASCII(switches::kAudioOutputChannels, - browser_command_line->GetSwitchValueASCII( - switches::kAudioOutputChannels)); - } - } else if (process_type == switches::kGpuProcess) { -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - // Necessary for accelerated 2d canvas. By default on Linux, Chromium - // assumes GLES2 contexts can be lost to a power-save mode, which breaks GPU - // canvas apps. - command_line->AppendSwitch(switches::kGpuNoContextLost); -#endif - -#if defined(USE_AURA) - static const char* const kForwardSwitches[] = { - switches::kCastInitialScreenHeight, - switches::kCastInitialScreenWidth, - switches::kVSyncInterval, - }; - command_line->CopySwitchesFrom(*browser_command_line, kForwardSwitches); - - auto display = display::Screen::GetScreen()->GetPrimaryDisplay(); - gfx::Size res = display.GetSizeInPixel(); - if (display.rotation() == display::Display::ROTATE_90 || - display.rotation() == display::Display::ROTATE_270) { - res = gfx::Size(res.height(), res.width()); - } - - if (!command_line->HasSwitch(switches::kCastInitialScreenWidth)) { - command_line->AppendSwitchASCII(switches::kCastInitialScreenWidth, - base::NumberToString(res.width())); - } - if (!command_line->HasSwitch(switches::kCastInitialScreenHeight)) { - command_line->AppendSwitchASCII(switches::kCastInitialScreenHeight, - base::NumberToString(res.height())); - } - - if (chromecast::IsFeatureEnabled(kSingleBuffer)) { - command_line->AppendSwitchASCII(switches::kGraphicsBufferCount, "1"); - } else if (chromecast::IsFeatureEnabled(chromecast::kTripleBuffer720)) { - command_line->AppendSwitchASCII(switches::kGraphicsBufferCount, "3"); - } -#endif // defined(USE_AURA) - } -} - -std::string CastContentBrowserClient::GetAcceptLangs( - content::BrowserContext* context) { - return CastHttpUserAgentSettings::AcceptLanguage(); -} - -network::mojom::NetworkContext* -CastContentBrowserClient::GetSystemNetworkContext() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - return cast_network_contexts_->GetSystemContext(); -} - -void CastContentBrowserClient::OverrideWebkitPrefs( - content::WebContents* web_contents, - blink::web_pref::WebPreferences* prefs) { - prefs->allow_scripts_to_close_windows = true; - - // Enable 5% margins for WebVTT cues to keep within title-safe area - prefs->text_track_margin_percentage = 5; - - prefs->hide_scrollbars = true; - - // Disable images rendering in Cast for Audio configuration -#if BUILDFLAG(IS_CAST_AUDIO_ONLY) - prefs->images_enabled = false; -#endif - -#if BUILDFLAG(IS_ANDROID) - // Enable the television style for viewport so that all cast apps have a - // 1280px wide layout viewport by default. - DCHECK(prefs->viewport_enabled); - DCHECK(prefs->viewport_meta_enabled); - prefs->viewport_style = blink::mojom::ViewportStyle::kTelevision; -#endif // BUILDFLAG(IS_ANDROID) - - // Disable WebSQL databases by default. - prefs->databases_enabled = false; - if (web_contents) { - chromecast::CastWebContents* cast_web_contents = - chromecast::CastWebContents::FromWebContents(web_contents); - if (cast_web_contents && cast_web_contents->is_websql_enabled()) { - prefs->databases_enabled = true; - } - } - - prefs->preferred_color_scheme = - static_cast( - CastBrowserProcess::GetInstance()->pref_service()->GetInteger( - prefs::kWebColorScheme)); - - // After all other default settings are set, check and see if there are any - // specific overrides for the WebContents. - CastWebPreferences* web_preferences = - static_cast(web_contents->GetUserData( - CastWebPreferences::kCastWebPreferencesDataKey)); - if (web_preferences) { - web_preferences->Update(prefs); - } -} - -std::string CastContentBrowserClient::GetApplicationLocale() { - const std::string locale(base::i18n::GetConfiguredLocale()); - return locale.empty() ? "en-US" : locale; -} - -void CastContentBrowserClient::AllowCertificateError( - content::WebContents* web_contents, - int cert_error, - const net::SSLInfo& ssl_info, - const GURL& request_url, - bool is_primary_main_frame_request, - bool strict_enforcement, - base::OnceCallback callback) { - // Allow developers to override certificate errors. - // Otherwise, any fatal certificate errors will cause an abort. - if (callback) { - std::move(callback).Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL); - } - return; -} - -base::OnceClosure CastContentBrowserClient::SelectClientCertificate( - content::BrowserContext* browser_context, - int process_id, - content::WebContents* web_contents, - net::SSLCertRequestInfo* cert_request_info, - net::ClientCertIdentityList client_certs, - std::unique_ptr delegate) { - GURL requesting_url("https://" + cert_request_info->host_and_port.ToString()); - - if (!web_contents) { - LOG(ERROR) << "Invalid requestor."; - delegate->ContinueWithCertificate(nullptr, nullptr); - return base::OnceClosure(); - } - - if (!requesting_url.is_valid()) { - LOG(ERROR) << "Invalid URL string: " - << requesting_url.possibly_invalid_spec(); - delegate->ContinueWithCertificate(nullptr, nullptr); - return base::OnceClosure(); - } - - // In our case there are no relevant certs in |client_certs|. The cert - // we need to return (if permitted) is the Cast device cert, which we can - // access directly through the ClientAuthSigner instance. However, we need to - // be on the IO thread to determine whether the app is whitelisted to return - // it. - // Subsequently, the callback must then itself be performed back here - // on the UI thread. - // - // TODO(davidben): Stop using child ID to identify an app. - std::string session_id = - CastNavigationUIData::GetSessionIdForWebContents(web_contents); - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - content::GetIOThreadTaskRunner({})->PostTask( - FROM_HERE, - base::BindOnce( - &CastContentBrowserClient::SelectClientCertificateOnIOThread, - base::Unretained(this), requesting_url, session_id, - web_contents->GetPrimaryMainFrame()->GetProcess()->GetID(), - web_contents->GetPrimaryMainFrame()->GetRoutingID(), - base::SequencedTaskRunner::GetCurrentDefault(), - base::BindOnce( - &content::ClientCertificateDelegate::ContinueWithCertificate, - base::Owned(delegate.release())))); - return base::OnceClosure(); -} - -bool CastContentBrowserClient::IsWhitelisted( - const GURL& /* gurl */, - const std::string& /* session_id */, - int /* render_process_id */, - int /* render_frame_id */, - bool /* for_device_auth */) { - return false; -} - -void CastContentBrowserClient::SelectClientCertificateOnIOThread( - GURL requesting_url, - const std::string& session_id, - int render_process_id, - int render_frame_id, - scoped_refptr original_runner, - base::OnceCallback, - scoped_refptr)> - continue_callback) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - if (IsWhitelisted(requesting_url, session_id, render_process_id, - render_frame_id, false)) { - original_runner->PostTask( - FROM_HERE, base::BindOnce(std::move(continue_callback), DeviceCert(), - DeviceKey())); - return; - } else { - LOG(ERROR) << "Invalid host for client certificate request: " - << requesting_url.host() - << " with render_process_id: " << render_process_id - << " and render_frame_id: " << render_frame_id; - } - original_runner->PostTask( - FROM_HERE, - base::BindOnce(std::move(continue_callback), nullptr, nullptr)); -} - -bool CastContentBrowserClient::CanCreateWindow( - content::RenderFrameHost* opener, - const GURL& opener_url, - const GURL& opener_top_level_frame_url, - const url::Origin& source_origin, - content::mojom::WindowContainerType container_type, - const GURL& target_url, - const content::Referrer& referrer, - const std::string& frame_name, - WindowOpenDisposition disposition, - const blink::mojom::WindowFeatures& features, - bool user_gesture, - bool opener_suppressed, - bool* no_javascript_access) { - *no_javascript_access = true; - - // To show new page in the existing view for WebView new window navigations, - // when supports_multiple_windows is disabled, return true so - // RenderFrameHostImpl::CreateNewWindow returns with kReuse. - // Otherwise, return false. - content::WebContents* web_contents = - content::WebContents::FromRenderFrameHost(opener); - if (web_contents) { - CastWebPreferences* cast_prefs = - static_cast(web_contents->GetUserData( - CastWebPreferences::kCastWebPreferencesDataKey)); - - return (cast_prefs && - !cast_prefs->preferences()->supports_multiple_windows.value()); - } - - return false; -} - -void CastContentBrowserClient::GetApplicationMediaInfo( - std::string* application_session_id, - bool* mixer_audio_enabled, - content::RenderFrameHost* render_frame_host) { - content::WebContents* web_contents = - content::WebContents::FromRenderFrameHost(render_frame_host); - if (web_contents) { - *application_session_id = - CastNavigationUIData::GetSessionIdForWebContents(web_contents); - chromecast::CastWebContents* cast_web_contents = - chromecast::CastWebContents::FromWebContents(web_contents); - *mixer_audio_enabled = - (cast_web_contents && cast_web_contents->is_mixer_audio_enabled()); - } -} - -bool CastContentBrowserClient::IsBufferingEnabled() { - return true; -} - -std::optional -CastContentBrowserClient::GetServiceManifestOverlay( - std::string_view service_name) { - if (service_name == ServiceManagerContext::kBrowserServiceName) { - return GetCastContentBrowserOverlayManifest(); - } - - return std::nullopt; -} - -std::vector -CastContentBrowserClient::GetExtraServiceManifests() { - // NOTE: This could be simplified and the list of manifests could be inlined. - // Not done yet since it would require touching downstream cast code. - return GetCastContentPackagedServicesOverlayManifest().packaged_services; -} - -void CastContentBrowserClient::GetAdditionalMappedFilesForChildProcess( - const base::CommandLine& command_line, - int child_process_id, - content::PosixFileDescriptorInfo* mappings) { -#if BUILDFLAG(IS_ANDROID) - mappings->ShareWithRegion( - kAndroidPakDescriptor, - base::GlobalDescriptors::GetInstance()->Get(kAndroidPakDescriptor), - base::GlobalDescriptors::GetInstance()->GetRegion(kAndroidPakDescriptor)); -#endif // BUILDFLAG(IS_ANDROID) -#if !BUILDFLAG(IS_FUCHSIA) - // TODO(crbug.com/40534193): Complete crash reporting integration on Fuchsia. - int crash_signal_fd = GetCrashSignalFD(command_line); - if (crash_signal_fd >= 0) { - mappings->Share(kCrashDumpSignal, crash_signal_fd); - } -#endif // !BUILDFLAG(IS_FUCHSIA) -} - -void CastContentBrowserClient::GetAdditionalWebUISchemes( - std::vector* additional_schemes) { - additional_schemes->push_back(kChromeResourceScheme); -} - -std::unique_ptr -CastContentBrowserClient::CreateDevToolsManagerDelegate() { - return std::make_unique(); -} - -std::unique_ptr -CastContentBrowserClient::GetNavigationUIData( - content::NavigationHandle* navigation_handle) { - DCHECK(navigation_handle); - - content::WebContents* web_contents = navigation_handle->GetWebContents(); - DCHECK(web_contents); - - std::string session_id = - CastNavigationUIData::GetSessionIdForWebContents(web_contents); - return std::make_unique(session_id); -} - -bool CastContentBrowserClient::ShouldEnableStrictSiteIsolation() { - return false; -} - -scoped_refptr CastContentBrowserClient::DeviceCert() { - return nullptr; -} - -scoped_refptr CastContentBrowserClient::DeviceKey() { - return nullptr; -} - -#if BUILDFLAG(IS_ANDROID) -int CastContentBrowserClient::GetCrashSignalFD( - const base::CommandLine& command_line) { - return crashpad::CrashHandlerHost::Get()->GetDeathSignalSocket(); -} -#elif !BUILDFLAG(IS_FUCHSIA) -int CastContentBrowserClient::GetCrashSignalFD( - const base::CommandLine& command_line) { - std::string process_type = - command_line.GetSwitchValueASCII(switches::kProcessType); - - if (process_type == switches::kRendererProcess || - process_type == switches::kGpuProcess || - process_type == switches::kUtilityProcess) { - breakpad::CrashHandlerHostLinux* crash_handler = - crash_handlers_[process_type]; - if (!crash_handler) { - crash_handler = CreateCrashHandlerHost(process_type); - crash_handlers_[process_type] = crash_handler; - } - return crash_handler->GetDeathSignalSocket(); - } - - return -1; -} - -breakpad::CrashHandlerHostLinux* -CastContentBrowserClient::CreateCrashHandlerHost( - const std::string& process_type) { - // Let cast shell dump to /tmp. Internal minidump generator code can move it - // to /data/minidumps later, since /data/minidumps is file lock-controlled. - base::FilePath dumps_path; - base::PathService::Get(base::DIR_TEMP, &dumps_path); - - // Always set "upload" to false to use our own uploader. - breakpad::CrashHandlerHostLinux* crash_handler = - new breakpad::CrashHandlerHostLinux(process_type, dumps_path, - false /* upload */); - // StartUploaderThread() even though upload is diferred. - // Breakpad-related memory is freed in the uploader thread. - crash_handler->StartUploaderThread(); - return crash_handler; -} -#endif // BUILDFLAG(IS_ANDROID) - -std::vector> -CastContentBrowserClient::CreateThrottlesForNavigation( - content::NavigationHandle* handle) { - std::vector> throttles; - - if (chromecast::IsFeatureEnabled(kEnableGeneralAudienceBrowsing)) { - throttles.push_back( - std::make_unique( - handle, general_audience_browsing_service_.get())); - } - - return throttles; -} - -void CastContentBrowserClient::RegisterNonNetworkSubresourceURLLoaderFactories( - int render_process_id, - int render_frame_id, - const std::optional& request_initiator_origin, - NonNetworkURLLoaderFactoryMap* factories) { - if (render_frame_id == MSG_ROUTING_NONE) { - LOG(ERROR) << "Service worker not supported."; - return; - } - content::RenderFrameHost* frame_host = - content::RenderFrameHost::FromID(render_process_id, render_frame_id); - - factories->emplace( - kChromeResourceScheme, - content::CreateWebUIURLLoaderFactory( - frame_host, kChromeResourceScheme, - /*allowed_webui_hosts=*/base::flat_set())); -} - -void CastContentBrowserClient::OnNetworkServiceCreated( - network::mojom::NetworkService* network_service) { - // Need to set up global NetworkService state before anything else uses it. - cast_network_contexts_->OnNetworkServiceCreated(network_service); -} - -void CastContentBrowserClient::ConfigureNetworkContextParams( - content::BrowserContext* context, - bool in_memory, - const base::FilePath& relative_partition_path, - network::mojom::NetworkContextParams* network_context_params, - cert_verifier::mojom::CertVerifierCreationParams* - cert_verifier_creation_params) { - return cast_network_contexts_->ConfigureNetworkContextParams( - context, in_memory, relative_partition_path, network_context_params, - cert_verifier_creation_params); -} - -bool CastContentBrowserClient::DoesSiteRequireDedicatedProcess( - content::BrowserContext* browser_context, - const GURL& effective_site_url) { - return false; -} - -bool CastContentBrowserClient::IsWebUIAllowedToMakeNetworkRequests( - const url::Origin& origin) { - return false; -} - -content::ContentBrowserClient::PrivateNetworkRequestPolicyOverride -CastContentBrowserClient::ShouldOverridePrivateNetworkRequestPolicy( - content::BrowserContext* browser_context, - const url::Origin& origin) { - // Some Cast apps hosted over HTTP needs to access the private network so that - // media can be streamed from a local media server. - return content::ContentBrowserClient::PrivateNetworkRequestPolicyOverride:: - kForceAllow; -} - -std::string CastContentBrowserClient::GetUserAgent() { - return chromecast::GetUserAgent(); -} - -void CastContentBrowserClient::CreateGeneralAudienceBrowsingService() { - DCHECK(!general_audience_browsing_service_); - general_audience_browsing_service_ = - std::make_unique( - browser_main_parts()->connector(), - cast_network_contexts_->GetSystemSharedURLLoaderFactory()); -} - -void CastContentBrowserClient::BindMediaRenderer( - mojo::PendingReceiver<::media::mojom::Renderer> receiver) { - auto media_task_runner = GetMediaTaskRunner(); - if (!media_task_runner->BelongsToCurrentThread()) { - media_task_runner->PostTask( - FROM_HERE, base::BindOnce(&CastContentBrowserClient::BindMediaRenderer, - base::Unretained(this), std::move(receiver))); - return; - } - - ::media::MojoRendererService::Create( - nullptr /* mojo_cdm_service_context */, - std::make_unique( - GetCmaBackendFactory(), std::move(media_task_runner), - GetVideoModeSwitcher(), GetVideoResolutionPolicy(), - base::UnguessableToken::Create(), nullptr /* frame_interfaces */, - true /* is_buffering_enabled */), - std::move(receiver)); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_browser_client.h chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client.h --- chromium-132.0.6834.110/chromecast/browser/cast_content_browser_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,374 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_ -#define CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_ - -#include -#include -#include -#include -#include - -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/threading/thread.h" -#include "build/build_config.h" -#include "build/buildflag.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/metrics/cast_metrics_service_client.h" -#include "content/public/browser/certificate_request_result_type.h" -#include "content/public/browser/content_browser_client.h" -#include "content/public/browser/frame_tree_node_id.h" -#include "media/mojo/buildflags.h" -#include "media/mojo/mojom/media_service.mojom.h" -#include "media/mojo/mojom/renderer.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "services/service_manager/public/cpp/binder_registry.h" -#include "services/service_manager/public/cpp/identity.h" -#include "services/service_manager/public/cpp/manifest.h" -#include "services/service_manager/public/mojom/interface_provider.mojom-forward.h" -#include "services/service_manager/public/mojom/service.mojom-forward.h" -#include "storage/browser/quota/quota_settings.h" - -class PrefService; - -namespace base { -struct OnTaskRunnerDeleter; -} - -namespace breakpad { -class CrashHandlerHostLinux; -} - -namespace device { -class BluetoothAdapterCast; -} - -namespace media { -class CdmFactory; -} - -namespace metrics { -class MetricsService; -} - -namespace net { -class SSLPrivateKey; -class X509Certificate; -} - -namespace chromecast { -class CastService; -class CastSystemMemoryPressureEvaluatorAdjuster; -class CastWebService; -class CastWindowManager; -class CastFeatureListCreator; -class DisplaySettingsManager; -class GeneralAudienceBrowsingService; -class MemoryPressureControllerImpl; -class ServiceConnector; - -namespace media { -class MediaCapsImpl; -class CmaBackendFactory; -class MediaPipelineBackendManager; -class MediaResourceTracker; -class VideoGeometrySetterService; -class VideoPlaneController; -class VideoModeSwitcher; -class VideoResolutionPolicy; -} - -namespace shell { -class CastBrowserMainParts; -class CastNetworkContexts; - -class CastContentBrowserClient - : public content::ContentBrowserClient, - public chromecast::metrics::CastMetricsServiceDelegate { - public: - // Creates an implementation of CastContentBrowserClient. Platform should - // link in an implementation as needed. - static std::unique_ptr Create( - CastFeatureListCreator* cast_feature_list_creator); - - // Returns a list of headers that will be exempt from CORS preflight checks. - // This is needed since currently servers don't have the correct response to - // preflight checks. - static std::vector GetCorsExemptHeadersList(); - - CastContentBrowserClient(const CastContentBrowserClient&) = delete; - CastContentBrowserClient& operator=(const CastContentBrowserClient&) = delete; - - ~CastContentBrowserClient() override; - - // Creates a ServiceConnector for routing Cast-related service interface - // binding requests. - virtual std::unique_ptr - CreateServiceConnector(); - - // Creates and returns the CastService instance for the current process. - virtual std::unique_ptr CreateCastService( - content::BrowserContext* browser_context, - CastSystemMemoryPressureEvaluatorAdjuster* - cast_system_memory_pressure_evaluator_adjuster, - PrefService* pref_service, - media::VideoPlaneController* video_plane_controller, - CastWindowManager* window_manager, - CastWebService* web_service, - DisplaySettingsManager* display_settings_manager); - - virtual media::VideoModeSwitcher* GetVideoModeSwitcher(); - - virtual void InitializeURLLoaderThrottleDelegate(); - - virtual void SetPersistentCookieAccessSettings(PrefService* pref_service); - - // Returns the task runner that must be used for media IO. - scoped_refptr GetMediaTaskRunner(); - - // Gets object for enforcing video resolution policy restrictions. - virtual media::VideoResolutionPolicy* GetVideoResolutionPolicy(); - - // Creates a CmaBackendFactory. - virtual media::CmaBackendFactory* GetCmaBackendFactory(); - - media::MediaResourceTracker* media_resource_tracker(); - - void ResetMediaResourceTracker(); - - media::MediaPipelineBackendManager* media_pipeline_backend_manager(); - - std::unique_ptr<::media::AudioManager> CreateAudioManager( - ::media::AudioLogFactory* audio_log_factory) override; - bool OverridesAudioManager() override; - media::MediaCapsImpl* media_caps(); - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - // Create a BluetoothAdapter for WebBluetooth support. - // TODO(slan): This further couples the browser to the Cast service. Remove - // this once the dedicated Bluetooth service has been implemented. - // (b/76155468) - virtual scoped_refptr CreateBluetoothAdapter(); -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - - // chromecast::metrics::CastMetricsServiceDelegate implementation: - void SetMetricsClientId(const std::string& client_id) override; - void RegisterMetricsProviders( - ::metrics::MetricsService* metrics_service) override; - - // Returns whether or not the remote debugging service should be started - // on browser startup. - virtual bool EnableRemoteDebuggingImmediately(); - - // Note: These were originally part of ContentBrowserClient, but have been - // lifted into this class as they're now only used by Chromecast. This is a - // transitional step to avoid breakage in the internal downstream repository. - virtual void RunServiceInstance( - const service_manager::Identity& identity, - mojo::PendingReceiver* receiver); - virtual std::optional GetServiceManifestOverlay( - std::string_view service_name); - std::vector GetExtraServiceManifests(); - std::vector GetStartupServices(); - - // content::ContentBrowserClient implementation: - std::unique_ptr CreateBrowserMainParts( - bool is_integration_test) override; - bool IsHandledURL(const GURL& url) override; - void AppendExtraCommandLineSwitches(base::CommandLine* command_line, - int child_process_id) override; - std::string GetAcceptLangs(content::BrowserContext* context) override; - network::mojom::NetworkContext* GetSystemNetworkContext() override; - void OverrideWebkitPrefs(content::WebContents* web_contents, - blink::web_pref::WebPreferences* prefs) override; - std::string GetApplicationLocale() override; - void AllowCertificateError( - content::WebContents* web_contents, - int cert_error, - const net::SSLInfo& ssl_info, - const GURL& request_url, - bool is_primary_main_frame_request, - bool strict_enforcement, - base::OnceCallback callback) - override; - base::OnceClosure SelectClientCertificate( - content::BrowserContext* browser_context, - int process_id, - content::WebContents* web_contents, - net::SSLCertRequestInfo* cert_request_info, - net::ClientCertIdentityList client_certs, - std::unique_ptr delegate) override; - bool CanCreateWindow(content::RenderFrameHost* opener, - const GURL& opener_url, - const GURL& opener_top_level_frame_url, - const url::Origin& source_origin, - content::mojom::WindowContainerType container_type, - const GURL& target_url, - const content::Referrer& referrer, - const std::string& frame_name, - WindowOpenDisposition disposition, - const blink::mojom::WindowFeatures& features, - bool user_gesture, - bool opener_suppressed, - bool* no_javascript_access) override; - // New Mojo bindings should be added to - // cast_content_browser_client_receiver_bindings.cc, so that they go through - // security review. - void ExposeInterfacesToRenderer( - service_manager::BinderRegistry* registry, - blink::AssociatedInterfaceRegistry* associated_registry, - content::RenderProcessHost* render_process_host) override; - void BindMediaServiceReceiver(content::RenderFrameHost* render_frame_host, - mojo::GenericPendingReceiver receiver) override; - void RegisterBrowserInterfaceBindersForFrame( - content::RenderFrameHost* render_frame_host, - mojo::BinderMapWithContext* map) override; - mojo::Remote<::media::mojom::MediaService> RunSecondaryMediaService() - override; - void GetAdditionalMappedFilesForChildProcess( - const base::CommandLine& command_line, - int child_process_id, - content::PosixFileDescriptorInfo* mappings) override; - void GetAdditionalWebUISchemes( - std::vector* additional_schemes) override; - std::unique_ptr - CreateDevToolsManagerDelegate() override; - std::unique_ptr GetNavigationUIData( - content::NavigationHandle* navigation_handle) override; - bool ShouldEnableStrictSiteIsolation() override; - std::vector> - CreateThrottlesForNavigation(content::NavigationHandle* handle) override; - void RegisterNonNetworkSubresourceURLLoaderFactories( - int render_process_id, - int render_frame_id, - const std::optional& request_initiator_origin, - NonNetworkURLLoaderFactoryMap* factories) override; - void OnNetworkServiceCreated( - network::mojom::NetworkService* network_service) override; - void ConfigureNetworkContextParams( - content::BrowserContext* context, - bool in_memory, - const base::FilePath& relative_partition_path, - network::mojom::NetworkContextParams* network_context_params, - cert_verifier::mojom::CertVerifierCreationParams* - cert_verifier_creation_params) override; - std::string GetUserAgent() override; - bool DoesSiteRequireDedicatedProcess(content::BrowserContext* browser_context, - const GURL& effective_site_url) override; - bool IsWebUIAllowedToMakeNetworkRequests(const url::Origin& origin) override; - PrivateNetworkRequestPolicyOverride ShouldOverridePrivateNetworkRequestPolicy( - content::BrowserContext* browser_context, - const url::Origin& origin) override; - - CastFeatureListCreator* GetCastFeatureListCreator() { - return cast_feature_list_creator_; - } - - void CreateGeneralAudienceBrowsingService(); - - virtual std::unique_ptr<::media::CdmFactory> CreateCdmFactory( - ::media::mojom::FrameInterfaceFactory* frame_interfaces); - -#if BUILDFLAG(ENABLE_CAST_RENDERER) - void BindGpuHostReceiver(mojo::GenericPendingReceiver receiver) override; -#endif // BUILDFLAG(ENABLE_CAST_RENDERER) - - CastNetworkContexts* cast_network_contexts() { - return cast_network_contexts_.get(); - } - - protected: - explicit CastContentBrowserClient( - CastFeatureListCreator* cast_feature_list_creator); - - CastBrowserMainParts* browser_main_parts() { - return cast_browser_main_parts_; - } - - void BindMediaRenderer( - mojo::PendingReceiver<::media::mojom::Renderer> receiver); - - void GetApplicationMediaInfo(std::string* application_session_id, - bool* mixer_audio_enabled, - content::RenderFrameHost* render_frame_host); - - // Returns whether buffering should be used for the CMA Pipeline created for - // this runtime instance. May be called from any thread. - virtual bool IsBufferingEnabled(); - - private: - // Create device cert/key - virtual scoped_refptr DeviceCert(); - virtual scoped_refptr DeviceKey(); - - virtual bool IsWhitelisted(const GURL& gurl, - const std::string& session_id, - int render_process_id, - int render_frame_id, - bool for_device_auth); - - void SelectClientCertificateOnIOThread( - GURL requesting_url, - const std::string& session_id, - int render_process_id, - int render_frame_id, - scoped_refptr original_runner, - base::OnceCallback, - scoped_refptr)> - continue_callback); - -#if !BUILDFLAG(IS_FUCHSIA) - // Returns the crash signal FD corresponding to the current process type. - int GetCrashSignalFD(const base::CommandLine& command_line); - -#if !BUILDFLAG(IS_ANDROID) - // Creates a CrashHandlerHost instance for the given process type. - breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost( - const std::string& process_type); - - // A static cache to hold crash_handlers for each process_type - std::map crash_handlers_; - - // Notify renderers of memory pressure (Android renderers register directly - // with OS for this). - std::unique_ptr memory_pressure_controller_; -#endif // !BUILDFLAG(IS_ANDROID) -#endif // !BUILDFLAG(IS_FUCHSIA) - - // CMA thread used by AudioManager, MojoRenderer, and MediaPipelineBackend. - std::unique_ptr media_thread_; - - // Tracks usage of media resource by e.g. CMA pipeline, CDM. - media::MediaResourceTracker* media_resource_tracker_ = nullptr; - -#if BUILDFLAG(ENABLE_CAST_RENDERER) - void CreateMediaService( - mojo::PendingReceiver<::media::mojom::MediaService> receiver); - - // VideoGeometrySetterService must be constructed On a sequence, and later - // runs and destructs on this sequence. - void CreateVideoGeometrySetterServiceOnMediaThread(); - void BindVideoGeometrySetterServiceOnMediaThread( - mojo::GenericPendingReceiver receiver); - // video_geometry_setter_service_ lives on media thread. - std::unique_ptr - video_geometry_setter_service_; -#endif - - // Created by CastContentBrowserClient but owned by BrowserMainLoop. - CastBrowserMainParts* cast_browser_main_parts_; - std::unique_ptr cast_network_contexts_; - std::unique_ptr cma_backend_factory_; - std::unique_ptr - general_audience_browsing_service_; - - CastFeatureListCreator* cast_feature_list_creator_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_browser_client_receiver_bindings.cc chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client_receiver_bindings.cc --- chromium-132.0.6834.110/chromecast/browser/cast_content_browser_client_receiver_bindings.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_browser_client_receiver_bindings.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,211 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file exposes services from the cast browser to child processes. - -#include "chromecast/browser/cast_content_browser_client.h" - -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "base/threading/sequence_local_storage_slot.h" -#include "build/build_config.h" -#include "chromecast/browser/application_media_info_manager.h" -#include "chromecast/browser/cast_browser_interface_binders.h" -#include "chromecast/browser/cast_browser_main_parts.h" -#include "chromecast/browser/cast_browser_process.h" -#include "chromecast/browser/media/media_caps_impl.h" -#include "chromecast/browser/metrics/metrics_helper_impl.h" -#include "chromecast/browser/service_connector.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/media/cdm/cast_cdm_factory.h" -#include "components/cdm/browser/media_drm_storage_impl.h" -#include "content/public/browser/render_process_host.h" -#include "media/mojo/buildflags.h" -#include "mojo/public/cpp/bindings/binder_map.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "url/origin.h" - -#if BUILDFLAG(ENABLE_CAST_RENDERER) -#include "chromecast/media/service/cast_mojo_media_client.h" -#include "chromecast/media/service/video_geometry_setter_service.h" -#include "media/mojo/services/media_service.h" // nogncheck -#endif // BUILDFLAG(ENABLE_CAST_RENDERER) - -#if !BUILDFLAG(IS_ANDROID) -#include "chromecast/browser/memory_pressure_controller_impl.h" -#endif // !BUILDFLAG(IS_ANDROID) - -namespace chromecast { -namespace shell { - -namespace { - -void CreateOriginId(cdm::MediaDrmStorageImpl::OriginIdObtainedCB callback) { - std::move(callback).Run(true, base::UnguessableToken::Create()); -} - -void AllowEmptyOriginIdCB(base::OnceCallback callback) { - std::move(callback).Run(false); -} - -void CreateMediaDrmStorage( - content::RenderFrameHost* render_frame_host, - mojo::PendingReceiver<::media::mojom::MediaDrmStorage> receiver) { - DVLOG(1) << __func__; - PrefService* pref_service = CastBrowserProcess::GetInstance()->pref_service(); - DCHECK(pref_service); - - if (render_frame_host->GetLastCommittedOrigin().opaque()) { - DVLOG(1) << __func__ << ": Unique origin."; - return; - } - - // The object will be deleted on connection error, or when the frame navigates - // away. - new cdm::MediaDrmStorageImpl( - *render_frame_host, pref_service, base::BindRepeating(&CreateOriginId), - base::BindRepeating(&AllowEmptyOriginIdCB), std::move(receiver)); -} - -} // namespace - -void CastContentBrowserClient::ExposeInterfacesToRenderer( - service_manager::BinderRegistry* registry, - blink::AssociatedInterfaceRegistry* associated_registry, - content::RenderProcessHost* render_process_host) { - registry->AddInterface( - base::BindRepeating( - &media::MediaCapsImpl::AddReceiver, - base::Unretained(cast_browser_main_parts_->media_caps())), - base::SingleThreadTaskRunner::GetCurrentDefault()); - - registry->AddInterface( - base::BindRepeating( - &metrics::MetricsHelperImpl::AddReceiver, - base::Unretained(cast_browser_main_parts_->metrics_helper())), - base::SingleThreadTaskRunner::GetCurrentDefault()); - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - if (!memory_pressure_controller_) { - memory_pressure_controller_.reset(new MemoryPressureControllerImpl()); - } - - registry->AddInterface( - base::BindRepeating(&MemoryPressureControllerImpl::AddReceiver, - base::Unretained(memory_pressure_controller_.get())), - base::SingleThreadTaskRunner::GetCurrentDefault()); -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) -} - -void CastContentBrowserClient::BindMediaServiceReceiver( - content::RenderFrameHost* render_frame_host, - mojo::GenericPendingReceiver receiver) { - if (auto r = receiver.As<::media::mojom::MediaDrmStorage>()) { - CreateMediaDrmStorage(render_frame_host, std::move(r)); - return; - } - - if (auto r = receiver.As()) { - ServiceConnector::BindReceiver(kMediaServiceClientId, std::move(r)); - return; - } - - if (auto r = receiver.As<::media::mojom::CastApplicationMediaInfoManager>()) { - std::string application_session_id; - bool mixer_audio_enabled; - GetApplicationMediaInfo(&application_session_id, &mixer_audio_enabled, - render_frame_host); - media::ApplicationMediaInfoManager::Create( - render_frame_host, std::move(application_session_id), - mixer_audio_enabled, std::move(r)); - return; - } -} - -void CastContentBrowserClient::RegisterBrowserInterfaceBindersForFrame( - content::RenderFrameHost* render_frame_host, - mojo::BinderMapWithContext* map) { - PopulateCastFrameBinders(render_frame_host, map); -} - -mojo::Remote<::media::mojom::MediaService> -CastContentBrowserClient::RunSecondaryMediaService() { - mojo::Remote<::media::mojom::MediaService> remote; -#if BUILDFLAG(ENABLE_CAST_RENDERER) - GetMediaTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&CastContentBrowserClient::CreateMediaService, - base::Unretained(this), - remote.BindNewPipeAndPassReceiver())); -#endif // BUILDFLAG(ENABLE_CAST_RENDERER) - return remote; -} - -#if BUILDFLAG(ENABLE_CAST_RENDERER) -void CastContentBrowserClient::CreateMediaService( - mojo::PendingReceiver<::media::mojom::MediaService> receiver) { - DCHECK(GetMediaTaskRunner() && - GetMediaTaskRunner()->BelongsToCurrentThread()); - if (!video_geometry_setter_service_) { - CreateVideoGeometrySetterServiceOnMediaThread(); - } - - // Using base::Unretained is safe here because this class will persist for - // the duration of the browser process' lifetime. - auto mojo_media_client = std::make_unique( - GetCmaBackendFactory(), - base::BindRepeating(&CastContentBrowserClient::CreateCdmFactory, - base::Unretained(this)), - GetVideoModeSwitcher(), GetVideoResolutionPolicy(), - base::BindRepeating(&CastContentBrowserClient::IsBufferingEnabled, - base::Unretained(this))); - mojo_media_client->SetVideoGeometrySetterService( - video_geometry_setter_service_.get()); - - static base::SequenceLocalStorageSlot<::media::MediaService> service; - service.emplace(std::move(mojo_media_client), std::move(receiver)); -} - -void CastContentBrowserClient::CreateVideoGeometrySetterServiceOnMediaThread() { - DCHECK(GetMediaTaskRunner() && - GetMediaTaskRunner()->BelongsToCurrentThread()); - DCHECK(!video_geometry_setter_service_); - video_geometry_setter_service_ = - std::unique_ptr( - new media::VideoGeometrySetterService, - base::OnTaskRunnerDeleter( - base::SingleThreadTaskRunner::GetCurrentDefault())); -} - -void CastContentBrowserClient::BindVideoGeometrySetterServiceOnMediaThread( - mojo::GenericPendingReceiver receiver) { - DCHECK(GetMediaTaskRunner() && - GetMediaTaskRunner()->BelongsToCurrentThread()); - if (!video_geometry_setter_service_) { - CreateVideoGeometrySetterServiceOnMediaThread(); - } - if (auto r = receiver.As()) { - video_geometry_setter_service_->GetVideoGeometrySetter(std::move(r)); - } -} - -void CastContentBrowserClient::BindGpuHostReceiver( - mojo::GenericPendingReceiver receiver) { - DCHECK(GetMediaTaskRunner()); - GetMediaTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&CastContentBrowserClient:: - BindVideoGeometrySetterServiceOnMediaThread, - base::Unretained(this), std::move(receiver))); -} -#endif // BUILDFLAG(ENABLE_CAST_RENDERER) - -void CastContentBrowserClient::RunServiceInstance( - const service_manager::Identity& identity, - mojo::PendingReceiver* receiver) {} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_gesture_handler.cc chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler.cc --- chromium-132.0.6834.110/chromecast/browser/cast_content_gesture_handler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,123 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_content_gesture_handler.h" - -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "chromecast/base/chromecast_switches.h" - -namespace chromecast { - -namespace { -constexpr int kDefaultBackGestureHorizontalThreshold = 80; -} // namespace - -CastContentGestureHandler::CastContentGestureHandler( - GestureRouter* delegate, - bool enable_top_drag_gesture) - : priority_(Priority::NONE), - enable_top_drag_gesture_(enable_top_drag_gesture), - back_horizontal_threshold_( - GetSwitchValueInt(switches::kBackGestureHorizontalThreshold, - kDefaultBackGestureHorizontalThreshold)), - delegate_(delegate) { - DCHECK(delegate_); -} - -CastContentGestureHandler::CastContentGestureHandler(GestureRouter* delegate) - : CastContentGestureHandler( - delegate, - GetSwitchValueBoolean(switches::kEnableTopDragGesture, false)) {} - -CastContentGestureHandler::~CastContentGestureHandler() = default; - -void CastContentGestureHandler::SetPriority( - CastGestureHandler::Priority priority) { - priority_ = priority; -} - -CastGestureHandler::Priority CastContentGestureHandler::GetPriority() { - return priority_; -} - -bool CastContentGestureHandler::CanHandleSwipe( - CastSideSwipeOrigin swipe_origin) { - if (!delegate_) - return false; - return delegate_->CanHandleGesture(GestureForSwipeOrigin(swipe_origin)); -} - -GestureType CastContentGestureHandler::GestureForSwipeOrigin( - CastSideSwipeOrigin swipe_origin) { - switch (swipe_origin) { - case CastSideSwipeOrigin::LEFT: - return GestureType::GO_BACK; - case CastSideSwipeOrigin::TOP: - return enable_top_drag_gesture_ ? GestureType::TOP_DRAG - : GestureType::NO_GESTURE; - case CastSideSwipeOrigin::RIGHT: - return GestureType::RIGHT_DRAG; - default: - return GestureType::NO_GESTURE; - } -} - -void CastContentGestureHandler::HandleSideSwipe( - CastSideSwipeEvent event, - CastSideSwipeOrigin swipe_origin, - const gfx::Point& touch_location) { - if (!CanHandleSwipe(swipe_origin)) { - return; - } - GestureType gesture_type = GestureForSwipeOrigin(swipe_origin); - - switch (event) { - case CastSideSwipeEvent::BEGIN: - current_swipe_time_ = base::ElapsedTimer(); - if (gesture_type == GestureType::GO_BACK) { - DVLOG(1) << "back swipe gesture begin"; - } - break; - case CastSideSwipeEvent::CONTINUE: - DVLOG(1) << "swipe gesture continue, elapsed time: " - << current_swipe_time_.Elapsed().InMilliseconds() << "ms"; - delegate_->GestureProgress(gesture_type, touch_location); - break; - case CastSideSwipeEvent::END: - DVLOG(1) << "swipe end, elapsed time: " - << current_swipe_time_.Elapsed().InMilliseconds() << "ms"; - // If it's a back gesture, we have special handling to check for the - // horizontal threshold. If the finger has lifted before the horizontal - // gesture, cancel the back gesture and do not consume it. - if (gesture_type == GestureType::GO_BACK && - touch_location.x() < back_horizontal_threshold_) { - DVLOG(1) << "swipe gesture cancelled"; - delegate_->CancelGesture(GestureType::GO_BACK); - return; - } - delegate_->ConsumeGesture(gesture_type, base::DoNothing()); - DVLOG(1) << "gesture complete, elapsed time: " - << current_swipe_time_.Elapsed().InMilliseconds() << "ms"; - break; - } -} - -void CastContentGestureHandler::HandleTapDownGesture( - const gfx::Point& touch_location) { - if (!delegate_ || !delegate_->CanHandleGesture(GestureType::TAP_DOWN)) { - return; - } - delegate_->ConsumeGesture(GestureType::TAP_DOWN, base::DoNothing()); -} - -void CastContentGestureHandler::HandleTapGesture( - const gfx::Point& touch_location) { - if (!delegate_ || !delegate_->CanHandleGesture(GestureType::TAP)) { - return; - } - delegate_->ConsumeGesture(GestureType::TAP, base::DoNothing()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_gesture_handler.h chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler.h --- chromium-132.0.6834.110/chromecast/browser/cast_content_gesture_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_CONTENT_GESTURE_HANDLER_H_ -#define CHROMECAST_BROWSER_CAST_CONTENT_GESTURE_HANDLER_H_ - -#include "base/memory/weak_ptr.h" -#include "base/timer/elapsed_timer.h" -#include "chromecast/browser/gesture_router.h" -#include "chromecast/graphics/gestures/cast_gesture_handler.h" - -namespace chromecast { - -// Receives root window level gestures, interprets them, and hands them to the -// CastContentWindow::Delegate. -class CastContentGestureHandler : public CastGestureHandler { - public: - explicit CastContentGestureHandler(GestureRouter* delegate); - CastContentGestureHandler(GestureRouter* delegate, - bool enable_top_drag_gesture); - ~CastContentGestureHandler() override; - - // CastGestureHandler implementation: - Priority GetPriority() override; - bool CanHandleSwipe(CastSideSwipeOrigin swipe_origin) override; - void HandleSideSwipe(CastSideSwipeEvent event, - CastSideSwipeOrigin swipe_origin, - const gfx::Point& touch_location) override; - void HandleTapDownGesture(const gfx::Point& touch_location) override; - void HandleTapGesture(const gfx::Point& touch_location) override; - - void SetPriority(Priority priority); - - private: - GestureType GestureForSwipeOrigin(CastSideSwipeOrigin swipe_origin); - - Priority priority_; - - const bool enable_top_drag_gesture_; - - // Number of pixels past swipe origin to consider as a back gesture. - const int back_horizontal_threshold_; - GestureRouter* const delegate_; - base::ElapsedTimer current_swipe_time_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_CONTENT_GESTURE_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_gesture_handler_test.cc chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler_test.cc --- chromium-132.0.6834.110/chromecast/browser/cast_content_gesture_handler_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_gesture_handler_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,238 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_content_gesture_handler.h" - -#include "base/functional/callback_helpers.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/base/chromecast_switches.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_base.h" -#include "testing/gmock/include/gmock/gmock.h" - -// Gmock matchers and actions that we use below. -using testing::_; -using testing::AnyOf; -using testing::Eq; -using testing::Return; -using testing::SetArgPointee; -using testing::WithArg; - -namespace chromecast { - -namespace { - -constexpr gfx::Point kLeftSidePoint(5, 50); -constexpr gfx::Point kOngoingBackGesturePoint1(70, 50); -constexpr gfx::Point kOngoingBackGesturePoint2(75, 50); -constexpr gfx::Point kValidBackGestureEndPoint(90, 50); -constexpr gfx::Point kPastTheEndPoint1(105, 50); -constexpr gfx::Point kPastTheEndPoint2(200, 50); - -constexpr gfx::Point kTopSidePoint(100, 5); -constexpr gfx::Point kOngoingTopGesturePoint1(100, 70); -constexpr gfx::Point kOngoingTopGesturePoint2(100, 75); -constexpr gfx::Point kTopGestureEndPoint(100, 90); - -constexpr gfx::Point kRightSidePoint(500, 50); -constexpr gfx::Point kOngoingRightGesturePoint1(400, 50); -constexpr gfx::Point kRightGestureEndPoint(200, 60); - -class MockGestureHandler : public mojom::GestureHandler { - public: - MockGestureHandler() = default; - ~MockGestureHandler() override = default; - - MOCK_METHOD(void, OnBackGesture, (OnBackGestureCallback), (override)); - MOCK_METHOD(void, OnBackGestureProgress, (const gfx::Point&), (override)); - MOCK_METHOD(void, OnTopDragGestureProgress, (const gfx::Point&), (override)); - MOCK_METHOD(void, OnTopDragGestureDone, (), (override)); - MOCK_METHOD(void, - OnRightDragGestureProgress, - (const gfx::Point&), - (override)); - MOCK_METHOD(void, OnRightDragGestureDone, (), (override)); - MOCK_METHOD(void, OnBackGestureCancel, (), (override)); - MOCK_METHOD(void, OnTapGesture, (), (override)); - MOCK_METHOD(void, OnTapDownGesture, (), (override)); -}; - -} // namespace - -class CastContentGestureHandlerTest : public testing::Test { - public: - CastContentGestureHandlerTest() {} - - void SetUp() final { - gesture_router_ = std::make_unique(); - dispatcher_ = std::make_unique( - gesture_router_.get(), true); - gesture_router_->SetHandler(&handler_); - } - - protected: - std::unique_ptr gesture_router_; - std::unique_ptr dispatcher_; - MockGestureHandler handler_; -}; - -// Verify the simple case of a left swipe with the right horizontal leads to -// back. -TEST_F(CastContentGestureHandlerTest, VerifySimpleBackSuccess) { - gesture_router_->SetCanTopDrag(false); - gesture_router_->SetCanGoBack(true); - EXPECT_CALL(handler_, OnBackGestureProgress(Eq(kOngoingBackGesturePoint1))); - EXPECT_CALL(handler_, OnBackGesture(_)); - ASSERT_TRUE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::LEFT)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::LEFT, kLeftSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::LEFT, - kOngoingBackGesturePoint1); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::END, - CastSideSwipeOrigin::LEFT, - kValidBackGestureEndPoint); -} - -// Verify that if the finger is not lifted, that's not a back gesture. -TEST_F(CastContentGestureHandlerTest, VerifyNoDispatchOnNoLift) { - gesture_router_->SetCanTopDrag(false); - gesture_router_->SetCanGoBack(true); - EXPECT_CALL(handler_, OnBackGestureProgress(Eq(kValidBackGestureEndPoint))); - EXPECT_CALL(handler_, OnBackGesture(_)).Times(0); - EXPECT_CALL(handler_, OnBackGestureProgress(Eq(kPastTheEndPoint1))); - ASSERT_TRUE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::LEFT)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::LEFT, kLeftSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::LEFT, - kValidBackGestureEndPoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::LEFT, kPastTheEndPoint1); -} - -// Verify that multiple 'continue' events still only lead to one back -// invocation. -TEST_F(CastContentGestureHandlerTest, VerifyOnlySingleDispatch) { - gesture_router_->SetCanTopDrag(false); - gesture_router_->SetCanGoBack(true); - - EXPECT_CALL(handler_, OnBackGestureProgress(Eq(kValidBackGestureEndPoint))); - EXPECT_CALL(handler_, OnBackGestureProgress(Eq(kPastTheEndPoint1))); - EXPECT_CALL(handler_, OnBackGesture(_)); - ASSERT_TRUE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::LEFT)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::LEFT, kLeftSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::LEFT, - kValidBackGestureEndPoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::LEFT, kPastTheEndPoint1); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::END, - CastSideSwipeOrigin::LEFT, kPastTheEndPoint2); -} - -// Verify that if the delegate says it doesn't handle back that we won't try to -// ask them to consume it. -TEST_F(CastContentGestureHandlerTest, VerifyDelegateDoesNotConsumeUnwanted) { - gesture_router_->SetCanTopDrag(false); - gesture_router_->SetCanGoBack(false); - ASSERT_FALSE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::LEFT)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::LEFT, kLeftSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::LEFT, - kValidBackGestureEndPoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::END, - CastSideSwipeOrigin::LEFT, kPastTheEndPoint2); -} - -// Verify that a not-left gesture doesn't lead to a swipe. -TEST_F(CastContentGestureHandlerTest, VerifyNotLeftSwipeIsNotBack) { - gesture_router_->SetCanTopDrag(false); - - ASSERT_FALSE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::TOP)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::TOP, kTopSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::TOP, - kOngoingTopGesturePoint2); -} - -// Verify that if the gesture doesn't go far enough horizontally that we will -// not consider it a swipe. -TEST_F(CastContentGestureHandlerTest, VerifyNotFarEnoughRightIsNotBack) { - gesture_router_->SetCanTopDrag(false); - gesture_router_->SetCanGoBack(true); - - EXPECT_CALL(handler_, OnBackGestureProgress(Eq(kOngoingBackGesturePoint1))); - EXPECT_CALL(handler_, OnBackGestureCancel()); - ASSERT_TRUE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::LEFT)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::LEFT, kLeftSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::LEFT, - kOngoingBackGesturePoint1); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::END, - CastSideSwipeOrigin::LEFT, - kOngoingBackGesturePoint2); -} - -// Verify that if the gesture ends before going far enough, that's also not a -// swipe. -TEST_F(CastContentGestureHandlerTest, VerifyNotFarEnoughRightAndEndIsNotBack) { - gesture_router_->SetCanTopDrag(false); - gesture_router_->SetCanGoBack(true); - - EXPECT_CALL(handler_, OnBackGestureProgress(Eq(kOngoingBackGesturePoint1))); - EXPECT_CALL(handler_, OnBackGestureCancel()); - ASSERT_TRUE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::LEFT)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::LEFT, kLeftSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::LEFT, - kOngoingBackGesturePoint1); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::END, - CastSideSwipeOrigin::LEFT, - kOngoingBackGesturePoint2); -} - -// Verify simple top-down drag. -TEST_F(CastContentGestureHandlerTest, VerifySimpleTopSuccess) { - gesture_router_->SetCanTopDrag(true); - gesture_router_->SetCanGoBack(false); - - EXPECT_CALL(handler_, OnTopDragGestureProgress(Eq(kOngoingTopGesturePoint1))); - EXPECT_CALL(handler_, OnTopDragGestureDone()); - ASSERT_TRUE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::TOP)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::TOP, kTopSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::TOP, - kOngoingTopGesturePoint1); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::END, - CastSideSwipeOrigin::TOP, kTopGestureEndPoint); -} - -// Verify simple right-to-left drag. -TEST_F(CastContentGestureHandlerTest, VerifySimpleRightSuccess) { - gesture_router_->SetCanRightDrag(true); - gesture_router_->SetCanTopDrag(false); - gesture_router_->SetCanGoBack(false); - - EXPECT_CALL(handler_, - OnRightDragGestureProgress(Eq(kOngoingRightGesturePoint1))); - EXPECT_CALL(handler_, OnRightDragGestureDone()); - ASSERT_TRUE(dispatcher_->CanHandleSwipe(CastSideSwipeOrigin::RIGHT)); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - CastSideSwipeOrigin::RIGHT, kRightSidePoint); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - CastSideSwipeOrigin::RIGHT, - kOngoingRightGesturePoint1); - dispatcher_->HandleSideSwipe(CastSideSwipeEvent::END, - CastSideSwipeOrigin::RIGHT, - kRightGestureEndPoint); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_window.cc chromium-132.0.6834.159/chromecast/browser/cast_content_window.cc --- chromium-132.0.6834.110/chromecast/browser/cast_content_window.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_window.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_content_window.h" - -namespace chromecast { - -CastContentWindow::CastContentWindow(mojom::CastWebViewParamsPtr params) - : params_(std::move(params)) { - RegisterBackGestureRouter(gesture_router()); -} - -CastContentWindow::~CastContentWindow() = default; - -void CastContentWindow::SetCastWebContents(CastWebContents* cast_web_contents) { - cast_web_contents_ = cast_web_contents; - // Must provide binder callbacks with WeakPtr since CastContentWindow + these - // interface implementations are destroyed before CastWebContents. - cast_web_contents_->local_interfaces()->AddBinder(base::BindRepeating( - &CastContentWindow::BindReceiver, weak_factory_.GetWeakPtr())); - cast_web_contents_->local_interfaces()->AddBinder(base::BindRepeating( - &CastContentWindow::BindActivityWindow, weak_factory_.GetWeakPtr())); - cast_web_contents_->local_interfaces()->AddBinder( - gesture_router()->GetBinder()); -} - -void CastContentWindow::AddObserver(Observer* observer) { - DCHECK(observer); - sync_observers_.AddObserver(observer); -} - -void CastContentWindow::RemoveObserver(CastContentWindow::Observer* observer) { - DCHECK(observer); - sync_observers_.RemoveObserver(observer); -} - -void CastContentWindow::AddObserver( - mojo::PendingRemote observer) { - observers_.Add(std::move(observer)); -} - -void CastContentWindow::BindReceiver( - mojo::PendingReceiver receiver) { - receiver_.Bind(std::move(receiver)); -} - -void CastContentWindow::BindActivityWindow( - mojo::PendingReceiver receiver) { - activity_window_receiver_.Bind(std::move(receiver)); -} - -void CastContentWindow::Show() { - RequestVisibility(VisibilityPriority::STICKY_ACTIVITY); -} - -void CastContentWindow::Hide() {} - -void CastContentWindow::NotifyVisibilityChange(VisibilityType visibility_type) { - for (auto& observer : observers_) { - observer->OnVisibilityChange(visibility_type); - } - for (Observer& observer : sync_observers_) { - observer.OnVisibilityChange(visibility_type); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_window.h chromium-132.0.6834.159/chromecast/browser/cast_content_window.h --- chromium-132.0.6834.110/chromecast/browser/cast_content_window.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_window.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,100 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_H_ -#define CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_H_ - -#include "base/functional/callback_forward.h" -#include "base/observer_list.h" -#include "base/observer_list_types.h" -#include "chromecast/browser/cast_web_contents.h" -#include "chromecast/browser/gesture_router.h" -#include "chromecast/browser/mojom/cast_content_window.mojom.h" -#include "chromecast/browser/mojom/cast_web_service.mojom.h" -#include "chromecast/browser/visibility_types.h" -#include "chromecast/common/mojom/activity_window.mojom.h" -#include "chromecast/graphics/gestures/cast_gesture_handler.h" -#include "chromecast/ui/back_gesture_router.h" -#include "chromecast/ui/mojom/ui_service.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "ui/events/event.h" - -namespace chromecast { - -// Class that represents the "window" a WebContents is displayed in cast_shell. -// For Linux, this represents an Aura window. For Android, this is a Activity. -// See CastContentWindowAura and CastContentWindowAndroid. -class CastContentWindow : public mojom::CastContentWindow, - public mojom::ActivityWindow { - public: - // Synchronous in-process observer for CastContentWindow. - class Observer : public base::CheckedObserver { - public: - virtual void OnVisibilityChange(VisibilityType visibility_type) = 0; - }; - - explicit CastContentWindow(mojom::CastWebViewParamsPtr params); - ~CastContentWindow() override; - - // |cast_web_contents| must outlive the CastContentWindow. - void SetCastWebContents(CastWebContents* cast_web_contents); - - // Adds an observer that receives the notifications in-process. - void AddObserver(Observer* observer); - // Removes an observer that would receive the notifications in-process. - void RemoveObserver(Observer* observer); - - CastWebContents* cast_web_contents() { return cast_web_contents_; } - GestureRouter* gesture_router() { return &gesture_router_; } - - // mojom::CastContentWindow implementation: - void CreateWindow(mojom::ZOrder z_order, - VisibilityPriority visibility_priority) override = 0; - void AddObserver( - mojo::PendingRemote observer) override; - void GrantScreenAccess() override = 0; - void RevokeScreenAccess() override = 0; - void RequestVisibility(VisibilityPriority visibility_priority) override = 0; - void EnableTouchInput(bool enabled) override = 0; - - // mojom::ActivityWindow implementation: - void Show() override; - void Hide() override; - - // Notify the window that its visibility type has changed. This should only - // ever be called by the window manager. - // TODO(seantopping): Make this private to the window manager. - virtual void NotifyVisibilityChange(VisibilityType visibility_type); - - // Registers this as a delegate to BackGestureRouter. - virtual void RegisterBackGestureRouter( - ::chromecast::BackGestureRouter* gesture_router) {} - - // Binds a receiver for remote control of CastContentWindow. - void BindReceiver(mojo::PendingReceiver receiver); - - protected: - void BindActivityWindow( - mojo::PendingReceiver receiver); - - // Camel case due to conflict with WebContentsObserver::web_contents(). - content::WebContents* WebContents() { - return cast_web_contents() ? cast_web_contents()->web_contents() : nullptr; - } - - CastWebContents* cast_web_contents_ = nullptr; - mojom::CastWebViewParamsPtr params_; - - GestureRouter gesture_router_; - mojo::Receiver receiver_{this}; - mojo::Receiver activity_window_receiver_{this}; - mojo::RemoteSet observers_; - base::ObserverList sync_observers_; - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_window_aura.cc chromium-132.0.6834.159/chromecast/browser/cast_content_window_aura.cc --- chromium-132.0.6834.110/chromecast/browser/cast_content_window_aura.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_window_aura.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_content_window_aura.h" - -#include - -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/graphics/cast_window_manager.h" -#include "content/public/browser/web_contents.h" -#include "ui/aura/window.h" -#include "ui/display/display.h" -#include "ui/display/screen.h" - -namespace chromecast { - -namespace { - -CastGestureHandler::Priority ToGestureHandlerPriority( - mojom::GesturePriority priority) { - switch (priority) { - case mojom::GesturePriority::NONE: - return CastGestureHandler::Priority::NONE; - case mojom::GesturePriority::ROOT_UI: - return CastGestureHandler::Priority::ROOT_UI; - case mojom::GesturePriority::MAIN_ACTIVITY: - return CastGestureHandler::Priority::MAIN_ACTIVITY; - case mojom::GesturePriority::SETTINGS_UI: - return CastGestureHandler::Priority::SETTINGS_UI; - } -} - -} // namespace -class TouchBlocker : public ui::EventHandler, public aura::WindowObserver { - public: - TouchBlocker(aura::Window* window, bool activated) - : window_(window), activated_(activated) { - DCHECK(window_); - window_->AddObserver(this); - if (activated_) { - window_->AddPreTargetHandler(this); - } - } - - TouchBlocker(const TouchBlocker&) = delete; - TouchBlocker& operator=(const TouchBlocker&) = delete; - - ~TouchBlocker() override { - if (window_) { - window_->RemoveObserver(this); - if (activated_) { - window_->RemovePreTargetHandler(this); - } - } - } - - void Activate(bool activate) { - if (!window_ || activate == activated_) { - return; - } - - if (activate) { - window_->AddPreTargetHandler(this); - } else { - window_->RemovePreTargetHandler(this); - } - - activated_ = activate; - } - - private: - // Overriden from ui::EventHandler. - void OnTouchEvent(ui::TouchEvent* touch) override { - if (activated_) { - touch->SetHandled(); - } - } - - // Overriden from aura::WindowObserver. - void OnWindowDestroyed(aura::Window* window) override { window_ = nullptr; } - - aura::Window* window_; - bool activated_; -}; - -CastContentWindowAura::CastContentWindowAura(mojom::CastWebViewParamsPtr params, - CastWindowManager* window_manager) - : CastContentWindow(std::move(params)), - window_manager_(window_manager), - gesture_dispatcher_( - std::make_unique(gesture_router())), - window_(nullptr), - has_screen_access_(false), - resize_window_when_navigation_starts_(true) {} - -CastContentWindowAura::~CastContentWindowAura() { - content::WebContentsObserver::Observe(nullptr); - CastWebContentsObserver::Observe(nullptr); - if (window_manager_) { - window_manager_->RemoveGestureHandler(gesture_dispatcher_.get()); - } - if (window_) { - window_->RemoveObserver(this); - } -} - -void CastContentWindowAura::CreateWindow( - mojom::ZOrder z_order, - VisibilityPriority visibility_priority) { - DCHECK(window_manager_) << "A CastWindowManager must be provided before " - << "creating a window for WebContents."; - CastWebContentsObserver::Observe(cast_web_contents()); - content::WebContentsObserver::Observe(WebContents()); - window_ = WebContents()->GetNativeView(); - if (!window_->HasObserver(this)) { - window_->AddObserver(this); - } - window_manager_->SetZOrder(window_, z_order); - window_manager_->AddWindow(window_); - window_manager_->AddGestureHandler(gesture_dispatcher_.get()); - - touch_blocker_ = - std::make_unique(window_, !params_->enable_touch_input); - - if (has_screen_access_) { - window_->Show(); - } else { - window_->Hide(); - } - - cast_web_contents()->web_contents()->Focus(); -} - -void CastContentWindowAura::GrantScreenAccess() { - has_screen_access_ = true; - if (window_) { - SetFullWindowBounds(); - window_->Show(); - } -} - -void CastContentWindowAura::RevokeScreenAccess() { - has_screen_access_ = false; - resize_window_when_navigation_starts_ = false; - if (window_) { - window_->Hide(); - SetHiddenWindowBounds(); - } -} - -void CastContentWindowAura::EnableTouchInput(bool enabled) { - if (touch_blocker_) { - touch_blocker_->Activate(!enabled); - } -} - -void CastContentWindowAura::RequestVisibility( - VisibilityPriority visibility_priority) {} - -void CastContentWindowAura::OnWindowVisibilityChanged(aura::Window* window, - bool visible) { - if (visible) { - gesture_dispatcher_->SetPriority( - ToGestureHandlerPriority(params_->gesture_priority)); - } else { - gesture_dispatcher_->SetPriority(CastGestureHandler::Priority::NONE); - } -} - -void CastContentWindowAura::OnWindowDestroyed(aura::Window* window) { - window_ = nullptr; -} - -void CastContentWindowAura::DidStartNavigation( - content::NavigationHandle* navigation_handle) { - if (!resize_window_when_navigation_starts_ || !window_) { - return; - } - resize_window_when_navigation_starts_ = false; - SetFullWindowBounds(); -} - -void CastContentWindowAura::SetFullWindowBounds() { -#if !BUILDFLAG(IS_CAST_AUDIO_ONLY) - gfx::Size display_size = - display::Screen::GetScreen()->GetPrimaryDisplay().size(); - window_->SetBounds(gfx::Rect(display_size.width(), display_size.height())); -#endif -} - -void CastContentWindowAura::SetHiddenWindowBounds() { - // Because rendering a larger window may require more system resources, - // resize the window to one pixel while hidden. - LOG(INFO) << "Resizing window to 1x1 pixel while hidden"; - window_->SetBounds(gfx::Rect(1, 1)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_content_window_aura.h chromium-132.0.6834.159/chromecast/browser/cast_content_window_aura.h --- chromium-132.0.6834.110/chromecast/browser/cast_content_window_aura.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_content_window_aura.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_AURA_H_ -#define CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_AURA_H_ - -#include "chromecast/browser/cast_content_gesture_handler.h" -#include "chromecast/browser/cast_content_window.h" -#include "chromecast/browser/cast_web_contents_observer.h" -#include "chromecast/browser/mojom/cast_web_service.mojom.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_observer.h" -#include "ui/aura/window_observer.h" - -namespace aura { -class Window; -} // namespace aura - -namespace chromecast { - -class CastWindowManager; -class TouchBlocker; - -class CastContentWindowAura : public CastContentWindow, - public CastWebContentsObserver, - public content::WebContentsObserver, - public aura::WindowObserver { - public: - CastContentWindowAura(mojom::CastWebViewParamsPtr params, - CastWindowManager* window_manager); - - CastContentWindowAura(const CastContentWindowAura&) = delete; - CastContentWindowAura& operator=(const CastContentWindowAura&) = delete; - - ~CastContentWindowAura() override; - - // CastContentWindow implementation: - void CreateWindow(mojom::ZOrder z_order, - VisibilityPriority visibility_priority) override; - void GrantScreenAccess() override; - void RevokeScreenAccess() override; - void RequestVisibility(VisibilityPriority visibility_priority) override; - void EnableTouchInput(bool enabled) override; - - // content::WebContentsObserver implementation: - void DidStartNavigation( - content::NavigationHandle* navigation_handle) override; - - // aura::WindowObserver implementation: - void OnWindowVisibilityChanged(aura::Window* window, bool visible) override; - void OnWindowDestroyed(aura::Window* window) override; - - private: - void SetFullWindowBounds(); - void SetHiddenWindowBounds(); - - CastWindowManager* const window_manager_; - - // Utility class for detecting and dispatching gestures to delegates. - std::unique_ptr gesture_dispatcher_; - std::unique_ptr touch_blocker_; - - aura::Window* window_; - bool has_screen_access_; - bool resize_window_when_navigation_starts_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_AURA_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_display_configurator.cc chromium-132.0.6834.159/chromecast/browser/cast_display_configurator.cc --- chromium-132.0.6834.110/chromecast/browser/cast_display_configurator.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_display_configurator.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,302 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_display_configurator.h" - -#include - -#include -#include - -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/strings/string_number_conversions.h" -#include "build/build_config.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/browser/cast_touch_device_manager.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/graphics/cast_display_util.h" -#include "chromecast/graphics/cast_screen.h" -#include "chromecast/public/graphics_properties_shlib.h" -#include "ui/display/types/display_configuration_params.h" -#include "ui/display/types/display_snapshot.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/ozone/public/ozone_platform.h" - -namespace chromecast { -namespace shell { - -namespace { -constexpr int64_t kStubDisplayId = 1; -constexpr char kCastGraphicsHeight[] = "cast-graphics-height"; -constexpr char kCastGraphicsWidth[] = "cast-graphics-width"; - -gfx::Size GetDefaultScreenResolution() { -#if BUILDFLAG(IS_CAST_AUDIO_ONLY) - return gfx::Size(1, 1); -#else - const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); - if (!chromecast::IsFeatureEnabled(kTripleBuffer720) && - GraphicsPropertiesShlib::IsSupported(GraphicsPropertiesShlib::k1080p, - cmd_line->argv())) { - return gfx::Size(1920, 1080); - } - - return gfx::Size(1280, 720); -#endif -} - -// Helper to return the screen resolution (device pixels) -// to use. -gfx::Size GetScreenResolution() { - const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); - int cast_gfx_width = 0; - int cast_gfx_height = 0; - if (base::StringToInt(cmd_line->GetSwitchValueASCII(kCastGraphicsWidth), - &cast_gfx_width) && - base::StringToInt(cmd_line->GetSwitchValueASCII(kCastGraphicsHeight), - &cast_gfx_height) && - cast_gfx_width > 0 && cast_gfx_height > 0) { - return gfx::Size(cast_gfx_width, cast_gfx_height); - } - - return GetDefaultScreenResolution(); -} - -display::Display::Rotation RotationFromPanelOrientation( - display::PanelOrientation orientation) { - switch (orientation) { - case display::kNormal: - return display::Display::ROTATE_0; - case display::kRightUp: - return display::Display::ROTATE_90; - case display::kBottomUp: - return display::Display::ROTATE_180; - case display::kLeftUp: - return display::Display::ROTATE_270; - } -} - -gfx::Rect GetScreenBounds(const gfx::Size& size_in_pixels, - display::Display::Rotation rotation) { - switch (rotation) { - case display::Display::ROTATE_90: - case display::Display::ROTATE_270: - return gfx::Rect( - gfx::Size(size_in_pixels.height(), size_in_pixels.width())); - case display::Display::ROTATE_0: - case display::Display::ROTATE_180: - default: - return gfx::Rect(size_in_pixels); - } -} - -} // namespace - -CastDisplayConfigurator::CastDisplayConfigurator(CastScreen* screen) - : delegate_( -#if BUILDFLAG(IS_OZONE) && !BUILDFLAG(IS_CAST_AUDIO_ONLY) - ui::OzonePlatform::GetInstance()->CreateNativeDisplayDelegate() -#else - nullptr -#endif - ), - touch_device_manager_(std::make_unique()), - display_(nullptr), - cast_screen_(screen), - weak_factory_(this) { - if (delegate_) { - delegate_->AddObserver(this); - delegate_->Initialize(); - ForceInitialConfigure(); - } else { - ConfigureDisplayFromCommandLine(); - } -} - -CastDisplayConfigurator::~CastDisplayConfigurator() { - if (delegate_) - delegate_->RemoveObserver(this); -} - -// display::NativeDisplayObserver interface -void CastDisplayConfigurator::OnConfigurationChanged() { - DCHECK(delegate_); - delegate_->GetDisplays(base::BindOnce( - &CastDisplayConfigurator::OnDisplaysAcquired, weak_factory_.GetWeakPtr(), - false /* force_initial_configure */)); -} - -void CastDisplayConfigurator::OnDisplaySnapshotsInvalidated() { - display_ = nullptr; -} - -void CastDisplayConfigurator::EnableDisplay( - display::ConfigureCallback callback) { - if (!delegate_ || !display_) - return; - - display::DisplayConfigurationParams display_config_params( - display_->display_id(), gfx::Point(), display_->native_mode()); - std::vector config_request; - config_request.push_back(std::move(display_config_params)); - - delegate_->Configure(config_request, std::move(callback), - {display::ModesetFlag::kTestModeset, - display::ModesetFlag::kCommitModeset}); - NotifyObservers(); -} - -void CastDisplayConfigurator::DisableDisplay( - display::ConfigureCallback callback) { - if (!delegate_ || !display_) - return; - - display::DisplayConfigurationParams display_config_params( - display_->display_id(), gfx::Point(), nullptr); - std::vector config_request; - config_request.push_back(std::move(display_config_params)); - - delegate_->Configure(config_request, std::move(callback), - {display::ModesetFlag::kTestModeset, - display::ModesetFlag::kCommitModeset}); -} - -void CastDisplayConfigurator::ConfigureDisplayFromCommandLine() { - const gfx::Size size = GetScreenResolution(); - UpdateScreen(kStubDisplayId, gfx::Rect(size), GetDeviceScaleFactor(size), - display::Display::ROTATE_0); -} - -void CastDisplayConfigurator::SetColorTemperatureAdjustment( - const display::ColorTemperatureAdjustment& cta) { - if (!delegate_ || !display_) - return; - delegate_->SetColorTemperatureAdjustment(display_->display_id(), cta); - - NotifyObservers(); -} - -void CastDisplayConfigurator::SetGammaAdjustment( - const display::GammaAdjustment& adjustment) { - if (!delegate_ || !display_) - return; - delegate_->SetGammaAdjustment(display_->display_id(), adjustment); - NotifyObservers(); -} - -void CastDisplayConfigurator::NotifyObservers() { - for (Observer& observer : observers_) - observer.OnDisplayStateChanged(); -} - -void CastDisplayConfigurator::ForceInitialConfigure() { - if (!delegate_) - return; - delegate_->GetDisplays(base::BindOnce( - &CastDisplayConfigurator::OnDisplaysAcquired, weak_factory_.GetWeakPtr(), - true /* force_initial_configure */)); -} - -void CastDisplayConfigurator::OnDisplaysAcquired( - bool force_initial_configure, - const std::vector>& - displays) { - DCHECK(delegate_); - if (displays.empty()) { - LOG(WARNING) << "No displays detected, skipping display init."; - return; - } - - if (displays.size() > 1) { - LOG(WARNING) << "Multiple display detected, using the first one."; - } - - display_ = displays[0]; - if (!display_->native_mode()) { - LOG(WARNING) << "Display " << display_->display_id() - << " doesn't have a native mode."; - return; - } - - gfx::Point origin; - gfx::Size native_size(display_->native_mode()->size()); - if (force_initial_configure) { - // For initial configuration, pass the native geometry to gfx::Screen - // before calling Configure(), so that this information is available - // to chrome during startup. Otherwise we will not have a valid display - // during the first queries to display::Screen. - UpdateScreen(display_->display_id(), gfx::Rect(origin, native_size), - GetDeviceScaleFactor(native_size), - RotationFromPanelOrientation(display_->panel_orientation())); - } - - display::DisplayConfigurationParams display_config_params( - display_->display_id(), origin, display_->native_mode()); - std::vector config_request; - config_request.push_back(std::move(display_config_params)); - - delegate_->Configure( - config_request, - base::BindRepeating(&CastDisplayConfigurator::OnDisplayConfigured, - weak_factory_.GetWeakPtr()), - {display::ModesetFlag::kTestModeset, - display::ModesetFlag::kCommitModeset}); -} - -void CastDisplayConfigurator::OnDisplayConfigured( - const std::vector& request_results, - bool config_success) { - DCHECK_EQ(request_results.size(), 1u); - const auto& result = request_results[0]; - DCHECK(result.mode); - - // Discard events for previous configurations. It is safe to discard since a - // new configuration round was initiated and we're waiting for another - // OnDisplayConfigured() event with the up-to-date display to arrive. - // - // This typically only happens when there's crashes and the state updates at - // the same time old notifications are received. - if (result.id != display_->display_id()) { - return; - } - - const gfx::Rect bounds(result.origin, result.mode->size()); - DVLOG(1) << __func__ << " success=" << config_success - << " bounds=" << bounds.ToString(); - if (config_success) { - // Need to update the display state otherwise it becomes stale. - display_->set_current_mode(result.mode.get()); - display_->set_origin(result.origin); - - UpdateScreen(display_->display_id(), bounds, - GetDeviceScaleFactor(display_->native_mode()->size()), - RotationFromPanelOrientation(display_->panel_orientation())); - } else { - LOG(FATAL) << "Failed to configure display"; - } -} - -void CastDisplayConfigurator::UpdateScreen( - int64_t display_id, - const gfx::Rect& bounds, - float device_scale_factor, - display::Display::Rotation rotation) { - cast_screen_->OnDisplayChanged(display_id, device_scale_factor, rotation, - GetScreenBounds(bounds.size(), rotation)); - touch_device_manager_->OnDisplayConfigured(display_id, rotation, bounds); -} - -void CastDisplayConfigurator::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void CastDisplayConfigurator::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_display_configurator.h chromium-132.0.6834.159/chromecast/browser/cast_display_configurator.h --- chromium-132.0.6834.110/chromecast/browser/cast_display_configurator.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_display_configurator.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_DISPLAY_CONFIGURATOR_H_ -#define CHROMECAST_BROWSER_CAST_DISPLAY_CONFIGURATOR_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "ui/display/display.h" -#include "ui/display/types/display_color_management.h" -#include "ui/display/types/native_display_delegate.h" -#include "ui/display/types/native_display_observer.h" - -namespace display { -class DisplaySnapshot; - -struct DisplayConfigurationParams; -} // namespace display - -namespace chromecast { -class CastScreen; - -namespace shell { -class CastTouchDeviceManager; - -// The CastDisplayConfigurator class ensures native displays are initialized and -// configured properly on platforms that need that (e.g. GBM/DRM graphics via -// OzonePlatformGbm on odroid). But OzonePlatformCast, used by most Cast -// devices, relies on the platform code (outside of cast_shell) to initialize -// displays and exposes only a FakeDisplayDelegate. So CastDisplayConfigurator -// doesn't really do anything when using OzonePlatformCast. -class CastDisplayConfigurator : public display::NativeDisplayObserver { - public: - class Observer { - public: - virtual ~Observer() = default; - virtual void OnDisplayStateChanged() = 0; - }; - - explicit CastDisplayConfigurator(CastScreen* screen); - - CastDisplayConfigurator(const CastDisplayConfigurator&) = delete; - CastDisplayConfigurator& operator=(const CastDisplayConfigurator&) = delete; - - ~CastDisplayConfigurator() override; - - // display::NativeDisplayObserver implementation - void OnConfigurationChanged() override; - void OnDisplaySnapshotsInvalidated() override; - - void EnableDisplay(display::ConfigureCallback callback); - void DisableDisplay(display::ConfigureCallback callback); - - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - void ConfigureDisplayFromCommandLine(); - void SetColorTemperatureAdjustment( - const display::ColorTemperatureAdjustment& cta); - void SetGammaAdjustment(const display::GammaAdjustment& adjustment); - - private: - void ForceInitialConfigure(); - void NotifyObservers(); - void OnDisplaysAcquired( - bool force_initial_configure, - const std::vector>& - displays); - void OnDisplayConfigured( - const std::vector& request_results, - bool statuses); - void UpdateScreen(int64_t display_id, - const gfx::Rect& bounds, - float device_scale_factor, - display::Display::Rotation rotation); - - base::ObserverList::Unchecked observers_; - - std::unique_ptr delegate_; - std::unique_ptr touch_device_manager_; - display::DisplaySnapshot* display_; - CastScreen* const cast_screen_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_DISPLAY_CONFIGURATOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_download_manager_delegate.cc chromium-132.0.6834.159/chromecast/browser/cast_download_manager_delegate.cc --- chromium-132.0.6834.110/chromecast/browser/cast_download_manager_delegate.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_download_manager_delegate.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_download_manager_delegate.h" - -#include - -#include "base/files/file_path.h" -#include "components/download/public/common/download_danger_type.h" -#include "components/download/public/common/download_interrupt_reasons.h" -#include "components/download/public/common/download_item.h" -#include "components/download/public/common/download_target_info.h" - -namespace chromecast { -namespace shell { - -CastDownloadManagerDelegate::CastDownloadManagerDelegate() {} - -CastDownloadManagerDelegate::~CastDownloadManagerDelegate() {} - -void CastDownloadManagerDelegate::GetNextId( - content::DownloadIdCallback callback) { - // See default behavior of DownloadManagerImpl::GetNextId() - static uint32_t next_id = download::DownloadItem::kInvalidId + 1; - std::move(callback).Run(next_id++); -} - -bool CastDownloadManagerDelegate::DetermineDownloadTarget( - download::DownloadItem* item, - download::DownloadTargetCallback* callback) { - download::DownloadTargetInfo target_info; - target_info.danger_type = - download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT; - target_info.interrupt_reason = - download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED; - - std::move(*callback).Run(std::move(target_info)); - return true; -} - -bool CastDownloadManagerDelegate::ShouldCompleteDownload( - download::DownloadItem* item, - base::OnceClosure callback) { - return false; -} - -bool CastDownloadManagerDelegate::ShouldOpenDownload( - download::DownloadItem* item, - content::DownloadOpenDelayedCallback callback) { - // TODO(qinmin): When this returns false it means this should run the callback - // at some point. - return false; -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_download_manager_delegate.h chromium-132.0.6834.159/chromecast/browser/cast_download_manager_delegate.h --- chromium-132.0.6834.110/chromecast/browser/cast_download_manager_delegate.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_download_manager_delegate.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_DOWNLOAD_MANAGER_DELEGATE_H_ -#define CHROMECAST_BROWSER_CAST_DOWNLOAD_MANAGER_DELEGATE_H_ - -#include "base/supports_user_data.h" -#include "content/public/browser/download_manager_delegate.h" - -namespace chromecast { -namespace shell { - -class CastDownloadManagerDelegate : public content::DownloadManagerDelegate, - public base::SupportsUserData::Data { - public: - CastDownloadManagerDelegate(); - - CastDownloadManagerDelegate(const CastDownloadManagerDelegate&) = delete; - CastDownloadManagerDelegate& operator=(const CastDownloadManagerDelegate&) = - delete; - - ~CastDownloadManagerDelegate() override; - - // content::DownloadManagerDelegate implementation: - void GetNextId(content::DownloadIdCallback callback) override; - bool DetermineDownloadTarget( - download::DownloadItem* item, - download::DownloadTargetCallback* callback) override; - bool ShouldCompleteDownload(download::DownloadItem* item, - base::OnceClosure complete_callback) override; - bool ShouldOpenDownload( - download::DownloadItem* item, - content::DownloadOpenDelayedCallback callback) override; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_DOWNLOAD_MANAGER_DELEGATE_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_feature_list_creator.cc chromium-132.0.6834.159/chromecast/browser/cast_feature_list_creator.cc --- chromium-132.0.6834.110/chromecast/browser/cast_feature_list_creator.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_feature_list_creator.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_feature_list_creator.h" - -#include "base/base_switches.h" -#include "base/command_line.h" -#include "base/strings/string_util.h" -#include "base/values.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/base/pref_names.h" -#include "chromecast/browser/metrics/cast_metrics_prefs.h" -#include "chromecast/browser/pref_service_helper.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/pref_service.h" -#include "components/proxy_config/pref_proxy_config_tracker_impl.h" - -namespace chromecast { - -namespace { - -// Convert the |features| vector into a comma separated string. -std::string FeatureVectorToString( - const std::vector& features) { - std::vector feature_names; - - for (const auto* feature : features) - feature_names.push_back(feature->name); - - return base::JoinString(feature_names, ","); -} - -} // namespace - -CastFeatureListCreator::CastFeatureListCreator() {} - -CastFeatureListCreator::~CastFeatureListCreator() {} - -void CastFeatureListCreator::CreatePrefServiceAndFeatureList( - ProcessType process_type) { - DCHECK(!pref_service_); - - scoped_refptr pref_registry(new PrefRegistrySimple()); - metrics::RegisterPrefs(pref_registry.get()); - PrefProxyConfigTrackerImpl::RegisterPrefs(pref_registry.get()); - pref_service_ = shell::PrefServiceHelper::CreatePrefService( - pref_registry.get(), process_type); - - const base::Value::Dict& features_dict = - pref_service_->GetDict(prefs::kLatestDCSFeatures); - const base::Value::List& experiment_ids = - pref_service_->GetList(prefs::kActiveDCSExperiments); - auto* command_line = base::CommandLine::ForCurrentProcess(); - InitializeFeatureList( - features_dict, experiment_ids, - command_line->GetSwitchValueASCII(switches::kEnableFeatures), - command_line->GetSwitchValueASCII(switches::kDisableFeatures), - extra_enable_features_, extra_disable_features_); -} - -std::unique_ptr CastFeatureListCreator::TakePrefService() { - return std::move(pref_service_); -} - -void CastFeatureListCreator::SetExtraEnableFeatures( - const std::vector& extra_enable_features) { - extra_enable_features_ = FeatureVectorToString(extra_enable_features); -} - -void CastFeatureListCreator::SetExtraDisableFeatures( - const std::vector& extra_disable_features) { - extra_disable_features_ = FeatureVectorToString(extra_disable_features); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_feature_list_creator.h chromium-132.0.6834.159/chromecast/browser/cast_feature_list_creator.h --- chromium-132.0.6834.110/chromecast/browser/cast_feature_list_creator.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_feature_list_creator.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_FEATURE_LIST_CREATOR_H_ -#define CHROMECAST_BROWSER_CAST_FEATURE_LIST_CREATOR_H_ - -#include -#include - -#include "base/feature_list.h" -#include "chromecast/base/process_types.h" - -class PrefService; - -namespace chromecast { - -// Creator for the singleton |FeatureList|. Stateful due to having to create and -// hold a |PrefService| instance until |CastBrowserProcess| takes ownership when -// the full browser process starts, -class CastFeatureListCreator { - public: - CastFeatureListCreator(); - CastFeatureListCreator(const CastFeatureListCreator&) = delete; - CastFeatureListCreator& operator=(const CastFeatureListCreator&) = delete; - virtual ~CastFeatureListCreator(); - - // Creates the |PrefService| and uses it to initialize |FeatureList|. Retains - // ownership of the |PrefService|. Based on the given |ProcessType|, different - // files will be used to store prefs. - void CreatePrefServiceAndFeatureList( - ProcessType process_type = ProcessType::kCastService); - - // Takes ownership of the |PrefService| previously created. - std::unique_ptr TakePrefService(); - - // Sets the extra features to be enabled. - void SetExtraEnableFeatures( - const std::vector& extra_enable_features); - - // Sets the extra features to be disabled. - void SetExtraDisableFeatures( - const std::vector& extra_disable_features); - - private: - // Holds the |PrefService| until TakePrefService() is called and ownership - // is taken away. - std::unique_ptr pref_service_; - // Extra features that can be enabled at run time. - std::string extra_enable_features_; - // Extra features that can be disabled at run time. - std::string extra_disable_features_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_FEATURE_LIST_CREATOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_feature_update_observer.cc chromium-132.0.6834.159/chromecast/browser/cast_feature_update_observer.cc --- chromium-132.0.6834.110/chromecast/browser/cast_feature_update_observer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_feature_update_observer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_feature_update_observer.h" - -#include "base/check.h" -#include "base/functional/bind.h" -#include "chromecast/base/pref_names.h" -#include "chromecast/common/mojom/constants.mojom.h" -#include "chromecast/external_mojo/external_service_support/external_connector.h" -#include "components/prefs/pref_service.h" - -namespace chromecast { - -CastFeatureUpdateObserver::CastFeatureUpdateObserver( - external_service_support::ExternalConnector* connector, - PrefService* pref_service) - : connector_(connector), pref_service_(pref_service) { - DCHECK(connector_); - DCHECK(pref_service_); - - BindFeatureUpdateService(); -} - -CastFeatureUpdateObserver::~CastFeatureUpdateObserver() = default; - -void CastFeatureUpdateObserver::BindFeatureUpdateService() { - feature_update_service_.reset(); - receiver_.reset(); - connector_->BindInterface( - mojom::kChromecastServiceName, - feature_update_service_.BindNewPipeAndPassReceiver()); - feature_update_service_->RegisterFeatureUpdateObserver( - receiver_.BindNewPipeAndPassRemote()); - - // Right now we are in the process of making the `cast_service` manage the - // lifecycle of `cast_browser`. Until that is done, `cast_service` has a - // shorter lifecycle than `cast_browser`, so we need to handle disconnects - // here. - // TODO(crbug.com/40210465): remove once process lifecycles are inverted. - receiver_.set_disconnect_handler( - base::BindOnce(&CastFeatureUpdateObserver::BindFeatureUpdateService, - base::Unretained(this))); -} - -void CastFeatureUpdateObserver::OnFeaturesUpdated(base::Value::Dict features) { - pref_service_->SetDict(prefs::kLatestDCSFeatures, std::move(features)); - pref_service_->CommitPendingWrite(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_feature_update_observer.h chromium-132.0.6834.159/chromecast/browser/cast_feature_update_observer.h --- chromium-132.0.6834.110/chromecast/browser/cast_feature_update_observer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_feature_update_observer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_FEATURE_UPDATE_OBSERVER_H_ -#define CHROMECAST_BROWSER_CAST_FEATURE_UPDATE_OBSERVER_H_ - -#include "base/values.h" -#include "chromecast/common/mojom/feature_update.mojom.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" - -class PrefService; - -namespace chromecast { - -namespace external_service_support { -class ExternalConnector; -} // namespace external_service_support - -class CastFeatureUpdateObserver - : public chromecast::mojom::FeatureUpdateObserver { - public: - CastFeatureUpdateObserver( - external_service_support::ExternalConnector* connector, - PrefService* pref_service); - CastFeatureUpdateObserver(const CastFeatureUpdateObserver&) = delete; - CastFeatureUpdateObserver& operator=(const CastFeatureUpdateObserver&) = - delete; - ~CastFeatureUpdateObserver() override; - - private: - // chromecast::mojom::FeatureUpdateObserver implementation: - void OnFeaturesUpdated(base::Value::Dict features) override; - - void BindFeatureUpdateService(); - - external_service_support::ExternalConnector* const connector_; - PrefService* const pref_service_; - - mojo::Receiver receiver_{this}; - mojo::Remote feature_update_service_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_FEATURE_UPDATE_OBSERVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_http_user_agent_settings.cc chromium-132.0.6834.159/chromecast/browser/cast_http_user_agent_settings.cc --- chromium-132.0.6834.110/chromecast/browser/cast_http_user_agent_settings.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_http_user_agent_settings.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_http_user_agent_settings.h" - -#include "base/i18n/rtl.h" -#include "base/logging.h" -#include "build/build_config.h" -#include "chromecast/app/grit/chromecast_settings.h" -#include "chromecast/common/user_agent.h" -#include "content/public/browser/browser_thread.h" -#include "net/http/http_util.h" -#include "ui/base/l10n/l10n_util.h" - -#if BUILDFLAG(IS_ANDROID) -#include "base/android/locale_utils.h" -#endif // BUILDFLAG(IS_ANDROID) - -namespace { - -std::string GetLocale() { -#if BUILDFLAG(IS_ANDROID) - // TODO(byungchul): Use transient locale set when new app starts. - return base::android::GetDefaultLocaleString(); -#else - return base::i18n::GetConfiguredLocale(); -#endif -} - -std::string LocaleToAcceptLanguage(const std::string& locale) { - return net::HttpUtil::GenerateAcceptLanguageHeader( -#if BUILDFLAG(IS_ANDROID) - locale -#else - // Ignoring |locale| here is a bit weird, but locale is still used to - // avoid a l10n_util::GetStringUTF8() call when GetAcceptLanguage() is - // called. - l10n_util::GetStringUTF8(IDS_CHROMECAST_SETTINGS_ACCEPT_LANGUAGES) -#endif - ); -} - -} // namespace - -namespace chromecast { -namespace shell { - -std::string CastHttpUserAgentSettings::AcceptLanguage() { - return LocaleToAcceptLanguage(GetLocale()); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_http_user_agent_settings.h chromium-132.0.6834.159/chromecast/browser/cast_http_user_agent_settings.h --- chromium-132.0.6834.110/chromecast/browser/cast_http_user_agent_settings.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_http_user_agent_settings.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_HTTP_USER_AGENT_SETTINGS_H_ -#define CHROMECAST_BROWSER_CAST_HTTP_USER_AGENT_SETTINGS_H_ - -#include - -#include "base/compiler_specific.h" - -namespace chromecast { -namespace shell { - -class CastHttpUserAgentSettings { - public: - CastHttpUserAgentSettings() = delete; - CastHttpUserAgentSettings(const CastHttpUserAgentSettings&) = delete; - CastHttpUserAgentSettings& operator=(const CastHttpUserAgentSettings&) = - delete; - - ~CastHttpUserAgentSettings() = delete; - - // Returns the same value as GetAcceptLanguage(), but is static and can be - // called on any thread. - static std::string AcceptLanguage(); -}; - -} // namespace shell -} // namespace chromecast -#endif // CHROMECAST_BROWSER_CAST_HTTP_USER_AGENT_SETTINGS_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_media_blocker.cc chromium-132.0.6834.159/chromecast/browser/cast_media_blocker.cc --- chromium-132.0.6834.110/chromecast/browser/cast_media_blocker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_media_blocker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,173 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_media_blocker.h" - -#include - -#include "base/logging.h" -#include "chromecast/browser/cast_renderer_block_data.h" -#include "components/media_control/mojom/media_playback_options.mojom.h" -#include "content/public/browser/media_session.h" -#include "content/public/browser/web_contents.h" -#include "mojo/public/cpp/bindings/associated_remote.h" -#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" - -namespace chromecast { - -CastMediaBlocker::CastMediaBlocker(content::WebContents* web_contents) - : media_control::MediaBlocker(web_contents), - media_session_(content::MediaSession::Get(web_contents)) { - media_session_->AddObserver(observer_receiver_.BindNewPipeAndPassRemote()); -} - -CastMediaBlocker::~CastMediaBlocker() = default; - -void CastMediaBlocker::OnBlockMediaLoadingChanged() { - UpdatePlayingState(); -} - -void CastMediaBlocker::BlockMediaStarting(bool blocked) { - if (media_starting_blocked_ == blocked) - return; - - media_starting_blocked_ = blocked; - - shell::CastRendererBlockData::SetRendererBlockForWebContents( - web_contents(), media_starting_blocked_); - - UpdatePlayingState(); -} - -void CastMediaBlocker::UpdatePlayingState() { - LOG(INFO) << __FUNCTION__ - << " media_loading_blocked=" << media_loading_blocked() - << " media_starting_blocked=" << media_starting_blocked_ - << " suspended=" << suspended_ << " controllable=" << controllable_ - << " paused_by_user=" << paused_by_user_; - - // If blocking media, suspend if possible. - if (PlayingBlocked()) { - if (!suspended_ && controllable_) { - Suspend(); - } - return; - } - - // If unblocking media, resume if media was not paused by user. - if (!paused_by_user_ && suspended_ && controllable_) { - paused_by_user_ = true; - Resume(); - } -} - -void CastMediaBlocker::EnableBackgroundVideoPlayback(bool enabled) { - if (!web_contents()) - return; - - background_video_playback_enabled_ = enabled; - UpdateBackgroundVideoPlaybackState(); -} - -bool CastMediaBlocker::PlayingBlocked() const { - return (media_loading_blocked() || media_starting_blocked_); -} - -void CastMediaBlocker::MediaSessionInfoChanged( - media_session::mojom::MediaSessionInfoPtr session_info) { - bool is_suspended = session_info->playback_state == - media_session::mojom::MediaPlaybackState::kPaused; - - LOG(INFO) << __FUNCTION__ - << " media_loading_blocked=" << media_loading_blocked() - << " media_starting_blocked=" << media_starting_blocked_ - << " is_suspended=" << is_suspended - << " is_controllable=" << session_info->is_controllable - << " paused_by_user=" << paused_by_user_; - - // Process controllability first. - if (controllable_ != session_info->is_controllable) { - controllable_ = session_info->is_controllable; - - // If not blocked, and we regain control and the media wasn't paused when - // blocked, resume media if suspended. - if (!PlayingBlocked() && !paused_by_user_ && is_suspended && - controllable_) { - paused_by_user_ = true; - Resume(); - } - - // Suspend if blocked and the session becomes controllable. - if (PlayingBlocked() && !is_suspended && controllable_) { - // Only suspend if suspended_ doesn't change. Otherwise, this will be - // handled in the suspended changed block. - if (suspended_ == is_suspended) - Suspend(); - } - } - - // TODO(crbug.com/40120884): Rename suspended to paused to be consistent with - // MediaSession types. - // Process suspended state next. - if (suspended_ != is_suspended) { - suspended_ = is_suspended; - // If blocking, suspend media whenever possible. - if (PlayingBlocked() && !suspended_) { - // If media was resumed when blocked, the user tried to play music. - paused_by_user_ = false; - if (controllable_) - Suspend(); - } - - // If not blocking, cache the user's play intent. - if (!PlayingBlocked()) - paused_by_user_ = suspended_; - } -} - -void CastMediaBlocker::Suspend() { - if (!media_session_) - return; - - LOG(INFO) << "Suspending media session."; - media_session_->Suspend(content::MediaSession::SuspendType::kSystem); -} - -void CastMediaBlocker::Resume() { - if (!media_session_) - return; - - LOG(INFO) << "Resuming media session."; - media_session_->Resume(content::MediaSession::SuspendType::kSystem); -} - -void CastMediaBlocker::OnRenderFrameCreated( - content::RenderFrameHost* render_frame_host) { - UpdateRenderFrameBackgroundVideoPlaybackState(render_frame_host); -} - -void CastMediaBlocker::UpdateBackgroundVideoPlaybackState() { - if (!web_contents()) - return; - web_contents()->ForEachRenderFrameHost( - [this](content::RenderFrameHost* frame) { - UpdateRenderFrameBackgroundVideoPlaybackState(frame); - }); -} - -void CastMediaBlocker::UpdateRenderFrameBackgroundVideoPlaybackState( - content::RenderFrameHost* frame) { - mojo::AssociatedRemote - media_playback_options; - frame->GetRemoteAssociatedInterfaces()->GetInterface(&media_playback_options); - media_playback_options->SetBackgroundVideoPlaybackEnabled( - background_video_playback_enabled_); -} - -void CastMediaBlocker::SetMediaSessionForTesting( - content::MediaSession* media_session) { - media_session_ = media_session; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_media_blocker.h chromium-132.0.6834.159/chromecast/browser/cast_media_blocker.h --- chromium-132.0.6834.110/chromecast/browser/cast_media_blocker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_media_blocker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_MEDIA_BLOCKER_H_ -#define CHROMECAST_BROWSER_CAST_MEDIA_BLOCKER_H_ - -#include - -#include "components/media_control/browser/media_blocker.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "services/media_session/public/mojom/media_session.mojom.h" - -namespace content { -class MediaSession; -} // namespace content - -namespace chromecast { - -namespace shell { -class CastMediaBlockerTest; -} // namespace shell - -// This class implements a blocking mode for web applications and is used in -// Chromecast internal code. Media is unblocked by default. -class CastMediaBlocker : public media_control::MediaBlocker, - public media_session::mojom::MediaSessionObserver { - public: - // Observes WebContents and the associated MediaSession. - explicit CastMediaBlocker(content::WebContents* web_contents); - - ~CastMediaBlocker() override; - - CastMediaBlocker(const CastMediaBlocker&) = delete; - CastMediaBlocker& operator=(const CastMediaBlocker&) = delete; - - // Called when there's a change in whether or not web contents is allowed to - // load and play media. - // If media is unblocked, previously suspended elements should begin playing - // again. Media is unblocked when both MediaLoading and MediaStarting blocks - // are off. - void OnBlockMediaLoadingChanged() override; - // Sets if the web contents is allowed to play media or not. If media is - // unblocked, previously suspended elements should begin playing again. Media - // is unblocked when both MediaLoading and MediaStarting blocks are off. - // This is a more relaxed block than BlockMediaLoading since the block doesn't - // block media from loading but it does block media from starting. - void BlockMediaStarting(bool blocked); - void EnableBackgroundVideoPlayback(bool enabled); - - // media_session::mojom::MediaSessionObserver implementation: - void MediaSessionInfoChanged( - media_session::mojom::MediaSessionInfoPtr session_info) override; - void MediaSessionMetadataChanged( - const std::optional& metadata) override {} - void MediaSessionActionsChanged( - const std::vector& action) - override {} - void MediaSessionImagesChanged( - const base::flat_map>& images) - override {} - void MediaSessionPositionChanged( - const std::optional& position) override {} - - private: - friend shell::CastMediaBlockerTest; - // components::media_control::MediaBlocker implementation: - void OnRenderFrameCreated( - content::RenderFrameHost* render_frame_host) override; - - // Suspends or resumes the media session for the web contents. - void Suspend(); - void Resume(); - - void UpdatePlayingState(); - - void UpdateBackgroundVideoPlaybackState(); - void UpdateRenderFrameBackgroundVideoPlaybackState( - content::RenderFrameHost* frame); - - bool PlayingBlocked() const; - - // MediaSession when initialized from WebContesnts is always a - // MediaSessionImpl type. This method allows to replace the MediaSession with - // mockable MediaSessions for testing. - void SetMediaSessionForTesting(content::MediaSession* media_session); - - // Whether or not media starting should be blocked. This value caches the last - // call to BlockMediaStarting. - bool media_starting_blocked_ = false; - - // Whether or not the user paused media on the page. - bool paused_by_user_ = true; - - // Whether or not media in the app can be controlled and if media is currently - // suspended. These variables cache arguments from MediaSessionInfoChanged(). - bool suspended_ = true; - bool controllable_ = false; - - // Setting for whether or not the WebContents should suspend video when the - // content is put into the background. For most content, this setting should - // be disabled. - bool background_video_playback_enabled_ = false; - - content::MediaSession* media_session_; - - mojo::Receiver observer_receiver_{ - this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_MEDIA_BLOCKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_media_blocker_browsertest.cc chromium-132.0.6834.159/chromecast/browser/cast_media_blocker_browsertest.cc --- chromium-132.0.6834.110/chromecast/browser/cast_media_blocker_browsertest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_media_blocker_browsertest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include "base/logging.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/threading/platform_thread.h" -#include "chromecast/browser/cast_media_blocker.h" -#include "chromecast/browser/test/cast_browser_test.h" -#include "chromecast/chromecast_buildflags.h" -#include "content/public/browser/media_session.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "media/base/test_data_util.h" -#include "url/gurl.h" -#include "url/url_constants.h" - -namespace chromecast { -namespace shell { - -// TODO(crbug.com/40120884): Move relevant tests to components/browsertests so -// there is common coverage of MediaBlocker across platforms. -class CastMediaBlockerBrowserTest : public CastBrowserTest { - protected: - // CastBrowserTest implementation. - void TearDownOnMainThread() override { - blocker_.reset(); - - CastBrowserTest::TearDownOnMainThread(); - } - - void PlayMedia(const std::string& tag, const std::string& media_file) { - base::StringPairs query_params; - query_params.push_back(std::make_pair(tag, media_file)); - query_params.push_back(std::make_pair("loop", "true")); - - std::string query = ::media::GetURLQueryString(query_params); - GURL gurl = content::GetFileUrlWithQuery( - ::media::GetTestDataFilePath("player.html"), query); - - web_contents_ = NavigateToURL(gurl); - EXPECT_TRUE(WaitForLoadStop(web_contents_)); - - blocker_ = std::make_unique(web_contents_); - } - - void BlockAndTestPlayerState(const std::string& media_type, bool blocked) { - blocker_->BlockMediaLoading(blocked); - - // Changing states is not instant, but should be timely (< 0.5s). - for (size_t i = 0; i < 5; i++) { - LOG(INFO) << "Checking media blocking, re-try = " << i; - base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(100)); - run_loop.Run(); - - const std::string command = - "document.getElementsByTagName(\"" + media_type + "\")[0].paused"; - - bool paused = EvalJs(web_contents_, command).ExtractBool(); - - if (paused == blocked) { - SUCCEED() << "Media element has been successfullly " - << (blocked ? "blocked" : "unblocked"); - return; - } - } - - FAIL() << "Could not successfullly " << (blocked ? "block" : "unblock") - << " media element"; - } - - private: - content::WebContents* web_contents_; - std::unique_ptr blocker_; -}; - -// TODO(b/341792190): Re-enable tests. -IN_PROC_BROWSER_TEST_F(CastMediaBlockerBrowserTest, - DISABLED_Audio_BlockUnblock) { - PlayMedia("audio", "bear-audio-10s-CBR-has-TOC.mp3"); - - BlockAndTestPlayerState("audio", true); - BlockAndTestPlayerState("audio", false); -} - -#if !BUILDFLAG(IS_CAST_AUDIO_ONLY) -// TODO(b/341792190): Re-enable tests. -IN_PROC_BROWSER_TEST_F(CastMediaBlockerBrowserTest, - DISABLED_Video_BlockUnblock) { - PlayMedia("video", "tulip2.webm"); - - BlockAndTestPlayerState("video", true); - BlockAndTestPlayerState("video", false); -} -#endif - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_media_blocker_unittest.cc chromium-132.0.6834.159/chromecast/browser/cast_media_blocker_unittest.cc --- chromium-132.0.6834.110/chromecast/browser/cast_media_blocker_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_media_blocker_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,392 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_media_blocker.h" - -#include -#include - -#include "base/time/time.h" -#include "content/public/browser/media_session.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/mock_media_session.h" -#include "content/public/test/test_content_client_initializer.h" -#include "content/public/test/test_renderer_host.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gl/test/gl_surface_test_support.h" - -namespace chromecast { -namespace shell { - -using ::testing::_; -using ::testing::Invoke; - -class CastMediaBlockerTest : public content::RenderViewHostTestHarness { - public: - CastMediaBlockerTest() {} - - CastMediaBlockerTest(const CastMediaBlockerTest&) = delete; - CastMediaBlockerTest& operator=(const CastMediaBlockerTest&) = delete; - - ~CastMediaBlockerTest() override {} - - void SetUp() override { - gl::GLSurfaceTestSupport::InitializeOneOff(); - initializer_ = std::make_unique(); - content::RenderViewHostTestHarness::SetUp(); - web_contents_ = CreateTestWebContents(); - media_session_ = std::make_unique(); - media_blocker_ = std::make_unique(web_contents_.get()); - media_blocker_->SetMediaSessionForTesting(media_session_.get()); - } - - void MediaSessionChanged(bool controllable, bool suspended) { - media_session::mojom::MediaSessionInfoPtr session_info( - media_session::mojom::MediaSessionInfo::New()); - session_info->is_controllable = controllable; - session_info->playback_state = - suspended ? media_session::mojom::MediaPlaybackState::kPaused - : media_session::mojom::MediaPlaybackState::kPlaying; - - media_blocker_->MediaSessionInfoChanged(std::move(session_info)); - } - - void TearDown() override { - media_blocker_.reset(); - web_contents_.reset(); - content::RenderViewHostTestHarness::TearDown(); - } - - protected: - std::unique_ptr initializer_; - std::unique_ptr media_session_; - std::unique_ptr media_blocker_; - std::unique_ptr web_contents_; -}; - -TEST_F(CastMediaBlockerTest, Block_Unblock_Suspended) { - // Testing block/unblock operations do nothing if media never plays. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(true); - media_blocker_->BlockMediaLoading(false); - - MediaSessionChanged(true, true); - media_blocker_->BlockMediaLoading(true); - media_blocker_->BlockMediaLoading(false); - - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(false, true); - media_blocker_->BlockMediaLoading(false); -} - -TEST_F(CastMediaBlockerTest, No_Block) { - // Tests CastMediaBlocker does nothing if block/unblock is not called. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - - // Media becomes controllable/uncontrollable. - MediaSessionChanged(true, true); - MediaSessionChanged(false, true); - - // Media starts and stops. - MediaSessionChanged(false, false); - MediaSessionChanged(false, true); - - // Media starts, changes controllability and stops. - MediaSessionChanged(false, false); - MediaSessionChanged(true, false); - MediaSessionChanged(false, false); - MediaSessionChanged(false, true); - - // Media starts, changes controllability and stops. - MediaSessionChanged(false, false); - MediaSessionChanged(true, false); - MediaSessionChanged(true, true); -} - -TEST_F(CastMediaBlockerTest, Block_Before_Controllable) { - // Tests CastMediaBlocker only suspends when controllable. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Session becomes controllable - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); -} - -TEST_F(CastMediaBlockerTest, Block_After_Controllable) { - // Tests CastMediaBlocker suspends immediately on block if controllable. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Block when media is playing - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(true, true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Unblock - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(1); - media_blocker_->BlockMediaLoading(false); -} - -TEST_F(CastMediaBlockerTest, Block_Multiple) { - // Tests CastMediaBlocker repeatively suspends when blocked. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(false, false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - MediaSessionChanged(true, true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - MediaSessionChanged(true, true); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(false, true); - MediaSessionChanged(false, false); - MediaSessionChanged(false, true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); -} - -TEST_F(CastMediaBlockerTest, Block_Unblock_Uncontrollable) { - // Tests CastMediaBlocker does not suspend or resume when uncontrollable. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(false, false); - media_blocker_->BlockMediaLoading(false); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(false, true); - media_blocker_->BlockMediaLoading(false); - media_blocker_->BlockMediaLoading(true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); -} - -TEST_F(CastMediaBlockerTest, Block_Unblock_Uncontrollable2) { - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, true); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(false, true); - MediaSessionChanged(true, true); - MediaSessionChanged(true, false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(false, false); - MediaSessionChanged(false, true); - MediaSessionChanged(true, true); - MediaSessionChanged(true, false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(false); -} - -TEST_F(CastMediaBlockerTest, Resume_When_Controllable) { - // Tests CastMediaBlocker will only resume after unblock when controllable. - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(true, true); - MediaSessionChanged(false, true); - media_blocker_->BlockMediaLoading(false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(1); - MediaSessionChanged(true, true); -} - -TEST_F(CastMediaBlockerTest, No_Resume) { - // Tests CastMediaBlocker will not resume if media starts playing by itself - // after unblock. - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(true, true); - MediaSessionChanged(false, true); - media_blocker_->BlockMediaLoading(false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(false, false); -} - -TEST_F(CastMediaBlockerTest, Block_Before_Resume) { - // Tests CastMediaBlocker does not resume if blocked again after an unblock. - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(true, true); - MediaSessionChanged(false, true); - media_blocker_->BlockMediaLoading(false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(true, true); -} - -TEST_F(CastMediaBlockerTest, Unblocked_Already_Playing) { - // Tests CastMediaBlocker does not resume if unblocked and media is playing. - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - media_blocker_->BlockMediaLoading(true); - media_blocker_->BlockMediaLoading(false); -} - -TEST_F(CastMediaBlockerTest, BlockStarting_UnblockStarting_Suspended) { - // Testing block/unblock operations do nothing if media never plays. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaStarting(true); - media_blocker_->BlockMediaStarting(false); - - MediaSessionChanged(true, true); - media_blocker_->BlockMediaStarting(true); - media_blocker_->BlockMediaStarting(false); - - media_blocker_->BlockMediaStarting(true); - MediaSessionChanged(false, true); - media_blocker_->BlockMediaStarting(false); -} - -TEST_F(CastMediaBlockerTest, BlockStarting_Before_Controllable) { - // Tests CastMediaBlocker only suspends when controllable. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaStarting(true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Session becomes controllable - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); -} - -TEST_F(CastMediaBlockerTest, BlockStarting_After_Controllable) { - // Tests CastMediaBlocker suspends immediately on block if controllable. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Block when media is playing - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaStarting(true); - MediaSessionChanged(true, true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Unblock - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(1); - media_blocker_->BlockMediaStarting(false); -} - -TEST_F(CastMediaBlockerTest, BlockStarting_Unblock_Suspended) { - // Testing block/unblock operations do nothing if media never plays. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaStarting(true); - media_blocker_->BlockMediaStarting(false); - - MediaSessionChanged(true, true); - media_blocker_->BlockMediaStarting(true); - media_blocker_->BlockMediaStarting(false); - - media_blocker_->BlockMediaStarting(true); - MediaSessionChanged(false, true); - media_blocker_->BlockMediaStarting(false); -} - -TEST_F(CastMediaBlockerTest, BlockLoading_BlockStarting_After_Controllable) { - // Tests CastMediaBlocker suspends immediately on block if controllable. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Block when media is playing - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(true); - MediaSessionChanged(true, true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaStarting(true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Unblock - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(1); - media_blocker_->BlockMediaStarting(false); -} - -TEST_F(CastMediaBlockerTest, BlockStarting_BlockLoading_After_Controllable) { - // Tests CastMediaBlocker suspends immediately on block if controllable. - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - MediaSessionChanged(true, false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Block when media is playing - EXPECT_CALL(*media_session_, Suspend(_)).Times(1); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaStarting(true); - MediaSessionChanged(true, true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaLoading(true); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - // Unblock - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(0); - media_blocker_->BlockMediaStarting(false); - testing::Mock::VerifyAndClearExpectations(media_session_.get()); - - EXPECT_CALL(*media_session_, Suspend(_)).Times(0); - EXPECT_CALL(*media_session_, Resume(_)).Times(1); - media_blocker_->BlockMediaLoading(false); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_navigation_ui_data.cc chromium-132.0.6834.159/chromecast/browser/cast_navigation_ui_data.cc --- chromium-132.0.6834.110/chromecast/browser/cast_navigation_ui_data.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_navigation_ui_data.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_navigation_ui_data.h" - -#include "chromecast/browser/cast_session_id_map.h" -#include "content/public/browser/web_contents.h" - -namespace chromecast { -namespace shell { -namespace { - -const char kUserDataKey[] = "chromecast.shell.SessionIdUserData key"; - -class SessionIdUserData : public base::SupportsUserData::Data { - public: - explicit SessionIdUserData(const std::string& session_id) - : session_id_(session_id) {} - - const std::string& session_id() const { return session_id_; } - - private: - std::string session_id_; -}; - -} // namespace - -// static -void CastNavigationUIData::SetAppPropertiesForWebContents( - content::WebContents* web_contents, - const std::string& session_id, - bool is_audio_app) { - DCHECK(web_contents); - web_contents->SetUserData(kUserDataKey, - std::make_unique(session_id)); - CastSessionIdMap::GetInstance()->SetAppProperties(session_id, is_audio_app, - web_contents); -} - -// static -std::string CastNavigationUIData::GetSessionIdForWebContents( - content::WebContents* web_contents) { - DCHECK(web_contents); - SessionIdUserData* data = - static_cast(web_contents->GetUserData(kUserDataKey)); - return data ? data->session_id() : ""; -} - -CastNavigationUIData::CastNavigationUIData(const std::string& session_id) - : session_id_(session_id) {} - -std::unique_ptr CastNavigationUIData::Clone() { - return std::make_unique(session_id_); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_navigation_ui_data.h chromium-132.0.6834.159/chromecast/browser/cast_navigation_ui_data.h --- chromium-132.0.6834.110/chromecast/browser/cast_navigation_ui_data.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_navigation_ui_data.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_NAVIGATION_UI_DATA_H_ -#define CHROMECAST_BROWSER_CAST_NAVIGATION_UI_DATA_H_ - -#include - -#include "content/public/browser/navigation_ui_data.h" - -namespace content { -class WebContents; -} - -namespace chromecast { -namespace shell { - -class CastNavigationUIData : public content::NavigationUIData { - public: - static void SetAppPropertiesForWebContents(content::WebContents* web_contents, - const std::string& session_id, - bool is_audio_app); - static std::string GetSessionIdForWebContents( - content::WebContents* web_contents); - - explicit CastNavigationUIData(const std::string& session_id); - - CastNavigationUIData(const CastNavigationUIData&) = delete; - CastNavigationUIData& operator=(const CastNavigationUIData&) = delete; - - const std::string& session_id() const { return session_id_; } - - std::unique_ptr Clone() override; - - private: - std::string session_id_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_NAVIGATION_UI_DATA_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_network_contexts.cc chromium-132.0.6834.159/chromecast/browser/cast_network_contexts.cc --- chromium-132.0.6834.110/chromecast/browser/cast_network_contexts.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_network_contexts.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,374 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_network_contexts.h" - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/strings/strcat.h" -#include "base/time/time.h" -#include "base/values.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/browser/cast_browser_context.h" -#include "chromecast/browser/cast_browser_process.h" -#include "chromecast/browser/cast_http_user_agent_settings.h" -#include "chromecast/common/user_agent.h" -#include "components/proxy_config/pref_proxy_config_tracker_impl.h" -#include "components/variations/net/variations_http_headers.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/network_service_instance.h" -#include "content/public/browser/storage_partition.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h" -#include "services/network/network_context.h" -#include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h" -#include "services/network/public/cpp/resource_request.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" -#include "services/network/public/mojom/cookie_manager.mojom.h" - -namespace chromecast { -namespace shell { - -namespace { - -constexpr char kCookieStoreFile[] = "Cookies"; - -ContentSettingPatternSource CreateContentSetting( - const std::string& primary_pattern, - const std::string& secondary_pattern, - ContentSetting setting) { - return ContentSettingPatternSource( - ContentSettingsPattern::FromString(primary_pattern), - ContentSettingsPattern::FromString(secondary_pattern), - base::Value(setting), content_settings::ProviderType::kNone, - /*incognito=*/false); -} - -} // namespace - -// SharedURLLoaderFactory backed by a CastNetworkContexts and its system -// NetworkContext. Transparently handles crashes. -class CastNetworkContexts::URLLoaderFactoryForSystem - : public network::SharedURLLoaderFactory { - public: - explicit URLLoaderFactoryForSystem(CastNetworkContexts* network_context) - : network_context_(network_context) { - DETACH_FROM_SEQUENCE(sequence_checker_); - } - - URLLoaderFactoryForSystem(const URLLoaderFactoryForSystem&) = delete; - URLLoaderFactoryForSystem& operator=(const URLLoaderFactoryForSystem&) = - delete; - - // mojom::URLLoaderFactory implementation: - void CreateLoaderAndStart( - mojo::PendingReceiver receiver, - int32_t request_id, - uint32_t options, - const network::ResourceRequest& url_request, - mojo::PendingRemote client, - const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) - override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!network_context_) - return; - network_context_->GetSystemURLLoaderFactory()->CreateLoaderAndStart( - std::move(receiver), request_id, options, url_request, - std::move(client), traffic_annotation); - } - - void Clone(mojo::PendingReceiver receiver) - override { - if (!network_context_) - return; - network_context_->GetSystemURLLoaderFactory()->Clone(std::move(receiver)); - } - - // SharedURLLoaderFactory implementation: - std::unique_ptr Clone() override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return std::make_unique( - this); - } - - void Shutdown() { network_context_ = nullptr; } - - private: - friend class base::RefCounted; - ~URLLoaderFactoryForSystem() override {} - - SEQUENCE_CHECKER(sequence_checker_); - CastNetworkContexts* network_context_; -}; - -CastNetworkContexts::CastNetworkContexts( - std::vector cors_exempt_headers_list) - : cors_exempt_headers_list_(std::move(cors_exempt_headers_list)), - system_shared_url_loader_factory_( - base::MakeRefCounted(this)) {} - -CastNetworkContexts::~CastNetworkContexts() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - system_shared_url_loader_factory_->Shutdown(); -} - -network::mojom::NetworkContext* CastNetworkContexts::GetSystemContext() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - if (!system_network_context_ || !system_network_context_.is_connected()) { - // This should call into OnNetworkServiceCreated(), which will re-create - // the network service, if needed. There's a chance that it won't be - // invoked, if the NetworkContext has encountered an error but the - // NetworkService has not yet noticed its pipe was closed. In that case, - // trying to create a new NetworkContext would fail, anyways, and hopefully - // a new NetworkContext will be created on the next GetContext() call. - content::GetNetworkService(); - DCHECK(system_network_context_); - } - - return system_network_context_.get(); -} - -network::mojom::URLLoaderFactory* -CastNetworkContexts::GetSystemURLLoaderFactory() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - // Create the URLLoaderFactory as needed. - if (system_url_loader_factory_ && system_url_loader_factory_.is_connected()) { - return system_url_loader_factory_.get(); - } - - network::mojom::URLLoaderFactoryParamsPtr params = - network::mojom::URLLoaderFactoryParams::New(); - params->process_id = network::mojom::kBrowserProcessId; - params->is_orb_enabled = false; - params->is_trusted = true; - GetSystemContext()->CreateURLLoaderFactory( - system_url_loader_factory_.BindNewPipeAndPassReceiver(), - std::move(params)); - return system_shared_url_loader_factory_.get(); -} - -scoped_refptr -CastNetworkContexts::GetSystemSharedURLLoaderFactory() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - return system_shared_url_loader_factory_; -} - -void CastNetworkContexts::SetAllowedDomainsForPersistentCookies( - std::vector allowed_domains_list) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - allowed_domains_for_persistent_cookies_ = std::move(allowed_domains_list); -} - -void CastNetworkContexts::ConfigureNetworkContextParams( - content::BrowserContext* context, - bool in_memory, - const base::FilePath& relative_partition_path, - network::mojom::NetworkContextParams* network_context_params, - cert_verifier::mojom::CertVerifierCreationParams* - cert_verifier_creation_params) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - ConfigureDefaultNetworkContextParams(network_context_params); - - // Copy of what's in ContentBrowserClient::CreateNetworkContext for now. - network_context_params->accept_language = "en-us,en"; -} - -void CastNetworkContexts::OnNetworkServiceCreated( - network::mojom::NetworkService* network_service) { - // Disable QUIC if instructed by DCS. This remains constant for the lifetime - // of the process. - if (!chromecast::IsFeatureEnabled(kEnableQuic)) - network_service->DisableQuic(); - - network_service->CreateNetworkContext( - system_network_context_.BindNewPipeAndPassReceiver(), - CreateSystemNetworkContextParams()); -} - -void CastNetworkContexts::OnLocaleUpdate() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - auto accept_language = CastHttpUserAgentSettings::AcceptLanguage(); - - GetSystemContext()->SetAcceptLanguage(accept_language); - - auto* browser_context = CastBrowserProcess::GetInstance()->browser_context(); - browser_context->GetDefaultStoragePartition() - ->GetNetworkContext() - ->SetAcceptLanguage(accept_language); -} - -void CastNetworkContexts::OnPrefServiceShutdown() { - if (proxy_config_service_) - proxy_config_service_->RemoveObserver(this); - - if (pref_proxy_config_tracker_impl_) - pref_proxy_config_tracker_impl_->DetachFromPrefService(); -} - -void CastNetworkContexts::ConfigureDefaultNetworkContextParams( - network::mojom::NetworkContextParams* network_context_params) { - network_context_params->http_cache_enabled = false; - network_context_params->user_agent = GetUserAgent(); - network_context_params->accept_language = - CastHttpUserAgentSettings::AcceptLanguage(); - - auto* browser_context = CastBrowserProcess::GetInstance()->browser_context(); - DCHECK(browser_context); - network_context_params->file_paths = - network::mojom::NetworkContextFilePaths::New(); - network_context_params->file_paths->data_directory = - browser_context->GetPath(); - network_context_params->file_paths->cookie_database_name = - base::FilePath(kCookieStoreFile); - network_context_params->restore_old_session_cookies = false; - network_context_params->persist_session_cookies = true; - network_context_params->cookie_manager_params = CreateCookieManagerParams(); - - // Disable idle sockets close on memory pressure, if instructed by DCS. On - // memory constrained devices: - // 1. if idle sockets are closed when memory pressure happens, cast_shell will - // close and re-open lots of connections to server. - // 2. if idle sockets are kept alive when memory pressure happens, this may - // cause JS engine gc frequently, leading to JS suspending. - network_context_params->disable_idle_sockets_close_on_memory_pressure = - IsFeatureEnabled(kDisableIdleSocketsCloseOnMemoryPressure); - - AddProxyToNetworkContextParams(network_context_params); - - network_context_params->cors_exempt_header_list.insert( - network_context_params->cors_exempt_header_list.end(), - cors_exempt_headers_list_.begin(), cors_exempt_headers_list_.end()); -} - -network::mojom::NetworkContextParamsPtr -CastNetworkContexts::CreateSystemNetworkContextParams() { - network::mojom::NetworkContextParamsPtr network_context_params = - network::mojom::NetworkContextParams::New(); - ConfigureDefaultNetworkContextParams(network_context_params.get()); - - network_context_params->cert_verifier_params = content::GetCertVerifierParams( - cert_verifier::mojom::CertVerifierCreationParams::New()); - - return network_context_params; -} - -network::mojom::CookieManagerParamsPtr -CastNetworkContexts::CreateCookieManagerParams() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - auto params = network::mojom::CookieManagerParams::New(); - if (allowed_domains_for_persistent_cookies_.empty()) { - // Don't restrict persistent cookie access if no allowlist is set. - return params; - } - - ContentSettingsForOneType settings; - ContentSettingsForOneType settings_for_storage_access; - ContentSettingsForOneType settings_for_top_level_storage_access; - - // Grant cookie and storage access to domains in the allowlist. - for (const auto& domain : allowed_domains_for_persistent_cookies_) { - auto allow_storage_access_setting = CreateContentSetting( - /*primary_pattern=*/base::StrCat({"[*.]", domain}), - /*secondary_pattern=*/"*", ContentSetting::CONTENT_SETTING_ALLOW); - settings.push_back(allow_storage_access_setting); - settings_for_storage_access.push_back( - std::move(allow_storage_access_setting)); - - // TODO(crbug.com/40246640): Consolidate this with the regular - // STORAGE_ACCESS setting as usage becomes better-defined. - auto allow_top_level_storage_access_setting = CreateContentSetting( - /*primary_pattern=*/base::StrCat({"[*.]", domain}), - /*secondary_pattern=*/"*", ContentSetting::CONTENT_SETTING_ALLOW); - settings_for_top_level_storage_access.push_back( - std::move(allow_top_level_storage_access_setting)); - } - - // Restrict cookie access to session only and block storage access for - // domains not in the allowlist. - // Note: storage access control depends on the feature |kStorageAccessAPI| - // which has not been enabled by default in chromium. - settings.push_back(CreateContentSetting( - /*primary_pattern=*/"*", - /*secondary_pattern=*/"*", ContentSetting::CONTENT_SETTING_SESSION_ONLY)); - settings_for_storage_access.push_back(CreateContentSetting( - /*primary_pattern=*/"*", - /*secondary_pattern=*/"*", ContentSetting::CONTENT_SETTING_BLOCK)); - settings_for_top_level_storage_access.push_back(CreateContentSetting( - /*primary_pattern=*/"*", - /*secondary_pattern=*/"*", ContentSetting::CONTENT_SETTING_BLOCK)); - params->content_settings[ContentSettingsType::COOKIES] = std::move(settings); - params->content_settings[ContentSettingsType::STORAGE_ACCESS] = - std::move(settings_for_storage_access); - params->content_settings[ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS] = - std::move(settings_for_top_level_storage_access); - - return params; -} - -void CastNetworkContexts::AddProxyToNetworkContextParams( - network::mojom::NetworkContextParams* network_context_params) { - if (!proxy_config_service_) { - pref_proxy_config_tracker_impl_ = - std::make_unique( - CastBrowserProcess::GetInstance()->pref_service(), nullptr); - proxy_config_service_ = - pref_proxy_config_tracker_impl_->CreateTrackingProxyConfigService( - nullptr); - proxy_config_service_->AddObserver(this); - } - - mojo::PendingRemote proxy_config_client; - network_context_params->proxy_config_client_receiver = - proxy_config_client.InitWithNewPipeAndPassReceiver(); - proxy_config_client_set_.Add(std::move(proxy_config_client)); - - poller_receiver_set_.Add(this, - network_context_params->proxy_config_poller_client - .InitWithNewPipeAndPassReceiver()); - - net::ProxyConfigWithAnnotation proxy_config; - net::ProxyConfigService::ConfigAvailability availability = - proxy_config_service_->GetLatestProxyConfig(&proxy_config); - if (availability != net::ProxyConfigService::CONFIG_PENDING) - network_context_params->initial_proxy_config = proxy_config; -} - -void CastNetworkContexts::OnProxyConfigChanged( - const net::ProxyConfigWithAnnotation& config, - net::ProxyConfigService::ConfigAvailability availability) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - for (const auto& proxy_config_client : proxy_config_client_set_) { - switch (availability) { - case net::ProxyConfigService::CONFIG_VALID: - proxy_config_client->OnProxyConfigUpdated(config); - break; - case net::ProxyConfigService::CONFIG_UNSET: - proxy_config_client->OnProxyConfigUpdated( - net::ProxyConfigWithAnnotation::CreateDirect()); - break; - case net::ProxyConfigService::CONFIG_PENDING: - NOTREACHED(); - } - } -} - -void CastNetworkContexts::OnLazyProxyConfigPoll() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - proxy_config_service_->OnLazyPoll(); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_network_contexts.h chromium-132.0.6834.159/chromecast/browser/cast_network_contexts.h --- chromium-132.0.6834.110/chromecast/browser/cast_network_contexts.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_network_contexts.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,154 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_NETWORK_CONTEXTS_H_ -#define CHROMECAST_BROWSER_CAST_NETWORK_CONTEXTS_H_ - -#include -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "mojo/public/cpp/bindings/remote_set.h" -#include "net/proxy_resolution/proxy_config_service.h" -#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom-forward.h" -#include "services/network/public/mojom/network_context.mojom.h" -#include "services/network/public/mojom/network_service.mojom.h" -#include "services/network/public/mojom/proxy_config.mojom.h" -#include "services/network/public/mojom/proxy_config_with_annotation.mojom.h" -#include "services/network/public/mojom/url_loader_factory.mojom.h" - -class PrefProxyConfigTracker; - -namespace base { -class FilePath; -} - -namespace content { -class BrowserContext; -} - -namespace network { -namespace mojom { -class NetworkContext; -class URLLoaderFactory; -} // namespace mojom -class SharedURLLoaderFactory; -} // namespace network - -namespace chromecast { -namespace shell { - -// This class owns the NetworkContext used for the system and for configuring it -// along with the BrowserContext's NetworkContext. -// It will create and configure its own NetworkContext for the system, and -// create the BrowserContext's main StoragePartition's NetworkContext. -// It lives on the UI thread. -class CastNetworkContexts : public net::ProxyConfigService::Observer, - public network::mojom::ProxyConfigPollerClient { - public: - explicit CastNetworkContexts( - std::vector cors_exempt_headers_list); - - CastNetworkContexts(const CastNetworkContexts&) = delete; - CastNetworkContexts& operator=(const CastNetworkContexts&) = delete; - - ~CastNetworkContexts() override; - - // Returns the System NetworkContext. Does any initialization of the - // NetworkService that may be needed when first called. - network::mojom::NetworkContext* GetSystemContext(); - - // Returns a URLLoaderFactory owned by the CastNetworkContexts that is - // backed by the system NetworkContext. Allows sharing of the - // URLLoaderFactory. Prefer this to creating a new one. Call Clone() on the - // value returned by this method to get a URLLoaderFactory that can be used on - // other threads. - network::mojom::URLLoaderFactory* GetSystemURLLoaderFactory(); - - // Returns a SharedURLLoaderFactory that is backed by the system - // NetworkContext. - scoped_refptr - GetSystemSharedURLLoaderFactory(); - - // Sets a list of domains which will be allowed to persist cookies. - void SetAllowedDomainsForPersistentCookies( - std::vector allowed_domains_list); - - // Called when content creates a NetworkService. Creates the - // system NetworkContext, if the network service is enabled. - void OnNetworkServiceCreated(network::mojom::NetworkService* network_service); - - void ConfigureNetworkContextParams( - content::BrowserContext* context, - bool in_memory, - const base::FilePath& relative_partition_path, - network::mojom::NetworkContextParams* network_context_params, - cert_verifier::mojom::CertVerifierCreationParams* - cert_verifier_creation_params); - - // Called when the locale has changed. - void OnLocaleUpdate(); - - // Called on shutdown of the PrefService. - void OnPrefServiceShutdown(); - - private: - class URLLoaderFactoryForSystem; - - // Fills in |network_context_params| with the default set of parameters for - // configuring the network service. - void ConfigureDefaultNetworkContextParams( - network::mojom::NetworkContextParams* network_context_params); - - // Creates parameters for the system NetworkContext. May only be called once, - // since it initializes some class members. - network::mojom::NetworkContextParamsPtr CreateSystemNetworkContextParams(); - - // Creates parameters for CookieManager of all NetworkContexts. - network::mojom::CookieManagerParamsPtr CreateCookieManagerParams(); - - // Populates proxy-related fields of |network_context_params|. Updated - // ProxyConfigs will be sent to a NetworkContext created with those params - // whenever the configuration changes. Can be called more than once to inform - // multiple NetworkContexts of proxy changes. - void AddProxyToNetworkContextParams( - network::mojom::NetworkContextParams* network_context_params); - - // net::ProxyConfigService::Observer implementation: - void OnProxyConfigChanged( - const net::ProxyConfigWithAnnotation& config, - net::ProxyConfigService::ConfigAvailability availability) override; - - // network::mojom::ProxyConfigPollerClient implementation: - void OnLazyProxyConfigPoll() override; - - const std::vector cors_exempt_headers_list_; - std::vector allowed_domains_for_persistent_cookies_; - - // The system NetworkContext. - mojo::Remote system_network_context_; - - // URLLoaderFactory backed by the NetworkContext returned by - // GetSystemContext(), so consumers don't all need to create their own - // factory. - scoped_refptr system_shared_url_loader_factory_; - mojo::Remote system_url_loader_factory_; - - std::unique_ptr proxy_config_service_; - // Monitors prefs related to proxy configuration. - std::unique_ptr pref_proxy_config_tracker_impl_; - - mojo::ReceiverSet - poller_receiver_set_; - mojo::RemoteSet proxy_config_client_set_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_NETWORK_CONTEXTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_overlay_manifests.cc chromium-132.0.6834.159/chromecast/browser/cast_overlay_manifests.cc --- chromium-132.0.6834.110/chromecast/browser/cast_overlay_manifests.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_overlay_manifests.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_overlay_manifests.h" - -#include "base/no_destructor.h" -#include "build/build_config.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/common/mojom/application_media_capabilities.mojom.h" -#include "chromecast/common/mojom/media_caps.mojom.h" -#include "chromecast/common/mojom/memory_pressure.mojom.h" -#include "services/service_manager/public/cpp/manifest_builder.h" - -#if BUILDFLAG(ENABLE_EXTERNAL_MOJO_SERVICES) -#include "chromecast/external_mojo/broker_service/broker_service.h" // nogncheck -#endif - -namespace chromecast { -namespace shell { - -const service_manager::Manifest& GetCastContentBrowserOverlayManifest() { - static base::NoDestructor manifest { - service_manager::ManifestBuilder() - .ExposeCapability("renderer", - service_manager::Manifest::InterfaceList< - chromecast::media::mojom::MediaCaps, - chromecast::mojom::MemoryPressureController>()) - .Build() - }; - return *manifest; -} - -const service_manager::Manifest& -GetCastContentPackagedServicesOverlayManifest() { - static base::NoDestructor manifest { - service_manager::ManifestBuilder() -#if BUILDFLAG(ENABLE_EXTERNAL_MOJO_SERVICES) - .PackageService(chromecast::external_mojo::BrokerService::GetManifest()) -#endif - .Build() - }; - return *manifest; -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_overlay_manifests.h chromium-132.0.6834.159/chromecast/browser/cast_overlay_manifests.h --- chromium-132.0.6834.110/chromecast/browser/cast_overlay_manifests.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_overlay_manifests.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_OVERLAY_MANIFESTS_H_ -#define CHROMECAST_BROWSER_CAST_OVERLAY_MANIFESTS_H_ - -#include "services/service_manager/public/cpp/manifest.h" - -namespace chromecast { -namespace shell { - -// Returns the manifest Cast amends to Content's content_browser service -// manifest. This allows Cast to extend the capabilities exposed and/or -// required by content_browser service instances. -const service_manager::Manifest& GetCastContentBrowserOverlayManifest(); - -// Returns the manifest Cast amends to Content's content_packaged_services -// service manifest. This allows Cast to extend the set of in- and out-of- -// process services packaged by the browser. -const service_manager::Manifest& -GetCastContentPackagedServicesOverlayManifest(); - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_OVERLAY_MANIFESTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_permission_manager.cc chromium-132.0.6834.159/chromecast/browser/cast_permission_manager.cc --- chromium-132.0.6834.110/chromecast/browser/cast_permission_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_permission_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,214 +0,0 @@ -// 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 "chromecast/browser/cast_permission_manager.h" - -#include "base/functional/callback.h" -#include "base/logging.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/browser/cast_permission_user_data.h" -#include "chromecast/common/activity_url_filter.h" -#include "components/cast_receiver/browser/public/permissions_manager.h" -#include "content/public/browser/permission_controller.h" -#include "content/public/browser/web_contents.h" -#include "third_party/blink/public/common/permissions/permission_utils.h" - -namespace { - -bool IsRequestingOriginAllowed( - const GURL& requesting_origin, - const GURL& app_web_url, - const std::vector& additional_feature_permission_origins) { - // |app_web_url| is allowed by default. - if (requesting_origin == app_web_url.DeprecatedGetOriginAsURL()) { - return true; - } - chromecast::ActivityUrlFilter activity_url_filter( - additional_feature_permission_origins); - return activity_url_filter.UrlMatchesWhitelist(requesting_origin); -} - -blink::mojom::PermissionStatus GetPermissionStatusFromCastPermissionUserData( - blink::PermissionType permission, - const GURL& requesting_origin, - chromecast::shell::CastPermissionUserData* cast_permission_user_data) { - std::string app_id = cast_permission_user_data->GetAppId(); - GURL app_web_url = cast_permission_user_data->GetAppWebUrl(); - // We expect to grant blink::PermissionType::PROTECTED_MEDIA_IDENTIFIER - // to origins same as |app_web_url| by default. - if (requesting_origin != app_web_url.DeprecatedGetOriginAsURL() || - permission != blink::PermissionType::PROTECTED_MEDIA_IDENTIFIER) { - chromecast::metrics::CastMetricsHelper::GetInstance() - ->RecordApplicationEventWithValue( - app_id, /*session_id=*/"", /*sdk_version=*/"", - "Cast.Platform.PermissionRequestWithFrame", - static_cast(permission)); - } - - if (!cast_permission_user_data->GetEnforceFeaturePermissions()) { - return blink::mojom::PermissionStatus::GRANTED; - } - - // Permissions that are granted by default should have been added to the - // FeaturePermissions in CastPermissionUserData. - bool permitted = - cast_permission_user_data->GetFeaturePermissions().count( - static_cast(permission)) > 0 && - IsRequestingOriginAllowed( - requesting_origin, app_web_url, - cast_permission_user_data->GetAdditionalFeaturePermissionOrigins()); - - return permitted ? blink::mojom::PermissionStatus::GRANTED - : ::blink::mojom::PermissionStatus::DENIED; -} - -} // namespace - -namespace chromecast { -namespace shell { - -// TODO(b/191718807): Be more restrictive on the permissions. -// Currently, only collect metrics. -blink::mojom::PermissionStatus GetPermissionStatusInternal( - blink::PermissionType permission, - const GURL& requesting_origin) { - // We expect to grant blink::PermissionType::BACKGROUND_SYNC by - // default. - if (permission != blink::PermissionType::BACKGROUND_SYNC) { - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEventWithValue( - "Cast.Platform.PermissionRequestWithoutFrame", - static_cast(permission)); - } - blink::mojom::PermissionStatus permission_status = - blink::mojom::PermissionStatus::GRANTED; - LOG(INFO) << __func__ << ": " - << (permission_status == blink::mojom::PermissionStatus::GRANTED - ? " grants " - : " doesn't grant ") - << "permission " << static_cast(permission) - << " out of frame context."; - return permission_status; -} - -blink::mojom::PermissionStatus GetPermissionStatusInternal( - blink::PermissionType permission, - content::RenderFrameHost* render_frame_host, - const GURL& requesting_origin) { - content::WebContents* web_contents = - content::WebContents::FromRenderFrameHost(render_frame_host); - const cast_receiver::PermissionsManager* permissions_manager = - cast_receiver::PermissionsManager::GetInstance(*web_contents); - if (permissions_manager) { - const blink::mojom::PermissionStatus permission_status = - permissions_manager->GetPermissionStatus(permission, requesting_origin); - if (permission_status == blink::mojom::PermissionStatus::GRANTED) { - return permission_status; - } - } - - DCHECK(render_frame_host); - CastPermissionUserData* cast_permission_user_data = - CastPermissionUserData::FromWebContents(web_contents); - - if (!cast_permission_user_data) { - LOG(ERROR) << __func__ << ": No permission data in frame!"; - return GetPermissionStatusInternal(permission, requesting_origin); - } - - blink::mojom::PermissionStatus permission_status = - GetPermissionStatusFromCastPermissionUserData( - permission, requesting_origin, cast_permission_user_data); - LOG(INFO) << __func__ << ": " - << (permission_status == blink::mojom::PermissionStatus::GRANTED - ? " grants " - : " doesn't grant ") - << "permission " << static_cast(permission) - << " to frame associated with app: " - << cast_permission_user_data->GetAppId(); - return permission_status; -} - -CastPermissionManager::CastPermissionManager() {} - -CastPermissionManager::~CastPermissionManager() {} - -void CastPermissionManager::RequestPermissions( - content::RenderFrameHost* render_frame_host, - const content::PermissionRequestDescription& request_description, - base::OnceCallback&)> - callback) { - std::vector permission_statuses; - for (auto permission : request_description.permissions) { - permission_statuses.push_back(GetPermissionStatusInternal( - permission, render_frame_host, request_description.requesting_origin)); - } - std::move(callback).Run(permission_statuses); -} - -void CastPermissionManager::ResetPermission(blink::PermissionType permission, - const GURL& requesting_origin, - const GURL& embedding_origin) {} - -void CastPermissionManager::RequestPermissionsFromCurrentDocument( - content::RenderFrameHost* render_frame_host, - const content::PermissionRequestDescription& request_description, - base::OnceCallback&)> - callback) { - std::vector permission_statuses; - for (auto permission : request_description.permissions) { - permission_statuses.push_back(GetPermissionStatusInternal( - permission, render_frame_host, - render_frame_host->GetLastCommittedOrigin().GetURL())); - } - std::move(callback).Run(permission_statuses); -} - -blink::mojom::PermissionStatus CastPermissionManager::GetPermissionStatus( - blink::PermissionType permission, - const GURL& requesting_origin, - const GURL& embedding_origin) { - return GetPermissionStatusInternal(permission, requesting_origin); -} - -content::PermissionResult -CastPermissionManager::GetPermissionResultForOriginWithoutContext( - blink::PermissionType permission, - const url::Origin& requesting_origin, - const url::Origin& embedding_origin) { - blink::mojom::PermissionStatus status = GetPermissionStatus( - permission, requesting_origin.GetURL(), embedding_origin.GetURL()); - - return content::PermissionResult( - status, content::PermissionStatusSource::UNSPECIFIED); -} - -blink::mojom::PermissionStatus -CastPermissionManager::GetPermissionStatusForCurrentDocument( - blink::PermissionType permission, - content::RenderFrameHost* render_frame_host, - bool should_include_device_status) { - return GetPermissionStatusInternal( - permission, render_frame_host, - render_frame_host->GetLastCommittedOrigin().GetURL()); -} - -blink::mojom::PermissionStatus -CastPermissionManager::GetPermissionStatusForWorker( - blink::PermissionType permission, - content::RenderProcessHost* render_process_host, - const GURL& worker_origin) { - return GetPermissionStatusInternal(permission, worker_origin); -} - -blink::mojom::PermissionStatus -CastPermissionManager::GetPermissionStatusForEmbeddedRequester( - blink::PermissionType permission, - content::RenderFrameHost* render_frame_host, - const url::Origin& requesting_origin) { - return GetPermissionStatusInternal(permission, render_frame_host, - requesting_origin.GetURL()); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_permission_manager.h chromium-132.0.6834.159/chromecast/browser/cast_permission_manager.h --- chromium-132.0.6834.110/chromecast/browser/cast_permission_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_permission_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BROWSER_CAST_PERMISSION_MANAGER_H_ -#define CHROMECAST_BROWSER_CAST_PERMISSION_MANAGER_H_ - -#include "base/functional/callback_forward.h" -#include "content/public/browser/permission_controller_delegate.h" -#include "content/public/browser/permission_result.h" -#include "third_party/blink/public/common/permissions/permission_utils.h" -#include "url/gurl.h" - -namespace blink { -enum class PermissionType; -} - -namespace chromecast { -namespace shell { - -class CastPermissionManager : public content::PermissionControllerDelegate { - public: - CastPermissionManager(); - - CastPermissionManager(const CastPermissionManager&) = delete; - CastPermissionManager& operator=(const CastPermissionManager&) = delete; - - ~CastPermissionManager() override; - - // content::PermissionControllerDelegate implementation: - void RequestPermissions( - content::RenderFrameHost* render_frame_host, - const content::PermissionRequestDescription& request_description, - base::OnceCallback< - void(const std::vector&)> callback) - override; - void ResetPermission(blink::PermissionType permission, - const GURL& requesting_origin, - const GURL& embedding_origin) override; - void RequestPermissionsFromCurrentDocument( - content::RenderFrameHost* render_frame_host, - const content::PermissionRequestDescription& request_description, - base::OnceCallback< - void(const std::vector&)> callback) - override; - blink::mojom::PermissionStatus GetPermissionStatus( - blink::PermissionType permission, - const GURL& requesting_origin, - const GURL& embedding_origin) override; - content::PermissionResult GetPermissionResultForOriginWithoutContext( - blink::PermissionType permission, - const url::Origin& requesting_origin, - const url::Origin& embedding_origin) override; - blink::mojom::PermissionStatus GetPermissionStatusForCurrentDocument( - blink::PermissionType permission, - content::RenderFrameHost* render_frame_host, - bool should_include_device_status) override; - blink::mojom::PermissionStatus GetPermissionStatusForWorker( - blink::PermissionType permission, - content::RenderProcessHost* render_process_host, - const GURL& worker_origin) override; - blink::mojom::PermissionStatus GetPermissionStatusForEmbeddedRequester( - blink::PermissionType permission, - content::RenderFrameHost* render_frame_host, - const url::Origin& requesting_origin) override; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_PERMISSION_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_permission_user_data.cc chromium-132.0.6834.159/chromecast/browser/cast_permission_user_data.cc --- chromium-132.0.6834.110/chromecast/browser/cast_permission_user_data.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_permission_user_data.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_permission_user_data.h" - -#include - -#include "base/memory/ptr_util.h" -#include "content/public/browser/web_contents.h" -#include "third_party/blink/public/common/permissions/permission_utils.h" - -namespace { -const char kCastPermissionUserDataKey[] = - "chromecast.shell.CastPermissionUserDataKey"; -} // namespace - -namespace chromecast { -namespace shell { - -CastPermissionUserData::CastPermissionUserData( - content::WebContents* web_contents, - const std::string& app_id, - const GURL& app_web_url, - bool enforce_feature_permissions, - std::vector feature_permissions, - std::vector additional_feature_permission_origins) - : app_id_(app_id), - app_web_url_(app_web_url), - enforce_feature_permissions_(enforce_feature_permissions), - feature_permissions_(std::move(feature_permissions)), - additional_feature_permission_origins_( - std::move(additional_feature_permission_origins)) { - feature_permissions_.insert( - static_cast(blink::PermissionType::PROTECTED_MEDIA_IDENTIFIER)); - web_contents->SetUserData(&kCastPermissionUserDataKey, - base::WrapUnique(this)); -} - -CastPermissionUserData::~CastPermissionUserData() {} - -// static -CastPermissionUserData* CastPermissionUserData::FromWebContents( - content::WebContents* web_contents) { - return static_cast( - web_contents->GetUserData(&kCastPermissionUserDataKey)); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_permission_user_data.h chromium-132.0.6834.159/chromecast/browser/cast_permission_user_data.h --- chromium-132.0.6834.110/chromecast/browser/cast_permission_user_data.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_permission_user_data.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_PERMISSION_USER_DATA_H_ -#define CHROMECAST_BROWSER_CAST_PERMISSION_USER_DATA_H_ - -#include -#include - -#include "base/containers/flat_set.h" -#include "base/supports_user_data.h" -#include "url/gurl.h" - -namespace content { -class WebContents; -} - -// TODO(b/191718807) Add App's page permission into this class. - -namespace chromecast { -namespace shell { - -class CastPermissionUserData : public base::SupportsUserData::Data { - public: - // Lifetime of the object is managed by |web_contents|. - CastPermissionUserData( - content::WebContents* web_contents, - const std::string& app_id, - const GURL& app_web_url, - bool enforce_feature_permissions, - std::vector feature_permissions, - std::vector additional_feature_permission_origins); - CastPermissionUserData(const CastPermissionUserData&) = delete; - CastPermissionUserData& operator=(const CastPermissionUserData&) = delete; - ~CastPermissionUserData() override; - - static CastPermissionUserData* FromWebContents( - content::WebContents* web_contents); - std::string GetAppId() { return app_id_; } - GURL GetAppWebUrl() { return app_web_url_; } - bool GetEnforceFeaturePermissions() { return enforce_feature_permissions_; } - const base::flat_set& GetFeaturePermissions() const { - return feature_permissions_; - } - const std::vector& GetAdditionalFeaturePermissionOrigins() - const { - return additional_feature_permission_origins_; - } - - private: - const std::string app_id_; - const GURL app_web_url_; - const bool enforce_feature_permissions_; - base::flat_set feature_permissions_; - const std::vector additional_feature_permission_origins_; -}; - -} // namespace shell -} // namespace chromecast -#endif // CHROMECAST_BROWSER_CAST_PERMISSION_USER_DATA_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_renderer_block_data.cc chromium-132.0.6834.159/chromecast/browser/cast_renderer_block_data.cc --- chromium-132.0.6834.110/chromecast/browser/cast_renderer_block_data.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_renderer_block_data.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_renderer_block_data.h" - -#include "base/logging.h" -#include "chromecast/browser/application_media_info_manager.h" -#include "chromecast/browser/cast_session_id_map.h" -#include "content/public/browser/web_contents.h" - -namespace chromecast { -namespace shell { -namespace { - -const char kUserDataKey[] = "chromecast.shell.RenderBlockUserData.key"; - -CastRendererBlockData* GetOrCreateCastRendererBlockData( - content::WebContents* web_contents) { - CastRendererBlockData* data = static_cast( - web_contents->GetUserData(kUserDataKey)); - if (!data) { - auto cast_renderer_block_data = std::make_unique(); - data = cast_renderer_block_data.get(); - web_contents->SetUserData(kUserDataKey, - std::move(cast_renderer_block_data)); - } - return data; -} - -} // namespace - -// static -void CastRendererBlockData::SetRendererBlockForWebContents( - content::WebContents* web_contents, - bool blocked) { - DCHECK(web_contents); - CastRendererBlockData* data = GetOrCreateCastRendererBlockData(web_contents); - data->SetBlocked(blocked); -} - -// static -void CastRendererBlockData::SetApplicationMediaInfoManagerForWebContents( - content::WebContents* web_contents, - base::WeakPtr - application_media_info_manager) { - DCHECK(web_contents); - CastRendererBlockData* data = GetOrCreateCastRendererBlockData(web_contents); - data->SetApplicationMediaInfoManager(application_media_info_manager); -} - -CastRendererBlockData::CastRendererBlockData() : blocked_(false) {} -CastRendererBlockData::~CastRendererBlockData() = default; - -void CastRendererBlockData::SetBlocked(bool blocked) { - LOG(INFO) << "Setting blocked to: " << blocked << " from " << blocked_; - blocked_ = blocked; - if (application_media_info_manager_) { - application_media_info_manager_->SetRendererBlock(blocked); - } -} - -void CastRendererBlockData::SetApplicationMediaInfoManager( - base::WeakPtr - application_media_info_manager) { - DCHECK(application_media_info_manager); - application_media_info_manager_ = application_media_info_manager; - application_media_info_manager_->SetRendererBlock(blocked_); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_renderer_block_data.h chromium-132.0.6834.159/chromecast/browser/cast_renderer_block_data.h --- chromium-132.0.6834.110/chromecast/browser/cast_renderer_block_data.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_renderer_block_data.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_RENDERER_BLOCK_DATA_H_ -#define CHROMECAST_BROWSER_CAST_RENDERER_BLOCK_DATA_H_ - -#include "base/memory/weak_ptr.h" -#include "base/supports_user_data.h" - -namespace content { -class WebContents; -} - -namespace chromecast { -namespace media { -class ApplicationMediaInfoManager; -} - -namespace shell { - -class CastRendererBlockData : public base::SupportsUserData::Data { - public: - static void SetRendererBlockForWebContents(content::WebContents* web_contents, - bool blocked); - static void SetApplicationMediaInfoManagerForWebContents( - content::WebContents* web_contents, - base::WeakPtr - application_media_info_manager); - CastRendererBlockData(); - ~CastRendererBlockData() override; - - bool blocked() const { return blocked_; } - void SetBlocked(bool blocked); - void SetApplicationMediaInfoManager( - base::WeakPtr - application_media_info_manager); - - private: - bool blocked_; - base::WeakPtr - application_media_info_manager_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_RENDERER_BLOCK_DATA_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_resource_bundle_unittest.cc chromium-132.0.6834.159/chromecast/browser/cast_resource_bundle_unittest.cc --- chromium-132.0.6834.110/chromecast/browser/cast_resource_bundle_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_resource_bundle_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/containers/span.h" -#include "base/memory/ref_counted_memory.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/resource/mock_resource_bundle_delegate.h" -#include "ui/base/resource/resource_bundle.h" - -using ::testing::Return; - -namespace ui { - -class CastResourceBundleTest : public testing::Test { - public: - CastResourceBundleTest() {} - - CastResourceBundleTest(const CastResourceBundleTest&) = delete; - CastResourceBundleTest& operator=(const CastResourceBundleTest&) = delete; - - ~CastResourceBundleTest() override {} -}; - -TEST_F(CastResourceBundleTest, DelegateLoadLocalizedResourceBytes) { - MockResourceBundleDelegate delegate; - ResourceBundle::InitSharedInstanceWithLocale( - "en-US", &delegate, ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES); - ResourceBundle& resource_bundle = ResourceBundle::GetSharedInstance(); - - const unsigned char data[] = "My test data"; - scoped_refptr static_memory( - new base::RefCountedStaticMemory(data)); - - int resource_id = 5; - - EXPECT_CALL(delegate, - LoadDataResourceBytes(resource_id, ui::kScaleFactorNone)) - .Times(1) - .WillOnce(Return(static_memory.get())); - - scoped_refptr result = - resource_bundle.LoadLocalizedResourceBytes(resource_id); - EXPECT_EQ(static_memory, result); - ResourceBundle::CleanupSharedInstance(); -} - -} // namespace ui diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_session_id_map.cc chromium-132.0.6834.159/chromecast/browser/cast_session_id_map.cc --- chromium-132.0.6834.110/chromecast/browser/cast_session_id_map.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_session_id_map.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,185 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_session_id_map.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/no_destructor.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_observer.h" - -namespace chromecast { -namespace shell { - -// A small class that listens for the destruction of a WebContents, and forwards -// the event to the CastSessionIdMap with the appropriate group_id. -class CastSessionIdMap::GroupObserver : content::WebContentsObserver { - public: - using GroupDestroyedCallback = - base::OnceCallback; - - GroupObserver(content::WebContents* web_contents, - GroupDestroyedCallback destroyed_callback) - : destroyed_callback_(std::move(destroyed_callback)), - group_id_(web_contents->GetAudioGroupId()) { - content::WebContentsObserver::Observe(web_contents); - } - - private: - // content::WebContentsObserver implementation: - void WebContentsDestroyed() override { - DCHECK(destroyed_callback_); - content::WebContentsObserver::Observe(nullptr); - std::move(destroyed_callback_).Run(group_id_); - } - - GroupDestroyedCallback destroyed_callback_; - base::UnguessableToken group_id_; -}; - -// static -CastSessionIdMap* CastSessionIdMap::GetInstance( - base::SequencedTaskRunner* task_runner) { - static base::NoDestructor map(task_runner); - return map.get(); -} - -void CastSessionIdMap::SetAppProperties(std::string session_id, - bool is_audio_app, - content::WebContents* web_contents) { - base::UnguessableToken group_id = web_contents->GetAudioGroupId(); - // Unretained is safe here, because the singleton CastSessionIdMap never gets - // destroyed. - auto destroyed_callback = base::BindOnce(&CastSessionIdMap::OnGroupDestroyed, - base::Unretained(GetInstance())); - auto group_observer = std::make_unique( - web_contents, std::move(destroyed_callback)); - SetAppPropertiesInternal(session_id, is_audio_app, group_id, - std::move(group_observer)); -} - -void CastSessionIdMap::SetGroupInfo(std::string session_id, bool is_group) { - if (!task_runner_->RunsTasksInCurrentSequence()) { - // Unretained is safe here, because the singleton CastSessionIdMap never - // gets destroyed. - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&CastSessionIdMap::SetGroupInfo, base::Unretained(this), - std::move(session_id), is_group)); - return; - } - group_info_mapping_.emplace(session_id, is_group); -} - -CastSessionIdMap::CastSessionIdMap(base::SequencedTaskRunner* task_runner) - : task_runner_(task_runner) { - DCHECK(task_runner_); - DETACH_FROM_SEQUENCE(sequence_checker_); -} - -CastSessionIdMap::~CastSessionIdMap() = default; - -void CastSessionIdMap::SetAppPropertiesInternal( - std::string session_id, - bool is_audio_app, - base::UnguessableToken group_id, - std::unique_ptr group_observer) { - if (!task_runner_->RunsTasksInCurrentSequence()) { - // Unretained is safe here, because the singleton CastSessionIdMap never - // gets destroyed. - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&CastSessionIdMap::SetAppPropertiesInternal, - base::Unretained(this), std::move(session_id), - is_audio_app, group_id, std::move(group_observer))); - return; - } - - // This check is required to bind to the current sequence. - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(GetSessionId(group_id.ToString()).empty()); - DCHECK(group_observer); - - DVLOG(1) << "Mapping session_id=" << session_id - << " to group_id=" << group_id.ToString(); - auto group_data = std::make_pair(session_id, std::move(group_observer)); - mapping_.emplace(group_id.ToString(), std::move(group_data)); - application_capability_mapping_.emplace(session_id, is_audio_app); -} - -std::string CastSessionIdMap::GetSessionId(const std::string& group_id) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto it = mapping_.find(group_id); - if (it != mapping_.end()) - return it->second.first; - return std::string(); -} - -bool CastSessionIdMap::IsAudioOnlySession(const std::string& session_id) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto it = application_capability_mapping_.find(session_id); - if (it != application_capability_mapping_.end()) - return it->second; - return false; -} - -bool CastSessionIdMap::IsGroup(const std::string& session_id) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto it = group_info_mapping_.find(session_id); - if (it != group_info_mapping_.end()) - return it->second; - return false; -} - -void CastSessionIdMap::IsAudioOnlySessionAsync( - const std::string& session_id, - IsAudioOnlySessionAsyncCallback callback) { - if (!task_runner_->RunsTasksInCurrentSequence()) { - // Unretained is safe here, because the singleton CastSessionIdMap never - // gets destroyed. - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&CastSessionIdMap::IsAudioOnlySessionAsync, - base::Unretained(this), session_id, - BindToCurrentSequence(std::move(callback)))); - return; - } - - std::move(callback).Run(IsAudioOnlySession(session_id)); -} - -void CastSessionIdMap::OnGroupDestroyed(base::UnguessableToken group_id) { - // Unretained is safe here, because the singleton CastSessionIdMap never gets - // destroyed. - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&CastSessionIdMap::RemoveGroupId, - base::Unretained(this), group_id)); -} - -void CastSessionIdMap::RemoveGroupId(base::UnguessableToken group_id) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - auto it = mapping_.find(group_id.ToString()); - if (it != mapping_.end()) { - DVLOG(1) << "Removing mapping for session_id=" << it->second.first - << " to group_id=" << group_id.ToString(); - auto it_app = application_capability_mapping_.find(it->second.first); - if (it_app != application_capability_mapping_.end()) { - application_capability_mapping_.erase(it_app); - } - auto it_group = group_info_mapping_.find(it->second.first); - if (it_group != group_info_mapping_.end()) { - group_info_mapping_.erase(it_group); - } - mapping_.erase(it); - } -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_session_id_map.h chromium-132.0.6834.159/chromecast/browser/cast_session_id_map.h --- chromium-132.0.6834.110/chromecast/browser/cast_session_id_map.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_session_id_map.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,109 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_SESSION_ID_MAP_H_ -#define CHROMECAST_BROWSER_CAST_SESSION_ID_MAP_H_ - -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/no_destructor.h" -#include "base/sequence_checker.h" -#include "base/task/sequenced_task_runner.h" -#include "base/unguessable_token.h" -#include "chromecast/media/audio/cast_audio_manager_helper.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace content { -class WebContents; -} // namespace content - -namespace chromecast { -namespace shell { - -class CastSessionIdMap : public media::CastAudioManagerHelper::Delegate { - public: - // Retrieve the map instance. The first time this is called, a task runner can - // be specified for the instance to run on. Any subsequent calls to this - // function will return the same map instance, but will not change the task - // runner. - // This must be called for the first time on the browser main thread. - static CastSessionIdMap* GetInstance( - base::SequencedTaskRunner* task_runner = nullptr); - - CastSessionIdMap(const CastSessionIdMap&) = delete; - CastSessionIdMap& operator=(const CastSessionIdMap&) = delete; - - // Map a session id to a particular group id in the provided WebContents. - // Record whether the session is an audio only session. - // Can be called on any thread. - void SetAppProperties(std::string session_id, - bool is_audio_app, - content::WebContents* web_contents); - // Record whether the session is launched in a group. - // Can be called on any thread. - void SetGroupInfo(std::string session_id, bool is_group); - - // CastAudioManagerHelper::Delegate implementation: - // Fetch the session id that is mapped to the provided group_id. Defaults to - // empty string if the mapping is not found. - // Must be called on the sequence for |task_runner_|. - std::string GetSessionId(const std::string& group_id) override; - // Fetch whether the session is an audio only session based on the provided - // session id. Defaults to false if the mapping is not found. - // Must be called on the sequence for |task_runner_|. - bool IsAudioOnlySession(const std::string& session_id) override; - // Fetch whether the session is launched in a group based on the provided - // session id. Defaults to false if the mapping is not found. - // Must be called on the sequence for |task_runner_|. - bool IsGroup(const std::string& session_id) override; - - // Async version of IsAudioOnlySession. It can be called from any thread. - using IsAudioOnlySessionAsyncCallback = base::OnceCallback; - void IsAudioOnlySessionAsync(const std::string& session_id, - IsAudioOnlySessionAsyncCallback callback); - - private: - class GroupObserver; - friend class base::NoDestructor; - - explicit CastSessionIdMap(base::SequencedTaskRunner* task_runner); - ~CastSessionIdMap() override; - - // Callback for the group being destroyed. - void OnGroupDestroyed(base::UnguessableToken group_id); - // Removes the mapping between group_id and session_id and release the - // GroupObserver. This must not be called in the group destructor callback, - // because it releases the GroupObserver who owns the destuctor callback. - void RemoveGroupId(base::UnguessableToken group_id); - // Maps the session id for the provided group id. - // Record whether the session is an audio only session. - // This call be called on any thread. - void SetAppPropertiesInternal(std::string session_id, - bool is_audio_app, - base::UnguessableToken group_id, - std::unique_ptr group_observer); - - base::flat_map< - std::string, - std::pair>> - mapping_; - - base::flat_map - application_capability_mapping_; - base::flat_map - group_info_mapping_; - base::SequencedTaskRunner* const task_runner_; - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_SESSION_ID_MAP_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_session_id_map_unittest.cc chromium-132.0.6834.159/chromecast/browser/cast_session_id_map_unittest.cc --- chromium-132.0.6834.110/chromecast/browser/cast_session_id_map_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_session_id_map_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,115 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_session_id_map.h" - -#include - -#include "base/run_loop.h" -#include "base/test/test_simple_task_runner.h" -#include "content/public/test/test_content_client_initializer.h" -#include "content/public/test/test_renderer_host.h" -#include "content/public/test/web_contents_tester.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gl/test/gl_surface_test_support.h" - -namespace { -const char kTestSessionId[] = "test_session_id"; -} // namespace - -namespace chromecast { -namespace shell { - -class CastSessionIdMapTest : public content::RenderViewHostTestHarness { - public: - CastSessionIdMapTest() : task_runner_(new base::TestSimpleTaskRunner) {} - - CastSessionIdMapTest(const CastSessionIdMapTest&) = delete; - CastSessionIdMapTest& operator=(const CastSessionIdMapTest&) = delete; - - void SetUp() override { - // Required for creating TestWebContents. - gl::GLSurfaceTestSupport::InitializeOneOff(); - initializer_ = std::make_unique(); - content::RenderViewHostTestHarness::SetUp(); - - // Create the map. - cast_session_id_map_ = CastSessionIdMap::GetInstance(task_runner_.get()); - } - - protected: - scoped_refptr task_runner_; - std::unique_ptr initializer_; - CastSessionIdMap* cast_session_id_map_; -}; - -TEST_F(CastSessionIdMapTest, DefaultsToEmptyString) { - std::string saved_session_id = cast_session_id_map_->GetSessionId(""); - EXPECT_EQ(saved_session_id, ""); -} - -TEST_F(CastSessionIdMapTest, CanRetrieveSessionId) { - auto web_contents = CreateTestWebContents(); - base::UnguessableToken group_id = web_contents->GetAudioGroupId(); - cast_session_id_map_->SetAppProperties( - kTestSessionId, false /* is_audio_app */, web_contents.get()); - task_runner_->RunUntilIdle(); - - std::string saved_session_id = - cast_session_id_map_->GetSessionId(group_id.ToString()); - EXPECT_EQ(saved_session_id, kTestSessionId); -} - -TEST_F(CastSessionIdMapTest, RemovesMappingOnWebContentsDestroyed) { - auto web_contents = CreateTestWebContents(); - base::UnguessableToken group_id = web_contents->GetAudioGroupId(); - cast_session_id_map_->SetAppProperties( - kTestSessionId, false /* is_audio_app */, web_contents.get()); - task_runner_->RunUntilIdle(); - - web_contents.reset(); - task_runner_->RunUntilIdle(); - - std::string saved_session_id = - cast_session_id_map_->GetSessionId(group_id.ToString()); - EXPECT_EQ(saved_session_id, ""); -} - -TEST_F(CastSessionIdMapTest, CanHoldMultiple) { - const std::string test_session_id_1 = "test_session_id_1"; - const std::string test_session_id_2 = "test_session_id_2"; - const std::string test_session_id_3 = "test_session_id_3"; - auto web_contents_1 = CreateTestWebContents(); - auto web_contents_2 = CreateTestWebContents(); - auto web_contents_3 = CreateTestWebContents(); - cast_session_id_map_->SetAppProperties( - test_session_id_1, false /* is_audio_app */, web_contents_1.get()); - cast_session_id_map_->SetAppProperties( - test_session_id_2, false /* is_audio_app */, web_contents_2.get()); - cast_session_id_map_->SetAppProperties( - test_session_id_3, false /* is_audio_app */, web_contents_3.get()); - task_runner_->RunUntilIdle(); - - std::string saved_session_id = ""; - base::UnguessableToken group_id = web_contents_1->GetAudioGroupId(); - if (group_id) { - saved_session_id = cast_session_id_map_->GetSessionId(group_id.ToString()); - EXPECT_EQ(saved_session_id, test_session_id_1); - } - - group_id = web_contents_2->GetAudioGroupId(); - if (group_id) { - saved_session_id = cast_session_id_map_->GetSessionId(group_id.ToString()); - EXPECT_EQ(saved_session_id, test_session_id_2); - } - - group_id = web_contents_3->GetAudioGroupId(); - if (group_id) { - saved_session_id = cast_session_id_map_->GetSessionId(group_id.ToString()); - EXPECT_EQ(saved_session_id, test_session_id_3); - } -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_system_memory_pressure_evaluator.cc chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator.cc --- chromium-132.0.6834.110/chromecast/browser/cast_system_memory_pressure_evaluator.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,196 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_system_memory_pressure_evaluator.h" - -#include - -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/process/process_metrics.h" -#include "base/strings/string_number_conversions.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" - -#define MAKE_SURE_THREAD(callback, ...) \ - if (!task_runner_->BelongsToCurrentThread()) { \ - task_runner_->PostTask( \ - FROM_HERE, \ - base::BindOnce(&CastSystemMemoryPressureEvaluator::callback, \ - weak_ptr_factory_.GetWeakPtr(), ##__VA_ARGS__)); \ - return; \ - } - -namespace chromecast { -namespace { - -// Memory thresholds (as fraction of total memory) for memory pressure levels. -// See more detailed description of pressure heuristic in PollPressureLevel. -// TODO(halliwell): tune thresholds based on data. -constexpr float kCriticalMemoryFraction = 0.25f; -constexpr float kModerateMemoryFraction = 0.4f; - -// Default Relaxed memory thresholds selectively applied to a few apps. -constexpr float kRelaxedCriticalMemoryFraction = 0.1f; -constexpr float kRelaxedModerateMemoryFraction = 0.2f; - -// Memory thresholds in MB for the simple heuristic based on 'free' memory. -constexpr int kCriticalFreeMemoryKB = 20 * 1024; -constexpr int kModerateFreeMemoryKB = 30 * 1024; - -constexpr int kPollingIntervalMS = 5000; - -int GetSystemReservedKb() { - int rtn_kb_ = 0; - const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess()); - base::StringToInt( - command_line->GetSwitchValueASCII(switches::kMemPressureSystemReservedKb), - &rtn_kb_); - DCHECK(rtn_kb_ >= 0); - return std::max(rtn_kb_, 0); -} - -} // namespace - -CastSystemMemoryPressureEvaluator::CastSystemMemoryPressureEvaluator( - std::unique_ptr voter) - : memory_pressure::SystemMemoryPressureEvaluator(std::move(voter)), - critical_memory_fraction_command_line_( - GetSwitchValueDouble(switches::kCastMemoryPressureCriticalFraction, - -1.0f)), - moderate_memory_fraction_command_line_( - GetSwitchValueDouble(switches::kCastMemoryPressureModerateFraction, - -1.0f)), - system_reserved_kb_(GetSystemReservedKb()), - task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()), - weak_ptr_factory_(this) { - relaxed_critical_memory_fraction_ = kRelaxedCriticalMemoryFraction; - relaxed_moderate_memory_fraction_ = kRelaxedModerateMemoryFraction; - critical_memory_fraction_ = critical_memory_fraction_command_line_; - moderate_memory_fraction_ = moderate_memory_fraction_command_line_; - // If the fractions from command line parameters are invalid they are subject - // to adjustment. - AdjustMemoryFractions(false); - PollPressureLevel(); -} - -CastSystemMemoryPressureEvaluator::~CastSystemMemoryPressureEvaluator() = - default; - -void CastSystemMemoryPressureEvaluator::PollPressureLevel() { - DCHECK(task_runner_->BelongsToCurrentThread()); - base::MemoryPressureListener::MemoryPressureLevel level = - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE; - - base::SystemMemoryInfoKB info; - if (!base::GetSystemMemoryInfo(&info)) { - LOG(ERROR) << "GetSystemMemoryInfo failed"; - } else if (system_reserved_kb_ != 0 || info.available != 0) { - // Preferred memory pressure heuristic: - // 1. Use /proc/meminfo's MemAvailable if possible, fall back to estimate - // of free + buffers + cached otherwise. - const int total_available = (info.available != 0) - ? info.available - : (info.free + info.buffers + info.cached); - - // 2. Allow some memory to be 'reserved' on command line. - const int available = total_available - system_reserved_kb_; - const int total = info.total - system_reserved_kb_; - DCHECK_GT(total, 0); - const float ratio = available / static_cast(total); - - if (ratio < critical_memory_fraction_) - level = base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL; - else if (ratio < moderate_memory_fraction_) - level = base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE; - } else { - // Backup method purely using 'free' memory. It may generate more - // pressure events than necessary, since more memory may actually be free. - if (info.free < kCriticalFreeMemoryKB) - level = base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL; - else if (info.free < kModerateFreeMemoryKB) - level = base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE; - } - - UpdateMemoryPressureLevel(level); - - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce(&CastSystemMemoryPressureEvaluator::PollPressureLevel, - weak_ptr_factory_.GetWeakPtr()), - base::Milliseconds(kPollingIntervalMS)); -} - -void CastSystemMemoryPressureEvaluator::UpdateMemoryPressureLevel( - base::MemoryPressureListener::MemoryPressureLevel new_level) { - DCHECK(task_runner_->BelongsToCurrentThread()); - auto old_vote = current_vote(); - SetCurrentVote(new_level); - - SendCurrentVote(/* notify = */ current_vote() != - base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE); - - if (old_vote == current_vote()) - return; - - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEventWithValue( - "Memory.Pressure.LevelChange", new_level); -} - -void CastSystemMemoryPressureEvaluator::AdjustMemoryFractions(bool relax) { - DCHECK(task_runner_->BelongsToCurrentThread()); - - if (critical_memory_fraction_command_line_ < 0) { - critical_memory_fraction_ = - relax ? relaxed_critical_memory_fraction_ : kCriticalMemoryFraction; - } - if (moderate_memory_fraction_command_line_ < 0) { - moderate_memory_fraction_ = - relax ? relaxed_moderate_memory_fraction_ : kModerateMemoryFraction; - } - LOG(INFO) << __func__ - << ": critical_memory_fraction_=" << critical_memory_fraction_ - << ", moderate_memory_fraction_=" << moderate_memory_fraction_; -} - -void CastSystemMemoryPressureEvaluator::ConfigRelaxMemoryPressureThresholds( - float relaxed_critical_memory_fraction, - float relaxed_moderate_memory_fraction) { - MAKE_SURE_THREAD(ConfigRelaxMemoryPressureThresholds, - relaxed_critical_memory_fraction, - relaxed_moderate_memory_fraction); - - LOG(INFO) << __func__ << ", " << relaxed_critical_memory_fraction << ", " - << relaxed_moderate_memory_fraction; - - if (relaxed_critical_memory_fraction > 0) { - relaxed_critical_memory_fraction_ = relaxed_critical_memory_fraction; - } - if (relaxed_moderate_memory_fraction > 0) { - relaxed_moderate_memory_fraction_ = relaxed_moderate_memory_fraction; - } -} - -void CastSystemMemoryPressureEvaluator::RelaxMemoryPressureThresholds( - std::string requesting_app_session_id) { - MAKE_SURE_THREAD(RelaxMemoryPressureThresholds, - std::move(requesting_app_session_id)); - apps_needing_relaxed_memory_pressure_thresholds_.insert( - std::move(requesting_app_session_id)); - AdjustMemoryFractions(true); -} -void CastSystemMemoryPressureEvaluator::RestoreMemoryPressureThresholds( - const std::string& requesting_app_session_id) { - MAKE_SURE_THREAD(RestoreMemoryPressureThresholds, requesting_app_session_id); - apps_needing_relaxed_memory_pressure_thresholds_.erase( - requesting_app_session_id); - if (apps_needing_relaxed_memory_pressure_thresholds_.empty()) { - AdjustMemoryFractions(false); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_system_memory_pressure_evaluator.h chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator.h --- chromium-132.0.6834.110/chromecast/browser/cast_system_memory_pressure_evaluator.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_SYSTEM_MEMORY_PRESSURE_EVALUATOR_H_ -#define CHROMECAST_BROWSER_CAST_SYSTEM_MEMORY_PRESSURE_EVALUATOR_H_ - -#include - -#include "base/containers/flat_set.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.h" -#include "components/memory_pressure/system_memory_pressure_evaluator.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { - -// Memory pressure evaluator for Cast: polls for current memory -// usage periodically and sends memory pressure notifications. -class CastSystemMemoryPressureEvaluator - : public memory_pressure::SystemMemoryPressureEvaluator, - public CastSystemMemoryPressureEvaluatorAdjuster { - public: - explicit CastSystemMemoryPressureEvaluator( - std::unique_ptr voter); - - CastSystemMemoryPressureEvaluator(const CastSystemMemoryPressureEvaluator&) = - delete; - CastSystemMemoryPressureEvaluator& operator=( - const CastSystemMemoryPressureEvaluator&) = delete; - - ~CastSystemMemoryPressureEvaluator() override; - - // CastSystemMemoryPressureEvaluatorAdjuster implementation: - void ConfigRelaxMemoryPressureThresholds( - float relaxed_critical_memory_fraction, - float relaxed_moderate_memory_fraction) override; - void RelaxMemoryPressureThresholds( - std::string requesting_app_session_id) override; - void RestoreMemoryPressureThresholds( - const std::string& requesting_app_session_id) override; - - private: - void PollPressureLevel(); - void UpdateMemoryPressureLevel( - base::MemoryPressureListener::MemoryPressureLevel new_level); - void AdjustMemoryFractions(bool relax); - - // Fractions in effect. - float critical_memory_fraction_; - float moderate_memory_fraction_; - - // Fractions when the thrsholds are relaxed. - float relaxed_critical_memory_fraction_; - float relaxed_moderate_memory_fraction_; - - // When negative, no valid critical/moderate memory fraction present - // in command line parameters. - float const critical_memory_fraction_command_line_; - float const moderate_memory_fraction_command_line_; - - base::flat_set apps_needing_relaxed_memory_pressure_thresholds_; - - const int system_reserved_kb_; - scoped_refptr task_runner_; - base::WeakPtrFactory weak_ptr_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_SYSTEM_MEMORY_PRESSURE_EVALUATOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.cc chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.cc --- chromium-132.0.6834.110/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.h" - -namespace chromecast { - -void CastSystemMemoryPressureEvaluatorAdjuster:: - ConfigRelaxMemoryPressureThresholds( - float relaxed_critical_memory_fraction, - float relaxed_moderate_memory_fraction) {} - -void CastSystemMemoryPressureEvaluatorAdjuster::RelaxMemoryPressureThresholds( - std::string requesting_app_session_id) {} - -void CastSystemMemoryPressureEvaluatorAdjuster::RestoreMemoryPressureThresholds( - const std::string& requesting_app_session_id) {} - -} // namespace chromecast \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.h chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.h --- chromium-132.0.6834.110/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_system_memory_pressure_evaluator_adjuster.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_SYSTEM_MEMORY_PRESSURE_EVALUATOR_ADJUSTER_H_ -#define CHROMECAST_BROWSER_CAST_SYSTEM_MEMORY_PRESSURE_EVALUATOR_ADJUSTER_H_ - -#include - -namespace chromecast { -class CastSystemMemoryPressureEvaluatorAdjuster { - public: - CastSystemMemoryPressureEvaluatorAdjuster() = default; - virtual ~CastSystemMemoryPressureEvaluatorAdjuster() = default; - - // The three functions below can be called from any thread. - // Negative fractions are invalid. - virtual void ConfigRelaxMemoryPressureThresholds( - float relaxed_critical_memory_fraction, - float relaxed_moderate_memory_fraction); - virtual void RelaxMemoryPressureThresholds( - std::string requesting_app_session_id); - virtual void RestoreMemoryPressureThresholds( - const std::string& requesting_app_session_id); -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_SYSTEM_MEMORY_PRESSURE_EVALUATOR_ADJUSTER_H_ \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_touch_device_manager.cc chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager.cc --- chromium-132.0.6834.110/chromecast/browser/cast_touch_device_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_touch_device_manager.h" - -#include "chromecast/graphics/cast_screen.h" -#include "ui/events/devices/device_data_manager.h" -#include "ui/events/devices/touchscreen_device.h" -#include "ui/gfx/geometry/rect_f.h" -#include "ui/gfx/geometry/size_f.h" - -namespace chromecast { -namespace shell { -namespace { - -ui::TouchDeviceTransform GetDeviceTransform( - const ui::TouchscreenDevice& touchscreen, - int64_t display_id, - display::Display::Rotation rotation, - const gfx::Rect& native_bounds_in_pixel) { - gfx::SizeF touchscreen_size = gfx::SizeF(touchscreen.size); - - ui::TouchDeviceTransform touch_device_transform; - touch_device_transform.display_id = display_id; - touch_device_transform.device_id = touchscreen.id; - touch_device_transform.transform.Translate(native_bounds_in_pixel.x(), - native_bounds_in_pixel.y()); - - touch_device_transform.transform.Scale( - native_bounds_in_pixel.width() / touchscreen_size.width(), - native_bounds_in_pixel.height() / touchscreen_size.height()); - - return touch_device_transform; -} - -} // namespace - -CastTouchDeviceManager::CastTouchDeviceManager() { - ui::DeviceDataManager::GetInstance()->AddObserver(this); -} - -CastTouchDeviceManager::~CastTouchDeviceManager() { - ui::DeviceDataManager::GetInstance()->RemoveObserver(this); -} - -void CastTouchDeviceManager::OnInputDeviceConfigurationChanged( - uint8_t input_device_types) { - if (input_device_types & ui::InputDeviceEventObserver::kTouchscreen) { - UpdateTouchscreenConfiguration(); - } -} - -void CastTouchDeviceManager::OnDisplayConfigured( - int64_t display_id, - display::Display::Rotation rotation, - const gfx::Rect& native_bounds_in_pixel) { - display_id_ = display_id; - display_rotation_ = rotation; - native_display_bounds_in_pixel_ = native_bounds_in_pixel; - UpdateTouchscreenConfiguration(); -} - -void CastTouchDeviceManager::UpdateTouchscreenConfiguration() { - const std::vector& touchscreen_devices = - ui::DeviceDataManager::GetInstance()->GetTouchscreenDevices(); - if (native_display_bounds_in_pixel_ == gfx::Rect()) - return; // Waiting for display configuration. - std::vector touch_device_transforms; - - // All touchscreens are mapped onto primary display. - for (const auto& touchscreen : touchscreen_devices) { - touch_device_transforms.push_back( - GetDeviceTransform(touchscreen, display_id_, display_rotation_, - native_display_bounds_in_pixel_)); - } - - ui::DeviceDataManager::GetInstance()->ConfigureTouchDevices( - touch_device_transforms); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_touch_device_manager.h chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager.h --- chromium-132.0.6834.110/chromecast/browser/cast_touch_device_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_TOUCH_DEVICE_MANAGER_H_ -#define CHROMECAST_BROWSER_CAST_TOUCH_DEVICE_MANAGER_H_ - -#include - -#include "ui/display/display.h" -#include "ui/events/devices/input_device_event_observer.h" -#include "ui/gfx/geometry/rect.h" - -namespace chromecast { -namespace shell { - -// Manages touchscreen->display mapping for cast browser. -class CastTouchDeviceManager : public ui::InputDeviceEventObserver { - public: - explicit CastTouchDeviceManager(); - - CastTouchDeviceManager(const CastTouchDeviceManager&) = delete; - CastTouchDeviceManager& operator=(const CastTouchDeviceManager&) = delete; - - ~CastTouchDeviceManager() override; - - // ui::InputDeviceEventObserver: - void OnInputDeviceConfigurationChanged(uint8_t input_device_types) override; - - void OnDisplayConfigured(int64_t display_id, - display::Display::Rotation rotation, - const gfx::Rect& native_bounds_in_pixel); - - private: - void UpdateTouchscreenConfiguration(); - - int64_t display_id_; - display::Display::Rotation display_rotation_; - gfx::Rect native_display_bounds_in_pixel_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_TOUCH_DEVICE_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_touch_device_manager_unittest.cc chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager_unittest.cc --- chromium-132.0.6834.110/chromecast/browser/cast_touch_device_manager_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_touch_device_manager_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,128 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_touch_device_manager.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/events/devices/device_data_manager.h" -#include "ui/events/devices/device_hotplug_event_observer.h" -#include "ui/gfx/geometry/rect.h" - -namespace { - -constexpr int64_t kDisplayId = 1; -constexpr int kTouchDeviceId = 100; - -} // namespace - -class CastTouchDeviceManagerTest : public testing::Test { - public: - CastTouchDeviceManagerTest() {} - - void SetUp() override { - ui::DeviceDataManager::CreateInstance(); - touch_device_manager_ = - std::make_unique(); - } - - void TearDown() override { - touch_device_manager_.reset(); - ui::DeviceDataManager::DeleteInstance(); - } - - ui::DeviceHotplugEventObserver* GetHotplugObserver() { - return ui::DeviceDataManager::GetInstance(); - } - - protected: - std::unique_ptr - touch_device_manager_; -}; - -TEST_F(CastTouchDeviceManagerTest, CheckOneToOneMapping) { - std::vector touchscreens; - const gfx::Size display_size = gfx::Size(1280, 720); - touch_device_manager_->OnDisplayConfigured( - kDisplayId, display::Display::ROTATE_0, gfx::Rect(display_size)); - touchscreens.push_back(ui::TouchscreenDevice(kTouchDeviceId, - ui::INPUT_DEVICE_INTERNAL, - "Touchscreen", display_size, 1)); - GetHotplugObserver()->OnTouchscreenDevicesUpdated(touchscreens); - - // 1:1 mapping for touch coordinates to display coordinates. - { - float x = display_size.width(), y = display_size.height(); - ui::DeviceDataManager::GetInstance()->ApplyTouchTransformer(kTouchDeviceId, - &x, &y); - EXPECT_EQ(display_size.width(), x); - EXPECT_EQ(display_size.height(), y); - } - - { - float x = display_size.width(), y = 0; - ui::DeviceDataManager::GetInstance()->ApplyTouchTransformer(kTouchDeviceId, - &x, &y); - EXPECT_EQ(display_size.width(), x); - EXPECT_EQ(0, y); - } - - { - float x = 0, y = display_size.height(); - ui::DeviceDataManager::GetInstance()->ApplyTouchTransformer(kTouchDeviceId, - &x, &y); - EXPECT_EQ(0, x); - EXPECT_EQ(display_size.height(), y); - } - - { - float x = display_size.width() / 2, y = display_size.height() / 2; - ui::DeviceDataManager::GetInstance()->ApplyTouchTransformer(1, &x, &y); - EXPECT_EQ(display_size.width() / 2, x); - EXPECT_EQ(display_size.height() / 2, y); - } -} - -TEST_F(CastTouchDeviceManagerTest, CheckMappingWithLargerTouchscreen) { - std::vector touchscreens; - const gfx::Size display_size = gfx::Size(1280, 720); - touch_device_manager_->OnDisplayConfigured( - kDisplayId, display::Display::ROTATE_0, gfx::Rect(display_size)); - touchscreens.push_back(ui::TouchscreenDevice( - kTouchDeviceId, ui::INPUT_DEVICE_INTERNAL, "Touchscreen", - gfx::ScaleToRoundedSize(display_size, 2, 2), 1)); - GetHotplugObserver()->OnTouchscreenDevicesUpdated(touchscreens); - - // Touch screen is twice the size, so transformed events will be half the - // reported value. - { - float x = display_size.width(), y = display_size.height(); - ui::DeviceDataManager::GetInstance()->ApplyTouchTransformer(kTouchDeviceId, - &x, &y); - EXPECT_EQ(display_size.width() / 2, x); - EXPECT_EQ(display_size.height() / 2, y); - } - - { - float x = display_size.width(), y = 0; - ui::DeviceDataManager::GetInstance()->ApplyTouchTransformer(kTouchDeviceId, - &x, &y); - EXPECT_EQ(display_size.width() / 2, x); - EXPECT_EQ(0, y); - } - - { - float x = 0, y = display_size.height(); - ui::DeviceDataManager::GetInstance()->ApplyTouchTransformer(kTouchDeviceId, - &x, &y); - EXPECT_EQ(0, x); - EXPECT_EQ(display_size.height() / 2, y); - } - - { - float x = display_size.width() / 2, y = display_size.height() / 2; - ui::DeviceDataManager::GetInstance()->ApplyTouchTransformer(kTouchDeviceId, - &x, &y); - EXPECT_EQ(display_size.width() / 4, x); - EXPECT_EQ(display_size.height() / 4, y); - } -} diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_web_contents.cc chromium-132.0.6834.159/chromecast/browser/cast_web_contents.cc --- chromium-132.0.6834.110/chromecast/browser/cast_web_contents.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_web_contents.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/cast_web_contents.h" - -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" - -namespace chromecast { - -CastWebContents::CastWebContents() = default; - -CastWebContents::~CastWebContents() = default; - -void CastWebContents::BindOwnerReceiver( - mojo::PendingReceiver receiver) { - DCHECK(!owner_receiver_.is_bound()); - owner_receiver_.Bind(std::move(receiver)); - owner_receiver_.set_disconnect_handler( - base::BindOnce(&CastWebContents::OnDisconnect, base::Unretained(this))); -} - -void CastWebContents::BindSharedReceiver( - mojo::PendingReceiver receiver) { - shared_receivers_.Add(this, std::move(receiver)); -} - -void CastWebContents::AddObserver( - mojo::PendingRemote observer) { - observers_.Add(std::move(observer)); -} - -void CastWebContents::AddObserver(CastWebContents::Observer* observer) { - DCHECK(observer); - sync_observers_.AddObserver(observer); -} - -void CastWebContents::RemoveObserver(CastWebContents::Observer* observer) { - DCHECK(observer); - sync_observers_.RemoveObserver(observer); -} - -void CastWebContents::SetDisconnectCallback(base::OnceClosure cb) { - disconnect_cb_ = std::move(cb); -} - -void CastWebContents::OnDisconnect() { - if (disconnect_cb_) { - std::move(disconnect_cb_).Run(); - } -} - -CastWebContents::Observer::Observer() : cast_web_contents_(nullptr) {} - -CastWebContents::Observer::~Observer() { - Observe(nullptr); -} - -void CastWebContents::Observer::Observe(CastWebContents* cast_web_contents) { - if (cast_web_contents == cast_web_contents_) { - // Early exit to avoid infinite loops if we're in the middle of a callback. - return; - } - if (cast_web_contents_) { - cast_web_contents_->RemoveObserver(this); - } - cast_web_contents_ = cast_web_contents; - if (cast_web_contents_) { - cast_web_contents_->AddObserver(this); - } -} - -void CastWebContents::Observer::ResetCastWebContents() { - cast_web_contents_ = nullptr; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_web_contents.h chromium-132.0.6834.159/chromecast/browser/cast_web_contents.h --- chromium-132.0.6834.110/chromecast/browser/cast_web_contents.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_web_contents.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,321 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_ -#define CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_ - -#include -#include -#include -#include - -#include "base/containers/flat_set.h" -#include "base/functional/callback_forward.h" -#include "base/observer_list.h" -#include "base/observer_list_types.h" -#include "base/process/process.h" -#include "chromecast/bindings/public/mojom/api_bindings.mojom.h" -#include "chromecast/browser/cast_web_contents_observer.h" -#include "chromecast/browser/mojom/cast_web_contents.mojom.h" -#include "chromecast/browser/web_types.h" -#include "chromecast/common/mojom/feature_manager.mojom.h" -#include "chromecast/mojo/interface_bundle.h" -#include "content/public/common/media_playback_renderer_type.mojom.h" -#include "mojo/public/cpp/bindings/generic_pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "mojo/public/cpp/bindings/remote_set.h" -#include "services/service_manager/public/cpp/interface_provider.h" -#include "third_party/blink/public/common/messaging/web_message_port.h" -#include "ui/gfx/geometry/rect.h" -#include "url/gurl.h" - -namespace content { -class NavigationHandle; -class WebContents; -} // namespace content - -namespace media_control { -class MediaBlocker; -} // namespace media_control - -namespace chromecast { - -struct RendererFeature { - const std::string name; - base::Value value; -}; - -// Simplified WebContents wrapper class for Cast platforms. -// -// Proper usage of content::WebContents relies on understanding the meaning -// behind various WebContentsObserver methods, and then translating those -// signals into some concrete state. CastWebContents does *not* own the -// underlying WebContents (usually whatever class implements -// content::WebContentsDelegate is the actual owner). -// -// ============================================================================= -// Lifetime -// ============================================================================= -// CastWebContents *must* be created before WebContents begins loading any -// content. Once content begins loading (via CWC::LoadUrl() or one of the -// WebContents navigation APIs), CastWebContents will calculate its state based -// on the status of the WebContents' *main* RenderFrame. Events from sub-frames -// (e.g. iframes) are ignored, since we expect the web app to take care of -// sub-frame errors. -// -// We consider the CastWebContents to be in a LOADED state when the content of -// the main frame is fully loaded and running (all resources fetched, -// redirection finished, JS is running). Iframes might still be loading in this -// case, but in general we consider the page to be in a presentable state at -// this stage, so it is appropriate to display the WebContents to the user. -// -// During or after the page is loaded, there are multiple error conditions that -// can occur. The following events will cause the page to enter an ERROR state: -// -// 1. If the main frame is served an HTTP error page (such as a 404 page), then -// it means the desired content wasn't loaded. -// -// 2. If the main frame fails to load, such as when the browser blocked the URL -// request, we treat this as an error. -// -// 3. The RenderProcess for the main frame could crash, so the page is not in a -// usable state. -// -// The CastWebContents user can respond to these errors in a few ways: The -// content can be reloaded, or the entire page activity can be cancelled. If we -// totally cancel the activity, we prefer to notify the user with an error -// screen or visible/audible error message. Otherwise, a silent retry is -// preferred. -// -// CastWebContents can be used to close the underlying WebContents gracefully -// via CWC::Close(). This initiates web page tear-down logic so that the web -// app has a chance to perform its own finalization logic in JS. Next, we call -// WebContents::ClosePage(), which defers the page closure logic to the -// content::WebContentsDelegate. Usually, it will run its own finalization -// logic and then destroy the WebContents. CastWebContents will be notified of -// the WebContents destruction and enter the DESTROYED state. In the event -// the page isn't destroyed, the page will enter the CLOSED state automatically -// after a timeout. CastWebContents users should not try to reload the page, as -// page closure is intentional. -// -// The web app may decide to close itself (such as via "window.close()" in JS). -// This is similar to initiating the close flow via CWC::Close(), with the end -// result being the same. We consider this an intentional closure, and should -// not attempt to reload the page. -// -// Once CastWebContents is in the DESTROYED state, it is not really usable -// anymore; most of the methods will simply no-op, and no more observer signals -// will be emitted. -// -// CastWebContents can be deleted at any time, *except* during Observer -// notifications. If the owner wants to destroy CastWebContents as a result of -// an Observer event, it should post a task to destroy CastWebContents. -class CastWebContents : public mojom::CastWebContents { - public: - // Synchronous in-process observer for CastWebContents. Observers must not - // destroy CastWebContents in any of the methods below. - class Observer : public base::CheckedObserver { - public: - Observer(); - - // Adds |this| to the CastWebContents observer list. Observe(nullptr) will - // remove |this| from the observer list of the current CastWebContents being - // observed. - void Observe(CastWebContents* cast_web_contents); - - // Called when the navigation is ready to be committed in the WebContents' - // main frame. - virtual void MainFrameReadyToCommitNavigation( - content::NavigationHandle* navigation_handle) {} - - // Notify that an inner WebContents was created. |inner_contents| is created - // in a default-initialized state with no delegate, and can be safely - // initialized by the delegate. - virtual void InnerContentsCreated(CastWebContents* inner_contents, - CastWebContents* outer_contents) {} - - // Notify the page state changed. - virtual void PageStateChanged(PageState page_state) {} - - // Notify the page stopped. - virtual void PageStopped(PageState page_state, int32_t error_code) {} - - // Notify media playback state changes for the underlying WebContents. - virtual void MediaPlaybackChanged(bool media_playing) {} - - // Sets |cast_web_contents_| to |nullptr| but does not remove the Observer - // from the ObserverList. Called for each Observer during CastWebContents - // destruction; we don't use Observe(nullptr) since it would mutate the - // ObserverList during iteration. - void ResetCastWebContents(); - - protected: - ~Observer() override; - - CastWebContents* cast_web_contents_; - }; - - static std::vector& GetAll(); - - // Returns the CastWebContents that wraps the content::WebContents, or nullptr - // if the CastWebContents does not exist. - static CastWebContents* FromWebContents(content::WebContents* web_contents); - - CastWebContents(); - - CastWebContents(const CastWebContents&) = delete; - CastWebContents& operator=(const CastWebContents&) = delete; - - ~CastWebContents() override; - - // Tab identifier for the WebContents, mainly used by the tabs extension API. - // Tab IDs may be re-used, but no two live CastWebContents should have the - // same tab ID at any given time. - virtual int tab_id() const = 0; - - // An identifier for the WebContents, mainly used by platform views service. - // IDs may be re-used but are unique among all live CastWebContents. - virtual int id() const = 0; - - // TODO(seantopping): Hide this, clients shouldn't use WebContents directly. - virtual content::WebContents* web_contents() const = 0; - virtual PageState page_state() const = 0; - virtual const media_control::MediaBlocker* media_blocker() const = 0; - - // mojom::CastWebContents implementation: - void SetAppProperties(const std::string& app_id, - const std::string& session_id, - bool is_audio_app, - const GURL& app_web_url, - bool enforce_feature_permissions, - const std::vector& feature_permissions, - const std::vector& - additional_feature_permission_origins) override = 0; - void SetGroupInfo(const std::string& session_id, - bool is_multizone_launch) override = 0; - void AddRendererFeatures(base::Value::Dict features) override = 0; - void SetInterfacesForRenderer(mojo::PendingRemote - remote_interfaces) override = 0; - void LoadUrl(const GURL& url) override = 0; - void ClosePage() override = 0; - void SetWebVisibilityAndPaint(bool visible) override = 0; - void BlockMediaLoading(bool blocked) override = 0; - void BlockMediaStarting(bool blocked) override = 0; - void EnableBackgroundVideoPlayback(bool enabled) override = 0; - void ConnectToBindingsService( - mojo::PendingRemote api_bindings_remote) override = 0; - void SetEnabledForRemoteDebugging(bool enabled) override = 0; - void AddObserver( - mojo::PendingRemote observer) override; - void GetMainFramePid(GetMainFramePidCallback cb) override = 0; - - // =========================================================================== - // Page Lifetime - // =========================================================================== - - // Stop the page immediately. This will automatically invoke - // Delegate::OnPageStopped(error_code), allowing the delegate to delete or - // reload the page without waiting for the WebContents owner to tear down the - // page. - virtual void Stop(int error_code) = 0; - - // =========================================================================== - // Page Communication - // =========================================================================== - - // Executes a UTF-8 encoded |script| for every subsequent page load where - // the frame's URL has an origin reflected in |origins|. The script is - // executed early, prior to the execution of the document's scripts. - // - // Scripts are identified by a client-managed |id|. Any - // script previously injected using the same |id| will be replaced. - // - // The order in which multiple bindings are executed is the same as the - // order in which the bindings were added. If a script is added which - // clobbers an existing script of the same |id|, the previous script's - // precedence in the injection order will be preserved. - // |script| and |id| must be non-empty string. - virtual void AddBeforeLoadJavaScript(uint64_t id, - std::string_view script) = 0; - - // Posts a message to the frame's onMessage handler. - // - // `target_origin` restricts message delivery to the specified origin. - // If `target_origin` is "*", then the message will be sent to the - // document regardless of its origin. - // See html.spec.whatwg.org/multipage/web-messaging.html sect. 9.4.3 - // for more details on how the target origin policy is applied. - // Should be called on UI thread. - virtual void PostMessageToMainFrame( - const std::string& target_origin, - const std::string& data, - std::vector ports) = 0; - - // Executes a string of JavaScript in the main frame's context. - // This is no-op if the main frame is not available. - // Pass in a callback to receive a result when it is available. - // If there is no need to receive the result, pass in a - // default-constructed callback. If provided, the callback - // will be invoked on the UI thread. - virtual void ExecuteJavaScript( - const std::u16string& javascript, - base::OnceCallback callback) = 0; - - // =========================================================================== - // Utility Methods - // =========================================================================== - - // Asks the CastWebContents to bind an interface receiver using either its - // registry or any registered InterfaceProvider. - virtual bool TryBindReceiver(mojo::GenericPendingReceiver& receiver) = 0; - - // Locally-registered interfaces which are exposed to render frames. - virtual InterfaceBundle* local_interfaces() = 0; - - // Returns true if WebSQL database is configured enabled for this - // CastWebContents. - virtual bool is_websql_enabled() = 0; - - // Returns true if mixer audio is enabled. - virtual bool is_mixer_audio_enabled() = 0; - - // Binds an owning receiver for remote control of CastWebContents. When the - // CastWebContents is managed by CastWebService, its lifetime is scoped to the - // duration of the connection. Only one owner can be bound at a time. - void BindOwnerReceiver( - mojo::PendingReceiver receiver); - - // Binds a non-owning receiver for CastWebContents. This can be called by - // multiple clients. - void BindSharedReceiver( - mojo::PendingReceiver receiver); - - // |cb| is called when |receiver_| is disconnected. This allows the web - // service to destroy CastWebContents which are owned via a remote handle. - void SetDisconnectCallback(base::OnceClosure cb); - - protected: - mojo::Receiver owner_receiver_{this}; - mojo::ReceiverSet shared_receivers_; - mojo::RemoteSet observers_; - base::ObserverList sync_observers_; - - private: - friend class Observer; - - // These functions should only be invoked by CastWebContents::Observer in a - // valid sequence, enforced via SequenceChecker. - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - void OnDisconnect(); - - base::OnceClosure disconnect_cb_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/cast_web_contents_browsertest.cc chromium-132.0.6834.159/chromecast/browser/cast_web_contents_browsertest.cc --- chromium-132.0.6834.110/chromecast/browser/cast_web_contents_browsertest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/cast_web_contents_browsertest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,1177 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_CAST_WEB_CONTENTS_BROWSERTEST_H_ -#define CHROMECAST_BROWSER_CAST_WEB_CONTENTS_BROWSERTEST_H_ - -#include -#include - -#include "base/check_op.h" -#include "base/command_line.h" -#include "base/containers/flat_set.h" -#include "base/files/file_util.h" -#include "base/functional/callback_helpers.h" -#include "base/path_service.h" -#include "base/ranges/algorithm.h" -#include "base/run_loop.h" -#include "base/strings/strcat.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/bind.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/browser/cast_browser_context.h" -#include "chromecast/browser/cast_browser_process.h" -#include "chromecast/browser/cast_web_contents_impl.h" -#include "chromecast/browser/cast_web_contents_observer.h" -#include "chromecast/browser/mojom/cast_web_service.mojom.h" -#include "chromecast/browser/test/cast_browser_test.h" -#include "chromecast/browser/test_interfaces.test-mojom.h" -#include "chromecast/mojo/interface_bundle.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_delegate.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/common/content_switches.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "content/public/test/url_loader_interceptor.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "net/http/http_status_code.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" -#include "services/service_manager/public/cpp/interface_provider.h" -#include "services/service_manager/public/mojom/interface_provider.mojom.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -using ::testing::_; -using ::testing::AllOf; -using ::testing::AtLeast; -using ::testing::ElementsAre; -using ::testing::Eq; -using ::testing::Expectation; -using ::testing::InSequence; -using ::testing::Invoke; -using ::testing::InvokeWithoutArgs; -using ::testing::Mock; -using ::testing::NiceMock; -using ::testing::Property; -using ::testing::WithArgs; - -namespace content { -class WebContents; -} - -namespace chromecast { - -namespace { - -const base::FilePath::CharType kTestDataPath[] = - FILE_PATH_LITERAL("chromecast/browser/test/data"); - -base::FilePath GetTestDataPath() { - return base::FilePath(kTestDataPath); -} - -base::FilePath GetTestDataFilePath(const std::string& name) { - base::FilePath file_path; - CHECK(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &file_path)); - return file_path.Append(GetTestDataPath()).AppendASCII(name); -} - -std::unique_ptr DefaultHandler( - net::HttpStatusCode status_code, - const net::test_server::HttpRequest& request) { - auto http_response = std::make_unique(); - http_response->set_code(status_code); - return http_response; -} - -// ============================================================================= -// Mocks -// ============================================================================= -class MockCastWebContentsObserver : public CastWebContentsObserver { - public: - MockCastWebContentsObserver() {} - - MockCastWebContentsObserver(const MockCastWebContentsObserver&) = delete; - MockCastWebContentsObserver& operator=(const MockCastWebContentsObserver&) = - delete; - - ~MockCastWebContentsObserver() override = default; - - MOCK_METHOD1(PageStateChanged, void(PageState page_state)); - MOCK_METHOD2(PageStopped, void(PageState page_state, int error_code)); - MOCK_METHOD2(RenderFrameCreated, - void(int render_process_id, int render_frame_id)); - MOCK_METHOD0(ResourceLoadFailed, void()); - MOCK_METHOD1(UpdateTitle, void(const std::string& title)); -}; - -class MockWebContentsDelegate : public content::WebContentsDelegate { - public: - MockWebContentsDelegate() = default; - ~MockWebContentsDelegate() override = default; - - MOCK_METHOD1(CloseContents, void(content::WebContents* source)); -}; - -class TitleChangeObserver : public CastWebContentsObserver { - public: - TitleChangeObserver() = default; - - TitleChangeObserver(const TitleChangeObserver&) = delete; - TitleChangeObserver& operator=(const TitleChangeObserver&) = delete; - - ~TitleChangeObserver() override = default; - - // Spins a Runloop until the title of the page matches the |expected_title| - // that have been set. - void RunUntilTitleEquals(const std::string& expected_title) { - expected_title_ = expected_title; - // Spin the runloop until the expected conditions are met. - if (current_title_ != expected_title_) { - expected_title_ = expected_title; - base::RunLoop run_loop; - quit_closure_ = run_loop.QuitClosure(); - run_loop.Run(); - } - } - - // CastWebContentsObserver implementation: - void UpdateTitle(const std::string& title) override { - // Resumes execution of RunUntilTitleEquals() if |title| matches - // expectations. - current_title_ = title; - if (!quit_closure_.is_null() && current_title_ == expected_title_) { - DCHECK_EQ(current_title_, expected_title_); - std::move(quit_closure_).Run(); - } - } - - private: - std::string current_title_; - std::string expected_title_; - - base::OnceClosure quit_closure_; -}; - -class TestMessageReceiver : public blink::WebMessagePort::MessageReceiver { - public: - TestMessageReceiver() = default; - - TestMessageReceiver(const TestMessageReceiver&) = delete; - TestMessageReceiver& operator=(const TestMessageReceiver&) = delete; - - ~TestMessageReceiver() override = default; - - void WaitForNextIncomingMessage( - base::OnceCallback)> callback) { - DCHECK(message_received_callback_.is_null()) - << "Only one waiting event is allowed."; - message_received_callback_ = std::move(callback); - } - - void SetOnPipeErrorCallback(base::OnceCallback callback) { - on_pipe_error_callback_ = std::move(callback); - } - - private: - bool OnMessage(blink::WebMessagePort::Message message) override { - std::string message_text; - if (!base::UTF16ToUTF8(message.data.data(), message.data.size(), - &message_text)) { - return false; - } - - std::optional incoming_port = std::nullopt; - // Only one MessagePort should be sent to here. - if (!message.ports.empty()) { - DCHECK(message.ports.size() == 1) - << "Only one control port can be provided"; - incoming_port = std::make_optional( - std::move(message.ports[0])); - } - - if (message_received_callback_) { - std::move(message_received_callback_) - .Run(message_text, std::move(incoming_port)); - } - return true; - } - - void OnPipeError() override { - if (on_pipe_error_callback_) { - std::move(on_pipe_error_callback_).Run(); - } - } - - base::OnceCallback incoming_port)> - message_received_callback_; - - base::OnceCallback on_pipe_error_callback_; -}; - -} // namespace - -// ============================================================================= -// Test class -// ============================================================================= -class CastWebContentsBrowserTest : public shell::CastBrowserTest, - public content::WebContentsObserver { - protected: - void SetUpCommandLine(base::CommandLine* command_line) override { - CastBrowserTest::SetUpCommandLine(command_line); - command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, "MojoJS"); - } - - void PreRunTestOnMainThread() override { - // Pump startup related events. - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::RunLoop().RunUntilIdle(); - - metrics::CastMetricsHelper::GetInstance()->SetDummySessionIdForTesting(); - content::WebContents::CreateParams create_params( - shell::CastBrowserProcess::GetInstance()->browser_context(), nullptr); - web_contents_ = content::WebContents::Create(create_params); - web_contents_->SetDelegate(&mock_wc_delegate_); - - mojom::CastWebViewParamsPtr params = mojom::CastWebViewParams::New(); - params->is_root_window = true; - cast_web_contents_ = std::make_unique( - web_contents_.get(), std::move(params)); - mock_cast_wc_observer_.Observe(cast_web_contents_.get()); - title_change_observer_.Observe(cast_web_contents_.get()); - - render_frames_.clear(); - content::WebContentsObserver::Observe(web_contents_.get()); - - run_loop_ = std::make_unique(); - } - - void PostRunTestOnMainThread() override { - cast_web_contents_.reset(); - web_contents_.reset(); - } - - // content::WebContentsObserver implementation: - void RenderFrameCreated(content::RenderFrameHost* render_frame_host) final { - render_frames_.insert(render_frame_host); - } - - void StartTestServer() { - ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); - embedded_test_server()->StartAcceptingConnections(); - } - - void QuitRunLoop() { - DCHECK(run_loop_); - if (run_loop_->running()) { - run_loop_->QuitWhenIdle(); - } - } - - MockWebContentsDelegate mock_wc_delegate_; - NiceMock mock_cast_wc_observer_; - TitleChangeObserver title_change_observer_; - std::unique_ptr web_contents_; - std::unique_ptr cast_web_contents_; - std::unique_ptr run_loop_; - - base::flat_set render_frames_; -}; - -MATCHER_P2(CheckPageState, cwc_ptr, expected_state, "") { - if (arg != cwc_ptr) { - return false; - } - return arg->page_state() == expected_state; -} - -// ============================================================================= -// Test cases -// ============================================================================= -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, Lifecycle) { - // =========================================================================== - // Test: Load a blank page successfully, verify LOADED state. - // =========================================================================== - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL)); - run_loop_->Run(); - - // =========================================================================== - // Test: Load a blank page via WebContents API, verify LOADED state. - // =========================================================================== - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - web_contents_->GetController().LoadURL(GURL(url::kAboutBlankURL), - content::Referrer(), - ui::PAGE_TRANSITION_TYPED, ""); - run_loop_->Run(); - - // =========================================================================== - // Test: Inject an iframe, verify no events are received for the frame. - // =========================================================================== - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(_)).Times(0); - EXPECT_CALL(mock_cast_wc_observer_, PageStopped(_, _)).Times(0); - std::string script = - "var iframe = document.createElement('iframe');" - "document.body.appendChild(iframe);" - "iframe.src = 'about:blank';"; - ASSERT_TRUE(ExecJs(web_contents_.get(), script)); - - // =========================================================================== - // Test: Inject an iframe and navigate it to an error page. Verify no events. - // =========================================================================== - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(_)).Times(0); - EXPECT_CALL(mock_cast_wc_observer_, PageStopped(_, _)).Times(0); - script = "iframe.src = 'https://www.fake-non-existent-cast-page.com';"; - ASSERT_TRUE(ExecJs(web_contents_.get(), script)); - - // =========================================================================== - // Test: Close the CastWebContents. WebContentsDelegate will be told to close - // the page, and then after the timeout elapses CWC will enter the CLOSED - // state and notify that the page has stopped. - // =========================================================================== - run_loop_ = std::make_unique(); - EXPECT_CALL(mock_wc_delegate_, CloseContents(web_contents_.get())) - .Times(AtLeast(1)); - EXPECT_CALL(mock_cast_wc_observer_, PageStopped(PageState::CLOSED, net::OK)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - cast_web_contents_->ClosePage(); - run_loop_->Run(); - - // =========================================================================== - // Test: Destroy the underlying WebContents. Verify DESTROYED state. - // =========================================================================== - run_loop_ = std::make_unique(); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::DESTROYED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - web_contents_.reset(); - run_loop_->Run(); - cast_web_contents_.reset(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, WebContentsDestroyed) { - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL)); - run_loop_->Run(); - - // =========================================================================== - // Test: Destroy the WebContents. Verify PageStopped(DESTROYED, net::OK). - // =========================================================================== - run_loop_ = std::make_unique(); - EXPECT_CALL(mock_cast_wc_observer_, - PageStopped(PageState::DESTROYED, net::OK)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - web_contents_.reset(); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorPageCrash) { - // =========================================================================== - // Test: If the page's main render process crashes, enter ERROR state. - // =========================================================================== - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL)); - run_loop_->Run(); - - run_loop_ = std::make_unique(); - EXPECT_CALL(mock_cast_wc_observer_, - PageStopped(PageState::ERROR, net::ERR_UNEXPECTED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - CrashTab(web_contents_.get()); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorLocalFileMissing) { - // =========================================================================== - // Test: Loading a page with an HTTP error should enter ERROR state. - // =========================================================================== - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStopped(PageState::ERROR, _)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - base::FilePath path = GetTestDataFilePath("this_file_does_not_exist.html"); - cast_web_contents_->LoadUrl(content::GetFileUrlWithQuery(path, "")); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorLoadFailSubFrames) { - // =========================================================================== - // Test: Ignore load errors in sub-frames. - // =========================================================================== - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL)); - run_loop_->Run(); - - // Create a sub-frame. - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(_)).Times(0); - EXPECT_CALL(mock_cast_wc_observer_, PageStopped(_, _)).Times(0); - std::string script = - "var iframe = document.createElement('iframe');" - "document.body.appendChild(iframe);" - "iframe.src = 'about:blank';"; - ASSERT_TRUE(ExecJs(web_contents_.get(), script)); - - ASSERT_EQ(2, (int)render_frames_.size()); - auto it = - base::ranges::find(render_frames_, web_contents_->GetPrimaryMainFrame(), - &content::RenderFrameHost::GetParent); - ASSERT_NE(render_frames_.end(), it); - content::RenderFrameHost* sub_frame = *it; - ASSERT_NE(nullptr, sub_frame); - cast_web_contents_->DidFailLoad(sub_frame, sub_frame->GetLastCommittedURL(), - net::ERR_FAILED); - - // =========================================================================== - // Test: Ignore main frame load failures with net::ERR_ABORTED. - // =========================================================================== - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(_)).Times(0); - EXPECT_CALL(mock_cast_wc_observer_, PageStopped(_, _)).Times(0); - cast_web_contents_->DidFailLoad( - web_contents_->GetPrimaryMainFrame(), - web_contents_->GetPrimaryMainFrame()->GetLastCommittedURL(), - net::ERR_ABORTED); - - // =========================================================================== - // Test: If main frame fails to load, page should enter ERROR state. - // =========================================================================== - run_loop_ = std::make_unique(); - EXPECT_CALL(mock_cast_wc_observer_, - PageStopped(PageState::ERROR, net::ERR_FAILED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - cast_web_contents_->DidFailLoad( - web_contents_->GetPrimaryMainFrame(), - web_contents_->GetPrimaryMainFrame()->GetLastCommittedURL(), - net::ERR_FAILED); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorHttp4XX) { - // =========================================================================== - // Test: If a server responds with an HTTP 4XX error, page should enter ERROR - // state. - // =========================================================================== - embedded_test_server()->RegisterRequestHandler( - base::BindRepeating(&DefaultHandler, net::HTTP_NOT_FOUND)); - StartTestServer(); - - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL( - mock_cast_wc_observer_, - PageStopped(PageState::ERROR, net::ERR_HTTP_RESPONSE_CODE_FAILURE)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - cast_web_contents_->LoadUrl(embedded_test_server()->GetURL("/dummy.html")); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorLoadFailed) { - // =========================================================================== - // Test: When main frame load fails, enter ERROR state. This test simulates a - // load error by intercepting the URL request and failing it with an arbitrary - // error code. - // =========================================================================== - base::FilePath path = GetTestDataFilePath("dummy.html"); - GURL gurl = content::GetFileUrlWithQuery(path, ""); - content::URLLoaderInterceptor url_interceptor(base::BindRepeating( - [](const GURL& url, - content::URLLoaderInterceptor::RequestParams* params) { - if (params->url_request.url != url) { - return false; - } - network::URLLoaderCompletionStatus status; - status.error_code = net::ERR_ADDRESS_UNREACHABLE; - params->client->OnComplete(status); - return true; - }, - gurl)); - - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, - PageStopped(PageState::ERROR, net::ERR_ADDRESS_UNREACHABLE)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - cast_web_contents_->LoadUrl(gurl); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, LoadCanceledByApp) { - // =========================================================================== - // Test: When the app calls window.stop(), the page should not enter the ERROR - // state. Instead, we treat it as LOADED. This is a historical behavior for - // some apps which intentionally stop the page and reload content. - // =========================================================================== - embedded_test_server()->ServeFilesFromSourceDirectory(GetTestDataPath()); - StartTestServer(); - - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - cast_web_contents_->LoadUrl( - embedded_test_server()->GetURL("/load_cancel.html")); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, LocationRedirectLifecycle) { - // =========================================================================== - // Test: When the app redirects to another url via window.location. Another - // navigation will be committed. LOADING -> LOADED -> LOADING -> LOADED state - // trasition is expected. - // =========================================================================== - embedded_test_server()->ServeFilesFromSourceDirectory(GetTestDataPath()); - StartTestServer(); - - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - - cast_web_contents_->LoadUrl( - embedded_test_server()->GetURL("/location_redirect.html")); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, NotifyMissingResource) { - // =========================================================================== - // Test: Loading a page with a missing resource should notify observers. - // =========================================================================== - run_loop_ = std::make_unique(); - { - InSequence seq; - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADING)); - EXPECT_CALL(mock_cast_wc_observer_, PageStateChanged(PageState::LOADED)) - .WillOnce(InvokeWithoutArgs([&]() { QuitRunLoop(); })); - } - EXPECT_CALL(mock_cast_wc_observer_, ResourceLoadFailed()); - - base::FilePath path = GetTestDataFilePath("missing_resource.html"); - cast_web_contents_->LoadUrl(content::GetFileUrlWithQuery(path, "")); - run_loop_->Run(); -} - -IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ExecuteJavaScriptOnLoad) { - // =========================================================================== - // Test: Injecting script to change title should work. - // =========================================================================== - const std::string kExpectedTitle = "hello"; - const std::string kOriginalTitle = - "Welcome to Stan the Offline Dino's Homepage"; - - // The script should be able to run before HTML - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/data/interface_binding.html chromium-132.0.6834.159/chromecast/browser/test/data/interface_binding.html --- chromium-132.0.6834.110/chromecast/browser/test/data/interface_binding.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/data/interface_binding.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ - - Binding some Mojo interfaces - - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/data/load_cancel.html chromium-132.0.6834.159/chromecast/browser/test/data/load_cancel.html --- chromium-132.0.6834.110/chromecast/browser/test/data/load_cancel.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/data/load_cancel.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ - - - - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/data/location_redirect.html chromium-132.0.6834.159/chromecast/browser/test/data/location_redirect.html --- chromium-132.0.6834.110/chromecast/browser/test/data/location_redirect.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/data/location_redirect.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ - - - - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/data/message_port.html chromium-132.0.6834.159/chromecast/browser/test/data/message_port.html --- chromium-132.0.6834.110/chromecast/browser/test/data/message_port.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/data/message_port.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ - - messageport - - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/data/missing_resource.html chromium-132.0.6834.159/chromecast/browser/test/data/missing_resource.html --- chromium-132.0.6834.110/chromecast/browser/test/data/missing_resource.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/data/missing_resource.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ - - - - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/data/title1.html chromium-132.0.6834.159/chromecast/browser/test/data/title1.html --- chromium-132.0.6834.110/chromecast/browser/test/data/title1.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/data/title1.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ - - title 1 - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/data/title2.html chromium-132.0.6834.159/chromecast/browser/test/data/title2.html --- chromium-132.0.6834.110/chromecast/browser/test/data/title2.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/data/title2.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ - - title 2 - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/data/window_post_message.html chromium-132.0.6834.159/chromecast/browser/test/data/window_post_message.html --- chromium-132.0.6834.110/chromecast/browser/test/data/window_post_message.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/data/window_post_message.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ - - postmessage - - - - diff -Nru chromium-132.0.6834.110/chromecast/browser/test/mock_cast_web_view.cc chromium-132.0.6834.159/chromecast/browser/test/mock_cast_web_view.cc --- chromium-132.0.6834.110/chromecast/browser/test/mock_cast_web_view.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/mock_cast_web_view.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// 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 "chromecast/browser/test/mock_cast_web_view.h" - -namespace chromecast { - -MockCastWebContents::MockCastWebContents() {} - -MockCastWebContents::~MockCastWebContents() = default; - -bool MockCastWebContents::TryBindReceiver(mojo::GenericPendingReceiver&) { - return false; -} - -MockCastWebView::MockCastWebView() - : mock_cast_web_contents_(std::make_unique()), - cast_web_contents_receiver_(mock_cast_web_contents_.get()) {} - -MockCastWebView::~MockCastWebView() = default; - -CastContentWindow* MockCastWebView::window() const { - return nullptr; -} - -content::WebContents* MockCastWebView::web_contents() const { - return nullptr; -} - -CastWebContents* MockCastWebView::cast_web_contents() { - return mock_cast_web_contents_.get(); -} - -base::TimeDelta MockCastWebView::shutdown_delay() const { - return base::TimeDelta(); -} - -void MockCastWebView::OwnerDestroyed() {} - -void MockCastWebView::Bind( - mojo::PendingReceiver receiver) { - cast_web_contents_receiver_.Bind(std::move(receiver)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/test/mock_cast_web_view.h chromium-132.0.6834.159/chromecast/browser/test/mock_cast_web_view.h --- chromium-132.0.6834.110/chromecast/browser/test/mock_cast_web_view.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test/mock_cast_web_view.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ -// 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. -#ifndef CHROMECAST_BROWSER_TEST_MOCK_CAST_WEB_VIEW_H_ -#define CHROMECAST_BROWSER_TEST_MOCK_CAST_WEB_VIEW_H_ - -#include - -#include "chromecast/browser/cast_web_contents.h" -#include "chromecast/browser/cast_web_view.h" -#include "components/url_rewrite/mojom/url_request_rewrite.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { - -class MockCastWebContents : public CastWebContents { - public: - MockCastWebContents(); - ~MockCastWebContents() override; - - // CastWebContents implementation - MOCK_METHOD(int, tab_id, (), (const, override)); - MOCK_METHOD(int, id, (), (const, override)); - MOCK_METHOD(content::WebContents*, web_contents, (), (const, override)); - MOCK_METHOD(PageState, page_state, (), (const, override)); - MOCK_METHOD(const media_control::MediaBlocker*, - media_blocker, - (), - (const override)); - MOCK_METHOD(void, AddRendererFeatures, (base::Value::Dict), (override)); - MOCK_METHOD(void, - SetInterfacesForRenderer, - (mojo::PendingRemote), - (override)); - MOCK_METHOD(void, - SetAppProperties, - (const std::string&, - const std::string&, - bool, - const GURL&, - bool, - const std::vector&, - const std::vector&), - (override)); - MOCK_METHOD(void, SetGroupInfo, (const std::string&, bool), (override)); - MOCK_METHOD(void, LoadUrl, (const GURL&), (override)); - MOCK_METHOD(void, ClosePage, (), (override)); - MOCK_METHOD(void, Stop, (int), (override)); - MOCK_METHOD(void, SetWebVisibilityAndPaint, (bool), (override)); - MOCK_METHOD(void, BlockMediaLoading, (bool), (override)); - MOCK_METHOD(void, BlockMediaStarting, (bool), (override)); - MOCK_METHOD(void, EnableBackgroundVideoPlayback, (bool), (override)); - MOCK_METHOD(void, - AddBeforeLoadJavaScript, - (uint64_t, std::string_view), - (override)); - MOCK_METHOD(void, - PostMessageToMainFrame, - (const std::string&, - const std::string&, - std::vector), - (override)); - MOCK_METHOD(void, - ExecuteJavaScript, - (const std::u16string&, base::OnceCallback), - (override)); - MOCK_METHOD(void, - ConnectToBindingsService, - (mojo::PendingRemote api_bindings_remote), - (override)); - MOCK_METHOD(void, SetEnabledForRemoteDebugging, (bool), (override)); - MOCK_METHOD(void, GetMainFramePid, (GetMainFramePidCallback), (override)); - MOCK_METHOD(InterfaceBundle*, local_interfaces, (), (override)); - MOCK_METHOD(bool, is_websql_enabled, (), (override)); - MOCK_METHOD(bool, is_mixer_audio_enabled, (), (override)); - - bool TryBindReceiver(mojo::GenericPendingReceiver&) override; - - private: -}; - -class MockCastWebView : public CastWebView { - public: - MockCastWebView(); - ~MockCastWebView() override; - - // CastWebView implementation - CastContentWindow* window() const override; - content::WebContents* web_contents() const override; - CastWebContents* cast_web_contents() override; - base::TimeDelta shutdown_delay() const override; - void OwnerDestroyed() override; - - MockCastWebContents* mock_cast_web_contents() { - return mock_cast_web_contents_.get(); - } - - void Bind(mojo::PendingReceiver web_contents); - - private: - std::unique_ptr mock_cast_web_contents_; - mojo::Receiver cast_web_contents_receiver_; -}; -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_TEST_MOCK_CAST_WEB_VIEW_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/test_interfaces.test-mojom chromium-132.0.6834.159/chromecast/browser/test_interfaces.test-mojom --- chromium-132.0.6834.110/chromecast/browser/test_interfaces.test-mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/test_interfaces.test-mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// 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. - -module chromecast.mojom; - -interface TestAdder { - Add(int32 a, int32 b) => (int32 result); -}; - -interface TestDoubler { - Double(int32 x) => (int32 result); -}; diff -Nru chromium-132.0.6834.110/chromecast/browser/visibility_types.h chromium-132.0.6834.159/chromecast/browser/visibility_types.h --- chromium-132.0.6834.110/chromecast/browser/visibility_types.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/visibility_types.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_VISIBILITY_TYPES_H_ -#define CHROMECAST_BROWSER_VISIBILITY_TYPES_H_ - -namespace chromecast { - -// Describes visual context of the window within the UI. -// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chromecast.shell -enum class VisibilityType { - // Unknown visibility state. - UNKNOWN = 0, - - // Window is occupying the entire screen and can be interacted with. - FULL_SCREEN = 1, - - // Window occupies a portion of the screen, supporting user interaction. - PARTIAL_OUT = 2, - - // Window is hidden after dismissal by back gesture, and cannot be interacted - // with via touch. - HIDDEN = 3, - - // Window is being displayed as a small visible tile. - TILE = 4, - - // Window is covered by other activities and cannot be interacted with via - // touch. - TRANSIENTLY_HIDDEN = 5 -}; - -// Represents requested activity windowing behavior. Behavior includes: -// 1. How long the activity should show -// 2. Whether the window should become immediately visible -// 3. How much screen space the window should occupy -// 4. What state to return to when the activity is completed -// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chromecast.shell -enum class VisibilityPriority { - // Default priority. It is up to system to decide how to show the activity. - DEFAULT = 0, - - // The activity wants to occupy the full screen for some period of time and - // then become hidden after a timeout. When timeout, it returns to the - // previous activity. - TRANSIENT_TIMEOUTABLE = 1, - - // A high priority interruption occupies half of the screen if a sticky - // activity is showing on the screen. Otherwise, it occupies the full screen. - HIGH_PRIORITY_INTERRUPTION = 2, - - // The activity takes place of other activity and won't be timeout. - STICKY_ACTIVITY = 3, - - // The activity stays on top of others (transient) but won't be timeout. - // When the activity finishes, it returns to the previous one. - TRANSIENT_STICKY = 4, - - // The activity should not be visible. - HIDDEN = 5, - - // The activity should not be visible, but the activity will consider itself - // to be visible. This is useful for opaque overlays while the activity is - // still active. - HIDDEN_STICKY = 6, -}; - -// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chromecast.shell -enum class GestureType { - NO_GESTURE = 0, - GO_BACK = 1, - TAP = 2, - TAP_DOWN = 3, - TOP_DRAG = 4, - RIGHT_DRAG = 5, -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_VISIBILITY_TYPES_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/web_types.cc chromium-132.0.6834.159/chromecast/browser/web_types.cc --- chromium-132.0.6834.110/chromecast/browser/web_types.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/web_types.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/web_types.h" - -namespace chromecast { - -std::ostream& operator<<(std::ostream& os, PageState state) { -#define CASE(state) \ - case PageState::state: \ - os << #state; \ - return os; - - switch (state) { - CASE(IDLE); - CASE(LOADING); - CASE(LOADED); - CASE(CLOSED); - CASE(DESTROYED); - CASE(ERROR); - } -#undef CASE -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/web_types.h chromium-132.0.6834.159/chromecast/browser/web_types.h --- chromium-132.0.6834.110/chromecast/browser/web_types.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/web_types.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_WEB_TYPES_H_ -#define CHROMECAST_BROWSER_WEB_TYPES_H_ - -#include - -namespace chromecast { - -enum class BackgroundColor { - NONE, - WHITE, - BLACK, - TRANSPARENT, -}; - -// Page state for the main frame. -enum class PageState { - IDLE = 0, // Main frame has not started yet. - LOADING = 1, // Main frame is loading resources. - LOADED = 2, // Main frame is loaded, but sub-frames may still be loading. - CLOSED = 3, // Page is closed and should be cleaned up. - DESTROYED = 4, // The WebContents is destroyed and can no longer be used. - ERROR = 5, // Main frame is in an error state. -}; - -std::ostream& operator<<(std::ostream& os, PageState state); - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_WEB_TYPES_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_resource_data_source.cc chromium-132.0.6834.159/chromecast/browser/webui/cast_resource_data_source.cc --- chromium-132.0.6834.110/chromecast/browser/webui/cast_resource_data_source.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_resource_data_source.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,133 +0,0 @@ -// 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 "chromecast/browser/webui/cast_resource_data_source.h" - -#include "base/files/file_path.h" -#include "base/functional/bind.h" -#include "base/memory/ref_counted_memory.h" -#include "chromecast/base/cast_constants.h" -#include "net/base/mime_util.h" -#include "net/url_request/url_request.h" -#include "services/network/public/mojom/content_security_policy.mojom.h" - -namespace chromecast { - -namespace { - -void GotData(base::OnceCallback)> cb, - scoped_refptr memory) { - std::move(cb).Run(std::move(memory)); -} - -} // namespace - -CastResourceDataSource::CastResourceDataSource(const std::string& host, - bool for_webui) - : host_(host), for_webui_(for_webui) {} - -CastResourceDataSource::~CastResourceDataSource() = default; - -std::string CastResourceDataSource::GetSource() { - return host_; -} - -void CastResourceDataSource::StartDataRequest( - const GURL& url, - const content::WebContents::Getter& wc_getter, - content::URLDataSource::GotDataCallback callback) { - std::string path = content::URLDataSource::URLToRequestPath(url); - remote_->RequestResourceBytes(path, - base::BindOnce(&GotData, std::move(callback))); -} - -std::string CastResourceDataSource::GetMimeType(const GURL& url) { - const std::string path = content::URLDataSource::URLToRequestPath(url); - - if (!for_webui_) { - std::string mime_type; - base::FilePath::StringType file_ext = - base::FilePath().AppendASCII(path).Extension(); - // net::GetMimeTypeFromFile() will crash at base::nix::GetFileMimeType() - // because IO is not allowed. - if (!file_ext.empty()) - net::GetWellKnownMimeTypeFromExtension(file_ext.substr(1), &mime_type); - return mime_type; - } - - // Remove the query string for to determine the mime type. - std::string file_path = path.substr(0, path.find_first_of('?')); - - if (base::EndsWith(file_path, ".css", base::CompareCase::INSENSITIVE_ASCII)) - return "text/css"; - - if (base::EndsWith(file_path, ".js", base::CompareCase::INSENSITIVE_ASCII)) - return "application/javascript"; - - if (base::EndsWith(file_path, ".json", base::CompareCase::INSENSITIVE_ASCII)) - return "application/json"; - - if (base::EndsWith(file_path, ".pdf", base::CompareCase::INSENSITIVE_ASCII)) - return "application/pdf"; - - if (base::EndsWith(file_path, ".svg", base::CompareCase::INSENSITIVE_ASCII)) - return "image/svg+xml"; - - if (base::EndsWith(file_path, ".jpg", base::CompareCase::INSENSITIVE_ASCII)) - return "image/jpeg"; - - if (base::EndsWith(file_path, ".png", base::CompareCase::INSENSITIVE_ASCII)) - return "image/png"; - - return "text/html"; -} - -bool CastResourceDataSource::ShouldServiceRequest( - const GURL& url, - content::BrowserContext* browser_context, - int render_process_id) { - if (url.SchemeIs(kChromeResourceScheme)) - return true; - return URLDataSource::ShouldServiceRequest(url, browser_context, - render_process_id); -} - -std::string CastResourceDataSource::GetAccessControlAllowOriginForOrigin( - const std::string& origin) { - // For now we give access for all "chrome://*" origins. - std::string allowed_origin_prefix = "chrome://"; - if (!base::StartsWith(origin, allowed_origin_prefix, - base::CompareCase::SENSITIVE)) { - return ""; - } - return origin; -} - -mojo::PendingReceiver -CastResourceDataSource::BindNewPipeAndPassReceiver() { - return remote_.BindNewPipeAndPassReceiver(); -} - -void CastResourceDataSource::OverrideContentSecurityPolicyChildSrc( - const std::string& data) { - frame_src_ = data; -} - -void CastResourceDataSource::DisableDenyXFrameOptions() { - deny_xframe_options_ = false; -} - -std::string CastResourceDataSource::GetContentSecurityPolicy( - network::mojom::CSPDirectiveName directive) { - if (directive == network::mojom::CSPDirectiveName::ChildSrc && frame_src_) { - return *frame_src_; - } - return URLDataSource::GetContentSecurityPolicy(directive); -} - -bool CastResourceDataSource::ShouldDenyXFrameOptions() { - return deny_xframe_options_; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_resource_data_source.h chromium-132.0.6834.159/chromecast/browser/webui/cast_resource_data_source.h --- chromium-132.0.6834.110/chromecast/browser/webui/cast_resource_data_source.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_resource_data_source.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BROWSER_WEBUI_CAST_RESOURCE_DATA_SOURCE_H_ -#define CHROMECAST_BROWSER_WEBUI_CAST_RESOURCE_DATA_SOURCE_H_ - -#include -#include - -#include "chromecast/browser/webui/mojom/webui.mojom.h" -#include "content/public/browser/url_data_source.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { - -// A minimal subset of content::WebUiDataSource logic has been pulled into -// CastResourceDataSource, in order to maintain parity with the previous design. -class CastResourceDataSource : public content::URLDataSource { - public: - CastResourceDataSource(const std::string& host, bool for_webui); - ~CastResourceDataSource() override; - - mojo::PendingReceiver BindNewPipeAndPassReceiver(); - void OverrideContentSecurityPolicyChildSrc(const std::string& data); - void DisableDenyXFrameOptions(); - - // content::URLDataSource implementation. - std::string GetSource() override; - void StartDataRequest( - const GURL& url, - const content::WebContents::Getter& wc_getter, - content::URLDataSource::GotDataCallback callback) override; - std::string GetMimeType(const GURL& url) override; - bool ShouldServiceRequest(const GURL& url, - content::BrowserContext* browser_context, - int render_process_id) override; - std::string GetAccessControlAllowOriginForOrigin( - const std::string& origin) override; - std::string GetContentSecurityPolicy( - network::mojom::CSPDirectiveName directive) override; - bool ShouldDenyXFrameOptions() override; - - private: - const std::string host_; - const bool for_webui_; - mojo::Remote remote_; - - std::optional frame_src_; - bool deny_xframe_options_ = true; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_WEBUI_CAST_RESOURCE_DATA_SOURCE_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_webui.cc chromium-132.0.6834.159/chromecast/browser/webui/cast_webui.cc --- chromium-132.0.6834.110/chromecast/browser/webui/cast_webui.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_webui.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// 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 "chromecast/browser/webui/cast_webui.h" - -#include "base/command_line.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/browser/webui/cast_resource_data_source.h" -#include "chromecast/browser/webui/cast_webui_message_handler.h" -#include "chromecast/browser/webui/constants.h" -#include "content/public/browser/url_data_source.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_ui.h" -#include "content/public/common/bindings_policy.h" - -namespace chromecast { - -CastWebUI::CastWebUI(content::WebUI* webui, - const std::string& host, - mojom::WebUiClient* client) - : WebUIController(webui), - web_contents_(webui->GetWebContents()), - browser_context_(web_contents_->GetBrowserContext()) { - DCHECK(web_contents_); - DCHECK(browser_context_); - weak_this_ = weak_factory_.GetWeakPtr(); - webui->SetBindings(content::kWebUIBindingsPolicySet); - auto cast_resources = - std::make_unique(host, true /* for_webui */); - client->CreateController(host, web_ui_.BindNewPipeAndPassRemote(), - cast_resources->BindNewPipeAndPassReceiver()); - if (host == kCastWebUIHomeHost) { - cast_resources->OverrideContentSecurityPolicyChildSrc( - "frame-src https://*.google.com;"); - cast_resources->DisableDenyXFrameOptions(); - } else if (host == kCastWebUIForceUpdateHost) { - const std::string candidate_remote_url = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kForceUpdateRemoteUrl); - cast_resources->OverrideContentSecurityPolicyChildSrc( - "frame-src https://*.google.com " + candidate_remote_url); - cast_resources->DisableDenyXFrameOptions(); - } - content::URLDataSource::Add(browser_context_, std::move(cast_resources)); - auto message_handler = std::make_unique(); - message_handler_ = message_handler.get(); - webui->AddMessageHandler(std::move(message_handler)); -} - -CastWebUI::~CastWebUI() {} - -void CastWebUI::InvokeCallback(const std::string& message, - const base::Value::List& args) { - if (message_callbacks_.count(message) == 0) { - return; - } - message_callbacks_[message]->OnMessage(args.Clone()); -} - -void CastWebUI::RegisterMessageCallback( - const std::string& message, - mojo::PendingRemote callback) { - message_callbacks_.emplace(message, std::move(callback)); - web_ui()->RegisterMessageCallback( - message, - base::BindRepeating(&CastWebUI::InvokeCallback, weak_this_, message)); -} - -void CastWebUI::CallJavascriptFunction(const std::string& function, - base::Value::List args) { - message_handler_->CallJavascriptFunction( - function, std::vector(args.begin(), args.end())); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_webui.h chromium-132.0.6834.159/chromecast/browser/webui/cast_webui.h --- chromium-132.0.6834.110/chromecast/browser/webui/cast_webui.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_webui.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_H_ -#define CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_H_ - -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/memory/weak_ptr.h" -#include "base/values.h" -#include "chromecast/browser/webui/mojom/webui.mojom.h" -#include "chromecast/chromecast_buildflags.h" -#include "content/public/browser/web_ui_controller.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace content { -class BrowserContext; -class WebContents; -class WebUI; -} // namespace content - -namespace chromecast { - -class CastWebUIMessageHandler; - -class CastWebUI : public mojom::WebUi, public content::WebUIController { - public: - CastWebUI(content::WebUI* webui, - const std::string& host, - mojom::WebUiClient* client); - ~CastWebUI() override; - - static std::unique_ptr Create(content::WebUI* webui, - const std::string& host, - mojom::WebUiClient* client); - - protected: - content::WebContents* const web_contents_; - content::BrowserContext* const browser_context_; - - private: - void InvokeCallback(const std::string& message, - const base::Value::List& args); - - // mojom::WebUI implementation: - void RegisterMessageCallback( - const std::string& message, - mojo::PendingRemote callback) override; - void CallJavascriptFunction(const std::string& function, - base::Value::List args) override; - - // Pointer to the generic message handler owned by the Web UI. The message - // handler is guaranteed to outlive CastWebUI since |this| is the first member - // to be deleted in the Web UI. - CastWebUIMessageHandler* message_handler_; - - mojo::Receiver web_ui_{this}; - - base::flat_map> - message_callbacks_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_controller_factory.cc chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_controller_factory.cc --- chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_controller_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_controller_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -// 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 "chromecast/browser/webui/cast_webui_controller_factory.h" - -#include -#include - -#include "base/containers/contains.h" -#include "chromecast/browser/webui/cast_resource_data_source.h" -#include "chromecast/browser/webui/cast_webui.h" -#include "chromecast/browser/webui/constants.h" -#include "content/public/browser/url_data_source.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_ui_controller_factory.h" -#include "url/gurl.h" - -namespace chromecast { - -CastWebUiControllerFactory::CastWebUiControllerFactory( - mojo::PendingRemote client, - const std::vector& hosts) - : client_(std::move(client)), hosts_(hosts) { - DCHECK(client_); -} - -CastWebUiControllerFactory::~CastWebUiControllerFactory() = default; - -content::WebUI::TypeID CastWebUiControllerFactory::GetWebUIType( - content::BrowserContext* browser_context, - const GURL& url) { - if (base::Contains(hosts_, url.host())) { - return const_cast(this); - } - return content::WebUI::kNoWebUI; -} - -bool CastWebUiControllerFactory::UseWebUIForURL( - content::BrowserContext* browser_context, - const GURL& url) { - return GetWebUIType(browser_context, url) != content::WebUI::kNoWebUI; -} - -std::unique_ptr -CastWebUiControllerFactory::CreateWebUIControllerForURL(content::WebUI* web_ui, - const GURL& url) { - static std::once_flag flag; - std::call_once(flag, [this, web_ui] { - auto cast_resources = std::make_unique( - kCastWebUIResourceHost, false /* for_webui */); - client_->CreateResources(cast_resources->GetSource(), - cast_resources->BindNewPipeAndPassReceiver()); - content::URLDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(), - std::move(cast_resources)); - }); - - return CastWebUI::Create(web_ui, url.host(), client_.get()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_controller_factory.h chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_controller_factory.h --- chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_controller_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_controller_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_CONTROLLER_FACTORY_H_ -#define CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_CONTROLLER_FACTORY_H_ - -#include "chromecast/browser/webui/mojom/webui.mojom.h" -#include "content/public/browser/web_ui_controller_factory.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace content { -class BrowserContext; -class WebUI; -class WebUIController; -} // namespace content - -namespace chromecast { - -class CastWebUiControllerFactory : public content::WebUIControllerFactory { - public: - CastWebUiControllerFactory(mojo::PendingRemote client, - const std::vector& hosts); - CastWebUiControllerFactory(const CastWebUiControllerFactory&) = delete; - CastWebUiControllerFactory& operator=(const CastWebUiControllerFactory&) = - delete; - ~CastWebUiControllerFactory() override; - - // content::WebUIControllerFactory implementation: - content::WebUI::TypeID GetWebUIType(content::BrowserContext* browser_context, - const GURL& url) override; - bool UseWebUIForURL(content::BrowserContext* browser_context, - const GURL& url) override; - std::unique_ptr CreateWebUIControllerForURL( - content::WebUI* web_ui, - const GURL& url) override; - - private: - mojo::Remote client_; - const std::vector hosts_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_CONTROLLER_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_default.cc chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_default.cc --- chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// 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 "chromecast/browser/webui/cast_webui.h" - -namespace chromecast { - -// static -std::unique_ptr CastWebUI::Create(content::WebUI* webui, - const std::string& host, - mojom::WebUiClient* client) { - return std::make_unique(webui, host, client); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_message_handler.cc chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_message_handler.cc --- chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_message_handler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_message_handler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// 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 "chromecast/browser/webui/cast_webui_message_handler.h" - -#include - -#include "base/logging.h" - -namespace chromecast { - -CastWebUIMessageHandler::CastWebUIMessageHandler() = default; - -CastWebUIMessageHandler::~CastWebUIMessageHandler() = default; - -void CastWebUIMessageHandler::RegisterMessages() {} - -void CastWebUIMessageHandler::OnJavascriptDisallowed() { - if (javascript_called_) { - LOG(ERROR) << "The Web UI page navigated after JS was invoked externally. " - << "This may be a bug."; - } -} - -void CastWebUIMessageHandler::CallJavascriptFunction( - std::string_view function, - base::span args) { - AllowJavascript(); - javascript_called_ = true; - WebUIMessageHandler::CallJavascriptFunction(function, args); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_message_handler.h chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_message_handler.h --- chromium-132.0.6834.110/chromecast/browser/webui/cast_webui_message_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/cast_webui_message_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_MESSAGE_HANDLER_H_ -#define CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_MESSAGE_HANDLER_H_ - -#include -#include - -#include "base/containers/span.h" -#include "base/values.h" -#include "content/public/browser/web_ui_message_handler.h" - -namespace chromecast { - -// Simple generic message handler for Web UIs. This class exposes a public -// method for running JS in the Web UI. This class is owned by the Web UI, -// but a reference is maintained inside of CastWebUI. -class CastWebUIMessageHandler : public content::WebUIMessageHandler { - public: - CastWebUIMessageHandler(); - ~CastWebUIMessageHandler() override; - - // content::WebUIMessageHandler implementation: - void RegisterMessages() override; - void OnJavascriptDisallowed() override; - - // Invoke a JS function in the Web UI. - void CallJavascriptFunction(std::string_view function, - base::span args); - - private: - bool javascript_called_ = false; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_WEBUI_CAST_WEBUI_MESSAGE_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/constants.cc chromium-132.0.6834.159/chromecast/browser/webui/constants.cc --- chromium-132.0.6834.110/chromecast/browser/webui/constants.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/constants.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// 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 "chromecast/browser/webui/constants.h" - -namespace chromecast { - -const char kCastWebUIForceUpdateHost[] = "force_update"; -const char kCastWebUIHomeHost[] = "home"; -const char kCastWebUIResourceHost[] = "cast_resources"; - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/constants.h chromium-132.0.6834.159/chromecast/browser/webui/constants.h --- chromium-132.0.6834.110/chromecast/browser/webui/constants.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/constants.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// 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. - -#ifndef CHROMECAST_BROWSER_WEBUI_CONSTANTS_H_ -#define CHROMECAST_BROWSER_WEBUI_CONSTANTS_H_ - -namespace chromecast { - -// Web UI hostnames for Cast. -extern const char kCastWebUIForceUpdateHost[]; -extern const char kCastWebUIHomeHost[]; -extern const char kCastWebUIResourceHost[]; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_WEBUI_CONSTANTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/mojom/OWNERS chromium-132.0.6834.159/chromecast/browser/webui/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/browser/webui/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/browser/webui/mojom/webui.mojom chromium-132.0.6834.159/chromecast/browser/webui/mojom/webui.mojom --- chromium-132.0.6834.110/chromecast/browser/webui/mojom/webui.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/browser/webui/mojom/webui.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// 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. - -module chromecast.mojom; - -import "mojo/public/mojom/base/ref_counted_memory.mojom"; -import "mojo/public/mojom/base/values.mojom"; - -// ============================================================================= -// These interfaces allow a remote client to control Chromium Web UIs in the -// Cast Browser. The client will provide resources to specific Web UIs based on -// host name. The only intended client for these interfaces is the Cast Service, -// which currently lives in the browser process. Eventually Cast will be moved -// to its own process, which is why these IPC interfaces are needed. -// ============================================================================= - -// Wraps a repeating callback which is invoked by the Web UI messenger. -interface MessageCallback { - // Receive a message with generic parameters. - OnMessage(mojo_base.mojom.ListValue list); -}; - -// Use this interface to control the Web UI. This interface is hosted in the -// Cast Browser process. -interface WebUi { - // Register a repeating message callback for a Web UI. - RegisterMessageCallback(string message, pending_remote cb); - - // Execute a Javascript |function| with |args|. - CallJavascriptFunction(string function, mojo_base.mojom.ListValue args); -}; - -// Implement this interface to provide resources for a given host. This -// interface is owned by the Cast Service process. -interface Resources { - // Resources are requested for /|path|. - RequestResourceBytes(string path) => (mojo_base.mojom.RefCountedMemory bytes); -}; - -// Implement this interface to control Chromium Web UI pages. This interface -// is implemented by the Cast Service process. -interface WebUiClient { - // Called whenever a Web UI is about to be launched. The client must bind - // |resources|. The resources will only be used by the matching Web UI |host|. - CreateController(string host, - pending_remote web_ui, - pending_receiver resources); - - // Requests the client to create a resource provider for |host|. These - // resources may be used by multiple Web UI pages. - CreateResources(string host, - pending_receiver resources); -}; diff -Nru chromium-132.0.6834.110/chromecast/cast_core/DEPS chromium-132.0.6834.159/chromecast/cast_core/DEPS --- chromium-132.0.6834.110/chromecast/cast_core/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -include_rules = [ - "+chromecast/cast_core", - "+chromecast/app", - "+chromecast/base", - "+content/public/app", -] diff -Nru chromium-132.0.6834.110/chromecast/cast_core/OWNERS chromium-132.0.6834.159/chromecast/cast_core/OWNERS --- chromium-132.0.6834.110/chromecast/cast_core/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -brettk@google.com -mfoltz@chromium.org -sandv@google.com -sanfin@chromium.org -vigeni@google.com diff -Nru chromium-132.0.6834.110/chromecast/cast_core/README.md chromium-132.0.6834.159/chromecast/cast_core/README.md --- chromium-132.0.6834.110/chromecast/cast_core/README.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -# Introduction - -This directory defines the Cast Web Runtime, an implementation of the -`//components/cast_streaming` Chromecast receiver, for use with the internal -Cast Core library. - -# Local Testing - -### The below instructions are intended for Googlers only! - -## Build - -Build flags for Cast Web Runtime can be found in `//chromecast/build/args/product/`: - - atv* configs target Android TV - - linuxtv* configs target Linux-based TVs. - -Building of this directory can be done by building the `chromecast/cast_core:core_runtime_simple` target. - - -## Run - -Running the Cast Web Runtime on Linux can be done with the following steps: - -1. Build the Cast Web Runtime using the above flags -2. Build Cast Core following instructions -[here](https://goto.google.com/cast-core-on-glinux#build). -3. [Run](https://goto.google.com/cast-core-on-glinux#run) the Cast Core and -Platform Service applications built in step 2. Note that if it is your first -time running Cast Core you will need to -[generate certificates](https://goto.google.com/cast-core-on-glinux#certificates) -for device type `tv`. -4. Cast from a Chrome instance running on the local machine (either an official -Chrome release or a locally built Chromium instance). It may take a few minutes -for the Cast Core instance to show up as a valid cast target. - -# Troubleshooting - -## Common issues and their resolutions: - -When running Cast Core, error -`Unable to load application config from file /app.conf because the file does not exist or could not be read`: -This occurs when the certificates were not generated correctly. Ensure they were -generated for device type `tv`. - -When starting the Cast Web Runtime, hitting -[this DCHECK](https://source.chromium.org/chromium/chromium/src/+/main:components/metrics/metrics_state_manager.cc;l=414): -This occurs when flags are not set correctly. Ensure you are using the correct -config file for running on Linux. - -When starting Cast Core, you hit -[this DCHECK](https://goto.google.com/castcoreportfailure): This occurs when the -gRPC port is already is use. Kill the existing process using the following -commands: - -``` -user$ netstat -ltnp | grep -w "10101" -(Not all processes could be identified, non-owned process info - will not be shown, you would have to be root to see it all.) -tcp6 0 0 :::10101 :::* LISTEN / -user$ kill -9 -``` - -Then re-run Cast Core. diff -Nru chromium-132.0.6834.110/chromecast/cast_core/cast_core_switches.h chromium-132.0.6834.159/chromecast/cast_core/cast_core_switches.h --- chromium-132.0.6834.110/chromecast/cast_core/cast_core_switches.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/cast_core_switches.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_CAST_CORE_SWITCHES_H_ -#define CHROMECAST_CAST_CORE_CAST_CORE_SWITCHES_H_ - -namespace cast { -namespace core { - -// Specifies the Cast Core runtime ID, --cast-core-runtime-id=. -constexpr char kCastCoreRuntimeIdSwitch[] = "cast-core-runtime-id"; - -// Specifies the Cast Core runtime gRPC endpoint, -// --runtime-service-path=. -constexpr char kRuntimeServicePathSwitch[] = "runtime-service-path"; - -} // namespace core -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_CAST_CORE_SWITCHES_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/cast_runtime_main.cc chromium-132.0.6834.159/chromecast/cast_core/cast_runtime_main.cc --- chromium-132.0.6834.110/chromecast/cast_core/cast_runtime_main.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/cast_runtime_main.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/app/cast_main_delegate.h" -#include "content/public/app/content_main.h" - -int main(int argc, const char** argv) { - chromecast::shell::CastMainDelegate delegate; - content::ContentMainParams params(&delegate); - params.argc = argc; - params.argv = argv; - return content::ContentMain(std::move(params)); -} diff -Nru chromium-132.0.6834.110/chromecast/cast_core/cast_starboard_runtime_main.cc chromium-132.0.6834.159/chromecast/cast_core/cast_starboard_runtime_main.cc --- chromium-132.0.6834.110/chromecast/cast_core/cast_starboard_runtime_main.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/cast_starboard_runtime_main.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,153 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// The entrypoint for the starboard cast runtime. If loggy is enabled (typically -// used for partner builds), this code forks a separate process to run loggy for -// logging. -// -// Also contains logic for parsing chromium args passed as JSON (used by some -// partner platforms). - -#include -#include -#include -#include - -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "chromecast/app/cast_main_delegate.h" -#include "chromecast/cast_core/child_log_process.h" -#include "content/public/app/content_main.h" - -namespace { - -constexpr char kHomeEnvOverride[] = "home-env-override"; -constexpr char kRuntimeHomeSubdirUsedFile[] = ".dirty"; -constexpr char kParametersKey[] = "parameters"; -constexpr char kArgvKey[] = "argv"; - -// JSONArgsParser determines whether command line arguments were delivered -// as JSON or the standard format and, if necessary, parses the JSON -// arguments. -class JSONArgsParser { - public: - JSONArgsParser(int argc, const char** argv) { - if (!TryParseJson(argc, argv)) { - // If args were not provided as JSON, use defaults. - for (int i = 0; i < argc; i++) { - argv_.push_back(argv[i]); - } - argv_.push_back(nullptr); - } - } - - int argc() { return argv_.size() - 1; } - - const char** argv() { return argv_.data(); } - - private: - // If the command is of the format ` `, tries to parse - // parameters from the JSON blob in |argv[1] instead of directly from - // |argv|. Returns true if successful; otherwise, returns false. - bool TryParseJson(int argc, const char** argv) { - // Required format is ` ` - if (argc != 2) { - return false; - } - - // JSON must be the following format. All keys and values are strings. - // {"parameters":{"argv":["arg1", ...]}} - std::string argv1 = std::string(argv[1]); - std::optional root = base::JSONReader::ReadDict(argv1); - if (!root) { - // Try to fix unquoted JSON - base::ReplaceSubstringsAfterOffset(&argv1, 0, "{", "{\""); - base::ReplaceSubstringsAfterOffset(&argv1, 0, "[", "[\""); - base::ReplaceSubstringsAfterOffset(&argv1, 0, "]", "\"]"); - base::ReplaceSubstringsAfterOffset(&argv1, 0, ":", "\":\""); - base::ReplaceSubstringsAfterOffset(&argv1, 0, ",", "\",\""); - base::ReplaceSubstringsAfterOffset(&argv1, 0, ":\"[", ":["); - base::ReplaceSubstringsAfterOffset(&argv1, 0, ":\"{", ":{"); - - // Special case to handle unix:/tmp. This means that things like - // "valid_key_unix":"/valid_value" will fail to parse. Known issue. - base::ReplaceSubstringsAfterOffset(&argv1, 0, "unix\":\"/", "unix:/"); - root = base::JSONReader::ReadDict(argv1); - } - - if (!root) { - return false; - } - - base::Value::Dict* v = root->FindDict(kParametersKey); - if (!v) { - return false; - } - - base::Value::List* argv_list = v->FindList(kArgvKey); - if (!argv_list) { - return false; - } - - for (const auto& val : *argv_list) { - // All values must be strings. - if (!val.is_string()) { - return false; - } - argv_parsed_.push_back(val.GetString()); - } - - // Parsing is successful, so load up |argv_| and return |true|. - argv_.push_back(argv[0]); - for (const std::string& arg : argv_parsed_) { - argv_.push_back(arg.c_str()); - } - argv_.push_back(nullptr); - return true; - } - - // Persists the backing memory of |argv|. - std::vector argv_parsed_; - std::vector argv_; -}; - -} // namespace - -int main(int argc, const char** argv) { - JSONArgsParser args(argc, argv); - - chromecast::ForkAndRunLogProcessIfSpecified(args.argc(), args.argv()); - - chromecast::shell::CastMainDelegate delegate; - content::ContentMainParams params(&delegate); - - base::CommandLine temp_cmd(args.argc(), args.argv()); - std::string home_override = temp_cmd.GetSwitchValueASCII(kHomeEnvOverride); - if (!home_override.empty()) { - LOG(INFO) << "HOME variable was previously \"" << getenv("HOME") - << "\"; overriding to \"" << home_override << "\"."; - setenv("HOME", home_override.c_str(), 1); - - base::FilePath home_directory(home_override); - if (!base::DirectoryExists(home_directory)) { - CHECK(base::CreateDirectory(home_directory)); - } - - base::FilePath home_directory_used_file = - home_directory.AppendASCII(kRuntimeHomeSubdirUsedFile); - if (!base::PathExists(home_directory_used_file)) { - base::File(home_directory_used_file, - base::File::FLAG_CREATE | base::File::FLAG_WRITE); - } - } - - params.argc = args.argc(); - params.argv = args.argv(); - - return content::ContentMain(std::move(params)); -} diff -Nru chromium-132.0.6834.110/chromecast/cast_core/child_log_process.cc chromium-132.0.6834.159/chromecast/cast_core/child_log_process.cc --- chromium-132.0.6834.110/chromecast/cast_core/child_log_process.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/child_log_process.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,100 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/child_log_process.h" - -#include -#include -#include -#include - -#include -#include - -#include "base/command_line.h" -#include "base/strings/string_split.h" - -namespace chromecast { - -constexpr char kChildLogProcess[] = "child_log_process"; -constexpr char kChildLogProcessArgs[] = "child_log_process_args"; - -void ForkAndRunLogProcess(std::string log_process_path, - std::string log_process_args) { - if (log_process_args.size() > 2 && - (log_process_args[0] == '\"' && log_process_args.back() == '\"')) { - log_process_args = log_process_args.substr(1, log_process_args.size() - 2); - } - std::vector raw_args = base::SplitString( - log_process_args, " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - std::vector argv = {log_process_path.c_str()}; - for (const auto& arg : raw_args) { - argv.push_back(arg.c_str()); - } - argv.push_back(nullptr); - - int pipefds[2]; - pid_t cpid; - if (pipe(pipefds) == -1) { - fprintf(stderr, "Could not create pipes for logging process: %s\n", - strerror(errno)); - fflush(stderr); - return; - } - cpid = fork(); - if (cpid == -1) { - fprintf(stderr, "Could not fork new process for logging process: %s\n", - strerror(errno)); - fflush(stderr); - close(pipefds[0]); - close(pipefds[1]); - return; - } - - if (cpid == 0) { - // child - close(pipefds[1]); // writable end - dup2(pipefds[0], fileno(stdin)); - close(pipefds[0]); - int ret = - execv(log_process_path.c_str(), const_cast(&argv[0])); - if (ret == -1) { - fprintf(stderr, "Could not start process: %s error: %s\n", - log_process_path.c_str(), strerror(errno)); - _exit(1); - } - } else { - // parent - close(pipefds[0]); // readable end - - int original_stderr = dup(fileno(stderr)); - int original_stdout = dup(fileno(stdout)); - if (dup2(pipefds[1], fileno(stdout)) == -1 || - dup2(pipefds[1], fileno(stderr)) == -1) { - dup2(original_stderr, fileno(stderr)); - dup2(original_stdout, fileno(stdout)); - fprintf(stderr, - "Failed to map stderr and stdout to writable pipe for logging\n"); - fflush(stderr); - } else { - printf("Log client initialized.\n"); - close(original_stderr); - close(original_stdout); - } - close(pipefds[1]); // stderr now references the pipe, or dup2 failed. - // regardless we can close our old fd. - } -} - -void ForkAndRunLogProcessIfSpecified(const int argc, const char* const* argv) { - base::CommandLine::Init(argc, argv); - auto* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(kChildLogProcess)) { - ForkAndRunLogProcess( - command_line->GetSwitchValueASCII(kChildLogProcess), - command_line->GetSwitchValueASCII(kChildLogProcessArgs)); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/child_log_process.h chromium-132.0.6834.159/chromecast/cast_core/child_log_process.h --- chromium-132.0.6834.110/chromecast/cast_core/child_log_process.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/child_log_process.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_CHILD_LOG_PROCESS_H_ -#define CHROMECAST_CAST_CORE_CHILD_LOG_PROCESS_H_ - -#include - -namespace chromecast { - -// Forks and runs a separate process specified by `log_process_path`. -// -// Pipes the parent's stderr to the child's stdin. -// -// Arguments are provided by `log_process_args`. If `log_process_args` starts -// and ends with double quotes, it will be stripped. arguments are tokenized by -// spaces. -void ForkAndRunLogProcess(std::string log_process_path, - std::string log_process_args); - -void ForkAndRunLogProcessIfSpecified(int argc, const char* const* argv); - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_CHILD_LOG_PROCESS_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/core_runtime_starboard.sym chromium-132.0.6834.159/chromecast/cast_core/core_runtime_starboard.sym --- chromium-132.0.6834.110/chromecast/cast_core/core_runtime_starboard.sym 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/core_runtime_starboard.sym 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -{ - local: - *; -}; diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/DEPS chromium-132.0.6834.159/chromecast/cast_core/grpc/DEPS --- chromium-132.0.6834.110/chromecast/cast_core/grpc/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+third_party/cast_core/public/src/proto/common", - "+third_party/grpc/src/include", -] diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/cancellable_reactor.h chromium-132.0.6834.159/chromecast/cast_core/grpc/cancellable_reactor.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/cancellable_reactor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/cancellable_reactor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,166 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_CANCELLABLE_REACTOR_H_ -#define CHROMECAST_CAST_CORE_GRPC_CANCELLABLE_REACTOR_H_ - -#include - -#include - -#include "base/logging.h" -#include "base/synchronization/lock.h" - -namespace grpc { -class ByteBuffer; -} - -namespace cast { -namespace utils { - -// A facade around reactor implementation that allows to finish the reactor in -// case it was cancelled. No actions will happen if reactor was already -// finished. -template -class CancellableReactor : public TReactor { - public: - using TReactor::name; - using typename TReactor::RequestType; - - template - explicit CancellableReactor(TArgs&&... args) - : TReactor(std::forward(args)...) {} - - bool is_done() override { - base::AutoLock l(lock_); - return done_deferred_ || finished_; - } - - protected: - // Implements GrpcServerReactor APIs. - void WriteResponse(const grpc::ByteBuffer* buffer) override { - { - base::ReleasableAutoLock l(&lock_); - request_pending_ = false; - if (done_deferred_) { - // The gRPC framework tried to finalize the reactor, but it was pending - // the handler response. Now it can be fully finalized. - LOG(INFO) << "Finalizing deferred reactor: " << name(); - - // The lock must be released, so that the object can be destroyed - // without debug warnings. - l.Release(); - - // Need to call OnResponseDone to let the caller know in the write - // callback that the reactor is finished. - TReactor::OnResponseDone( - grpc::Status(grpc::StatusCode::ABORTED, "Reactor done")); - TReactor::OnDone(); - return; - } - if (finished_) { - // The reactor is already being finalized - ignore. - LOG(WARNING) - << "Not writing response to reactor as it's already finished: " - << name(); - return; - } - } - - TReactor::WriteResponse(buffer); - } - - void FinishWriting(const grpc::ByteBuffer* buffer, - const grpc::Status& status) override { - { - base::ReleasableAutoLock l(&lock_); - request_pending_ = false; - if (done_deferred_) { - // The gRPC framework tried to finalize the reactor, but it was pending - // the handler response. Now it can be fully finalized. - LOG(INFO) << "Finalizing deferred reactor: " << name(); - - // The lock must be released, so that the object can be destroyed - // without debug warnings. - l.Release(); - - TReactor::OnDone(); - return; - } - if (finished_) { - // The reactor is already being finalized - ignore. - LOG(WARNING) - << "Not finishing the reactor as it's already being finished: " - << name(); - return; - } - finished_ = true; - } - - TReactor::FinishWriting(buffer, status); - } - - void OnRequestDone(GrpcStatusOr request) override { - { - base::AutoLock l(lock_); - if (finished_) { - // Do not process the request if reactor has been cancelled/finished. - LOG(WARNING) << "Got a request, but reactor was already finished: " - << name(); - return; - } - request_pending_ = true; - } - - TReactor::OnRequestDone(std::move(request)); - } - - // Implements grpc::ServerGenericBidiReactor APIs. - // OnCancel is called on pending reactors while the gRPC server is - // shutting down. At this point, we don't expect users to call the - // reactors. If they were not finished properly, we must finish them - // forcefully to unblock server shutdown process. - void OnCancel() override { - { - base::AutoLock l(lock_); - if (finished_) { - LOG(WARNING) << "Not cancelling the reactor as it's already finished: " - << name(); - return; - } - LOG(WARNING) << "Active reactor got cancelled: " << name(); - finished_ = true; - } - - TReactor::FinishWriting(nullptr, grpc::Status(grpc::StatusCode::ABORTED, - "Reactor was cancelled")); - } - - void OnDone() override { - { - base::AutoLock l(lock_); - if (request_pending_) { - // Need to wait for the client to release the reactor. - done_deferred_ = true; - LOG(WARNING) - << "Waiting for client write before finishing the reactor: " - << name(); - return; - } - } - - TReactor::OnDone(); - } - - private: - base::Lock lock_; - bool done_deferred_ GUARDED_BY(lock_) = false; - bool finished_ GUARDED_BY(lock_) = false; - bool request_pending_ GUARDED_BY(lock_) = false; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_CANCELLABLE_REACTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_call.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_call.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_CALL_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_CALL_H_ - -#include - -#include - -#include "base/logging.h" -#include "base/memory/raw_ptr.h" -#include "chromecast/cast_core/grpc/grpc_call_options.h" - -namespace cast { -namespace utils { - -// The base class for all gRPC call implementations. Provides some common -// functionality used to instantiate the call (ie request, stub interface etc). -template -class GrpcCall { - public: - using SyncInterface = typename TGrpcStub::SyncInterface; - using AsyncInterface = typename TGrpcStub::AsyncInterface; - using Request = TRequest; - - // Client call context valid only through duration of the call. - class Context { - public: - explicit Context(grpc::ClientContext* grpc_context) - : grpc_context_(grpc_context) {} - - // Try cancelling the call. - void Cancel() { grpc_context_->TryCancel(); } - - private: - raw_ptr grpc_context_; - }; - - explicit GrpcCall(SyncInterface* stub) : GrpcCall(stub, Request()) {} - - GrpcCall(SyncInterface* stub, Request request) - : stub_(stub), request_(std::move(request)) { - DCHECK(stub_); - async_ = stub_->async(); - } - - virtual ~GrpcCall() = default; - - // Returns the reference to the request. - Request& request() & { return request_; } - - // Returns the move reference to the request. - Request&& request() && { return std::move(request_); } - - // Sets a deadline for gRPC call. - void SetDeadline(int64_t deadline_ms) { options_.SetDeadline(deadline_ms); } - - protected: - SyncInterface* sync() && { - DCHECK(stub_); - return std::exchange(stub_, nullptr); - } - - AsyncInterface* async() && { - DCHECK(async_); - return std::exchange(async_, nullptr); - } - - GrpcCallOptions&& options() && { return std::move(options_); } - - private: - raw_ptr stub_; - raw_ptr async_; - Request request_; - GrpcCallOptions options_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_CALL_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_call_options.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call_options.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_call_options.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call_options.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/grpc/grpc_call_options.h" - -#include - -#include - -#include "base/check_op.h" -#include "base/logging.h" - -namespace cast { -namespace utils { - -namespace { - -// Default gRPC call deadline. -static const auto kDefaultCallDeadline = 60 * 1000; - -} // namespace - -GrpcCallOptions::GrpcCallOptions() : deadline_ms_(kDefaultCallDeadline) {} - -GrpcCallOptions::~GrpcCallOptions() = default; - -void GrpcCallOptions::SetDeadline(int64_t deadline_ms) { - DCHECK_GE(deadline_ms, 0); - deadline_ms_ = std::move(deadline_ms); -} - -void GrpcCallOptions::ApplyOptionsToContext( - grpc::ClientContext* context) const { - if (deadline_ms_ == 0 || - deadline_ms_ == std::numeric_limits::max()) { - return; - } - - context->set_deadline(ToGprTimespec(deadline_ms_)); - DVLOG(1) << "Call deadline is set to " << deadline_ms_; -} - -// static -gpr_timespec GrpcCallOptions::ToGprTimespec(int64_t duration_ms) { - DCHECK_GE(duration_ms, 0); - if (duration_ms == 0 || duration_ms == std::numeric_limits::max()) { - return gpr_inf_future(GPR_CLOCK_MONOTONIC); - } - - gpr_timespec span; - span.tv_sec = duration_ms / 1000; - span.tv_nsec = static_cast((duration_ms % 1000) * 1000 * 1000); - span.clock_type = GPR_TIMESPAN; - return gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), span); -} - -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_call_options.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call_options.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_call_options.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_call_options.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_CALL_OPTIONS_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_CALL_OPTIONS_H_ - -#include - -namespace grpc { -class ClientContext; -} - -namespace cast { -namespace utils { - -// Various options that control gRPC ClientContext behavior. -class GrpcCallOptions { - public: - GrpcCallOptions(); - ~GrpcCallOptions(); - - // Sets the client call deadline. - void SetDeadline(int64_t deadline_ms); - - // Applies the options to a give grpc client |context|. - void ApplyOptionsToContext(grpc::ClientContext* context) const; - - // Converts an int64_t to gRPC's gpr_timespec. - static gpr_timespec ToGprTimespec(int64_t duration_ms); - - private: - // gRPC read request deadline. - int64_t deadline_ms_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_CALL_OPTIONS_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_client_reactor.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_client_reactor.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_client_reactor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_client_reactor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_CLIENT_REACTOR_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_CLIENT_REACTOR_H_ - -#include - -#include - -#include "base/task/sequenced_task_runner.h" -#include "chromecast/cast_core/grpc/grpc_call_options.h" - -namespace cast { -namespace utils { - -// A base class for all gRPC client reactor implementations. -// -// The gRPC Callback stack is built on the Reactor concept which serves as the -// observer/callback mechanism for notifications on received responses. The -// instance of the Reactor always belongs to the gRPC framework. It is created -// in GrpcCall implementation and deleted in Reactor::OnDone callback from gRPC. -// -// |TRequest| is the gRPC API request type. -// |TUnderlyingReactor| is the type of the gRPC framework reactor that is added -// as a base class for GrpcClientReactor and used in implementation. -template -class GrpcClientReactor : public TUnderlyingReactor { - public: - ~GrpcClientReactor() override = default; - - // Copy and move are deleted. - GrpcClientReactor(const GrpcClientReactor&) = delete; - GrpcClientReactor(GrpcClientReactor&&) = delete; - GrpcClientReactor& operator=(const GrpcClientReactor&) = delete; - GrpcClientReactor& operator=(GrpcClientReactor&&) = delete; - - // Returns the gRPC client context. - grpc::ClientContext* context() { return &context_; } - - // Returns the original request. - const TRequest* request() const { return &request_; } - - // Initiates the gRPC client call. - virtual void Start() { options_.ApplyOptionsToContext(&context_); } - - protected: - explicit GrpcClientReactor(TRequest request, GrpcCallOptions options) - : request_(std::move(request)), - options_(std::move(options)), - task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) {} - - void DeleteThis() { - // Client reactors must be deleted asynchronously to avoid a crash in debug - // builds caused absl::Mutex assert on "unlocking a mutex after dtor" - // triggered by the ClientContext mutex in TryCancel call. - task_runner_->DeleteSoon(FROM_HERE, this); - } - - private: - grpc::ClientContext context_; - TRequest request_; - GrpcCallOptions options_; - scoped_refptr task_runner_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_CLIENT_REACTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_handler.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_handler.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_handler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_handler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/grpc/grpc_handler.h" - -#include "base/check.h" - -namespace cast { -namespace utils { - -GrpcHandler::GrpcHandler(ServerReactorTracker* server_reactor_tracker) - : server_reactor_tracker_(server_reactor_tracker) { - DCHECK(server_reactor_tracker_); -} - -GrpcHandler::~GrpcHandler() = default; - -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_handler.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_handler.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_HANDLER_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_HANDLER_H_ - -#include -#include - -#include "base/memory/raw_ptr.h" -#include "chromecast/cast_core/grpc/server_reactor_tracker.h" - -namespace cast { -namespace utils { - -// A base class for all gRPC server reactor implementations. -// -// This class provides a mechanism to track currently active reactors. The data -// is used during server shutdown to notify about pending non-finished reactors. -class GrpcHandler { - public: - explicit GrpcHandler(ServerReactorTracker* server_reactor_tracker); - virtual ~GrpcHandler(); - - // Returns a tracker of all the reactors of the implemented handler. - ServerReactorTracker* server_reactor_tracker() { - return server_reactor_tracker_; - } - - // Creates a reactor used to process specific gRPC API. - virtual grpc::ServerGenericBidiReactor* CreateReactor( - grpc::CallbackServerContext* context) = 0; - - private: - raw_ptr server_reactor_tracker_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/grpc/grpc_server.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "base/task/thread_pool.h" -#include "chromecast/cast_core/grpc/grpc_call_options.h" - -namespace cast { -namespace utils { - -namespace { - -static const auto kDefaultServerStopTimeoutMs = 100; - -// Stops gRPC server. -static void StopGrpcServer( - std::unique_ptr server, - std::unique_ptr server_reactor_tracker, - int64_t timeout_ms, - base::OnceClosure server_stopped_callback) { - LOG(INFO) << "Shutting down gRPC server"; - - // The gRPC Reactors are owned by the gRPC framework and are 'pending' - // unless Reactor::Finish or similar (StartWriteAndFinish) API is called. - // This Shutdown call makes sure all the finished reactors are deleted via - // Reactor::OnDone API. As the timeout is reached, all pending reactors are - // cancelled via Reactor::OnCancel API. Hence, after Shutdow, all pending - // reactors can be treated as cancelled and manually destroyed. - auto gpr_timeout = GrpcCallOptions::ToGprTimespec(timeout_ms); - server->Shutdown(gpr_timeout); - - // As mentioned above, all the pending reactors are now cancelled and must - // be destroyed by the ServerReactorTracker. - server_reactor_tracker.reset(); - - // Finish server shutdown. - server->Wait(); - server.reset(); - LOG(INFO) << "gRPC server is shut down"; - - std::move(server_stopped_callback).Run(); -} - -} // namespace - -GrpcServer::GrpcServer() - : server_reactor_tracker_(std::make_unique()) {} - -GrpcServer::~GrpcServer() { - DCHECK(!server_) << "gRPC server must be explicitly stopped"; -} - -grpc::Status GrpcServer::Start(const std::string& endpoint) { - DCHECK(!server_) << "Server is already running"; - DCHECK(server_reactor_tracker_) << "Server was alreadys shutdown"; - - server_ = grpc::ServerBuilder() - .AddListeningPort(endpoint, grpc::InsecureServerCredentials()) - .RegisterCallbackGenericService(this) - .BuildAndStart(); - if (!server_) { - return grpc::Status(grpc::StatusCode::INTERNAL, - "can't start gRPC server on " + endpoint); - } - LOG(INFO) << "Grpc server started: " << endpoint; - return grpc::Status::OK; -} - -void GrpcServer::Stop() { - if (!server_) { - LOG(WARNING) << "Grpc server was already stopped"; - return; - } - - StopGrpcServer(std::move(server_), std::move(server_reactor_tracker_), - kDefaultServerStopTimeoutMs, base::BindOnce([]() {})); -} - -void GrpcServer::Stop(int64_t timeout_ms, - base::OnceClosure server_stopped_callback) { - if (!server_) { - LOG(WARNING) << "Grpc server was already stopped"; - std::move(server_stopped_callback).Run(); - return; - } - - // Synchronous requests will block gRPC shutdown unless we post shutdown on - // a different thread. - base::ThreadPool::PostTask( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&StopGrpcServer, std::move(server_), - std::move(server_reactor_tracker_), timeout_ms, - std::move(server_stopped_callback))); -} - -grpc::ServerGenericBidiReactor* GrpcServer::CreateReactor( - grpc::GenericCallbackServerContext* ctx) { - auto iter = registered_handlers_.find(ctx->method()); - if (iter != registered_handlers_.end()) { - DVLOG(1) << "Found a reactor for " << ctx->method(); - return iter->second->CreateReactor(ctx); - } - LOG(WARNING) << "No reactor was specified for " << ctx->method() - << " - falling back to a default unimplemented reactor"; - return grpc::CallbackGenericService::CreateReactor(ctx); -} - -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,128 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_H_ - -#include - -#include - -#include "base/functional/callback.h" -#include "base/logging.h" -#include "chromecast/cast_core/grpc/grpc_handler.h" -#include "chromecast/cast_core/grpc/server_reactor_tracker.h" - -namespace cast { -namespace utils { - -// Generic gRPC server that allows seamless registration of API handlers by -// specifying the API with GrpcHandler-based classes. The GrpcServer implements -// grpc::CallbackGenericService and is registered with the ServerBuilder as -// such. The implications are following: -// - All gRPC requests arrive to server. -// - The APIs are distiguished by the full RPC name (ie //method). -// - The user must register the full rpc name (as a string) with specific -// handler. -// -// An example usage that creates a server that combines below two services in -// one: -// PROTO: -// service Foo { -// rpc DoOneThing(OneThingRequest) returns (OneThingResponse); -// } -// -// service Bar { -// rpc DoAnotherThing(AnotherThingRequest) returns (AnotherThingResponse); -// } -// -// C++: -// // Create a CastCoreService.Register handler. -// constexpr const char DoOneThingMethod[] = "DoOneThing"; -// using DoOneThingHandler = -// GrpcUnaryHandler; -// -// constexpr const char DoAnotherThingMethod[] = "DoAnotherThing"; -// using DoAnotherThingHandler = -// GrpcUnaryHandler; -// -// server.SetHandler( -// base::BindOnce([](OneThingRequest request, -// DoOneThing::Reactor* reactor) { -// reactor->Write(OneThingResponse()); -// })); -// server.SetHandler( -// base::BindOnce([](AnotherThingRequest request, -// DoAnotherThing::Reactor* reactor) { -// reactor->Write(AnotherThingResponse()); -// })); -// -// // Start the server. -// server.Start("[::]:12345"); -// -// // Stop the server. -// server.Stop(); -// -class GrpcServer : public grpc::CallbackGenericService { - public: - GrpcServer(); - ~GrpcServer() override; - - // Sets the request callback for an RPC defined by |Handler| type. - // NOTE: Every handler must check that the GrpcServer associated with it is up - // and running before accessing the |reactor| object. - template - void SetHandler(typename THandler::OnRequestCallback on_request_callback) { - // The full rpc name is //method, ie - // /cast.core.CastCoreService/RegisterRuntime. - DCHECK(registered_handlers_.find(THandler::rpc_name()) == - registered_handlers_.end()) - << "Duplicate handler: " << THandler::rpc_name(); - registered_handlers_.emplace( - THandler::rpc_name(), - std::make_unique(std::move(on_request_callback), - server_reactor_tracker_.get())); - DVLOG(1) << "Request handler is set for " << THandler::rpc_name(); - } - - // Starts the gRPC server. - ABSL_MUST_USE_RESULT grpc::Status Start(const std::string& endpoint); - - // Stops the gRPC server synchronously. May block indefinitely if there's a - // non-finished pending reactor created by the gRPC framework. - // NOTE: This framework guarantees thread safety iff Stop and handler - // callbacks are called in the same sequence! - void Stop(); - - // Stops the gRPC server and calls the callback. The process will crash in - // case the |timeout| is reached as such case clearly points to a bug in - // reactor handling. - // NOTE: This framework guarantees thread safety iff Stop and handler - // callbacks are called in the same sequence! - void Stop(int64_t timeout_ms, base::OnceClosure server_stopped_callback); - - size_t active_reactor_count() const { - return server_reactor_tracker_->active_reactor_count(); - } - - private: - // Implements grpc::CallbackGenericService APIs. - // Creates a reactor for a given rpc method from the |ctx|. If a handler is - // registered for that method, it's reactor will be created. Otherwise a - // default (unimplemented) reactor will be returned. - grpc::ServerGenericBidiReactor* CreateReactor( - grpc::GenericCallbackServerContext* ctx) override; - - std::unordered_map> - registered_handlers_; - std::unique_ptr server_; - std::unique_ptr server_reactor_tracker_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_reactor.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_reactor.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_reactor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_reactor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,155 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_REACTOR_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_REACTOR_H_ - -#include -#include - -#include - -#include "base/check_op.h" -#include "base/logging.h" -#include "base/memory/raw_ptr.h" -#include "chromecast/cast_core/grpc/grpc_status_or.h" - -namespace cast { -namespace utils { - -// A base class for gRPC server reactors. -template -class GrpcServerReactor : public grpc::ServerGenericBidiReactor { - public: - using RequestType = TRequest; - - GrpcServerReactor(const std::string& name, - grpc::CallbackServerContext* context) - : name_(name), context_(context) {} - ~GrpcServerReactor() override = default; - - // Copy and move are deleted. - GrpcServerReactor(const GrpcServerReactor&) = delete; - GrpcServerReactor(GrpcServerReactor&&) = delete; - GrpcServerReactor& operator=(const GrpcServerReactor&) = delete; - GrpcServerReactor& operator=(GrpcServerReactor&&) = delete; - - // Flags that the reactor is done (finished or cancelled). - virtual bool is_done() = 0; - - // Set of overloaded methods to write responses or status to the clients. - // Writes a status. No writes can be done after this call. - void Write(const grpc::Status& status) { FinishWriting(nullptr, status); } - - // Writes a defined response. - void Write(TResponse response = TResponse()) { - if (response_byte_buffer_) { - LOG(ERROR) << "Writing is already in progress or reactor is cancelled"; - OnWriteDone(false); - return; - } - DVLOG(1) << "Writing response: " << name(); - response_byte_buffer_.emplace(); - Serialize(response, *response_byte_buffer_); - // The state machine expects the implementer to write the buffer which will - // trigger OnWriteDone and reset it back to allow more writes. - WriteResponse(&*response_byte_buffer_); - } - - // Returns reactor RPC name. - const std::string& name() const { return name_; } - - protected: - // Starts reading a request. - void ReadRequest() { - if (request_byte_buffer_) { - LOG(ERROR) << "Reading is already in progress: " << name(); - OnReadDone(false); - return; - } - DVLOG(1) << "Reading request: " << name(); - request_byte_buffer_.emplace(); - StartRead(&*request_byte_buffer_); - } - - // The following APIs must be implemented by a certain reactor, and allow - // proper state tracking while hiding the generic request\response processing. - - // Called when response is written on the wire. An error is set if writes are - // terminated. - virtual void WriteResponse(const grpc::ByteBuffer* buffer) = 0; - - // Called to actually write the status on the wire. - virtual void FinishWriting(const grpc::ByteBuffer* buffer, - const grpc::Status& status) = 0; - - // Called to actually write the response serialized into a buffer on the wire. - virtual void OnResponseDone(const grpc::Status& status) = 0; - - // Called when request was read and deserialized. An error is set if reads are - // terminated. - virtual void OnRequestDone(GrpcStatusOr request) = 0; - - // Implements grpc::ServerGenericBidiReactor APIs. - void OnReadDone(bool ok) override { - static const grpc::Status kReadsFailedError(grpc::StatusCode::ABORTED, - "Reads failed"); - DVLOG(1) << "Reads done: " << name() << ", ok=" << ok; - if (!ok) { - DVLOG(1) << "Reads failed: " << name(); - OnRequestDone(kReadsFailedError); - return; - } - - auto request = Deserialize(*request_byte_buffer_); - request_byte_buffer_.reset(); - OnRequestDone(std::move(request)); - } - - void OnWriteDone(bool ok) override { - static const grpc::Status kWritesFailedError(grpc::StatusCode::ABORTED, - "Writes failed"); - DVLOG(1) << "Writes done: " << name() << ", ok=" << ok; - response_byte_buffer_.reset(); - if (!ok) { - DVLOG(1) << "Writes failed: " << name(); - OnResponseDone(kWritesFailedError); - return; - } - - OnResponseDone(grpc::Status::OK); - } - - void OnDone() override { - DVLOG(1) << "Reactor done: " << name(); - delete this; - } - - private: - template - void Serialize(T t, grpc::ByteBuffer& buffer) { - bool own; - auto status = grpc::SerializationTraits::Serialize(t, &buffer, &own); - DCHECK(status.ok()) << "Failed to serialize"; - } - - template - T Deserialize(grpc::ByteBuffer& buffer) { - T t; - auto status = grpc::SerializationTraits::Deserialize(&buffer, &t); - DCHECK(status.ok()) << "Failed to serialize"; - return t; - } - - const std::string name_; - raw_ptr context_; - - std::optional request_byte_buffer_; - std::optional response_byte_buffer_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_REACTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_streaming_call.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_call.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_streaming_call.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_call.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,134 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_STREAMING_CALL_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_STREAMING_CALL_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/logging.h" -#include "base/memory/raw_ptr.h" -#include "chromecast/cast_core/grpc/grpc_call.h" -#include "chromecast/cast_core/grpc/grpc_client_reactor.h" -#include "chromecast/cast_core/grpc/grpc_status_or.h" - -namespace cast { -namespace utils { - -// Typedef for the server streaming method generated by gRPC compiler. -template -using GrpcServerStreamingMethod = - void (TAsyncInterface::*)(grpc::ClientContext*, - const TRequest*, - grpc::ClientReadReactor*); - -// A GrpcCall implementation for unary gRPC calls specialized by the -// |AsyncMethodPtr| function pointer. -// TGrpcStub - gRPC service stub type. -// TRequest - gRPC request type for a method in the stub. -// TResponse - gRPC response type for a method in the stub. -// AsyncMethodPtr - pointer to a method in the stub that handles a streaming -// call. -template AsyncMethodPtr> -class GrpcServerStreamingCall : public GrpcCall { - public: - using Base = GrpcCall; - using Base::async; - using Base::GrpcCall; - using Base::request; - using Base::sync; - using typename Base::AsyncInterface; - using typename Base::Context; - using typename Base::Request; - - using Response = TResponse; - using ResponseCallback = - base::RepeatingCallback, bool /*done*/)>; - - // Invokes a gRPC call asynchronously. The method follows moves semantics: - // std::move(call).InvokeAsync(...); - // The returned Context is valid only during duration of the call and can be - // used to cancel it. - Context InvokeAsync(ResponseCallback response_callback) && { - // gRPC doesn't support setting a deadline for individual streaming - // requests\responses. Hence, the zero timeout is set to allow for - // inifinitely long streaming connections. - Base::SetDeadline(0); - auto reactor = - new Reactor(std::move(*this).async(), std::move(*this).request(), - std::move(*this).options(), std::move(response_callback)); - reactor->Start(); - return Context(reactor->context()); - } - - private: - using ReactorBase = - GrpcClientReactor>; - - class Reactor final : public ReactorBase { - public: - using ReactorBase::context; - using ReactorBase::request; - - Reactor(AsyncInterface* async_stub, - Request request, - GrpcCallOptions options, - ResponseCallback response_callback) - : ReactorBase(std::move(request), std::move(options)), - async_interface_(async_stub), - response_callback_(std::move(response_callback)) {} - - void Start() override { - ReactorBase::Start(); - (async_interface_->*AsyncMethodPtr)(context(), request(), this); - grpc::ClientReadReactor::StartRead(&response_); - grpc::ClientReadReactor::StartCall(); - } - - private: - // Implements grpc::ClientReadReactor APIs. - void OnReadDone(bool ok) override { - DVLOG(1) << "Reads done: ok=" << ok; - if (!ok) { - return; - } - - response_callback_.Run(std::move(response_), false); - Reactor::StartRead(&response_); - } - - // The method is always called on completion of all operations associated - // with this call, and deletes itself on exit. - void OnDone(const grpc::Status& status) override { - DVLOG(1) << "Request done: " << GrpcStatusToString(status); - if (status.ok()) { - response_callback_.Run(Response(), true); - } else { - response_callback_.Run(status, true); - } - ReactorBase::DeleteThis(); - } - - using AsyncStubCall = - base::OnceCallback*)>; - - raw_ptr async_interface_; - ResponseCallback response_callback_; - Response response_; - }; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_STREAMING_CALL_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_streaming_handler.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_handler.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_streaming_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,142 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_STREAMING_HANDLER_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_STREAMING_HANDLER_H_ - -#include - -#include "base/functional/callback.h" -#include "base/logging.h" -#include "chromecast/cast_core/grpc/cancellable_reactor.h" -#include "chromecast/cast_core/grpc/grpc_server.h" -#include "chromecast/cast_core/grpc/grpc_server_reactor.h" -#include "chromecast/cast_core/grpc/grpc_status_or.h" -#include "chromecast/cast_core/grpc/server_reactor_tracker.h" -#include "chromecast/cast_core/grpc/trackable_reactor.h" - -namespace cast { -namespace utils { - -// A generic handler for server streaming unary, ie request followed by multiple -// responses from server, gRPC APIs. Can only be used with rpc that have the -// following signature: -// rpc Foo(Request) returns (stream Response) -// -// - TService is the gRPC service type. -// - TRequest is the service request type. -// - TResponse is the service response type. -// - MethodName is the rpc method as a string. -// -// This class is not thread-safe. Appropriate means have to be added by the -// users to guarantee thread-safety (ie task runners, mutexes etc). -template -class GrpcServerStreamingHandler : public GrpcHandler { - public: - using ReactorBase = GrpcServerReactor; - - // Reactor implementation of server streaming handler. - class Reactor : public ReactorBase { - public: - using ReactorBase::name; - using ReactorBase::Write; - - using OnRequestCallback = base::RepeatingCallback; - using WritesAvailableCallback = - base::RepeatingCallback; - - template - explicit Reactor(OnRequestCallback on_request_callback, Args&&... args) - : ReactorBase(std::forward(args)...), - on_request_callback_(std::move(on_request_callback)) { - ReadRequest(); - } - - // Sets the callback that is called when writes are available. - void SetWritesAvailableCallback( - WritesAvailableCallback writes_available_callback) { - writes_available_callback_ = std::move(writes_available_callback); - } - - // Writes a packet and sets the writes availability callback. - void Write(TResponse response, - WritesAvailableCallback writes_available_callback) { - writes_available_callback_ = std::move(writes_available_callback); - ReactorBase::Write(std::move(response)); - } - - protected: - using ReactorBase::Finish; - using ReactorBase::ReadRequest; - using ReactorBase::StartRead; - using ReactorBase::StartWrite; - - // Implements GrpcServerReactor APIs. - void WriteResponse(const grpc::ByteBuffer* buffer) override { - DCHECK(buffer); - StartWrite(buffer, grpc::WriteOptions()); - } - - void FinishWriting(const grpc::ByteBuffer* buffer, - const grpc::Status& status) override { - DVLOG(1) << "Reactor finished: " << name() - << ", status=" << GrpcStatusToString(status); - DCHECK(!buffer) - << "Server streaming call can only be finished with a status"; - if (!status.ok() && writes_available_callback_) { - // A signal that the caller has aborted the streaming session. - writes_available_callback_.Run(status, nullptr); - } - Finish(status); - } - - void OnResponseDone(const grpc::Status& status) override { - DCHECK(writes_available_callback_) - << "Writes available callback must be set"; - writes_available_callback_.Run(status, status.ok() ? this : nullptr); - } - - void OnRequestDone(GrpcStatusOr request) override { - if (!request.ok()) { - FinishWriting(nullptr, request.status()); - return; - } - - on_request_callback_.Run(std::move(*request), this); - } - - OnRequestCallback on_request_callback_; - WritesAvailableCallback writes_available_callback_; - }; - - using OnRequestCallback = typename Reactor::OnRequestCallback; - using WritesAvailableCallback = typename Reactor::WritesAvailableCallback; - - GrpcServerStreamingHandler(OnRequestCallback on_request_callback, - ServerReactorTracker* server_reactor_tracker) - : GrpcHandler(server_reactor_tracker), - on_request_callback_(std::move(on_request_callback)) {} - - static std::string rpc_name() { - return std::string("/") + TService::service_full_name() + "/" + MethodName; - } - - private: - // Implements GrpcHandler APIs. - grpc::ServerGenericBidiReactor* CreateReactor( - grpc::CallbackServerContext* context) override { - return new CancellableReactor>( - server_reactor_tracker(), on_request_callback_, rpc_name(), context); - } - - OnRequestCallback on_request_callback_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_SERVER_STREAMING_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_streaming_test.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_test.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_streaming_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_streaming_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,290 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/files/scoped_temp_dir.h" -#include "base/rand_util.h" -#include "base/strings/stringprintf.h" -#include "base/synchronization/waitable_event.h" -#include "base/task/bind_post_task.h" -#include "base/task/thread_pool.h" -#include "base/test/bind.h" -#include "base/test/task_environment.h" -#include "base/threading/thread_restrictions.h" -#include "base/time/time.h" -#include "base/uuid.h" -#include "chromecast/cast_core/grpc/grpc_server.h" -#include "chromecast/cast_core/grpc/status_matchers.h" -#include "chromecast/cast_core/grpc/test_service.castcore.pb.h" -#include "chromecast/cast_core/grpc/test_utils.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace cast { -namespace utils { -namespace { - -using ::cast::test::StatusIs; -using ::testing::IsNull; - -const auto kEventTimeout = base::Seconds(1); -const auto kServerStopTimeout = base::Seconds(1); - -class GrpcServerStreamingTest : public ::testing::Test { - protected: - GrpcServerStreamingTest() { - CHECK(temp_dir_.CreateUniqueTempDir()); - endpoint_ = - "unix:" + - temp_dir_.GetPath() - .AppendASCII( - "cast-uds-" + - base::Uuid::GenerateRandomV4().AsLowercaseString().substr(24)) - .value(); - } - - base::test::TaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; - base::ScopedTempDir temp_dir_; - std::string endpoint_; -}; - -TEST_F(GrpcServerStreamingTest, ServerStreamingCallSucceeds) { - const int kMaxResponseCount = base::RandInt(10, 300); - int server_response_count = 0; - auto writes_available_callback = base::BindLambdaForTesting( - [&](grpc::Status status, - ServerStreamingServiceHandler::StreamingCall::Reactor* reactor) { - CU_CHECK_OK(status); - if (server_response_count < kMaxResponseCount) { - TestResponse response; - response.set_bar( - base::StringPrintf("test_bar%d", ++server_response_count)); - reactor->Write(std::move(response)); - } else { - LOG(INFO) << "Writing finished"; - reactor->Write(grpc::Status::OK); - } - }); - auto call_handler = base::BindLambdaForTesting( - [&](TestRequest request, - ServerStreamingServiceHandler::StreamingCall::Reactor* reactor) { - EXPECT_EQ(request.foo(), "test_foo"); - - reactor->SetWritesAvailableCallback( - std::move(writes_available_callback)); - - TestResponse response; - response.set_bar( - base::StringPrintf("test_bar%d", ++server_response_count)); - reactor->Write(std::move(response)); - }); - - GrpcServer server; - server.SetHandler( - std::move(call_handler)); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - ServerStreamingServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - int call_count = 0; - base::WaitableEvent response_received_event; - std::move(call).InvokeAsync(base::BindLambdaForTesting( - [&](GrpcStatusOr response, bool done) { - CU_CHECK_OK(response); - if (done) { - response_received_event.Signal(); - } else { - EXPECT_EQ(response->bar(), - base::StringPrintf("test_bar%d", ++call_count)); - } - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - ASSERT_EQ(call_count, kMaxResponseCount); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -TEST_F(GrpcServerStreamingTest, ServerStreamingCallFailsRightAway) { - GrpcServer server; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest request, - ServerStreamingServiceHandler::StreamingCall::Reactor* reactor) { - EXPECT_EQ(request.foo(), "test_foo"); - reactor->Write( - grpc::Status(grpc::StatusCode::NOT_FOUND, "not found")); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - ServerStreamingServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - base::WaitableEvent response_received_event; - std::move(call).InvokeAsync(base::BindLambdaForTesting( - [&](GrpcStatusOr response, bool done) { - CHECK(done); - ASSERT_THAT(response.status(), - StatusIs(grpc::StatusCode::NOT_FOUND, "not found")); - response_received_event.Signal(); - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -TEST_F(GrpcServerStreamingTest, ServerStreamingCallCancelledIfServerIsStopped) { - GrpcServer server; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest request, - ServerStreamingServiceHandler::StreamingCall::Reactor* reactor) { - reactor->Write(grpc::Status::OK); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - ServerStreamingServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - base::WaitableEvent response_received_event{ - base::WaitableEvent::ResetPolicy::AUTOMATIC}; - std::move(call).InvokeAsync(base::BindLambdaForTesting( - [&](GrpcStatusOr response, bool done) { - CU_ASSERT_OK(response); - response_received_event.Signal(); - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - test::StopGrpcServer(server, kServerStopTimeout); - - auto call1 = stub.CreateCall(); - std::move(call1).InvokeAsync(base::BindLambdaForTesting( - [&](GrpcStatusOr response, bool done) { - ASSERT_THAT(response, StatusIs(grpc::StatusCode::UNAVAILABLE)); - response_received_event.Signal(); - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); -} - -TEST_F(GrpcServerStreamingTest, ServerStreamingCallIsCancelledByClient) { - base::WaitableEvent server_aborted_event; - auto writes_available_callback = base::BindLambdaForTesting( - [&](grpc::Status status, - ServerStreamingServiceHandler::StreamingCall::Reactor* reactor) { - // The write callback can be called at any point in time with - // ABORTED error, so ignore the success call. - if (status.ok()) { - return; - } - ASSERT_THAT(status, StatusIs(grpc::StatusCode::ABORTED)); - ASSERT_THAT(reactor, IsNull()); - server_aborted_event.Signal(); - }); - auto call_handler = base::BindLambdaForTesting( - [&](TestRequest request, - ServerStreamingServiceHandler::StreamingCall::Reactor* reactor) { - EXPECT_EQ(request.foo(), "test_foo"); - reactor->SetWritesAvailableCallback( - std::move(writes_available_callback)); - TestResponse response; - response.set_bar("test_bar"); - reactor->Write(std::move(response)); - }); - - GrpcServer server; - server.SetHandler( - std::move(call_handler)); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - size_t response_count = 0; - base::WaitableEvent response_received_event{ - base::WaitableEvent::ResetPolicy::AUTOMATIC}; - ServerStreamingServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - auto context = std::move(call).InvokeAsync(base::BindLambdaForTesting( - [&](GrpcStatusOr response, bool done) { - // Only one success response should be received. - ++response_count; - if (response_count == 1) { - CU_CHECK_OK(response); - EXPECT_EQ(response->bar(), "test_bar"); - response_received_event.Signal(); - } else { - EXPECT_EQ(response_count, 2u); - ASSERT_THAT(response, StatusIs(grpc::StatusCode::CANCELLED)); - response_received_event.Signal(); - } - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - // Cancel the client call and wait for server and client to get the - // notification. - context.Cancel(); - ASSERT_TRUE(server_aborted_event.TimedWait(kEventTimeout)); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - task_environment_.RunUntilIdle(); - - test::StopGrpcServer(server, kServerStopTimeout); - task_environment_.RunUntilIdle(); -} - -TEST_F(GrpcServerStreamingTest, - ServerStreamingCallIsCancelledByClientInActiveReactor) { - GrpcServer server; - - base::WaitableEvent server_request_received; - ServerStreamingServiceHandler::StreamingCall::Reactor* cancelled_reactor; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest request, - ServerStreamingServiceHandler::StreamingCall::Reactor* reactor) { - cancelled_reactor = reactor; - server_request_received.Signal(); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - base::WaitableEvent response_received_event; - ServerStreamingServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - auto context = std::move(call).InvokeAsync(base::BindLambdaForTesting( - [&](GrpcStatusOr response, bool done) { - ASSERT_THAT(response, StatusIs(grpc::StatusCode::CANCELLED)); - response_received_event.Signal(); - })); - - // Wait for server to receive the request. - ASSERT_TRUE(server_request_received.TimedWait(kEventTimeout)); - - // Cancel the client call and wait for server and client to get the - // notification. - context.Cancel(); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - // Try to write a response with the reactor, and expect the ABORTED error. - base::WaitableEvent reactor_aborted; - cancelled_reactor->SetWritesAvailableCallback(base::BindLambdaForTesting( - [&](grpc::Status status, - ServerStreamingServiceHandler::StreamingCall::Reactor* reactor) { - if (reactor) { - // Timing between threds may result in server reactor still receiving - // the empty TestResponse from below. Ignore it and continue waiting - // for the null reactor. - return; - } - ASSERT_THAT(status, StatusIs(grpc::StatusCode::ABORTED)); - reactor_aborted.Signal(); - })); - // The handler might have already been called by gRPC framework, so write an - // empty message to release its deferred state. - cancelled_reactor->Write(TestResponse()); - - ASSERT_TRUE(reactor_aborted.TimedWait(kEventTimeout)); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -} // namespace -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_test.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_test.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_server_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_server_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#include "chromecast/cast_core/grpc/grpc_server.h" - -#include "base/test/bind.h" -#include "base/test/task_environment.h" -#include "base/uuid.h" -#include "chromecast/cast_core/grpc/status_matchers.h" -#include "chromecast/cast_core/grpc/test_service.castcore.pb.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace cast { -namespace utils { -namespace { -using ::cast::test::StatusIs; - -class GrpcServerTest : public ::testing::Test { - protected: - GrpcServerTest() = default; - - const std::string endpoint_ = - "unix-abstract:cast-uds-" + - base::Uuid::GenerateRandomV4().AsLowercaseString(); - base::test::TaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; -}; - -TEST_F(GrpcServerTest, FailedStartReturnsError) { - GrpcServer server1; - server1.SetHandler( - base::BindLambdaForTesting( - [](TestRequest, SimpleServiceHandler::SimpleCall::Reactor* reactor) { - reactor->Write(TestResponse()); - })); - ASSERT_THAT(server1.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - // Verify server has started. - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - auto response_or = std::move(call).Invoke(); - CU_ASSERT_OK(response_or); - - // Verify that 2nd server on the same endpoint cannot be created. - GrpcServer server2; - server2.SetHandler( - base::BindLambdaForTesting( - [](TestRequest, SimpleServiceHandler::SimpleCall::Reactor*) {})); - EXPECT_THAT(server2.Start(endpoint_), StatusIs(grpc::StatusCode::INTERNAL)); - - server1.Stop(); -} - -} // namespace - -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_status_or.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_status_or.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/grpc/grpc_status_or.h" - -namespace cast { -namespace utils { - -namespace { - -// Converts gRPC StatusCode to string. -static std::string GrpcStatusCodeToString(grpc::StatusCode code) { - switch (code) { - case grpc::StatusCode::OK: - return "OK"; - case grpc::StatusCode::CANCELLED: - return "CANCELLED"; - case grpc::StatusCode::UNKNOWN: - return "UNKNOWN"; - case grpc::StatusCode::INVALID_ARGUMENT: - return "INVALID_ARGUMENT"; - case grpc::StatusCode::DEADLINE_EXCEEDED: - return "DEADLINE_EXCEEDED"; - case grpc::StatusCode::NOT_FOUND: - return "NOT_FOUND"; - case grpc::StatusCode::ALREADY_EXISTS: - return "ALREADY_EXISTS"; - case grpc::StatusCode::PERMISSION_DENIED: - return "PERMISSION_DENIED"; - case grpc::StatusCode::UNAUTHENTICATED: - return "UNAUTHENTICATED"; - case grpc::StatusCode::RESOURCE_EXHAUSTED: - return "RESOURCE_EXHAUSTED"; - case grpc::StatusCode::FAILED_PRECONDITION: - return "FAILED_PRECONDITION"; - case grpc::StatusCode::ABORTED: - return "ABORTED"; - case grpc::StatusCode::OUT_OF_RANGE: - return "OUT_OF_RANGE"; - case grpc::StatusCode::UNIMPLEMENTED: - return "UNIMPLEMENTED"; - case grpc::StatusCode::INTERNAL: - return "INTERNAL"; - case grpc::StatusCode::UNAVAILABLE: - return "UNAVAILABLE"; - case grpc::StatusCode::DATA_LOSS: - return "DATA_LOSS"; - default: - return ""; - } -} - -} // namespace - -// static -std::string GrpcStatusToString(const grpc::Status& status) { - return "[status=" + GrpcStatusCodeToString(status.error_code()) + ": " + - status.error_message() + "]"; -} - -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_status_or.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_status_or.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,127 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_STATUS_OR_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_STATUS_OR_H_ - -#include - -#include -#include -#include - -#include "base/check.h" - -namespace cast { -namespace utils { - -// Converts grpc::Status to a string message. -std::string GrpcStatusToString(const grpc::Status& status); - -// Holds a value of type T with grpc::Status::OK or an error grpc::Status. -template ::value, T*>::type = - nullptr> -class GrpcStatusOr { - public: - GrpcStatusOr() : status_(grpc::StatusCode::UNKNOWN, "") {} - - // Constructs GrpcStatusOr from an error |status_code|. - GrpcStatusOr(grpc::StatusCode status_code) // NOLINT - : GrpcStatusOr(status_code, "") {} - - // Constructs GrpcStatusOr from an error |status_code| and |error_message|. - GrpcStatusOr(grpc::StatusCode status_code, const std::string& error_message) - : status_(status_code, error_message) { - DCHECK(!status_.ok()); - } - - // Constructs GrpcStatusOr from an error |status|. - GrpcStatusOr(grpc::Status status) // NOLINT - : status_(std::move(status)) { - DCHECK(!status_.ok()); - } - - // Constructs GrpcStatusOr from the |data|. Status code is set to OK. - GrpcStatusOr(const T& data) // NOLINT - : status_(grpc::Status::OK), data_(data) {} - - // Constructs GrpcStatusOr from the |data|. Status code is set to OK. - GrpcStatusOr(T&& data) // NOLINT - : status_(grpc::Status::OK), data_(std::move(data)) {} - - // Constructs GrpcStatusOr from the |data| of type U that is possible to - // convert to type |T|. For example, std::unique_ptr converted to - // std::unique_ptr. Status code is set to OK. - template ::value, - U>::type* = nullptr> - GrpcStatusOr(U&& data) // NOLINT - : status_(grpc::Status::OK), data_(std::forward(data)) {} - - GrpcStatusOr(GrpcStatusOr&&) = default; - GrpcStatusOr& operator=(GrpcStatusOr&&) = default; - GrpcStatusOr(const GrpcStatusOr&) = default; - GrpcStatusOr& operator=(const GrpcStatusOr&) = default; - ~GrpcStatusOr() = default; - - // Returns if status is OK. - bool ok() const { return status_.ok(); } - - // Returns const reference to gRPC status. - const grpc::Status& status() const& { return status_; } - - // Returns r-value to gRPC status. - grpc::Status&& status() && { return std::move(status_); } - - // Returns the pointer to the stored data. Checks if status is not OK. - T* operator->() { - DCHECK(status_.ok()); - return &*data_; - } - - // Returns the const pointer to the stored data. Checks if status is not OK. - const T* operator->() const { - DCHECK(status_.ok()); - return &*data_; - } - - // Returns the const reference to the stored data. Checks if status is not OK. - const T& operator*() const& { - DCHECK(status_.ok()); - return *data_; - } - - // Returns the lvalue-ref to the underlying value. Checks if status is not OK. - const T& value() const& { - DCHECK(status_.ok()); - return *data_; - } - - // Returns the rvalue-ref to the underlying value. To trigger this accessor, - // the status object needs to be moved first: std::move(status_).value(). - // Checks if status is not OK. - T&& value() && { - DCHECK(status_.ok()); - status_ = grpc::Status(grpc::StatusCode::UNKNOWN, ""); - return std::move(data_).value(); - } - - // Sets the data. - void emplace(T&& data) { - status_ = grpc::Status::OK; - data_.emplace(std::move(data)); - } - - std::string ToString() const { return GrpcStatusToString(status()); } - - private: - grpc::Status status_; - std::optional data_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_STATUS_OR_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_status_or_test.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or_test.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_status_or_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_status_or_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/grpc/grpc_status_or.h" - -#include "chromecast/cast_core/grpc/status_matchers.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace cast { -namespace utils { -namespace { - -using ::cast::test::StatusIs; - -static_assert(test::internal::has_status_api>::value, - "GrpcStatusOr::status() API must exist"); -static_assert(!test::internal::has_status_api::value, - "grps::Status::status() API must not exist"); -static_assert(!test::internal::has_code_api::value, - "grpc::Status uses error_* APIs"); -static_assert(test::internal::has_error_code_api::value, - "grpc::Status uses error_* APIs"); - -TEST(GrpcStatusOrTest, DefaultConstructor) { - GrpcStatusOr status_or; - EXPECT_THAT(status_or, StatusIs(grpc::StatusCode::UNKNOWN)); -} - -TEST(GrpcStatusOrTest, ConstructorWithValue) { - GrpcStatusOr status_or(1); - CU_EXPECT_OK(status_or); - EXPECT_EQ(*status_or, 1); -} - -TEST(GrpcStatusOrTest, ConstructorStatusCode) { - GrpcStatusOr status_or(grpc::StatusCode::ABORTED); - EXPECT_THAT(status_or, StatusIs(grpc::StatusCode::ABORTED)); -} - -TEST(GrpcStatusOrTest, ConstructorStatusCodeAndErrorMessage) { - GrpcStatusOr status_or(grpc::StatusCode::NOT_FOUND, "error"); - EXPECT_THAT(status_or, StatusIs(grpc::StatusCode::NOT_FOUND, "error")); -} - -struct MoveableOnly { - explicit MoveableOnly(int v) : value(v) {} - MoveableOnly(MoveableOnly&&) = default; - MoveableOnly& operator=(MoveableOnly&&) { return *this; } - MoveableOnly(const MoveableOnly& rhs) = delete; - MoveableOnly& operator=(const MoveableOnly& rhs) = delete; - - int value; -}; - -int GetValueFromMoveableOnly(MoveableOnly&& mo) { - return mo.value; -} - -TEST(GrpcStatusOrTest, MoveValueOperator) { - GrpcStatusOr status_or(MoveableOnly(1)); - CU_EXPECT_OK(status_or); - MoveableOnly res = std::move(status_or).value(); - EXPECT_EQ(res.value, 1); - EXPECT_THAT(status_or, StatusIs(grpc::StatusCode::UNKNOWN)); - - status_or.emplace(MoveableOnly(10)); - EXPECT_EQ(GetValueFromMoveableOnly(std::move(status_or).value()), 10); - EXPECT_THAT(status_or, StatusIs(grpc::StatusCode::UNKNOWN)); -} - -TEST(GrpcStatusOrTest, MoveStatusOperator) { - GrpcStatusOr status_or(1); - CU_EXPECT_OK(status_or); - int value = std::move(status_or).value(); - EXPECT_THAT(status_or, StatusIs(grpc::StatusCode::UNKNOWN)); - EXPECT_EQ(value, 1); -} - -TEST(GrpcStatusOrTest, Emplace) { - GrpcStatusOr status_or; - status_or.emplace(1); - CU_EXPECT_OK(status_or); - EXPECT_EQ(*status_or, 1); -} - -TEST(GrpcStatusOrTest, Accessor) { - GrpcStatusOr status_or("12345"); - EXPECT_EQ(status_or->size(), 5U); - EXPECT_EQ(*status_or, "12345"); - status_or.emplace("567"); - EXPECT_EQ(*status_or, "567"); - status_or->append("89"); - EXPECT_EQ(*status_or, "56789"); - status_or.emplace("0"); - EXPECT_EQ(*status_or, "0"); -} - -TEST(GrpcStatusOrTest, StreamOperator) { - GrpcStatusOr status_or(1); - EXPECT_EQ(status_or.ToString(), "[status=OK: ]"); -} - -TEST(GrpcStatusOrTest, StreamOperatorWithStatus) { - GrpcStatusOr status_or(grpc::StatusCode::CANCELLED, "method cancelled"); - EXPECT_EQ(status_or.ToString(), "[status=CANCELLED: method cancelled]"); -} - -} // namespace -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_stub.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_stub.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_stub.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_stub.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_STUB_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_STUB_H_ - -#include - -#include "base/logging.h" -#include "chromecast/cast_core/grpc/grpc_server_streaming_call.h" -#include "chromecast/cast_core/grpc/grpc_unary_call.h" - -namespace cast { -namespace utils { - -// A gRPC stub definition with a copy/move enabled constructors and assignment -// operators. -template -class GrpcStub { - public: - using SyncInterface = typename TService::StubInterface; - using AsyncInterface = typename TService::StubInterface::async_interface; - - // Constructs a service stub on an |endpoint|. The is a fast call as gRPC - // creates actual resources for the channel in the background thread. - explicit GrpcStub(const std::string& endpoint) - : GrpcStub(grpc::CreateChannel(endpoint, - grpc::InsecureChannelCredentials())) {} - - // Constructs a service stub with an existing |channel|. The is a fast call - // that shares an existing channel with a new stub. - explicit GrpcStub(std::shared_ptr channel) - : channel_(std::move(channel)), stub_(TService::NewStub(channel_)) { - DCHECK(channel_); - } - - // Copy constructor that reuses the |channel_|. - GrpcStub(const GrpcStub& rhs) : GrpcStub(rhs.channel_) {} - - // Assignment operator that reuses the |channel_|. - GrpcStub& operator=(const GrpcStub& rhs) { - DCHECK(rhs.channel_); - channel_ = rhs.channel_; - stub_ = TService::NewStub(rhs.channel_); - return *this; - } - - // Default specification of move ctor's - placeholder for future expansion. - GrpcStub(GrpcStub&& rhs) = default; - GrpcStub& operator=(GrpcStub&& rhs) = default; - - virtual ~GrpcStub() = default; - - // Creates an instance of TGrpcCall that provides the request object and - // invoke APIs: - // auto call = stub.CreateCall(); - // call.request()->set_xxx(); - // std::move(call).InvokeAsync(); - template - TGrpcCall CreateCall() { - return TGrpcCall(stub_.get()); - } - - // Creates an instance of TGrpcCall and sets the initial |request| object. - template - TGrpcCall CreateCall(typename TGrpcCall::Request request) { - return TGrpcCall(stub_.get(), std::move(request)); - } - - private: - std::shared_ptr channel_; - std::unique_ptr stub_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_STUB_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_unary_call.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_call.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_unary_call.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_call.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,147 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_UNARY_CALL_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_UNARY_CALL_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/raw_ptr.h" -#include "chromecast/cast_core/grpc/grpc_call.h" -#include "chromecast/cast_core/grpc/grpc_client_reactor.h" -#include "chromecast/cast_core/grpc/grpc_status_or.h" - -namespace cast { -namespace utils { - -// Typedef for the unary sync method generated by gRPC compiler. -template -using SyncUnaryMethod = grpc::Status (TSyncInterface::*)(grpc::ClientContext*, - const TRequest&, - TResponse*); - -// Typedef for the unary async method generated by gRPC compiler. -template -using AsyncUnaryMethod = void (TAsyncInterface::*)(grpc::ClientContext*, - const TRequest*, - TResponse*, - grpc::ClientUnaryReactor*); - -// A GrpcCall implementation for unary gRPC calls specialized by the -// |AsyncMethodPtr| and SyncMethodPtr function pointers. The former must always -// be specified and is used for Async calls. The latter is used for Sync calls -// and could be omitted. -// TGrpcStub - gRPC service stub type. -// TRequest - gRPC request type for a method in the stub. -// TResponse - gRPC response type for a method in the stub. -// AsyncMethodPtr - pointer to an async method in the stub that handles a -// streaming call. -// SyncMethodPtr - pointer to a sync method in the stub that handles a -// streaming call. -template < - typename TGrpcStub, - typename TRequest, - typename TResponse, - AsyncUnaryMethod - AsyncMethodPtr, - SyncUnaryMethod - SyncMethodPtr = nullptr> -class GrpcUnaryCall : public GrpcCall { - public: - static_assert(AsyncMethodPtr != nullptr, "AsyncMethodPtr must be specified"); - - using Base = GrpcCall; - using Base::async; - using Base::GrpcCall; - using Base::request; - using Base::sync; - using typename Base::AsyncInterface; - using typename Base::Context; - using typename Base::Request; - - using Response = TResponse; - using ResponseCallback = base::OnceCallback)>; - - GrpcStatusOr Invoke() && { - static_assert(SyncMethodPtr != nullptr, - "The sync interface is not defined for the stub. Please, add " - "&StubInterface:: to the GrpcUnaryCall " - "definition in the stub class."); - Response response; - grpc::ClientContext context; - std::move(*this).options().ApplyOptionsToContext(&context); - auto status = (std::move(*this).sync()->*SyncMethodPtr)( - &context, std::move(*this).request(), &response); - if (status.ok()) { - return response; - } - return status; - } - - // Invokes a unary gRPC call for a given tuple of AsyncInterface, - // AsyncMethodPtr, Request and Response. The |service| must have a |method| of - // a certain signature generated by the proto compiler. - Context InvokeAsync(ResponseCallback response_callback) && { - // Although |reactor| is a plain pointer, its ownership is transferred to - // the gRPC stack in the |Start| call. - auto reactor = - new Reactor(std::move(*this).async(), std::move(*this).request(), - std::move(*this).options(), std::move(response_callback)); - reactor->Start(); - return Context(reactor->context()); - } - - private: - using ReactorBase = GrpcClientReactor; - - class Reactor final : public ReactorBase { - public: - using ReactorBase::context; - using ReactorBase::request; - - Reactor(AsyncInterface* async_stub, - Request request, - GrpcCallOptions options, - ResponseCallback response_callback) - : ReactorBase(std::move(request), std::move(options)), - async_interface_(async_stub), - response_callback_(std::move(response_callback)) {} - - void Start() override { - ReactorBase::Start(); - (async_interface_->*AsyncMethodPtr)(context(), request(), &response_, - this); - grpc::ClientUnaryReactor::StartCall(); - } - - private: - // Implements grpc::ClientUnaryReactor APIs. - // The method is always called on completion of all operations associated - // with this call, and deletes itself on exit. - void OnDone(const grpc::Status& status) override { - if (status.ok()) { - std::move(response_callback_).Run(std::move(response_)); - } else { - std::move(response_callback_).Run(status); - } - ReactorBase::DeleteThis(); - } - - using AsyncStubCall = base::OnceCallback; - - raw_ptr async_interface_; - ResponseCallback response_callback_; - Response response_; - }; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_UNARY_CALL_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_unary_handler.h chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_handler.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_unary_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,125 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_GRPC_UNARY_HANDLER_H_ -#define CHROMECAST_CAST_CORE_GRPC_GRPC_UNARY_HANDLER_H_ - -#include - -#include "base/functional/callback.h" -#include "base/logging.h" -#include "chromecast/cast_core/grpc/cancellable_reactor.h" -#include "chromecast/cast_core/grpc/grpc_handler.h" -#include "chromecast/cast_core/grpc/grpc_server_reactor.h" -#include "chromecast/cast_core/grpc/grpc_status_or.h" -#include "chromecast/cast_core/grpc/server_reactor_tracker.h" -#include "chromecast/cast_core/grpc/trackable_reactor.h" - -namespace cast { -namespace utils { - -// A generic handler for unary, ie request/response, gRPC APIs. Can only be used -// with rpc that have the following signature: -// rpc Foo(Request) returns (Response) -// -// - TService is the gRPC service type. -// - TRequest is the service request type. -// - TResponse is the service response type. -// - MethodName is the rpc method as a string. -// -// This class is not thread-safe. Appropriate means have to be added by the -// users to guarantee thread-safety (ie task runners, mutexes etc). -template -class GrpcUnaryHandler final : public GrpcHandler { - public: - using ReactorBase = GrpcServerReactor; - - class Reactor : public ReactorBase { - public: - using ReactorBase::name; - using ReactorBase::Write; - - using OnRequestCallback = base::RepeatingCallback; - - template - explicit Reactor(OnRequestCallback on_request_callback, TArgs&&... args) - : ReactorBase(std::forward(args)...), - on_request_callback_(std::move(on_request_callback)) { - ReadRequest(); - } - - protected: - using ReactorBase::Finish; - using ReactorBase::ReadRequest; - using ReactorBase::StartRead; - using ReactorBase::StartWriteAndFinish; - - // Implements GrpcServerReactor APIs. - void WriteResponse(const grpc::ByteBuffer* buffer) override { - DCHECK(buffer); - FinishWriting(buffer, grpc::Status::OK); - } - - void FinishWriting(const grpc::ByteBuffer* buffer, - const grpc::Status& status) override { - DCHECK((status.ok() && buffer) || !status.ok()) - << "Either buffer must be set or status must flag an error"; - DVLOG(1) << "Reactor is finished: " << name() - << ", status=" << GrpcStatusToString(status); - if (status.ok()) { - StartWriteAndFinish(buffer, grpc::WriteOptions(), grpc::Status::OK); - } else { - Finish(status); - } - } - - void OnResponseDone(const grpc::Status& status) override { - // This method may be called from the cancelled_reactor as a generic way - // to signal reactor is done via OnResponseDone API. For unary reactor it - // is a no-op. - CHECK(status.error_code() == grpc::StatusCode::ABORTED) - << "Unexpected status: " << GrpcStatusToString(status); - } - - void OnRequestDone(GrpcStatusOr request) override { - if (!request.ok()) { - FinishWriting(nullptr, request.status()); - return; - } - on_request_callback_.Run(std::move(request).value(), this); - } - - OnRequestCallback on_request_callback_; - }; - - using Response = TResponse; - using OnRequestCallback = typename Reactor::OnRequestCallback; - - GrpcUnaryHandler(OnRequestCallback on_request_callback, - ServerReactorTracker* server_reactor_tracker) - : GrpcHandler(server_reactor_tracker), - on_request_callback_(std::move(on_request_callback)) {} - - static std::string rpc_name() { - return std::string("/") + TService::service_full_name() + "/" + MethodName; - } - - private: - // Implements GrpcHandler APIs. - grpc::ServerGenericBidiReactor* CreateReactor( - grpc::CallbackServerContext* context) override { - return new CancellableReactor>( - server_reactor_tracker(), on_request_callback_, rpc_name(), context); - } - - OnRequestCallback on_request_callback_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_GRPC_UNARY_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_unary_test.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_test.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/grpc_unary_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/grpc_unary_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,326 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/files/scoped_temp_dir.h" -#include "base/functional/bind.h" -#include "base/strings/strcat.h" -#include "base/synchronization/waitable_event.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/thread_pool.h" -#include "base/test/bind.h" -#include "base/test/task_environment.h" -#include "base/threading/thread_restrictions.h" -#include "base/time/time.h" -#include "base/uuid.h" -#include "chromecast/cast_core/grpc/grpc_server.h" -#include "chromecast/cast_core/grpc/status_matchers.h" -#include "chromecast/cast_core/grpc/test_service.castcore.pb.h" -#include "chromecast/cast_core/grpc/test_service_extra.castcore.pb.h" -#include "chromecast/cast_core/grpc/test_utils.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace cast { -namespace utils { -namespace { - -using ::cast::test::StatusIs; - -const auto kEventTimeout = base::Seconds(1); -const auto kServerStopTimeout = base::Milliseconds(100); - -class GrpcUnaryTest : public ::testing::Test { - protected: - GrpcUnaryTest() { - CHECK(temp_dir_.CreateUniqueTempDir()); - endpoint_ = - "unix:" + - temp_dir_.GetPath() - .AppendASCII( - "cast-uds-" + - base::Uuid::GenerateRandomV4().AsLowercaseString().substr(24)) - .value(); - } - - base::test::TaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; - base::ScopedTempDir temp_dir_; - std::string endpoint_; -}; - -TEST_F(GrpcUnaryTest, SyncUnaryCallSucceeds) { - GrpcServer server; - server.SetHandler( - base::BindLambdaForTesting( - [](TestRequest request, - SimpleServiceHandler::SimpleCall::Reactor* reactor) { - EXPECT_EQ(request.foo(), "test_foo"); - TestResponse response; - response.set_bar("test_bar"); - reactor->Write(std::move(response)); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - auto response = std::move(call).Invoke(); - CU_ASSERT_OK(response); - EXPECT_EQ(response->bar(), "test_bar"); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -TEST_F(GrpcUnaryTest, SyncUnaryCallReturnsErrorStatus) { - GrpcServer server; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest request, - SimpleServiceHandler::SimpleCall::Reactor* reactor) { - EXPECT_EQ(request.foo(), "test_foo"); - reactor->Write( - grpc::Status(grpc::StatusCode::NOT_FOUND, "Not found")); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - auto response = std::move(call).Invoke(); - ASSERT_THAT(response.status(), - StatusIs(grpc::StatusCode::NOT_FOUND, "Not found")); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -TEST_F(GrpcUnaryTest, SyncUnaryCallCancelledIfServerIsStopped) { - GrpcServer server; - base::WaitableEvent request_received_event{ - base::WaitableEvent::ResetPolicy::AUTOMATIC}; - SimpleServiceHandler::SimpleCall::Reactor* reactor; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest request, - SimpleServiceHandler::SimpleCall::Reactor* r) { - reactor = r; - request_received_event.Signal(); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - // Need to run the client request in a separate thread, so that the main test - // thread can continue handling the case. - base::ThreadPool::PostTask( - FROM_HERE, base::BindLambdaForTesting([&]() { - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - auto response = std::move(call).Invoke(); - CU_ASSERT_OK(response); - })); - ASSERT_TRUE(request_received_event.TimedWait(kEventTimeout)); - // Allow first request to pass. - reactor->Write(TestResponse()); - - test::StopGrpcServer(server, kServerStopTimeout); - - // Server should not be available any more. - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - auto response = std::move(call).Invoke(); - ASSERT_THAT(response, StatusIs(grpc::StatusCode::UNAVAILABLE)); - ASSERT_FALSE(request_received_event.IsSignaled()); -} - -TEST_F(GrpcUnaryTest, AsyncUnaryCallSucceeds) { - GrpcServer server; - server.SetHandler( - base::BindLambdaForTesting( - [](TestRequest request, - SimpleServiceHandler::SimpleCall::Reactor* reactor) { - EXPECT_EQ(request.foo(), "test_foo"); - TestResponse response; - response.set_bar("test_bar"); - reactor->Write(std::move(response)); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - base::WaitableEvent response_received_event; - std::move(call).InvokeAsync( - base::BindLambdaForTesting([&](GrpcStatusOr response) { - CU_CHECK_OK(response); - EXPECT_EQ(response->bar(), "test_bar"); - response_received_event.Signal(); - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -TEST_F(GrpcUnaryTest, AsyncUnaryCallReturnsErrorStatus) { - GrpcServer server; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest request, - SimpleServiceHandler::SimpleCall::Reactor* reactor) { - EXPECT_EQ(request.foo(), "test_foo"); - reactor->Write( - grpc::Status(grpc::StatusCode::NOT_FOUND, "Not Found")); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - base::WaitableEvent response_received_event; - std::move(call).InvokeAsync( - base::BindLambdaForTesting([&](GrpcStatusOr response) { - ASSERT_THAT(response.status(), - StatusIs(grpc::StatusCode::NOT_FOUND, "Not Found")); - response_received_event.Signal(); - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -TEST_F(GrpcUnaryTest, AsyncUnaryCallCancelledIfServerIsStopped) { - GrpcServer server; - base::WaitableEvent request_received_event; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest request, - SimpleServiceHandler::SimpleCall::Reactor* reactor) { - reactor->Write(TestResponse()); - request_received_event.Signal(); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_foo("test_foo"); - base::WaitableEvent response_received_event{ - base::WaitableEvent::ResetPolicy::AUTOMATIC}; - std::move(call).InvokeAsync( - base::BindLambdaForTesting([&](GrpcStatusOr response) { - CU_ASSERT_OK(response); - response_received_event.Signal(); - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - test::StopGrpcServer(server, kServerStopTimeout); - - auto call1 = stub.CreateCall(); - std::move(call1).InvokeAsync( - base::BindLambdaForTesting([&](GrpcStatusOr response) { - ASSERT_THAT(response, StatusIs(grpc::StatusCode::UNAVAILABLE)); - response_received_event.Signal(); - })); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); -} - -TEST_F(GrpcUnaryTest, SyncUnaryCallSucceedsExtra) { - GrpcServer server; - server.SetHandler( - base::BindLambdaForTesting( - [](TestExtraRequest request, - SimpleServiceExtraHandler::SimpleCall::Reactor* reactor) { - EXPECT_EQ(request.extra(), "test_extra"); - TestResponse response; - response.set_bar("test_bar"); - reactor->Write(std::move(response)); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - SimpleServiceExtraStub stub(endpoint_); - auto call = stub.CreateCall(); - call.request().set_extra("test_extra"); - auto response = std::move(call).Invoke(); - CU_ASSERT_OK(response); - EXPECT_EQ(response->bar(), "test_bar"); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -TEST_F(GrpcUnaryTest, - AsyncUnaryCallCancelledByClientAndDestroyedBeforeServerShutdown) { - GrpcServer server; - SimpleServiceHandler::SimpleCall::Reactor* cancelled_reactor; - base::WaitableEvent request_received_event; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest, SimpleServiceHandler::SimpleCall::Reactor* r) { - cancelled_reactor = r; - request_received_event.Signal(); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - base::WaitableEvent response_received_event; - auto context = std::move(call).InvokeAsync( - base::BindLambdaForTesting([&](GrpcStatusOr response) { - ASSERT_THAT(response, StatusIs(grpc::StatusCode::CANCELLED)); - response_received_event.Signal(); - })); - ASSERT_TRUE(request_received_event.TimedWait(kEventTimeout)); - - context.Cancel(); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - // Actually sleep to allow gRPC framework to propagate the cancellation to the - // server side and mark the reactor cancelled. - ASSERT_TRUE( - test::WaitForPredicate(kEventTimeout, base::BindLambdaForTesting([&]() { - return cancelled_reactor->is_done(); - }))); - - // This releases the cancelled reactor on the server side and destroys it. - cancelled_reactor->Write(TestResponse()); - ASSERT_TRUE( - test::WaitForPredicate(kEventTimeout, base::BindLambdaForTesting([&]() { - return server.active_reactor_count() == 0; - }))); - ASSERT_EQ(server.active_reactor_count(), 0u); - - test::StopGrpcServer(server, kServerStopTimeout); -} - -TEST_F(GrpcUnaryTest, - AsyncUnaryCallCancelledByClientAndLeftActiveDuringServerShutdown) { - GrpcServer server; - base::WaitableEvent request_received_event; - server.SetHandler( - base::BindLambdaForTesting( - [&](TestRequest, SimpleServiceHandler::SimpleCall::Reactor*) { - request_received_event.Signal(); - })); - ASSERT_THAT(server.Start(endpoint_), StatusIs(grpc::StatusCode::OK)); - - SimpleServiceStub stub(endpoint_); - auto call = stub.CreateCall(); - base::WaitableEvent response_received_event; - auto context = std::move(call).InvokeAsync( - base::BindLambdaForTesting([&](GrpcStatusOr response) { - ASSERT_THAT(response, StatusIs(grpc::StatusCode::CANCELLED)); - response_received_event.Signal(); - })); - ASSERT_TRUE(request_received_event.TimedWait(kEventTimeout)); - - context.Cancel(); - ASSERT_TRUE(response_received_event.TimedWait(kEventTimeout)); - - CHECK_EQ(server.active_reactor_count(), 1u); - - // All active reactors will be destroyed after this call. - test::StopGrpcServer(server, kServerStopTimeout); -} - -} // namespace -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/server_reactor_tracker.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/server_reactor_tracker.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/server_reactor_tracker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/server_reactor_tracker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/grpc/server_reactor_tracker.h" - -#include "base/logging.h" -#include "base/ranges/algorithm.h" - -namespace cast { -namespace utils { - -ServerReactorTracker::ServerReactorTracker() = default; - -ServerReactorTracker::~ServerReactorTracker() { - std::vector reactors_to_destroy; - { - base::AutoLock l(lock_); - if (active_reactors_.empty()) { - return; - } - // Need to copy all active reactors to allow for Reactor::dtor() -> - // RemoveReactor flow to happen without deadlocking. - base::ranges::for_each(active_reactors_, [&](const auto& pair) { - reactors_to_destroy.push_back(pair.first); - }); - } - - // Force delete any pending server reactors to avoid memory leaks. The - // handlers must confirm in their callbacks that the GrpcServer is available - // before accessing the |reactor| in the callback. - LOG(WARNING) - << "Reactor tracker detected active reactors on destruction: count=" - << reactors_to_destroy.size(); - for (auto* reactor : reactors_to_destroy) { - delete reactor; - } -} - -void ServerReactorTracker::AddReactor(grpc::ServerGenericBidiReactor* reactor, - const std::string& name) { - base::AutoLock l(lock_); - active_reactors_.emplace(reactor, name); -} - -void ServerReactorTracker::RemoveReactor( - grpc::ServerGenericBidiReactor* reactor) { - base::AutoLock l(lock_); - active_reactors_.erase(reactor); -} - -size_t ServerReactorTracker::active_reactor_count() const { - base::AutoLock l(lock_); - return active_reactors_.size(); -} - -} // namespace utils -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/server_reactor_tracker.h chromium-132.0.6834.159/chromecast/cast_core/grpc/server_reactor_tracker.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/server_reactor_tracker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/server_reactor_tracker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_SERVER_REACTOR_TRACKER_H_ -#define CHROMECAST_CAST_CORE_GRPC_SERVER_REACTOR_TRACKER_H_ - -#include "base/containers/flat_map.h" -#include "base/synchronization/lock.h" -#include "chromecast/cast_core/grpc/grpc_server_reactor.h" - -namespace cast { -namespace utils { - -// Tracks number of currently active reactors per server and allows to quickly -// diagnose the rpc names of the reactors that are left pending via ostream -// operator. -class ServerReactorTracker final { - public: - ServerReactorTracker(); - ~ServerReactorTracker(); - - void AddReactor(grpc::ServerGenericBidiReactor* reactor, - const std::string& name); - void RemoveReactor(grpc::ServerGenericBidiReactor* reactor); - - size_t active_reactor_count() const; - - private: - mutable base::Lock lock_; - base::flat_map active_reactors_ - GUARDED_BY(lock_); -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_SERVER_REACTOR_TRACKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/status_matchers.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/status_matchers.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/status_matchers.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/status_matchers.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/grpc/status_matchers.h" - -namespace cast { -namespace test { -namespace internal { - -StatusResolver::~StatusResolver() = default; - -StatusIsPolymorphicWrapper::StatusIsPolymorphicWrapper( - const StatusIsPolymorphicWrapper&) = default; - -StatusIsPolymorphicWrapper::~StatusIsPolymorphicWrapper() = default; - -} // namespace internal -} // namespace test -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/status_matchers.h chromium-132.0.6834.159/chromecast/cast_core/grpc/status_matchers.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/status_matchers.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/status_matchers.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,248 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_STATUS_MATCHERS_H_ -#define CHROMECAST_CAST_CORE_GRPC_STATUS_MATCHERS_H_ - -#include -#include - -#include "testing/gmock/include/gmock/gmock.h" - -namespace cast { -namespace test { -namespace internal { - -// Checks if a type T has a status() API helping distinguish if Status impl is -// nested inside T (eg GrpcStatusOr etc) or T is the Status impl. -template -class has_status_api { - struct no {}; - - template - static decltype(std::declval().status()) test(int); - template - static no test(...); - - public: - enum { value = !std::is_same(0)), no>::value }; -}; - -// Checks if a Status impl has 'code' API deducing that status code and message -// can be retrieved using T::code() and T::message APIs (eg absl::Status). -template -class has_code_api { - struct no {}; - - template - static decltype(&C::code) test(int); - template - static no test(...); - - public: - enum { value = !std::is_same(0)), no>::value }; -}; - -// Checks if a Status impl has 'error_code' API deducing that status code and -// message can be retrieved using T::error_code() and T::error_message APIs (eg -// grpc::Status). -template -class has_error_code_api { - struct no {}; - - template - static decltype(&C::error_code) test(int); - template - static no test(...); - - public: - enum { value = !std::is_same(0)), no>::value }; -}; - -// Reads the error code and message of the generic TStatus which can be either a -// wrapper object with TStatus::status() defined or the actual status object -// with TStatus::code\message() or TStatus::error_code\error_message APIs. The -// resolution works based on SFINAE when invalid type substitution results in -// dropping the method from compilation. -class StatusResolver { - public: - struct StatusInfo { - int code; - std::string message; - }; - - // Constructor that deduces the actual APIs of TStatus and sets the code and - // message. - template - explicit StatusResolver(const TStatus& status) - : status_info_(ResolveStatusInfo(ResolveStatus(status))) {} - ~StatusResolver(); - - // Returns the status code (as an integer) and message. - const StatusInfo& status_info() const { return status_info_; } - - // Checks if status is ok. - bool ok() const { return status_info_.code == 0; } - - private: - // Returns the actual status from the wrapper. - template ::value, - TWrappedStatus>::type* = nullptr> - static auto ResolveStatus(const TWrappedStatus& wrapped_status) - -> decltype(std::declval().status()) { - return wrapped_status.status(); - } - - // Returns itself. - template ::value, - TStatus>::type* = nullptr> - static auto ResolveStatus(const TStatus& status) -> TStatus { - return status; - } - - // Returns the pair of integer code and error message using TStatus::code() - // and TStatus::message() APIs. - template ::value, - TStatus>::type* = nullptr> - static StatusInfo ResolveStatusInfo(const TStatus& status) { - return StatusInfo( - {static_cast(status.code()), std::string(status.message())}); - } - - // Returns the pair of integer code and error message using - // TStatus::error_code() and TStatus::error_message() APIs. - template ::value, - TStatus>::type* = nullptr> - static StatusInfo ResolveStatusInfo(const TStatus& status) { - return StatusInfo({static_cast(status.error_code()), - std::string(status.error_message())}); - } - - const StatusInfo status_info_; -}; - -// Implementation of MatcherInterface for StatusIs matcher. -template -class StatusIsImpl : public ::testing::MatcherInterface { - public: - StatusIsImpl(::testing::Matcher code, - ::testing::Matcher message) - : code_(std::move(code)), message_(std::move(message)) {} - - // MatcherInterface implementation. - void DescribeTo(std::ostream* os) const override { - *os << "has code() that "; - code_.DescribeTo(os); - *os << " and message() that "; - message_.DescribeTo(os); - } - - void DescribeNegationTo(std::ostream* os) const override { - *os << "has code() that "; - code_.DescribeNegationTo(os); - *os << " and message() that "; - message_.DescribeNegationTo(os); - } - - bool MatchAndExplain( - TStatus status, - ::testing::MatchResultListener* result_listener) const override { - ::testing::StringMatchResultListener listener; - StatusResolver status_resolver(status); - auto status_info = status_resolver.status_info(); - if (!code_.Matches(status_info.code)) { - *result_listener << "has wrong status code " << status_info.code; - return false; - } - - if (!message_.Matches(status_info.message)) { - *result_listener << "has wrong error message " << status_info.message; - return false; - } - - return true; - } - - private: - const ::testing::Matcher code_; - const ::testing::Matcher message_; -}; - -// Allows usage of StatusIs without template parameter -class StatusIsPolymorphicWrapper { - public: - template - StatusIsPolymorphicWrapper(TStatusCode code, - ::testing::Matcher&& message) - : code_(static_cast(code)), message_(std::move(message)) {} - StatusIsPolymorphicWrapper(const StatusIsPolymorphicWrapper&); - ~StatusIsPolymorphicWrapper(); - - // Converts this polymorphic matcher to a monomorphic matcher. - template - operator ::testing::Matcher() const { - return ::testing::Matcher( - new StatusIsImpl(std::move(code_), std::move(message_))); - } - - private: - ::testing::Matcher code_; - ::testing::Matcher message_; -}; - -// Allows usage of IsOk without template parameter -template -class IsOkImpl : public ::testing::MatcherInterface { - public: - void DescribeTo(std::ostream* os) const override { - *os << "is OK"; - } // namespace internal - void DescribeNegationTo(std::ostream* os) const override { - *os << "is not OK"; - } - bool MatchAndExplain(TStatus actual_value, - ::testing::MatchResultListener*) const override { - return StatusResolver(actual_value).ok(); - } -}; // namespace test - -class IsOkPolymorphicWrapper { - public: - template - operator ::testing::Matcher() const { // NOLINT - return ::testing::Matcher(new IsOkImpl()); - } -}; - -} // namespace internal - -template -inline internal::StatusIsPolymorphicWrapper StatusIs(TStatusCode code) { - return internal::StatusIsPolymorphicWrapper(code, ::testing::_); -} - -template -inline internal::StatusIsPolymorphicWrapper StatusIs( - TStatusCode code, - ::testing::Matcher&& message_matcher) { - return internal::StatusIsPolymorphicWrapper(code, std::move(message_matcher)); -} - -inline internal::IsOkPolymorphicWrapper IsOk() { - return internal::IsOkPolymorphicWrapper(); -} - -#define CU_EXPECT_OK(expression) EXPECT_THAT(expression, ::cast::test::IsOk()) -#define CU_ASSERT_OK(expression) ASSERT_THAT(expression, ::cast::test::IsOk()) -#define CU_CHECK_OK(expression) \ - CHECK(::cast::test::internal::StatusResolver(expression).ok()) - -} // namespace test -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_STATUS_MATCHERS_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/test_service.proto chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service.proto --- chromium-132.0.6834.110/chromecast/cast_core/grpc/test_service.proto 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service.proto 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -syntax = "proto3"; - -package cast.utils; - -import "chromecast/cast_core/grpc/test_service_messages.proto"; - -option optimize_for = LITE_RUNTIME; - -// An unary test service. -service SimpleService { - // Makes an unary test call. - rpc SimpleCall(TestRequest) returns (TestResponse); -} - -// A server streaming test service. -service ServerStreamingService { - // Makes a server streaming test call. - rpc StreamingCall(TestRequest) returns (stream TestResponse); -} - -// The request is added here to verify the build rules. -message TestExtraRequest { - string extra = 1; -} diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/test_service_extra.proto chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service_extra.proto --- chromium-132.0.6834.110/chromecast/cast_core/grpc/test_service_extra.proto 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service_extra.proto 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -syntax = "proto3"; - -package cast.utils; - -import "chromecast/cast_core/grpc/test_service.proto"; -import "chromecast/cast_core/grpc/test_service_messages.proto"; - -option optimize_for = LITE_RUNTIME; - -// An unary test service. -service SimpleServiceExtra { - // Makes an unary test call. - rpc SimpleCall(TestExtraRequest) returns (TestResponse); -} diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/test_service_messages.proto chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service_messages.proto --- chromium-132.0.6834.110/chromecast/cast_core/grpc/test_service_messages.proto 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/test_service_messages.proto 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -syntax = "proto3"; - -package cast.utils; - -option optimize_for = LITE_RUNTIME; - -// Test request. -message TestRequest { - string foo = 1; -} - -// Test response. -message TestResponse { - string bar = 1; -} diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/test_utils.cc chromium-132.0.6834.159/chromecast/cast_core/grpc/test_utils.cc --- chromium-132.0.6834.110/chromecast/cast_core/grpc/test_utils.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/test_utils.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -#include "chromecast/cast_core/grpc/test_utils.h" - -#include "base/functional/callback_forward.h" -#include "base/run_loop.h" -#include "base/time/time.h" - -namespace cast { -namespace test { - -void StopGrpcServer(utils::GrpcServer& server, const base::TimeDelta& timeout) { - base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); - server.Stop(timeout.InMilliseconds(), run_loop.QuitClosure()); - run_loop.Run(); -} - -bool WaitForPredicate(const base::TimeDelta& timeout, - base::RepeatingCallback predicate) { - static constexpr auto kSleepTimeout = base::Milliseconds(10); - for (int i = 0; i < timeout / kSleepTimeout; ++i) { - if (predicate.Run()) { - return true; - } - usleep(kSleepTimeout.InMilliseconds()); - } - return false; -} - -} // namespace test -} // namespace cast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/test_utils.h chromium-132.0.6834.159/chromecast/cast_core/grpc/test_utils.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/test_utils.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/test_utils.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -#ifndef CHROMECAST_CAST_CORE_GRPC_TEST_UTILS_H_ -#define CHROMECAST_CAST_CORE_GRPC_TEST_UTILS_H_ - -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "chromecast/cast_core/grpc/grpc_server.h" - -namespace cast { -namespace test { - -// Stops the gRPC server in a separate task runner to avoid blocking the main -// test thread, and keep latter's run loop spinning. The process will crash -// in case the |timeout| is reached as such case clearly points to a bug in -// reactor handling. -void StopGrpcServer(utils::GrpcServer& server, const base::TimeDelta& timeout); - -// Waits for |timeout| time for predicate to return true. -bool WaitForPredicate(const base::TimeDelta& timeout, - base::RepeatingCallback predicate); - -} // namespace test -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_TEST_UTILS_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/grpc/trackable_reactor.h chromium-132.0.6834.159/chromecast/cast_core/grpc/trackable_reactor.h --- chromium-132.0.6834.110/chromecast/cast_core/grpc/trackable_reactor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/grpc/trackable_reactor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_GRPC_TRACKABLE_REACTOR_H_ -#define CHROMECAST_CAST_CORE_GRPC_TRACKABLE_REACTOR_H_ - -#include "base/check.h" -#include "base/memory/raw_ptr.h" -#include "chromecast/cast_core/grpc/server_reactor_tracker.h" - -namespace cast { -namespace utils { - -// A facade around reactor implementation that allows to easily track active -// reactors in a given ServerReactorTracker. -template -class TrackableReactor : public TReactor { - public: - template - explicit TrackableReactor(ServerReactorTracker* server_reactor_tracker, - TArgs&&... args) - : TReactor(std::forward(args)...), - server_reactor_tracker_(server_reactor_tracker) { - DCHECK(server_reactor_tracker_); - server_reactor_tracker_->AddReactor(this, TReactor::name()); - } - - ~TrackableReactor() override { server_reactor_tracker_->RemoveReactor(this); } - - private: - raw_ptr const server_reactor_tracker_; -}; - -} // namespace utils -} // namespace cast - -#endif // CHROMECAST_CAST_CORE_GRPC_TRACKABLE_REACTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/DEPS chromium-132.0.6834.159/chromecast/cast_core/runtime/DEPS --- chromium-132.0.6834.110/chromecast/cast_core/runtime/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -include_rules = [ - "+components/cast_receiver/common/public", -] diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/DEPS chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/DEPS --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -include_rules = [ - "+chromecast/base", - "+chromecast/bindings", - "+chromecast/browser", - "+chromecast/cast_core/common", - "+chromecast/chromecast_buildflags.h", - "+chromecast/common", - "+chromecast/media", - "+chromecast/metrics", - "+chromecast/service", - "+chromecast/shared", - "+chromecast/starboard", - "+components/cast", - "+components/cast_receiver/browser", - "+components/cast_streaming/browser", - "+components/cast_streaming/public", - "+components/guest_view/browser", - "+components/media_control/browser", - "+components/url_rewrite", - "+content/public/browser", - "+content/public/common", - "+media/base", - "+media/mojo", - "+mojo/public", - "+net/base", - "+url", - "+third_party/blink/public/common", - "+third_party/cast_core/public/src", - "+third_party/grpc", - "+third_party/metrics_proto", - "+third_party/openscreen/src/cast/common/public/cast_streaming_app_ids.h", - "+third_party/openscreen/src/cast/streaming", -] diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_core_switches.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_core_switches.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_core_switches.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_core_switches.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_CORE_SWITCHES_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_CORE_SWITCHES_H_ - -namespace chromecast { - -// Enables insecure content in Cast Web Runtime. This unblocks MSPs that serve -// content from HTTP sources, like Amazon Prime. -constexpr char kAllowRunningInsecureContentInRuntime[] = - "allow-running-insecure-content"; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_CORE_SWITCHES_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.h" - -#include "base/check.h" -#include "base/logging.h" -#include "base/metrics/user_metrics.h" - -namespace chromecast { -namespace { - -constexpr size_t kActionLimit = 1000000; - -} // namespace - -CastRuntimeActionRecorder::CastRuntimeActionRecorder() - : on_action_callback_( - base::BindRepeating(&CastRuntimeActionRecorder::OnAction, - base::Unretained(this))) { - DCHECK(base::GetRecordActionTaskRunner()); - base::AddActionCallback(on_action_callback_); -} - -CastRuntimeActionRecorder::~CastRuntimeActionRecorder() { - base::RemoveActionCallback(on_action_callback_); -} - -std::vector -CastRuntimeActionRecorder::TakeEvents() { - return std::move(events_); -} - -void CastRuntimeActionRecorder::OnAction(const std::string& name, - base::TimeTicks time) { - if (events_.size() >= kActionLimit) { - static bool logged_once = false; - if (!logged_once) { - LOG(ERROR) << "Too many actions, dropping..."; - logged_once = true; - } - return; - } - cast::metrics::UserActionEvent event; - event.set_name(name); - event.set_time((time - base::TimeTicks()).InMicroseconds()); - events_.push_back(std::move(event)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_ACTION_RECORDER_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_ACTION_RECORDER_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "third_party/cast_core/public/src/proto/metrics/metrics_recorder.pb.h" - -namespace chromecast { - -// This class records user action events. It begins recording via a callback at -// construction time. The current set of events can be taken with TakeEvents to -// send to Cast Core. -class CastRuntimeActionRecorder { - public: - CastRuntimeActionRecorder(); - ~CastRuntimeActionRecorder(); - - CastRuntimeActionRecorder(const CastRuntimeActionRecorder&) = delete; - CastRuntimeActionRecorder& operator=(const CastRuntimeActionRecorder&) = - delete; - - std::vector TakeEvents(); - - private: - void OnAction(const std::string& name, base::TimeTicks time); - - base::RepeatingCallback - on_action_callback_; - std::vector events_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_ACTION_RECORDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,165 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.h" - -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/memory/raw_ref.h" -#include "chromecast/browser/cast_content_browser_client.h" -#include "chromecast/browser/service/cast_service_simple.h" -#include "chromecast/cast_core/cast_core_switches.h" -#include "chromecast/cast_core/runtime/browser/runtime_service_impl.h" -#include "chromecast/common/cors_exempt_headers.h" -#include "chromecast/media/base/video_plane_controller.h" -#include "components/cast_receiver/browser/public/runtime_application.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/common/content_switches.h" -#include "media/base/cdm_factory.h" -#include "third_party/blink/public/common/loader/url_loader_throttle.h" - -namespace chromecast { - -namespace { - -// CastServiceSimple impl for Cast Core that allows the runtime service to start -// up and tear down. -class CoreCastService : public shell::CastServiceSimple { - public: - CoreCastService( - CastWebService* web_service, - cast_receiver::ContentBrowserClientMixins& cast_browser_client_mixins_) - : CastServiceSimple(web_service), - runtime_service_( - std::make_unique(cast_browser_client_mixins_, - *web_service)) {} - - // CastServiceSimple overrides: - void StartInternal() override { - if (!runtime_service_->Start().ok()) { - base::Process::TerminateCurrentProcessImmediately(1); - } - } - - void StopInternal() override { runtime_service_->Stop(); } - - void FinalizeInternal() override { runtime_service_.reset(); } - - private: - std::unique_ptr runtime_service_; -}; - -} // namespace - -CastRuntimeContentBrowserClient::CastRuntimeContentBrowserClient( - CastFeatureListCreator* feature_list_creator) - : shell::CastContentBrowserClient(feature_list_creator), - cast_browser_client_mixins_( - cast_receiver::ContentBrowserClientMixins::Create(base::BindRepeating( - &CastRuntimeContentBrowserClient::GetSystemNetworkContext, - base::Unretained(this)))) { - cast_browser_client_mixins_->AddStreamingResolutionObserver(&observer_); - cast_browser_client_mixins_->AddApplicationStateObserver(&observer_); -} - -CastRuntimeContentBrowserClient::~CastRuntimeContentBrowserClient() { - cast_browser_client_mixins_->RemoveStreamingResolutionObserver(&observer_); - cast_browser_client_mixins_->RemoveApplicationStateObserver(&observer_); -} - -std::unique_ptr CastRuntimeContentBrowserClient::CreateCastService( - content::BrowserContext* browser_context, - CastSystemMemoryPressureEvaluatorAdjuster* memory_pressure_adjuster, - PrefService* pref_service, - media::VideoPlaneController* video_plane_controller, - CastWindowManager* window_manager, - CastWebService* web_service, - DisplaySettingsManager* display_settings_manager) { - observer_.SetVideoPlaneController(video_plane_controller); - - // Unretained() is safe here because this instance will outlive CastService. - return std::make_unique(web_service, - *cast_browser_client_mixins_); -} - -std::unique_ptr<::media::CdmFactory> -CastRuntimeContentBrowserClient::CreateCdmFactory( - ::media::mojom::FrameInterfaceFactory* frame_interfaces) { - return nullptr; -} - -void CastRuntimeContentBrowserClient::AppendExtraCommandLineSwitches( - base::CommandLine* command_line, - int child_process_id) { - CastContentBrowserClient::AppendExtraCommandLineSwitches(command_line, - child_process_id); - - base::CommandLine* browser_command_line = - base::CommandLine::ForCurrentProcess(); - if (browser_command_line->HasSwitch(switches::kLogFile) && - !command_line->HasSwitch(switches::kLogFile)) { - static const char* const kPath[] = {switches::kLogFile}; - command_line->CopySwitchesFrom(*browser_command_line, kPath); - } -} - -bool CastRuntimeContentBrowserClient::IsWebUIAllowedToMakeNetworkRequests( - const url::Origin&) { - return false; -} - -bool CastRuntimeContentBrowserClient::IsBufferingEnabled() { - return observer_.IsBufferingEnabled(); -} - -void CastRuntimeContentBrowserClient::OnWebContentsCreated( - content::WebContents* web_contents) { - cast_browser_client_mixins_->OnWebContentsCreated(web_contents); -} - -std::vector> -CastRuntimeContentBrowserClient::CreateURLLoaderThrottles( - const network::ResourceRequest& request, - content::BrowserContext* browser_context, - const base::RepeatingCallback& wc_getter, - content::NavigationUIData* navigation_ui_data, - content::FrameTreeNodeId frame_tree_node_id, - std::optional navigation_id) { - return cast_browser_client_mixins_->CreateURLLoaderThrottles( - std::move(wc_getter), frame_tree_node_id, - base::BindRepeating(&IsCorsExemptHeader)); -} - -CastRuntimeContentBrowserClient::Observer::~Observer() = default; - -void CastRuntimeContentBrowserClient::Observer::SetVideoPlaneController( - media::VideoPlaneController* video_plane_controller) { - video_plane_controller_ = video_plane_controller; -} - -bool CastRuntimeContentBrowserClient::Observer::IsBufferingEnabled() const { - return is_buffering_enabled_.load(); -} - -void CastRuntimeContentBrowserClient::Observer::OnForegroundApplicationChanged( - cast_receiver::RuntimeApplication* app) { - bool enabled = true; - // Buffering must be disabled for streaming applications. - if (app && app->IsStreamingApplication()) { - enabled = false; - } - - is_buffering_enabled_.store(enabled); - DLOG(INFO) << "Buffering is " << (enabled ? "enabled" : "disabled"); -} - -void CastRuntimeContentBrowserClient::Observer::OnStreamingResolutionChanged( - const gfx::Rect& size, - const ::media::VideoTransformation& transformation) { - if (video_plane_controller_) { - video_plane_controller_->SetGeometryFromMediaType(size, transformation); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,98 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_CONTENT_BROWSER_CLIENT_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_CONTENT_BROWSER_CLIENT_H_ - -#include - -#include "base/memory/raw_ptr.h" -#include "chromecast/browser/cast_content_browser_client.h" -#include "components/cast_receiver/browser/public/content_browser_client_mixins.h" - -namespace gfx { -class Rect; -} // namespace gfx - -namespace media { -struct VideoTransformation; -} // namespace media - -namespace cast_receiver { -class RuntimeApplication; -} // namespace cast_receiver - -namespace chromecast { - -class CastRuntimeContentBrowserClient : public shell::CastContentBrowserClient { - public: - explicit CastRuntimeContentBrowserClient( - CastFeatureListCreator* feature_list_creator); - ~CastRuntimeContentBrowserClient() override; - - // CastContentBrowserClient overrides: - std::unique_ptr CreateCastService( - content::BrowserContext* browser_context, - CastSystemMemoryPressureEvaluatorAdjuster* memory_pressure_adjuster, - PrefService* pref_service, - media::VideoPlaneController* video_plane_controller, - CastWindowManager* window_manager, - CastWebService* web_service, - DisplaySettingsManager* display_settings_manager) override; - std::unique_ptr<::media::CdmFactory> CreateCdmFactory( - ::media::mojom::FrameInterfaceFactory* frame_interfaces) override; - bool IsWebUIAllowedToMakeNetworkRequests(const url::Origin& origin) override; - void AppendExtraCommandLineSwitches(base::CommandLine* command_line, - int child_process_id) override; - bool IsBufferingEnabled() override; - void OnWebContentsCreated(content::WebContents* web_contents) override; - std::vector> - CreateURLLoaderThrottles( - const network::ResourceRequest& request, - content::BrowserContext* browser_context, - const base::RepeatingCallback& wc_getter, - content::NavigationUIData* navigation_ui_data, - content::FrameTreeNodeId frame_tree_node_id, - std::optional navigation_id) override; - - private: - class Observer : public cast_receiver::StreamingResolutionObserver, - public cast_receiver::ApplicationStateObserver { - public: - ~Observer() override; - - void SetVideoPlaneController( - media::VideoPlaneController* video_plane_controller); - - bool IsBufferingEnabled() const; - - private: - // cast_receiver::ApplicationStateObserver overrides: - void OnForegroundApplicationChanged( - cast_receiver::RuntimeApplication* app) override; - - // cast_receiver::StreamResolutionObserver overrides: - // - // TODO(crbug.com/1358690): Remove this observer. - void OnStreamingResolutionChanged( - const gfx::Rect& size, - const ::media::VideoTransformation& transformation) override; - - // Responsible for modifying the resolution of the screen for the embedded - // device. Set during the first (and only) call to CreateCastService(). - raw_ptr video_plane_controller_ = nullptr; - - std::atomic_bool is_buffering_enabled_{false}; - }; - - std::unique_ptr - cast_browser_client_mixins_; - - // Wrapper around the observers used with the cast_receiver component. - Observer observer_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_CONTENT_BROWSER_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_simple.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_simple.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_simple.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_simple.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#include - -#include "chromecast/browser/cast_content_browser_client.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.h" -#include "chromecast/common/cors_exempt_headers.h" - -namespace chromecast { -namespace shell { - -// static -std::unique_ptr CastContentBrowserClient::Create( - CastFeatureListCreator* feature_list_creator) { - return std::make_unique( - feature_list_creator); -} - -// static -std::vector CastContentBrowserClient::GetCorsExemptHeadersList() { - auto headers = GetLegacyCorsExemptHeaders(); - return std::vector(headers.begin(), headers.end()); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,127 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.h" - -#include "base/memory/scoped_refptr.h" -#include "chromecast/browser/cast_web_service.h" -#include "chromecast/browser/cast_web_view_factory.h" -#include "chromecast/media/cdm/cast_cdm.h" -#include "chromecast/media/cdm/cast_cdm_factory.h" -#include "chromecast/media/cdm/cast_cdm_origin_provider.h" -#include "chromecast/media/common/media_resource_tracker.h" -#include "chromecast/service/cast_service.h" -#include "chromecast/starboard/media/cdm/starboard_decryptor_cast.h" -#include "content/public/browser/web_contents.h" -#include "media/base/provision_fetcher.h" -#include "media/mojo/mojom/frame_interface_factory.mojom.h" -#include "media/mojo/mojom/provision_fetcher.mojom.h" -#include "media/mojo/services/mojo_provision_fetcher.h" - -namespace chromecast { -namespace shell { - -namespace { - -// A CdmFactory that constructs StarboardDecryptorCast instances. These -// instances do not do actual decryption; decryption is done in the starboard -// library itself. Instead, StarboardDecryptorCast only acts as an intermediary -// between the Javascript Cast application and Starboard. -class StarboardCdmFactory : public chromecast::media::CastCdmFactory { - public: - StarboardCdmFactory( - ::media::CreateFetcherCB create_provision_fetcher_cb, - scoped_refptr task_runner, - const url::Origin& cdm_origin, - chromecast::media::MediaResourceTracker* media_resource_tracker) - : chromecast::media::CastCdmFactory(std::move(task_runner), - cdm_origin, - media_resource_tracker), - create_provision_fetcher_cb_(std::move(create_provision_fetcher_cb)), - media_resource_tracker_(media_resource_tracker) {} - - // Disallow copy and assign. - StarboardCdmFactory(const StarboardCdmFactory&) = delete; - StarboardCdmFactory& operator=(const StarboardCdmFactory&) = delete; - - ~StarboardCdmFactory() override = default; - - // CastCdmFactory implementation: - scoped_refptr CreatePlatformBrowserCdm( - const chromecast::media::CastKeySystem& cast_key_system, - const url::Origin& cdm_origin, - const ::media::CdmConfig& cdm_config) override { - if (cast_key_system != media::CastKeySystem::KEY_SYSTEM_WIDEVINE) { - LOG(ERROR) << "Widevine is the only DRM system supported via Starboard."; - return nullptr; - } - - return base::MakeRefCounted( - create_provision_fetcher_cb_, media_resource_tracker_); - } - - private: - ::media::CreateFetcherCB create_provision_fetcher_cb_; - chromecast::media::MediaResourceTracker* media_resource_tracker_ = nullptr; -}; - -} // namespace - -CastRuntimeContentBrowserClientStarboard:: - CastRuntimeContentBrowserClientStarboard( - CastFeatureListCreator* feature_list_creator) - : CastRuntimeContentBrowserClient(feature_list_creator) {} - -CastRuntimeContentBrowserClientStarboard:: - ~CastRuntimeContentBrowserClientStarboard() = default; - -std::unique_ptr<::media::CdmFactory> -CastRuntimeContentBrowserClientStarboard::CreateCdmFactory( - ::media::mojom::FrameInterfaceFactory* frame_interfaces) { - url::Origin cdm_origin; - if (!CastCdmOriginProvider::GetCdmOrigin(frame_interfaces, &cdm_origin)) { - LOG(ERROR) << "Failed to get CDM origin"; - return nullptr; - } - - ::media::CreateFetcherCB provision_fetcher_cb = base::BindRepeating( - [](::media::mojom::FrameInterfaceFactory* frame_interfaces) - -> std::unique_ptr<::media::ProvisionFetcher> { - mojo::PendingRemote<::media::mojom::ProvisionFetcher> provision_fetcher; - frame_interfaces->CreateProvisionFetcher( - provision_fetcher.InitWithNewPipeAndPassReceiver()); - return std::make_unique<::media::MojoProvisionFetcher>( - std::move(provision_fetcher)); - }, - frame_interfaces); - - return std::make_unique(std::move(provision_fetcher_cb), - GetMediaTaskRunner(), cdm_origin, - media_resource_tracker()); -} - -void CastRuntimeContentBrowserClientStarboard::OnWebContentsCreated( - content::WebContents* web_contents) { - CastRuntimeContentBrowserClient::OnWebContentsCreated(web_contents); - LOG(INFO) << "Creating a new StarboardWebContentsObserver"; - content_observer_.emplace(web_contents); -} - -CastRuntimeContentBrowserClientStarboard::StarboardWebContentsObserver:: - StarboardWebContentsObserver(content::WebContents* web_contents) - : content::WebContentsObserver(web_contents) {} - -CastRuntimeContentBrowserClientStarboard::StarboardWebContentsObserver:: - ~StarboardWebContentsObserver() = default; - -void CastRuntimeContentBrowserClientStarboard::StarboardWebContentsObserver:: - LoadProgressChanged(double progress) { - if (progress == 1.0) { - LOG(INFO) << "Focusing web contents"; - web_contents()->Focus(); - } -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_CONTENT_BROWSER_CLIENT_STARBOARD_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_CONTENT_BROWSER_CLIENT_STARBOARD_H_ - -#include -#include - -#include "chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.h" -#include "content/public/browser/web_contents_observer.h" - -namespace chromecast { -namespace shell { - -// A client that creates Starboard-based CDM factories. These factories produce -// CDMs that allow decryption to be done in Starboard. -// -// Additionally, when WebContents have been fully loaded, a -// StarboardWebContentsObserver owned by this class will focus the contents. -// This is necessary for inputs to be received, e.g. by a remote control for the -// TV. -// -// Aside from this, this client is identical to CastRuntimeBrowserClient. -class CastRuntimeContentBrowserClientStarboard - : public CastRuntimeContentBrowserClient { - public: - explicit CastRuntimeContentBrowserClientStarboard( - CastFeatureListCreator* feature_list_creator); - ~CastRuntimeContentBrowserClientStarboard() override; - - // CastRuntimeContentBrowserClient implementation: - std::unique_ptr<::media::CdmFactory> CreateCdmFactory( - ::media::mojom::FrameInterfaceFactory* frame_interfaces) override; - - void OnWebContentsCreated(content::WebContents* web_contents) override; - - private: - // The starboard cast web runtime requires that the web contents be focused - // after the page has loaded. Otherwise, user inputs will not reach the - // Javascript. - // - // This class simply waits for a page to load, then focuses the contents. - class StarboardWebContentsObserver : public content::WebContentsObserver { - public: - StarboardWebContentsObserver(content::WebContents* web_contents); - - ~StarboardWebContentsObserver() override; - - // content::WebContentsObserver implementation: - void LoadProgressChanged(double progress) override; - }; - - std::optional content_observer_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_CONTENT_BROWSER_CLIENT_STARBOARD_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard_factory.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard_factory.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "base/containers/span.h" -#include "chromecast/browser/cast_content_browser_client.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client_starboard.h" -#include "chromecast/common/cors_exempt_headers.h" - -namespace chromecast { -namespace shell { - -// static -std::unique_ptr CastContentBrowserClient::Create( - CastFeatureListCreator* feature_list_creator) { - return std::make_unique( - feature_list_creator); -} - -// static -std::vector CastContentBrowserClient::GetCorsExemptHeadersList() { - base::span headers = GetLegacyCorsExemptHeaders(); - return std::vector(headers.begin(), headers.end()); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.h" - -#include "base/metrics/histogram_flattener.h" -#include "base/metrics/histogram_snapshot_manager.h" -#include "base/metrics/statistics_recorder.h" - -namespace chromecast { -namespace { - -// This is an ephemeral utility class for interacting with StatisticsRecorder -// and HistogramSnapshotManager. It collects histogram samples via -// PrepareDeltas and then puts them in cast::metrics::Histogram form. -class CastRuntimeHistogramFlattener final : public base::HistogramFlattener { - public: - CastRuntimeHistogramFlattener() : snapshot_manager_(this) {} - ~CastRuntimeHistogramFlattener() override = default; - - CastRuntimeHistogramFlattener(const CastRuntimeHistogramFlattener&) = delete; - CastRuntimeHistogramFlattener& operator=( - const CastRuntimeHistogramFlattener&) = delete; - - std::vector GetDeltas() { - DCHECK(deltas_.empty()); - - // Gather all histogram deltas, which will be sent to RecordDelta() and - // buffered in |deltas_|. - base::StatisticsRecorder::PrepareDeltas( - // Only return in-memory/non-persisted histograms. - false, - // Do not set flags on histograms. - base::Histogram::kNoFlags, - // Only upload metrics marked for UMA upload. - base::Histogram::kUmaTargetedHistogramFlag, &snapshot_manager_); - - return std::move(deltas_); - } - - private: - void RecordDelta(const base::HistogramBase& histogram, - const base::HistogramSamples& samples) override { - DCHECK_NE(0, samples.TotalCount()); - - cast::metrics::Histogram converted; - converted.set_name(histogram.histogram_name()); - converted.set_sum(samples.sum()); - - for (std::unique_ptr it = samples.Iterator(); - !it->Done(); it->Next()) { - base::Histogram::Sample min; - int64_t max = 0; - base::Histogram::Count count; - it->Get(&min, &max, &count); - - cast::metrics::HistogramBucket* bucket = converted.add_bucket(); - bucket->set_min(min); - bucket->set_max(max); - bucket->set_count(count); - } - - deltas_.push_back(std::move(converted)); - } - - base::HistogramSnapshotManager snapshot_manager_; - std::vector deltas_; -}; - -} // namespace - -std::vector GetHistogramDeltas() { - return CastRuntimeHistogramFlattener().GetDeltas(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_HISTOGRAM_FLATTENER_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_HISTOGRAM_FLATTENER_H_ - -#include - -#include "third_party/cast_core/public/src/proto/metrics/metrics_recorder.pb.h" - -namespace chromecast { - -// Returns the current uncollected histogram samples. -std::vector GetHistogramDeltas(); - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_HISTOGRAM_FLATTENER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener_unittest.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener_unittest.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,166 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.h" - -#include -#include - -#include "base/metrics/histogram_macros.h" -#include "base/metrics/statistics_recorder.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -const cast::metrics::Histogram* LookupHistogram( - std::string_view name, - const std::vector& deltas) { - for (const auto& histogram : deltas) { - if (histogram.name() == name) { - return &histogram; - } - } - return nullptr; -} - -} // namespace - -class CastRuntimeHistogramFlattenerTest : public ::testing::Test { - public: - void SetUp() override { - // Create the temporary stats recorder to get a clean state - // for each test. - statistics_recorder_ = - base::StatisticsRecorder::CreateTemporaryForTesting(); - - // Ensure existing deltas from previous tests in the process are cleared. - ASSERT_TRUE(GetHistogramDeltas().empty()); - } - - void TearDown() override { - // Destroy the temporary stats recorder, implicitly restoring - // the previous global stats recorder. - statistics_recorder_.reset(); - } - - // Stand-in `StatisticsRecorder` for this test suite, to ensure - // each test is isolated from everything else in the process that - // could emit histograms. - std::unique_ptr statistics_recorder_; -}; - -TEST_F(CastRuntimeHistogramFlattenerTest, Empty) { - EXPECT_TRUE(GetHistogramDeltas().empty()); -} - -TEST_F(CastRuntimeHistogramFlattenerTest, EmptyAfterPoll) { - constexpr char kHistName[] = "Foo.Bar.SomeCount"; - UMA_HISTOGRAM_COUNTS_1M(kHistName, 13); - auto deltas = GetHistogramDeltas(); - EXPECT_EQ(1, GetCount(13, LookupHistogram(kHistName, deltas))); - - EXPECT_TRUE(GetHistogramDeltas().empty()); -} - -TEST_F(CastRuntimeHistogramFlattenerTest, Boolean) { - constexpr char kBooleanName[] = "Foo.Bar.SomeBool"; - UMA_HISTOGRAM_BOOLEAN(kBooleanName, true); - UMA_HISTOGRAM_BOOLEAN(kBooleanName, true); - UMA_HISTOGRAM_BOOLEAN(kBooleanName, false); - - auto deltas = GetHistogramDeltas(); - EXPECT_EQ(GetCount(0, LookupHistogram(kBooleanName, deltas)), 1); - EXPECT_EQ(GetCount(1, LookupHistogram(kBooleanName, deltas)), 2); -} - -TEST_F(CastRuntimeHistogramFlattenerTest, Linear) { - constexpr char kLinearName[] = "Foo.Bar.SomeLinear"; - constexpr int kHistogramLimit = 100; - for (int i = 0; i < kHistogramLimit; ++i) { - UMA_HISTOGRAM_EXACT_LINEAR(kLinearName, i, kHistogramLimit); - } - - auto deltas = GetHistogramDeltas(); - - const cast::metrics::Histogram* histogram = - LookupHistogram(kLinearName, deltas); - for (int i = 0; i < kHistogramLimit; ++i) { - EXPECT_EQ(GetCount(i, histogram), 1); - } -} - -TEST_F(CastRuntimeHistogramFlattenerTest, Percentage) { - constexpr char kPercentageName[] = "Foo.Bar.SomePercentage"; - for (int i = 0; i <= 100; ++i) { - for (int j = 0; j < 2 * i; ++j) { - UMA_HISTOGRAM_PERCENTAGE(kPercentageName, i); - } - } - - auto deltas = GetHistogramDeltas(); - - const cast::metrics::Histogram* histogram = - LookupHistogram(kPercentageName, deltas); - for (int i = 0; i <= 100; ++i) { - EXPECT_EQ(GetCount(i, histogram), 2 * i); - } -} - -TEST_F(CastRuntimeHistogramFlattenerTest, Enumeration) { - constexpr char kEnumName[] = "Foo.Bar.SomeEnum"; - enum Category { - kAlpha, - kBeta, - kGamma, - kDelta, - kCategoryMax = kDelta, - }; - - UMA_HISTOGRAM_ENUMERATION(kEnumName, kAlpha, kCategoryMax); - UMA_HISTOGRAM_ENUMERATION(kEnumName, kGamma, kCategoryMax); - UMA_HISTOGRAM_ENUMERATION(kEnumName, kDelta, kCategoryMax); - UMA_HISTOGRAM_ENUMERATION(kEnumName, kGamma, kCategoryMax); - - auto deltas = GetHistogramDeltas(); - - const cast::metrics::Histogram* histogram = - LookupHistogram(kEnumName, deltas); - EXPECT_EQ(1, GetCount(kAlpha, histogram)); - EXPECT_EQ(0, GetCount(kBeta, histogram)); - EXPECT_EQ(2, GetCount(kGamma, histogram)); - EXPECT_EQ(1, GetCount(kDelta, histogram)); -} - -TEST_F(CastRuntimeHistogramFlattenerTest, MultipleHistograms) { - constexpr char kHistName1[] = "Foo.Bar.SomeCount"; - constexpr char kHistName2[] = "Foo.Bar.SomeOtherCount"; - - UMA_HISTOGRAM_COUNTS_1M(kHistName1, 13); - UMA_HISTOGRAM_COUNTS_1M(kHistName2, 1337); - UMA_HISTOGRAM_COUNTS_1M(kHistName2, 1337); - - auto deltas = GetHistogramDeltas(); - EXPECT_EQ(1, GetCount(13, LookupHistogram(kHistName1, deltas))); - EXPECT_EQ(2, GetCount(1337, LookupHistogram(kHistName2, deltas))); -} - -TEST_F(CastRuntimeHistogramFlattenerTest, SeparateBuckets) { - constexpr char kHistName[] = "Foo.Bar.SomeCount"; - - UMA_HISTOGRAM_COUNTS_1M(kHistName, 13); - UMA_HISTOGRAM_COUNTS_1M(kHistName, 13000); - - auto deltas = GetHistogramDeltas(); - EXPECT_EQ(1, GetCount(13, LookupHistogram(kHistName, deltas))); - EXPECT_EQ(1, GetCount(13000, LookupHistogram(kHistName, deltas))); - - UMA_HISTOGRAM_COUNTS_1M(kHistName, 13000); - UMA_HISTOGRAM_COUNTS_1M(kHistName, 13000); - deltas = GetHistogramDeltas(); - EXPECT_EQ(2, GetCount(13000, LookupHistogram(kHistName, deltas))); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,326 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.h" - -#include -#include -#include - -#include "base/json/json_string_value_serializer.h" -#include "base/logging.h" -#include "base/metrics/histogram_base.h" -#include "base/metrics/sparse_histogram.h" -#include "base/metrics/user_metrics.h" -#include "base/notreached.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "base/values.h" -#include "chromecast/base/metrics/cast_histograms.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "third_party/metrics_proto/cast_logs.pb.h" - -namespace chromecast { -namespace { - -// The following are used by cast events created from a JSON format string. -constexpr char kEventName[] = "name"; -constexpr char kEventAppId[] = "app_id"; -constexpr char kEventSessionId[] = "session_id"; -constexpr char kEventSdkVersion[] = "sdk_version"; -constexpr char kEventTime[] = "time"; -constexpr char kEventValue[] = "value"; -constexpr char kEventEventsPair[] = "events"; -constexpr char kEventAuditReport[] = "audit_report"; - -constexpr int64_t kInt64DoubleMax = 1LL << DBL_MANT_DIG; - -constexpr size_t kCastEventLimit = 1000000; - -void PopulateEventBuilder(CastEventBuilder* event_builder, - double event_time, - const std::string& app_id, - const std::string& sdk_version, - const std::string& session_id) { - event_builder->SetTime(base::TimeTicks() + base::Microseconds(event_time)); - if (!app_id.empty()) - event_builder->SetAppId(app_id); - if (!sdk_version.empty()) - event_builder->SetSdkVersion(sdk_version); - if (!session_id.empty()) - event_builder->SetSessionId(session_id); -} - -} // namespace - -CastRuntimeMetricsRecorder::EventBuilderFactory::~EventBuilderFactory() = - default; - -// NOTE: This is the same as MetricsRecorderImpl but it seems improper to mix -// MetricsRecorderImpl's static functions when this is the actual -// MetricsRecorder instance that is live. -// static -void CastRuntimeMetricsRecorder::RecordSimpleActionWithValue( - const std::string& action, - int64_t value) { - MetricsRecorder* recorder = MetricsRecorder::GetInstance(); - std::unique_ptr event_builder( - recorder->CreateEventBuilder(action)); - event_builder->SetExtraValue(value); - recorder->RecordCastEvent(std::move(event_builder)); -} - -CastRuntimeMetricsRecorder::CastRuntimeMetricsRecorder( - EventBuilderFactory* event_builder_factory) - : task_runner_(base::SequencedTaskRunner::GetCurrentDefault()), - event_builder_factory_(event_builder_factory) { - DCHECK(event_builder_factory_); - - DCHECK(!MetricsRecorder::GetInstance()); - MetricsRecorder::SetInstance(this); - metrics::CastMetricsHelper::GetInstance()->SetRecordActionCallback( - base::BindRepeating( - &CastRuntimeMetricsRecorder::CastMetricsHelperRecordActionCallback, - weak_factory_.GetWeakPtr())); -} - -CastRuntimeMetricsRecorder::~CastRuntimeMetricsRecorder() { - DCHECK(MetricsRecorder::GetInstance() == this); - metrics::CastMetricsHelper::GetInstance()->SetRecordActionCallback( - base::BindRepeating(&base::RecordComputedAction)); - MetricsRecorder::SetInstance(nullptr); -} - -std::vector CastRuntimeMetricsRecorder::TakeEvents() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return std::move(events_); -} - -std::unique_ptr -CastRuntimeMetricsRecorder::CreateEventBuilder(const std::string& name) { - auto builder = event_builder_factory_->CreateEventBuilder(); - builder->SetName(name); - return builder; -} - -void CastRuntimeMetricsRecorder::AddActiveConnection( - const std::string& transport_connection_id, - const std::string& virtual_connection_id, - const base::Value& sender_info, - const net::IPAddressBytes& sender_ip) { - NOTIMPLEMENTED(); -} - -void CastRuntimeMetricsRecorder::RemoveActiveConnection( - const std::string& connection_id) { - NOTIMPLEMENTED(); -} - -void CastRuntimeMetricsRecorder::RecordCastEvent( - std::unique_ptr event_builder) { - if (task_runner_->RunsTasksInCurrentSequence()) { - DVLOG(1) << "RecordCastEvent direct"; - RecordCastEventOnSequence(std::move(event_builder)); - } else { - DVLOG(1) << "RecordCastEvent bounce"; - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&CastRuntimeMetricsRecorder::RecordCastEventOnSequence, - weak_factory_.GetWeakPtr(), std::move(event_builder))); - } -} - -void CastRuntimeMetricsRecorder::RecordCastEventOnSequence( - std::unique_ptr event_builder) { - DVLOG(1) << "RecordCastEventOnSequence"; - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (events_.size() >= kCastEventLimit) { - static bool logged_once = false; - if (!logged_once) { - LOG(ERROR) << "Too many events queued, dropping..."; - logged_once = true; - } - return; - } - std::unique_ptr<::metrics::CastLogsProto_CastEventProto> event_proto( - event_builder->Build()); - std::string str; - if (!event_proto->SerializeToString(&str)) { - LOG(ERROR) << "Failed to serialize CastEventProto"; - return; - } - - cast::metrics::Event e; - e.mutable_impl_defined_event()->set_name(event_builder->GetName()); - e.mutable_impl_defined_event()->set_data(str); - events_.push_back(std::move(e)); -} - -void CastRuntimeMetricsRecorder::RecordHistogramTime(const std::string& name, - int sample, - int min, - int max, - int num_buckets) { - UMA_HISTOGRAM_CUSTOM_TIMES_NO_CACHE(name, base::Milliseconds(sample), - base::Milliseconds(min), - base::Milliseconds(max), num_buckets); -} - -void CastRuntimeMetricsRecorder::RecordHistogramCount(const std::string& name, - int sample, - int min, - int max, - int num_buckets) { - UMA_HISTOGRAM_CUSTOM_COUNTS_NO_CACHE(name, sample, min, max, num_buckets, - /* count */ 1); -} - -void CastRuntimeMetricsRecorder::RecordHistogramCountRepeated( - const std::string& name, - int sample, - int min, - int max, - int num_buckets, - int count) { - UMA_HISTOGRAM_CUSTOM_COUNTS_NO_CACHE(name, sample, min, max, num_buckets, - count); -} - -void CastRuntimeMetricsRecorder::RecordHistogramEnum(const std::string& name, - int sample, - int boundary) { - UMA_HISTOGRAM_ENUMERATION_NO_CACHE(name, sample, boundary); -} - -void CastRuntimeMetricsRecorder::RecordHistogramSparse(const std::string& name, - int sample) { - base::HistogramBase* counter = base::SparseHistogram::FactoryGet( - name, base::HistogramBase::kUmaTargetedHistogramFlag); - counter->Add(sample); -} - -void CastRuntimeMetricsRecorder::CastMetricsHelperRecordActionCallback( - const std::string& action) { - DVLOG(1) << "Record action via CastMetricsHelper: " << action; - std::string action_name; - std::string app_id; - std::string session_id; - std::string sdk_version; - if (metrics::CastMetricsHelper::DecodeAppInfoFromMetricsName( - action, &action_name, &app_id, &session_id, &sdk_version)) { - if (app_id.empty() && session_id.empty()) { - LOG(ERROR) << "Missing app and session ID"; - return; - } - std::unique_ptr event_builder( - CreateEventBuilder(action_name)); - event_builder->SetAppId(app_id) - .SetSessionId(session_id) - .SetSdkVersion(sdk_version); - RecordCastEvent(std::move(event_builder)); - return; - } - - // Tries to parse and record event string as JSON event. - if (RecordJsonCastEvent(action)) { - return; - } - - // This is normal non-JSON user action event. - RecordCastEvent(CreateEventBuilder(action)); -} - -bool CastRuntimeMetricsRecorder::RecordJsonCastEvent(const std::string& event) { - std::unique_ptr value( - JSONStringValueDeserializer(event).Deserialize(nullptr, nullptr)); - if (!value) { - LOG(ERROR) << "This is not a JSON format event: " << event; - return false; - } - - if (!value->is_dict()) { - LOG(ERROR) << "This is not a dictionary JSON format event: " << event; - return false; - } - - const base::Value::Dict& value_dict = value->GetDict(); - const std::string* name = value_dict.FindString(kEventName); - if (!name) { - LOG(ERROR) << "Missing field:" << kEventName; - return false; - } - - // Gets event creation time. If unavailable use now. - std::optional maybe_event_time = value_dict.FindDouble(kEventTime); - double event_time = 0; - if (maybe_event_time && maybe_event_time.value() > 0) { - event_time = maybe_event_time.value(); - } else { - event_time = (base::TimeTicks::Now() - base::TimeTicks()).InMicroseconds(); - } - // Gets App Id. - const std::string* maybe_app_id = value_dict.FindString(kEventAppId); - std::string app_id; - if (maybe_app_id) { - app_id = *maybe_app_id; - } - // Gets session Id. - const std::string* maybe_session_id = value_dict.FindString(kEventSessionId); - std::string session_id; - if (maybe_session_id) { - session_id = *maybe_session_id; - } - // Gets SDK version. - const std::string* maybe_sdk_version = - value_dict.FindString(kEventSdkVersion); - std::string sdk_version; - if (maybe_sdk_version) { - sdk_version = *maybe_sdk_version; - } - - const base::Value::Dict* multiple_events = - value_dict.FindDict(kEventEventsPair); - if (!multiple_events) { - std::unique_ptr event_builder(CreateEventBuilder(*name)); - PopulateEventBuilder(event_builder.get(), event_time, app_id, sdk_version, - session_id); - std::optional maybe_event_value = - value_dict.FindDouble(kEventValue); - if (maybe_event_value) { - double event_value = maybe_event_value.value(); - DCHECK_EQ(event_value, std::nearbyint(event_value)); - DCHECK_LE(std::abs(event_value), kInt64DoubleMax); - event_builder->SetExtraValue(static_cast(event_value)); - } - - const std::string* audit_report = value_dict.FindString(kEventAuditReport); - if (audit_report) { - event_builder->SetAuditReport(*audit_report); - } - - RecordCastEvent(std::move(event_builder)); - return true; - } - - for (auto kv : *multiple_events) { - std::optional maybe_event_value = kv.second.GetIfDouble(); - if (!maybe_event_value) { - continue; - } - - double event_value = maybe_event_value.value(); - DCHECK_EQ(event_value, std::nearbyint(event_value)); - DCHECK_LE(std::abs(event_value), kInt64DoubleMax); - - std::unique_ptr event_builder( - CreateEventBuilder(*name + "." + kv.first)); - event_builder->SetExtraValue(static_cast(event_value)); - PopulateEventBuilder(event_builder.get(), event_time, app_id, sdk_version, - session_id); - RecordCastEvent(std::move(event_builder)); - } - return true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_RECORDER_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_RECORDER_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/metrics/metrics_recorder.h" -#include "third_party/cast_core/public/src/proto/metrics/metrics_recorder.pb.h" - -namespace chromecast { - -// This class handles receiving histograms and CastEvents from the Cast OS -// MetricsRecorder interface. Histograms are forwarded to the base UMA system -// and collected by CastRuntimeHistogramFlattener and CastEvents are store here -// to be sent later. -class CastRuntimeMetricsRecorder final : public MetricsRecorder { - public: - class EventBuilderFactory { - public: - virtual ~EventBuilderFactory(); - - virtual std::unique_ptr CreateEventBuilder() = 0; - }; - - explicit CastRuntimeMetricsRecorder( - EventBuilderFactory* event_builder_factory); - ~CastRuntimeMetricsRecorder() override; - - static void RecordSimpleActionWithValue(const std::string& action, - int64_t value); - - std::vector TakeEvents(); - - private: - // MetricsRecorder implementation: - std::unique_ptr CreateEventBuilder( - const std::string& name) override; - void AddActiveConnection(const std::string& transport_connection_id, - const std::string& virtual_connection_id, - const base::Value& sender_info, - const net::IPAddressBytes& sender_ip) override; - void RemoveActiveConnection(const std::string& connection_id) override; - void RecordCastEvent( - std::unique_ptr event_builder) override; - void RecordHistogramTime(const std::string& name, - int sample, - int min, - int max, - int num_buckets) override; - void RecordHistogramCount(const std::string& name, - int sample, - int min, - int max, - int num_buckets) override; - void RecordHistogramCountRepeated(const std::string& name, - int sample, - int min, - int max, - int num_buckets, - int count) override; - void RecordHistogramEnum(const std::string& name, - int sample, - int boundary) override; - void RecordHistogramSparse(const std::string& name, int sample) override; - - void RecordCastEventOnSequence( - std::unique_ptr event_builder); - void CastMetricsHelperRecordActionCallback(const std::string& action); - bool RecordJsonCastEvent(const std::string& event); - - scoped_refptr task_runner_; - - std::vector events_; - - EventBuilderFactory* const event_builder_factory_; - - SEQUENCE_CHECKER(sequence_checker_); - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_RECORDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.h" - -#include "base/logging.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_histogram_flattener.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.h" -#include "third_party/cast_core/public/src/proto/metrics/metrics_recorder.pb.h" - -namespace chromecast { -namespace { - -constexpr size_t kMaxBatchSize = 50; - -} // namespace - -CastRuntimeMetricsRecorderService::CastRuntimeMetricsRecorderService( - CastRuntimeMetricsRecorder* metrics_recorder, - CastRuntimeActionRecorder* action_recorder, - RecordMetricsCallback record_metrics_callback, - base::TimeDelta report_interval) - : metrics_recorder_(metrics_recorder), - action_recorder_(action_recorder), - record_metrics_callback_(record_metrics_callback) { - report_timer_.Start( - FROM_HERE, report_interval, - base::BindRepeating(&CastRuntimeMetricsRecorderService::Report, - weak_factory_.GetWeakPtr())); -} - -CastRuntimeMetricsRecorderService::~CastRuntimeMetricsRecorderService() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -void CastRuntimeMetricsRecorderService::OnCloseSoon( - base::OnceClosure complete_callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (flush_complete_callback_) { - return; - } - report_timer_.Stop(); - flush_complete_callback_ = std::move(complete_callback); - Report(); -} - -void CastRuntimeMetricsRecorderService::Report() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - std::vector events = metrics_recorder_->TakeEvents(); - for (auto& histogram : GetHistogramDeltas()) { - cast::metrics::Event event; - *event.mutable_histogram() = std::move(histogram); - events.push_back(std::move(event)); - } - - for (auto& action : action_recorder_->TakeEvents()) { - cast::metrics::Event event; - *event.mutable_user_action_event() = std::move(action); - events.push_back(std::move(event)); - } - - std::move(events.begin(), events.end(), std::back_inserter(send_buffer_)); - - DrainBuffer(); -} - -void CastRuntimeMetricsRecorderService::OnMetricsRecorded() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(ack_pending_); - ack_pending_ = false; - DrainBuffer(); -} - -void CastRuntimeMetricsRecorderService::DrainBuffer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (ack_pending_) { - return; - } - if (send_buffer_.empty()) { - if (flush_complete_callback_) { - std::move(flush_complete_callback_).Run(); - } - return; - } - // NOTE: Ordering doesn't matter, so we can more efficiently tear off the end - // of the vector each time. - size_t start_index = - send_buffer_.size() - std::min(send_buffer_.size(), kMaxBatchSize); - cast::metrics::RecordRequest request; - *request.mutable_event() = {send_buffer_.begin() + start_index, - send_buffer_.end()}; - send_buffer_.resize(start_index); - - DVLOG(2) << "Sending metrics"; - ack_pending_ = true; - record_metrics_callback_.Run( - std::move(request), - base::BindOnce(&CastRuntimeMetricsRecorderService::OnMetricsRecorded, - weak_factory_.GetWeakPtr())); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_RECORDER_SERVICE_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_RECORDER_SERVICE_H_ - -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "third_party/cast_core/public/src/proto/metrics/metrics_recorder.pb.h" - -namespace chromecast { - -class CastRuntimeActionRecorder; -class CastRuntimeMetricsRecorder; - -// This class uses a timer to periodically send all collected metrics to Cast -// Core via MetricsRecorderGrpc. It begins running the timer task on -// construction. After OnCloseSoon(), it only attempts one more round of -// metrics and then stops. -class CastRuntimeMetricsRecorderService { - public: - using RecordCompleteCallback = base::OnceClosure; - using RecordMetricsCallback = - base::RepeatingCallback; - - // All these pointers must outlive |this|. - CastRuntimeMetricsRecorderService( - CastRuntimeMetricsRecorder* metrics_recorder, - CastRuntimeActionRecorder* action_recorder, - RecordMetricsCallback record_metrics_callback, - base::TimeDelta report_interval); - ~CastRuntimeMetricsRecorderService(); - - void OnCloseSoon(base::OnceClosure complete_callback); - - private: - void Report(); - void DrainBuffer(); - void OnMetricsRecorded(); - - CastRuntimeMetricsRecorder* const metrics_recorder_; - CastRuntimeActionRecorder* const action_recorder_; - RecordMetricsCallback record_metrics_callback_; - base::RepeatingTimer report_timer_; - - bool ack_pending_{false}; - base::OnceClosure flush_complete_callback_; - std::vector send_buffer_; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_RECORDER_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.h" - -namespace chromecast { - -int64_t GetCount(int64_t value, const cast::metrics::Histogram* histogram) { - for (int i = 0; i < histogram->bucket_size(); ++i) { - const auto& bucket = histogram->bucket(i); - if (value >= bucket.min() && value < bucket.max()) { - return bucket.count(); - } - } - return 0; -} - -std::unique_ptr<::metrics::CastLogsProto_CastEventProto> ParseCastEventProto( - const std::string& serialized) { - auto event = std::make_unique<::metrics::CastLogsProto_CastEventProto>(); - if (!event->ParseFromString(serialized)) { - return nullptr; - } - return event; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/cast_runtime_metrics_test_helpers.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_TEST_HELPERS_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_TEST_HELPERS_H_ - -#include -#include -#include - -#include "third_party/cast_core/public/src/proto/metrics/metrics_recorder.pb.h" -#include "third_party/metrics_proto/cast_logs.pb.h" - -namespace chromecast { - -// Gets the number of samples in the bucket in |histogram| that |value| would go -// into. -int64_t GetCount(int64_t value, const cast::metrics::Histogram* histogram); - -// Returns nullptr if parsing failed. -std::unique_ptr<::metrics::CastLogsProto_CastEventProto> ParseCastEventProto( - const std::string& serialized); - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CAST_RUNTIME_METRICS_TEST_HELPERS_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_conversions.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_conversions.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_conversions.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_conversions.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/core_conversions.h" - -#include "base/ranges/algorithm.h" -#include "chromecast/common/feature_constants.h" -#include "third_party/blink/public/common/permissions/permission_utils.h" -#include "third_party/cast_core/public/src/proto/common/application_config.pb.h" -#include "url/gurl.h" -#include "url/origin.h" - -namespace chromecast { -namespace { - -std::vector GetFeaturePermissions( - const cast::common::ApplicationConfig& core_config) { - std::vector feature_permissions; - auto it = base::ranges::find(core_config.extra_features().entries(), - feature::kCastCoreFeaturePermissions, - &cast::common::Dictionary::Entry::key); - if (it == core_config.extra_features().entries().end()) { - return feature_permissions; - } - - CHECK(it->value().value_case() == cast::common::Value::kArray); - base::ranges::for_each( - it->value().array().values(), - [&feature_permissions](const cast::common::Value& value) { - CHECK(value.value_case() == cast::common::Value::kNumber); - // TODO(crbug.com/1383326): Ensure this is a valid permission from an - // allow list supported by the cast_receiver component. - feature_permissions.push_back( - static_cast(value.number())); - }); - return feature_permissions; -} - -std::vector GetAdditionalFeaturePermissionOrigins( - const cast::common::ApplicationConfig& core_config) { - std::vector feature_permission_origins; - auto it = base::ranges::find(core_config.extra_features().entries(), - feature::kCastCoreFeaturePermissionOrigins, - &cast::common::Dictionary::Entry::key); - if (it == core_config.extra_features().entries().end()) { - return feature_permission_origins; - } - - CHECK(it->value().value_case() == cast::common::Value::kArray); - base::ranges::for_each( - it->value().array().values(), - [&feature_permission_origins](const cast::common::Value& value) { - CHECK(value.value_case() == cast::common::Value::kText); - auto origin = url::Origin::Create(GURL(value.text())); - CHECK(!origin.opaque()); - feature_permission_origins.push_back(std::move(origin)); - }); - return feature_permission_origins; -} - -cast_receiver::ApplicationConfig::ContentPermissions ToReceiverPermissions( - const cast::common::ApplicationConfig& core_config) { - return cast_receiver::ApplicationConfig::ContentPermissions{ - GetFeaturePermissions(core_config), - GetAdditionalFeaturePermissionOrigins(core_config)}; -} - -} // namespace - -cast_receiver::ApplicationConfig ToReceiverConfig( - const cast::common::ApplicationConfig& core_config) { - cast_receiver::ApplicationConfig config{core_config.app_id(), - core_config.display_name(), - ToReceiverPermissions(core_config)}; - if (core_config.has_cast_web_app_config()) { - config.url = GURL(core_config.cast_web_app_config().url()); - if (!config.url->is_valid()) { - config.url = std::nullopt; - } - } - - return config; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_conversions.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_conversions.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_conversions.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_conversions.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CORE_CONVERSIONS_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CORE_CONVERSIONS_H_ - -#include "components/cast_receiver/browser/public/application_config.h" - -namespace cast::common { -class ApplicationConfig; -} // namespace cast::common - -namespace chromecast { - -cast_receiver::ApplicationConfig ToReceiverConfig( - const cast::common::ApplicationConfig& core_config); - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CORE_CONVERSIONS_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_streaming_config_manager.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_streaming_config_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,240 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/core_streaming_config_manager.h" - -#include -#include - -#include "base/containers/contains.h" -#include "base/logging.h" -#include "base/not_fatal_until.h" -#include "base/ranges/algorithm.h" -#include "base/strings/string_util.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/shared/platform_info_serializer.h" -#include "components/cast/message_port/platform_message_port.h" -#include "components/cast_receiver/browser/public/message_port_service.h" -#include "components/cast_receiver/common/public/status.h" -#include "media/base/audio_codecs.h" -#include "media/base/channel_layout.h" -#include "media/base/video_codecs.h" -#include "media/base/video_decoder_config.h" - -namespace chromecast { -namespace { - -constexpr char kMediaCapabilitiesBindingName[] = - "cast.__platform__.canDisplayType"; - -::media::VideoCodec ToChromiumCodec(media::VideoCodec codec) { - switch (codec) { - case media::VideoCodec::kCodecH264: - return ::media::VideoCodec::kH264; - case media::VideoCodec::kCodecVP8: - return ::media::VideoCodec::kVP8; - case media::VideoCodec::kCodecHEVC: - return ::media::VideoCodec::kHEVC; - case media::VideoCodec::kCodecVP9: - return ::media::VideoCodec::kVP9; - case media::VideoCodec::kCodecAV1: - return ::media::VideoCodec::kAV1; - default: - break; - } - - return ::media::VideoCodec::kUnknown; -} - -::media::AudioCodec ToChromiumCodec(media::AudioCodec codec) { - switch (codec) { - case media::AudioCodec::kCodecAAC: - return ::media::AudioCodec::kAAC; - case media::AudioCodec::kCodecOpus: - return ::media::AudioCodec::kOpus; - default: - break; - } - - return ::media::AudioCodec::kUnknown; -} - -cast_streaming::ReceiverConfig CreateConfig( - const PlatformInfoSerializer& deserializer) { - cast_streaming::ReceiverConfig constraints; - - const std::optional width = deserializer.MaxWidth(); - const std::optional height = deserializer.MaxHeight(); - const std::optional frame_rate = deserializer.MaxFrameRate(); - if (width && *width && height && *height && frame_rate && *frame_rate) { - cast_streaming::ReceiverConfig::Display display; - display.dimensions = gfx::Rect{*width, *height}; - display.max_frame_rate = *frame_rate; - constraints.display_description = std::move(display); - } else { - DLOG(WARNING) - << "Some Display properties missing. Using default values for " - << "MaxWidth, MaxHeight, and MaxFrameRate"; - -#if DCHECK_IS_ON() - if (!height) { - LOG(INFO) << "MaxHeight value not present in received AV Settings."; - } else if (!*height) { - LOG(WARNING) << "Invalid MaxHeight of 0 parsed from AV Settings."; - } else if (height) { - LOG(WARNING) - << "MaxHeight value ignored due to missing display properties."; - } - - if (!width) { - LOG(INFO) << "MaxWidth value not present in received AV Settings."; - } else if (!*width) { - LOG(WARNING) << "Invalid MaxWidth of 0 parsed from AV Settings."; - } else if (width) { - LOG(WARNING) - << "MaxWidth value ignored due to missing display properties."; - } - - if (!frame_rate) { - LOG(INFO) << "MaxFrameRate value not present in received AV Settings."; - } else if (!*frame_rate) { - LOG(WARNING) << "Invalid MaxFrameRate of 0 parsed from AV Settings."; - } else if (frame_rate) { - LOG(WARNING) - << "MaxFrameRate value ignored due to missing display properties."; - } -#endif // DCHECK_IS_ON() - } - - auto audio_codec_infos = deserializer.SupportedAudioCodecs(); - std::vector<::media::AudioCodec> audio_codecs; - std::vector audio_limits; - if (!audio_codec_infos || (*audio_codec_infos).empty()) { - DLOG(WARNING) << "No AudioCodecInfos in received AV Settings."; - } else { - for (auto& info : *audio_codec_infos) { - const auto converted_codec = ToChromiumCodec(info.codec); - if (converted_codec == ::media::AudioCodec::kUnknown) { - DLOG(INFO) << "Skipping processing of unknown audio codec..."; - continue; - } - - if (!base::Contains(audio_codecs, converted_codec)) { - audio_codecs.push_back(converted_codec); - - audio_limits.emplace_back(); - auto& limit = audio_limits.back(); - limit.codec = converted_codec; - limit.max_sample_rate = info.max_samples_per_second; - limit.channel_layout = - ::media::GuessChannelLayout(info.max_audio_channels); - continue; - } - - auto it = base::ranges::find( - audio_limits, converted_codec, - &cast_streaming::ReceiverConfig::AudioLimits::codec); - CHECK(it != audio_limits.end(), base::NotFatalUntil::M130); - if (it->max_sample_rate) { - it->max_sample_rate = - std::max(it->max_sample_rate.value(), info.max_samples_per_second); - } else { - it->max_sample_rate = info.max_samples_per_second; - } - it->channel_layout = ::media::GuessChannelLayout(info.max_audio_channels); - } - } - - if (!audio_codecs.empty()) { - DCHECK(!audio_limits.empty()); - constraints.audio_codecs = std::move(audio_codecs); - constraints.audio_limits = std::move(audio_limits); - } else { - auto max_channels = deserializer.MaxChannels(); - if (max_channels && *max_channels) { - constraints.audio_limits.emplace_back(); - constraints.audio_limits.back().channel_layout = - ::media::GuessChannelLayout(*max_channels); - } - } - - auto video_codec_infos = deserializer.SupportedVideoCodecs(); - if (!video_codec_infos || (*video_codec_infos).empty()) { - DLOG(WARNING) << "No VideoCodecInfos in received AV Settings."; - } else { - std::vector<::media::VideoCodec> video_codecs; - for (auto& info : *video_codec_infos) { - const auto converted_codec = ToChromiumCodec(info.codec); - if (converted_codec == ::media::VideoCodec::kUnknown) { - DLOG(INFO) << "Skipping processing of unknown video codec..."; - continue; - } - - if (!base::Contains(video_codecs, converted_codec)) { - video_codecs.push_back(converted_codec); - } - } - - if (!video_codecs.empty()) { - constraints.video_codecs = std::move(video_codecs); - } - } - - return constraints; -} - -} // namespace - -CoreStreamingConfigManager::CoreStreamingConfigManager( - cast_receiver::MessagePortService& message_port_service, - cast_receiver::RuntimeApplication::StatusCallback error_cb) - : CoreStreamingConfigManager(std::move(error_cb)) { - std::unique_ptr server; - cast_api_bindings::CreatePlatformMessagePortPair(&message_port_, &server); - message_port_->SetReceiver(this); - - message_port_service.ConnectToPortAsync(kMediaCapabilitiesBindingName, - std::move(server)); -} - -CoreStreamingConfigManager::CoreStreamingConfigManager( - cast_receiver::RuntimeApplication::StatusCallback error_cb) - : error_callback_(std::move(error_cb)) {} - -CoreStreamingConfigManager::~CoreStreamingConfigManager() = default; - -bool CoreStreamingConfigManager::OnMessage( - std::string_view message, - std::vector> ports) { - DLOG(INFO) << "AV Settings Response Received: " << message; - - DCHECK(ports.empty()); - - std::optional deserializer = - PlatformInfoSerializer::Deserialize(message); - if (!deserializer) { - LOG(ERROR) << "AV Settings with invalid protobuf received: " << message; - if (error_callback_) { - std::move(error_callback_) - .Run(cast_receiver::Status( - cast_receiver::StatusCode::kInvalidArgument, - "AV Settings with invalid protobuf received")); - } - return false; - } - - OnStreamingConfigSet(CreateConfig(*deserializer)); - return true; -} - -void CoreStreamingConfigManager::OnPipeError() { - DLOG(WARNING) << "Pipe disconnected."; - if (error_callback_) { - std::move(error_callback_) - .Run(cast_receiver::Status(cast_receiver::StatusCode::kInternal, - "MessagePort pipe disconnected")); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_streaming_config_manager.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_streaming_config_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CORE_STREAMING_CONFIG_MANAGER_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CORE_STREAMING_CONFIG_MANAGER_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/sequence_checker.h" -#include "components/cast/message_port/message_port.h" -#include "components/cast_receiver/browser/public/runtime_application.h" -#include "components/cast_receiver/browser/public/streaming_config_manager.h" - -namespace cast_receiver { -class MessagePortService; -} // namespace cast_receiver - -namespace chromecast { - -// This class implements retrieving of a cast_streaming::RuntimeConfig from an -// AV Settings MessagePort query. -class CoreStreamingConfigManager - : public cast_receiver::StreamingConfigManager, - public cast_api_bindings::MessagePort::Receiver { - public: - // Creates a new instance of this class. |message_port_service| must persist - // for the lifetime of this instance. - CoreStreamingConfigManager( - cast_receiver::MessagePortService& message_port_service, - cast_receiver::RuntimeApplication::StatusCallback error_cb); - ~CoreStreamingConfigManager() override; - - private: - friend class CoreStreamingConfigManagerTest; - - // Internal ctor that does not query for AV Settings. Intended to be used only - // for testing purposes. - CoreStreamingConfigManager( - cast_receiver::RuntimeApplication::StatusCallback error_cb); - - // cast_api_bindings::MessagePort::Receiver overrides. - bool OnMessage(std::string_view message, - std::vector> - ports) override; - void OnPipeError() override; - - // MessagePort responsible for receiving AV Settings Bindings Messages. - std::unique_ptr message_port_; - - cast_receiver::RuntimeApplication::StatusCallback error_callback_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_CORE_STREAMING_CONFIG_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_streaming_config_manager_unittest.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager_unittest.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/core_streaming_config_manager_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/core_streaming_config_manager_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,141 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/core_streaming_config_manager.h" - -#include - -#include "base/containers/contains.h" -#include "base/test/task_environment.h" -#include "chromecast/shared/platform_info_serializer.h" -#include "components/cast_receiver/browser/public/runtime_application.h" -#include "components/cast_receiver/common/public/status.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; -using testing::StrictMock; - -namespace network { -namespace mojom { -class NetworkContext; -} // namespace mojom -} // namespace network - -namespace chromecast { -namespace { - -class MockConfigObserver - : public cast_receiver::StreamingConfigManager::ConfigObserver { - public: - MOCK_METHOD1(OnStreamingConfigSet, - void(const cast_streaming::ReceiverConfig&)); -}; - -} // namespace - -class CoreStreamingConfigManagerTest : public testing::Test { - public: - CoreStreamingConfigManagerTest() - : streaming_config_manager_( - base::BindOnce(&CoreStreamingConfigManagerTest::FailOnError, - base::Unretained(this))) { - streaming_config_manager_.AddConfigObserver(observer_); - } - - ~CoreStreamingConfigManagerTest() override { ResetMessagePort(); } - - protected: - bool PostMessage(std::string_view message) { - return streaming_config_manager_.OnMessage(message, {}); - } - - // When calling task_environment_.FastForwardBy(), OnPipeError() gets called. - // Resetting the pipe is cleaner than passing in a base::OnceCallback() to - // create the MessagePort pair. - void ResetMessagePort() { streaming_config_manager_.message_port_.reset(); } - - void FailOnError(cast_receiver::Status status) { FAIL() << status; } - - base::test::SingleThreadTaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; - - CoreStreamingConfigManager streaming_config_manager_; - testing::StrictMock observer_; -}; - -TEST_F(CoreStreamingConfigManagerTest, OnSingleValidMessageEmpty) { - PlatformInfoSerializer serializer; - EXPECT_FALSE(streaming_config_manager_.has_config()); - EXPECT_CALL(observer_, OnStreamingConfigSet(_)); - EXPECT_TRUE(PostMessage(serializer.Serialize())); - EXPECT_TRUE(streaming_config_manager_.has_config()); -} - -TEST_F(CoreStreamingConfigManagerTest, OnSingleValidMessageNoCodecs) { - PlatformInfoSerializer serializer; - serializer.SetMaxChannels(2); - EXPECT_FALSE(streaming_config_manager_.has_config()); - EXPECT_CALL(observer_, OnStreamingConfigSet(_)); - EXPECT_TRUE(PostMessage(serializer.Serialize())); - EXPECT_TRUE(streaming_config_manager_.has_config()); - - auto config = streaming_config_manager_.config(); - ASSERT_EQ(config.audio_limits.size(), size_t{1}); - auto& limit = config.audio_limits.back(); - EXPECT_EQ(limit.codec, std::nullopt); - EXPECT_EQ(limit.channel_layout, ::media::CHANNEL_LAYOUT_STEREO); -} - -TEST_F(CoreStreamingConfigManagerTest, OnSingleValidMessageWithCodecs) { - PlatformInfoSerializer serializer; - std::vector audio_infos; - audio_infos.push_back(PlatformInfoSerializer::AudioCodecInfo{ - media::AudioCodec::kCodecOpus, media::SampleFormat::kSampleFormatU8, 123, - 2}); - audio_infos.push_back(PlatformInfoSerializer::AudioCodecInfo{ - media::AudioCodec::kCodecOpus, media::SampleFormat::kSampleFormatS24, 123, - 2}); - audio_infos.push_back(PlatformInfoSerializer::AudioCodecInfo{ - media::AudioCodec::kCodecMP3, media::SampleFormat::kSampleFormatU8, 42, - 42}); - audio_infos.push_back(PlatformInfoSerializer::AudioCodecInfo{ - media::AudioCodec::kCodecMP3, media::SampleFormat::kSampleFormatS24, 42, - 42}); - std::vector video_infos; - video_infos.push_back(PlatformInfoSerializer::VideoCodecInfo{ - media::VideoCodec::kCodecVP9, media::VideoProfile::kVP9Profile1}); - video_infos.push_back(PlatformInfoSerializer::VideoCodecInfo{ - media::VideoCodec::kCodecVP9, media::VideoProfile::kVP9Profile2}); - video_infos.push_back(PlatformInfoSerializer::VideoCodecInfo{ - media::VideoCodec::kCodecAV1, media::VideoProfile::kAV1ProfilePro}); - video_infos.push_back(PlatformInfoSerializer::VideoCodecInfo{ - media::VideoCodec::kCodecVP8, media::VideoProfile::kVP8ProfileAny}); - - serializer.SetSupportedAudioCodecs(std::move(audio_infos)); - serializer.SetSupportedVideoCodecs(std::move(video_infos)); - EXPECT_FALSE(streaming_config_manager_.has_config()); - EXPECT_CALL(observer_, OnStreamingConfigSet(_)); - EXPECT_TRUE(PostMessage(serializer.Serialize())); - EXPECT_TRUE(streaming_config_manager_.has_config()); - - const auto& config = streaming_config_manager_.config(); - ASSERT_GE(config.audio_codecs.size(), size_t{1}); - EXPECT_EQ(config.audio_codecs.size(), size_t{1}); - EXPECT_EQ(config.audio_codecs[0], ::media::AudioCodec::kOpus); - ASSERT_GE(config.audio_limits.size(), size_t{1}); - EXPECT_EQ(config.audio_limits.size(), size_t{1}); - auto& limit = config.audio_limits.back(); - ASSERT_TRUE(limit.codec.has_value()); - EXPECT_EQ(limit.codec.value(), ::media::AudioCodec::kOpus); - EXPECT_EQ(limit.max_sample_rate, 123); - - auto video_codecs = config.video_codecs; - EXPECT_EQ(video_codecs.size(), size_t{3}); - EXPECT_TRUE(base::Contains(video_codecs, ::media::VideoCodec::kVP9)); - EXPECT_TRUE(base::Contains(video_codecs, ::media::VideoCodec::kVP8)); - EXPECT_TRUE(config.video_limits.empty()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/message_port_handler.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_handler.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/message_port_handler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_handler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,268 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/message_port_handler.h" - -#include -#include - -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "components/cast/message_port/platform_message_port.h" -#include "components/cast_receiver/browser/public/message_port_service.h" - -namespace chromecast { -namespace { - -// This is used as a timeout for both sending cast::web::Message requests and -// awaiting responses. Reaching this timeout without a response from the peer -// will close the connection and Blink message port. -constexpr base::TimeDelta kMessageTimeout = base::Seconds(10); - -} // namespace - -#define DLOG_CHANNEL(level) DLOG(level) << "channel " << channel_id_ << ": " -#define DVLOG_CHANNEL(level) DVLOG(level) << "channel " << channel_id_ << ": " - -MessagePortHandler::MessagePortHandler( - std::unique_ptr message_port, - uint32_t channel_id, - cast_receiver::MessagePortService* message_port_service, - cast::v2::CoreMessagePortApplicationServiceStub* core_app_stub, - scoped_refptr task_runner) - : task_runner_(std::move(task_runner)), - message_port_service_(message_port_service), - core_app_stub_(core_app_stub), - message_port_(std::move(message_port)), - channel_id_(channel_id) { - DCHECK(message_port_service_); - DCHECK(core_app_stub_); - message_port_->SetReceiver(this); -} - -MessagePortHandler::~MessagePortHandler() = default; - -cast_receiver::Status MessagePortHandler::HandleMessage( - const cast::web::Message& message) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!message_port_) { - return cast_receiver::Status(cast_receiver::StatusCode::kFailedPrecondition, - "Invalid MessagePort"); - } - - switch (message.message_type_case()) { - case cast::web::Message::kStatus: { - if (message.status().status() == - cast::web::MessagePortStatus_Status_ERROR) { - DLOG_CHANNEL(WARNING) << "Received error message"; - CloseAndRemove(); - } else if (message.status().status() == - cast::web::MessagePortStatus_Status_STARTED) { - bool was_started = started_; - started_ = true; - if (!was_started && !pending_messages_.empty()) { - ForwardNextMessage(); - } - } - return cast_receiver::OkStatus(); - } - case cast::web::Message::kRequest: { - DLOG_CHANNEL(INFO) << "Received request: " << message.request().data(); - std::vector> ports; - ports.reserve(message.request().ports_size()); - for (const auto& port : message.request().ports()) { - std::unique_ptr client; - std::unique_ptr server; - cast_api_bindings::CreatePlatformMessagePortPair(&client, &server); - message_port_service_->RegisterIncomingPort(port.channel().channel_id(), - std::move(client)); - ports.push_back(std::move(server)); - - cast::web::Message notification; - notification.mutable_channel()->set_channel_id( - port.channel().channel_id()); - notification.mutable_status()->set_status( - cast::web::MessagePortStatus_Status_STARTED); - ForwardMessage(std::move(notification)); - } - bool result = message_port_->PostMessageWithTransferables( - message.request().data(), std::move(ports)); - SendResponse(result); - return cast_receiver::OkStatus(); - } - case cast::web::Message::kResponse: { - if (!is_awaiting_response_) { - LOG(FATAL) << "Received response while not expecting one."; - } - message_timeout_callback_.Cancel(); - is_awaiting_response_ = false; - if (!pending_messages_.empty() && !has_outstanding_request_) { - ForwardNextMessage(); - } - return cast_receiver::OkStatus(); - } - default: - return cast_receiver::Status(cast_receiver::StatusCode::kInvalidArgument, - "Invalid cast::web::Message"); - } -} - -void MessagePortHandler::Close() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DLOG_CHANNEL(INFO) << "Closing channel"; - message_timeout_callback_.Cancel(); - pending_messages_.clear(); - message_port_->Close(); - message_port_.reset(); -} - -void MessagePortHandler::CloseAndRemove() { - Close(); - message_port_service_->Remove(channel_id_); -} - -void MessagePortHandler::CloseWithError(CloseError error) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - switch (error) { - case CloseError::kPipeError: - DLOG_CHANNEL(INFO) << "Closing with pipe error"; - break; - case CloseError::kTimeout: - DLOG_CHANNEL(INFO) << "Closing from timeout"; - break; - } - Close(); - - auto call = core_app_stub_->CreateCall< - cast::v2::CoreMessagePortApplicationServiceStub::PostMessage>(); - call.request().mutable_status()->set_status( - cast::web::MessagePortStatus_Status_ERROR); - call.request().mutable_channel()->set_channel_id(channel_id_); - std::move(call).InvokeAsync(base::DoNothing()); - - message_port_service_->Remove(channel_id_); -} - -void MessagePortHandler::SendResponse(bool result) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - cast::web::Message message; - message.mutable_response()->set_result(result); - message.mutable_channel()->set_channel_id(channel_id_); - ForwardMessage(std::move(message)); -} - -void MessagePortHandler::ForwardNextMessage() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!is_awaiting_response_); - DCHECK(!pending_messages_.empty()); - DCHECK(!has_outstanding_request_); - cast::web::Message next = std::move(pending_messages_.front()); - pending_messages_.pop_front(); - ForwardMessageNow(std::move(next)); -} - -bool MessagePortHandler::ForwardMessage(cast::web::Message message) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (message.has_request() && - (!started_ || is_awaiting_response_ || !pending_messages_.empty() || - has_outstanding_request_)) { - pending_messages_.emplace_back(std::move(message)); - return true; - } - - ForwardMessageNow(std::move(message)); - return true; -} - -void MessagePortHandler::ForwardMessageNow(cast::web::Message message) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!message.has_request() || !has_outstanding_request_); - bool was_request = message.has_request(); - - auto call = core_app_stub_->CreateCall< - cast::v2::CoreMessagePortApplicationServiceStub::PostMessage>( - std::move(message)); - std::move(call).InvokeAsync(base::BindPostTask( - task_runner_, base::BindOnce(&MessagePortHandler::OnPortMessagePosted, - weak_factory_.GetWeakPtr(), was_request))); - if (was_request) { - has_outstanding_request_ = true; - is_awaiting_response_ = true; - } - ResetTimeout(); -} - -void MessagePortHandler::ResetTimeout() { - message_timeout_callback_.Reset( - base::BindOnce(&MessagePortHandler::CloseWithError, - weak_factory_.GetWeakPtr(), CloseError::kTimeout)); - task_runner_->PostDelayedTask(FROM_HERE, message_timeout_callback_.callback(), - kMessageTimeout); -} - -void MessagePortHandler::OnPortMessagePosted( - bool was_request, - cast::utils::GrpcStatusOr response_or) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - has_outstanding_request_ = false; - message_timeout_callback_.Cancel(); - if (!message_port_) { - return; - } - - if (!response_or.ok() || - response_or->status() != cast::web::MessagePortStatus_Status_OK) { - DLOG_CHANNEL(WARNING) << "Send failed (" << response_or.ToString() << ", " - << cast::web::MessagePortStatus_Status_Name( - response_or->status()) - << ")"; - CloseAndRemove(); - return; - } - - if (was_request && is_awaiting_response_) { - ResetTimeout(); - } else if (!is_awaiting_response_ && !pending_messages_.empty()) { - ForwardNextMessage(); - } -} - -bool MessagePortHandler::OnMessage( - std::string_view message, - std::vector> ports) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - cast::web::Message request; - request.mutable_request()->set_data(std::string(message)); - request.mutable_channel()->set_channel_id(channel_id_); - std::vector started_notifications; - started_notifications.reserve(ports.size()); - for (auto& port : ports) { - auto* descriptor = request.mutable_request()->mutable_ports()->Add(); - uint32_t channel_id = - message_port_service_->RegisterOutgoingPort(std::move(port)); - descriptor->mutable_channel()->set_channel_id(channel_id); - descriptor->set_sequence_number(0); - - cast::web::Message notification; - notification.mutable_channel()->set_channel_id(channel_id); - notification.mutable_status()->set_status( - cast::web::MessagePortStatus_Status_STARTED); - started_notifications.push_back(std::move(notification)); - } - ForwardMessage(std::move(request)); - for (auto& notification : started_notifications) { - ForwardMessage(std::move(notification)); - } - return true; -} - -void MessagePortHandler::OnPipeError() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CloseWithError(CloseError::kPipeError); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/message_port_handler.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_handler.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/message_port_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,113 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_MESSAGE_PORT_HANDLER_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_MESSAGE_PORT_HANDLER_H_ - -#include -#include -#include - -#include "base/cancelable_callback.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "base/task/sequenced_task_runner.h" -#include "components/cast/message_port/message_port.h" -#include "components/cast_receiver/common/public/status.h" -#include "third_party/cast_core/public/src/proto/v2/core_message_port_application_service.castcore.pb.h" -#include "third_party/cast_core/public/src/proto/web/message_channel.pb.h" - -namespace cast_receiver { -class MessagePortService; -} - -namespace chromecast { - -class MessagePortHandler final - : public cast_api_bindings::MessagePort::Receiver { - public: - // |message_port_service|, |cq|, and |core_app_stub| should all outlive - // |this|. Furthermore, |message_port_service| should actually own |this|. - MessagePortHandler( - std::unique_ptr message_port, - uint32_t channel_id, - cast_receiver::MessagePortService* message_port_service, - cast::v2::CoreMessagePortApplicationServiceStub* core_app_stub, - scoped_refptr task_runner); - ~MessagePortHandler() override; - - MessagePortHandler(const MessagePortHandler&) = delete; - MessagePortHandler(MessagePortHandler&&) = delete; - MessagePortHandler& operator=(const MessagePortHandler&) = delete; - MessagePortHandler& operator=(MessagePortHandler&&) = delete; - - // Handles a message incoming from the gRPC API. Returns true if it was able - // to be handled successfully, false otherwise. - cast_receiver::Status HandleMessage(const cast::web::Message& message); - - private: - enum class CloseError { - kPipeError, - kTimeout, - }; - - // Closes the message port. - void Close(); - - // Closes the message port and removes this channel from - // |message_port_service_|. - void CloseAndRemove(); - - // Closes the message port, sends an error on the channel, and removes this - // channel from |message_port_service_|. - void CloseWithError(CloseError error); - - // Sends a MessageResponse with the value |result|. - void SendResponse(bool result); - - // Forwards the next message from |pending_messages_| over this channel. - void ForwardNextMessage(); - - // Forwards |message| over this channel if possible, but queues it if there's - // already a pending request. - bool ForwardMessage(cast::web::Message message); - - // Forwards |message| over this channel now. - void ForwardMessageNow(cast::web::Message message); - - // Resets the timeout on the port that indicates we should close due to - // inactivity. - void ResetTimeout(); - - // Callback invoked when an AsyncMessage gets a gRPC result. - void OnPortMessagePosted( - bool was_request, - cast::utils::GrpcStatusOr response_or); - - // cast_api_bindings::MessagePort::Receiver overrides. - bool OnMessage(std::string_view message, - std::vector> - ports) override; - void OnPipeError() override; - - scoped_refptr task_runner_; - cast_receiver::MessagePortService* const message_port_service_; - cast::v2::CoreMessagePortApplicationServiceStub* const core_app_stub_; - std::unique_ptr message_port_; - uint32_t channel_id_; - - base::CancelableOnceClosure message_timeout_callback_; - std::deque pending_messages_; - bool has_outstanding_request_{false}; - bool is_awaiting_response_{false}; - bool started_{false}; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_MESSAGE_PORT_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/message_port_service_grpc.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_service_grpc.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/message_port_service_grpc.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_service_grpc.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,111 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/message_port_service_grpc.h" - -#include -#include - -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/cast_core/runtime/browser/message_port_handler.h" - -namespace chromecast { - -MessagePortServiceGrpc::MessagePortServiceGrpc( - cast::v2::CoreMessagePortApplicationServiceStub* core_app_stub) - : core_app_stub_(core_app_stub), - task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) { - DCHECK(core_app_stub_); -} - -MessagePortServiceGrpc::~MessagePortServiceGrpc() = default; - -cast_receiver::Status MessagePortServiceGrpc::HandleMessage( - cast::web::Message message) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - cast::web::MessagePortStatus response; - const uint32_t channel_id = message.channel().channel_id(); - auto entry = ports_.find(channel_id); - if (entry == ports_.end()) { - std::stringstream error_ss; - error_ss << "Got message for unknown channel: " << channel_id; - return cast_receiver::Status(cast_receiver::StatusCode::kUnknown, - error_ss.str()); - } - - return entry->second->HandleMessage(message); -} - -void MessagePortServiceGrpc::ConnectToPortAsync( - std::string_view port_name, - std::unique_ptr port) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DLOG(INFO) << "Connecting to port '" << port_name << "' as channel " - << next_outgoing_channel_id_; - - const uint32_t channel_id = next_outgoing_channel_id_++; - auto result = ports_.emplace( - channel_id, MakeMessagePortHandler(channel_id, std::move(port))); - DCHECK(result.second); - - auto call = core_app_stub_->CreateCall< - cast::v2::CoreMessagePortApplicationServiceStub::Connect>(); - call.request().set_port_name(std::string(port_name)); - cast::web::MessagePortDescriptor* port_descriptor = - call.request().mutable_port(); - port_descriptor->mutable_channel()->set_channel_id(channel_id); - port_descriptor->mutable_peer_status()->set_status( - cast::web::MessagePortStatus_Status_STARTED); - port_descriptor->set_sequence_number(0); - - std::move(call).InvokeAsync(base::BindPostTask( - task_runner_, - base::BindOnce(&MessagePortServiceGrpc::OnPortConnectionEstablished, - weak_factory_.GetWeakPtr(), channel_id))); -} - -uint32_t MessagePortServiceGrpc::RegisterOutgoingPort( - std::unique_ptr port) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - uint32_t channel_id = next_outgoing_channel_id_++; - ports_.emplace(channel_id, - MakeMessagePortHandler(channel_id, std::move(port))); - return channel_id; -} - -void MessagePortServiceGrpc::RegisterIncomingPort( - uint32_t channel_id, - std::unique_ptr port) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto result = ports_.emplace( - channel_id, MakeMessagePortHandler(channel_id, std::move(port))); - DCHECK(result.second); -} - -void MessagePortServiceGrpc::Remove(uint32_t channel_id) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - ports_.erase(channel_id); -} - -std::unique_ptr -MessagePortServiceGrpc::MakeMessagePortHandler( - uint32_t channel_id, - std::unique_ptr port) { - auto port_handler = std::make_unique( - std::move(port), channel_id, this, core_app_stub_, task_runner_); - return port_handler; -} - -void MessagePortServiceGrpc::OnPortConnectionEstablished( - uint32_t channel_id, - cast::utils::GrpcStatusOr response_or) { - if (!response_or.ok()) { - LOG(ERROR) << "Message port connect failed: channel_id=" << channel_id; - Remove(channel_id); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/message_port_service_grpc.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_service_grpc.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/message_port_service_grpc.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/message_port_service_grpc.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_MESSAGE_PORT_SERVICE_GRPC_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_MESSAGE_PORT_SERVICE_GRPC_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "base/task/sequenced_task_runner.h" -#include "components/cast/message_port/message_port.h" -#include "components/cast_receiver/browser/public/message_port_service.h" -#include "components/cast_receiver/common/public/status.h" -#include "third_party/cast_core/public/src/proto/v2/core_message_port_application_service.castcore.pb.h" -#include "third_party/cast_core/public/src/proto/web/message_channel.pb.h" - -namespace chromecast { - -class MessagePortHandler; - -// This class defines a gRPC-based implementation of the MessagePortService -// interface, for use with Cast Core. -class MessagePortServiceGrpc : public cast_receiver::MessagePortService { - public: - // |core_app_stub| must outlive |this|. - MessagePortServiceGrpc( - cast::v2::CoreMessagePortApplicationServiceStub* core_app_stub); - ~MessagePortServiceGrpc() override; - - // Handles a message incoming over RPC. The message will be routed to the - // appropriate destination based on its channel ID. Returns |true| in the case - // that this message was successfully processed, and false in all other cases - // including the case that there's no handler for the incoming channel ID. - cast_receiver::Status HandleMessage(cast::web::Message message); - - // MessagePortService implementation: - void ConnectToPortAsync( - std::string_view port_name, - std::unique_ptr port) override; - uint32_t RegisterOutgoingPort( - std::unique_ptr port) override; - void RegisterIncomingPort( - uint32_t channel_id, - std::unique_ptr port) override; - void Remove(uint32_t channel_id) override; - - private: - std::unique_ptr MakeMessagePortHandler( - uint32_t channel_id, - std::unique_ptr port); - - // Callback invoked when AsyncConnect gets a gRPC result. - void OnPortConnectionEstablished( - uint32_t channel_id, - cast::utils::GrpcStatusOr response_or); - - cast::v2::CoreMessagePortApplicationServiceStub* const core_app_stub_; - scoped_refptr task_runner_; - - int next_outgoing_channel_id_{0}; - // NOTE: Keyed by channel_id of cast::web::MessageChannelDescriptor. - base::flat_map> ports_; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_MESSAGE_PORT_SERVICE_GRPC_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/runtime_application_service_impl.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_application_service_impl.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/runtime_application_service_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_application_service_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,754 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/runtime_application_service_impl.h" - -#include - -#include "base/strings/stringprintf.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "build/build_config.h" -#include "build/chromecast_buildflags.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/base/version.h" -#include "chromecast/browser/cast_web_service.h" -#include "chromecast/browser/cast_web_view.h" -#include "chromecast/cast_core/grpc/grpc_status_or.h" -#include "chromecast/cast_core/runtime/browser/core_streaming_config_manager.h" -#include "chromecast/cast_core/runtime/browser/message_port_service_grpc.h" -#include "chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h" -#include "chromecast/common/feature_constants.h" -#include "components/cast_receiver/browser/public/content_window_controls.h" - -namespace chromecast { -namespace { - -class CastContentWindowControls : public cast_receiver::ContentWindowControls, - public CastContentWindow::Observer { - public: - explicit CastContentWindowControls(CastContentWindow& content_window) - : content_window_(content_window) { - content_window_->AddObserver(this); - } - - ~CastContentWindowControls() override { - content_window_->RemoveObserver(this); - } - - // cast_receiver::ContentWindowControls implementation. - void ShowWindow() override { - if (!was_window_created_) { - content_window_->GrantScreenAccess(); - content_window_->CreateWindow(mojom::ZOrder::APP, - VisibilityPriority::STICKY_ACTIVITY); - was_window_created_ = true; - return; - } - - content_window_->RequestVisibility(VisibilityPriority::STICKY_ACTIVITY); - content_window_->GrantScreenAccess(); - } - - void HideWindow() override { - if (!was_window_created_) { - content_window_->CreateWindow(mojom::ZOrder::APP, - VisibilityPriority::HIDDEN); - was_window_created_ = true; - return; - } - - content_window_->RequestVisibility(VisibilityPriority::HIDDEN); - content_window_->RevokeScreenAccess(); - } - - void EnableTouchInput() override { content_window_->EnableTouchInput(true); } - - void DisableTouchInput() override { - content_window_->EnableTouchInput(false); - } - - private: - // CastContentWindow::Observer implementation. - void OnVisibilityChange(VisibilityType visibility_type) override { - switch (visibility_type) { - case VisibilityType::FULL_SCREEN: - case VisibilityType::PARTIAL_OUT: - case VisibilityType::TRANSIENTLY_HIDDEN: - OnWindowShown(); - break; - default: - OnWindowHidden(); - break; - } - } - - bool was_window_created_ = false; - - raw_ref content_window_; -}; - -cast::common::StopReason::Type ToProtoType( - cast_receiver::EmbedderApplication::ApplicationStopReason reason) { - switch (reason) { - case cast_receiver::EmbedderApplication::ApplicationStopReason::kUndefined: - return cast::common::StopReason::UNDEFINED; - case cast_receiver::EmbedderApplication::ApplicationStopReason:: - kApplicationRequest: - return cast::common::StopReason::APPLICATION_REQUEST; - case cast_receiver::EmbedderApplication::ApplicationStopReason:: - kIdleTimeout: - return cast::common::StopReason::IDLE_TIMEOUT; - case cast_receiver::EmbedderApplication::ApplicationStopReason:: - kUserRequest: - return cast::common::StopReason::USER_REQUEST; - case cast_receiver::EmbedderApplication::ApplicationStopReason::kHttpError: - return cast::common::StopReason::HTTP_ERROR; - case cast_receiver::EmbedderApplication::ApplicationStopReason:: - kRuntimeError: - return cast::common::StopReason::RUNTIME_ERROR; - } -} - -// Parses renderer features. -const cast::common::Dictionary::Entry* FindEntry( - const std::string& key, - const cast::common::Dictionary& dict) { - auto iter = base::ranges::find(dict.entries(), key, - &cast::common::Dictionary::Entry::key); - if (iter == dict.entries().end()) { - return nullptr; - } - return &*iter; -} - -bool GetFlagEntry(const std::string& key, - const cast::common::Dictionary& dict, - bool default_value = false) { - auto* entry = FindEntry(key, dict); - if (!entry) { - return default_value; - } - CHECK(entry->value().value_case() == cast::common::Value::kFlag); - return entry->value().flag(); -} - -} // namespace - -RuntimeApplicationServiceImpl::RuntimeApplicationServiceImpl( - std::unique_ptr runtime_application, - cast::common::ApplicationConfig config, - scoped_refptr task_runner, - CastWebService& web_service) - : config_(std::move(config)), - task_runner_(std::move(task_runner)), - web_service_(web_service), - runtime_application_(std::move(runtime_application)) { - DCHECK(runtime_application_); - DCHECK(task_runner_); -} - -RuntimeApplicationServiceImpl::~RuntimeApplicationServiceImpl() = default; - -void RuntimeApplicationServiceImpl::Load( - const cast::runtime::LoadApplicationRequest& request, - StatusCallback callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!grpc_server_); - - if (request.runtime_application_service_info().grpc_endpoint().empty()) { - std::move(callback).Run( - cast_receiver::Status(cast_receiver::StatusCode::kInvalidArgument, - "RuntimeApplication service info missing")); - return; - } - - metrics::CastMetricsHelper::GetInstance()->DidStartLoad( - request.application_config().app_id()); - - // Start the gRPC server. - grpc_server_.emplace(); - grpc_server_->SetHandler< - cast::v2::RuntimeApplicationServiceHandler::SetUrlRewriteRules>( - base::BindPostTask( - task_runner_, - base::BindRepeating( - &RuntimeApplicationServiceImpl::HandleSetUrlRewriteRules, - weak_factory_.GetWeakPtr()))); - grpc_server_ - ->SetHandler( - base::BindPostTask( - task_runner_, - base::BindRepeating( - &RuntimeApplicationServiceImpl::HandleSetMediaState, - weak_factory_.GetWeakPtr()))); - grpc_server_ - ->SetHandler( - base::BindPostTask( - task_runner_, - base::BindRepeating( - &RuntimeApplicationServiceImpl::HandleSetVisibility, - weak_factory_.GetWeakPtr()))); - grpc_server_ - ->SetHandler( - base::BindPostTask( - task_runner_, - base::BindRepeating( - &RuntimeApplicationServiceImpl::HandleSetTouchInput, - weak_factory_.GetWeakPtr()))); - grpc_server_->SetHandler< - cast::v2::RuntimeMessagePortApplicationServiceHandler::PostMessage>( - base::BindPostTask( - task_runner_, - base::BindRepeating(&RuntimeApplicationServiceImpl::HandlePostMessage, - weak_factory_.GetWeakPtr()))); - - auto status = grpc_server_->Start( - request.runtime_application_service_info().grpc_endpoint()); - if (!status.ok()) { - LOG(ERROR) << "Failed to start runtime application server: status=" - << status.error_message(); - std::move(callback).Run(cast_receiver::Status( - cast_receiver::StatusCode::kInternal, status.error_message())); - return; - } - - LOG(INFO) << "Runtime application server started: endpoint=" - << request.runtime_application_service_info().grpc_endpoint(); - - // TODO(vigeni): Consider extacting this into RuntimeApplicationBase as a - // mojo. - url_rewrite::mojom::UrlRequestRewriteRulesPtr mojom_rules = - mojo::ConvertTo( - request.url_rewrite_rules()); - runtime_application_->SetUrlRewriteRules(std::move(mojom_rules)); - - cast_web_view_ = CreateCastWebView(); - metrics::CastMetricsHelper::GetInstance()->DidCompleteLoad( - request.application_config().app_id(), request.cast_session_id()); - runtime_application_->Load(std::move(callback)); -} - -void RuntimeApplicationServiceImpl::Launch( - const cast::runtime::LaunchApplicationRequest& request, - StatusCallback callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (request.core_application_service_info().grpc_endpoint().empty()) { - std::move(callback).Run( - cast_receiver::Status(cast_receiver::StatusCode::kInvalidArgument, - "CoreApplication service info missing")); - return; - } - - if (request.cast_media_service_info().grpc_endpoint().empty()) { - std::move(callback).Run( - cast_receiver::Status(cast_receiver::StatusCode::kInvalidArgument, - "CastMedia service info missing")); - return; - } - - // Create stubs for Core*ApplicationServices. - auto core_channel = grpc::CreateChannel( - request.core_application_service_info().grpc_endpoint(), - grpc::InsecureChannelCredentials()); - core_app_stub_.emplace(core_channel); - core_message_port_app_stub_.emplace(core_channel); - - // TODO(b/244455581): Configure multizone. - auto* cast_web_contents = cast_web_view_->cast_web_contents(); - DCHECK(cast_web_contents); - CastWebContents::Observer::Observe(cast_web_contents); - - SetMediaBlocking(request.media_state()); - SetVisibility(request.visibility()); - SetTouchInput(request.touch_input()); - - runtime_application_->Launch(std::move(callback)); -} - -void RuntimeApplicationServiceImpl::NavigateToPage(const GURL& url) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - auto* cast_web_contents = cast_web_view_->cast_web_contents(); - DCHECK(cast_web_contents); - - cast_web_contents->AddRendererFeatures(GetRendererFeatures()); - cast_web_contents->SetAppProperties( - runtime_application_->GetAppId(), - runtime_application_->GetCastSessionId(), IsAudioOnly(), url, - IsFeaturePermissionsEnforced(), std::vector(), - std::vector()); - - // Start loading the URL while JS visibility is disabled and no window is - // created. This way users won't see the progressive UI updates as the page is - // formed and styles are applied. The actual window will be created in - // OnApplicationStarted when application is fully launched. - cast_web_contents->LoadUrl(url); -} - -void RuntimeApplicationServiceImpl::Stop( - const cast::runtime::StopApplicationRequest& request, - StatusCallback callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - runtime_application_->Stop(std::move(callback)); -} - -void RuntimeApplicationServiceImpl::HandlePostMessage( - cast::web::Message request, - cast::v2::RuntimeMessagePortApplicationServiceHandler::PostMessage::Reactor* - reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!runtime_application_->IsApplicationRunning()) { - reactor->Write(grpc::Status(grpc::StatusCode::NOT_FOUND, - "No active cast session for PostMessage")); - return; - } - - auto* message_port_service = GetMessagePortServiceGrpc(); - if (message_port_service) { - auto status = message_port_service->HandleMessage(std::move(request)); - if (status) { - cast::web::MessagePortStatus message_port_status; - message_port_status.set_status(cast::web::MessagePortStatus::OK); - reactor->Write(std::move(message_port_status)); - return; - } - - LOG(INFO) << "Failed to post message port message: " << status; - } - - reactor->Write( - grpc::Status(grpc::StatusCode::UNKNOWN, "Failed to post message")); -} - -CastWebView::Scoped RuntimeApplicationServiceImpl::CreateCastWebView() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - mojom::CastWebViewParamsPtr params = mojom::CastWebViewParams::New(); - params->renderer_type = mojom::RendererType::MOJO_RENDERER; - params->handle_inner_contents = true; - params->session_id = runtime_application_->GetCastSessionId(); - params->use_media_blocker = true; - params->gesture_priority = mojom::GesturePriority::MAIN_ACTIVITY; - params->log_prefix = - base::StringPrintf("Cast App (%s)", config_.app_id().c_str()); - params->is_remote_control_mode = - GetFlagEntry(feature::kCastCoreIsRemoteControlMode, - config_.extra_features(), /*default_value=*/false); - params->enabled_for_dev = IsEnabledForDev(); - params->enable_touch_input = IsTouchInputAllowed(); - params->log_js_console_messages = - GetFlagEntry(feature::kCastCoreLogJsConsoleMessages, - config_.extra_features(), /*default_value=*/false); - params->allow_media_access = - GetFlagEntry(feature::kCastCoreAllowMediaAccess, config_.extra_features(), - /*default_value=*/false); - params->force_720p_resolution = - GetFlagEntry(feature::kCastCoreForce720p, config_.extra_features(), - /*default_value=*/false); -#if BUILDFLAG(ENABLE_CAST_RECEIVER) && BUILDFLAG(IS_LINUX) - // Starboard-based (linux) cast receivers may not render their UI at 720p, so - // we need to scale to the proper resolution. For example, a 4k TV may render - // the window at 1920x1080, so a scaling factor of 1.5 is necessary for a 720p - // app. Setting this to true would remove the scaling factor in - // CastWebViewDefault::CastWebViewDefault (calling - // OverridePrimaryDisplaySettings with a scaling factor of 1). As a result, - // certain apps (e.g. Fandango at Home) would only cover part of the TV - // screen. - params->force_720p_resolution = false; -#endif // BUILDFLAG(ENABLE_CAST_RECEIVER) && BUILDFLAG(IS_LINUX) - params->turn_on_screen = - GetFlagEntry(feature::kCastCoreTurnOnScreen, config_.extra_features(), - /*default_value=*/false); - params->keep_screen_on = - GetFlagEntry(feature::kCastCoreKeepScreenOn, config_.extra_features(), - /*default_value=*/false); - params->activity_id = - params->is_remote_control_mode ? params->session_id : config_.app_id(); - return web_service_->CreateWebViewInternal(std::move(params)); -} - -void RuntimeApplicationServiceImpl::SetTouchInput( - cast::common::TouchInput::Type state) { - switch (state) { - case cast::common::TouchInput::ENABLED: - runtime_application_->SetTouchInputEnabled(true); - break; - case cast::common::TouchInput::DISABLED: - runtime_application_->SetTouchInputEnabled(false); - break; - case cast::common::TouchInput::UNDEFINED: - break; - default: - NOTREACHED(); - } -} - -void RuntimeApplicationServiceImpl::SetVisibility( - cast::common::Visibility::Type state) { - switch (state) { - case cast::common::Visibility::FULL_SCREEN: - runtime_application_->SetVisibility(true); - break; - case cast::common::Visibility::HIDDEN: - runtime_application_->SetVisibility(false); - break; - case cast::common::Visibility::UNDEFINED: - break; - default: - NOTREACHED(); - } -} - -void RuntimeApplicationServiceImpl::SetMediaBlocking( - cast::common::MediaState::Type state) { - switch (state) { - case cast::common::MediaState::LOAD_BLOCKED: - runtime_application_->SetMediaBlocking(true, true); - break; - case cast::common::MediaState::START_BLOCKED: - runtime_application_->SetMediaBlocking(false, true); - break; - case cast::common::MediaState::UNBLOCKED: - runtime_application_->SetMediaBlocking(false, false); - break; - case cast::common::MediaState::UNDEFINED: - break; - default: - NOTREACHED(); - } -} - -void RuntimeApplicationServiceImpl::OnStreamingApplicationError( - cast_receiver::Status status) { - LOG(ERROR) << "Error while running streaming application: " << status - << ". Exiting application..."; - runtime_application_->Stop(StatusCallback{}); -} - -void RuntimeApplicationServiceImpl::HandleSetUrlRewriteRules( - cast::v2::SetUrlRewriteRulesRequest request, - cast::v2::RuntimeApplicationServiceHandler::SetUrlRewriteRules::Reactor* - reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (!runtime_application_->IsApplicationRunning()) { - reactor->Write( - grpc::Status(grpc::StatusCode::NOT_FOUND, - "No active cast session for SetUrlRewriteRules")); - return; - } - if (request.has_rules()) { - url_rewrite::mojom::UrlRequestRewriteRulesPtr mojom_rules = - mojo::ConvertTo( - request.rules()); - runtime_application_->SetUrlRewriteRules(std::move(mojom_rules)); - } - reactor->Write(cast::v2::SetUrlRewriteRulesResponse()); -} - -void RuntimeApplicationServiceImpl::HandleSetMediaState( - cast::v2::SetMediaStateRequest request, - cast::v2::RuntimeApplicationServiceHandler::SetMediaState::Reactor* - reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - SetMediaBlocking(request.media_state()); - reactor->Write(cast::v2::SetMediaStateResponse()); -} - -void RuntimeApplicationServiceImpl::HandleSetVisibility( - cast::v2::SetVisibilityRequest request, - cast::v2::RuntimeApplicationServiceHandler::SetVisibility::Reactor* - reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - SetVisibility(request.visibility()); - reactor->Write(cast::v2::SetVisibilityResponse()); -} - -void RuntimeApplicationServiceImpl::HandleSetTouchInput( - cast::v2::SetTouchInputRequest request, - cast::v2::RuntimeApplicationServiceHandler::SetTouchInput::Reactor* - reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - SetTouchInput(request.touch_input()); - reactor->Write(cast::v2::SetTouchInputResponse()); -} - -void RuntimeApplicationServiceImpl::NotifyApplicationStarted() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(core_app_stub_); - - LOG(INFO) << "Application is started: " << *runtime_application_; - - auto call = core_app_stub_->CreateCall< - cast::v2::CoreApplicationServiceStub::ApplicationStarted>(); - call.request().set_cast_session_id(runtime_application_->GetCastSessionId()); - std::move(call).InvokeAsync(base::BindOnce( - [](cast::utils::GrpcStatusOr - response_or) { - LOG_IF(ERROR, !response_or.ok()) - << "Failed to report that application started: " - << response_or.ToString(); - })); -} - -void RuntimeApplicationServiceImpl::NotifyApplicationStopped( - ApplicationStopReason stop_reason, - int32_t net_error_code) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(core_app_stub_); - - LOG(INFO) << "Application is stopped: stop_reason=" << stop_reason << ", " - << *runtime_application_; - - auto proto_stop_reason = ToProtoType(stop_reason); - auto call = core_app_stub_->CreateCall< - cast::v2::CoreApplicationServiceStub::ApplicationStopped>(); - call.request().set_cast_session_id(runtime_application_->GetCastSessionId()); - call.request().set_stop_reason(proto_stop_reason); - call.request().set_error_code(net_error_code); - std::move(call).InvokeAsync(base::BindOnce( - [](cast::utils::GrpcStatusOr - response_or) { - LOG_IF(ERROR, !response_or.ok()) - << "Failed to report that application stopped: " - << response_or.ToString(); - })); - - grpc_server_->Stop(); - grpc_server_.reset(); -} - -void RuntimeApplicationServiceImpl::NotifyMediaPlaybackChanged(bool playing) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(core_app_stub_); - - DLOG(INFO) << "Media playback changed: playing=" << playing << ", " - << *runtime_application_; - - auto call = core_app_stub_->CreateCall< - cast::v2::CoreApplicationServiceStub::MediaPlaybackChanged>(); - call.request().set_cast_session_id(runtime_application_->GetCastSessionId()); - call.request().set_media_playback_state( - playing ? cast::common::MediaPlaybackState::PLAYING - : cast::common::MediaPlaybackState::STOPPED); - std::move(call).InvokeAsync(base::BindOnce( - [](cast::utils::GrpcStatusOr - response_or) { - LOG_IF(ERROR, !response_or.ok()) - << "Failed to report media playback changed state: " - << response_or.ToString(); - })); -} - -void RuntimeApplicationServiceImpl::GetAllBindings( - GetAllBindingsCallback callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(core_message_port_app_stub_); - auto call = core_message_port_app_stub_->CreateCall< - cast::v2::CoreMessagePortApplicationServiceStub::GetAll>(); - std::move(call).InvokeAsync(base::BindPostTask( - task_runner_, - base::BindOnce(&RuntimeApplicationServiceImpl::OnAllBindingsReceived, - weak_factory_.GetWeakPtr(), std::move(callback)))); -} - -MessagePortServiceGrpc* -RuntimeApplicationServiceImpl::GetMessagePortServiceGrpc() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!core_message_port_app_stub_) { - return nullptr; - } - - if (!message_port_service_) { - message_port_service_ = std::make_unique( - &core_message_port_app_stub_.value()); - } - return message_port_service_.get(); -} - -cast_receiver::MessagePortService* -RuntimeApplicationServiceImpl::GetMessagePortService() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return GetMessagePortServiceGrpc(); -} - -content::WebContents* RuntimeApplicationServiceImpl::GetWebContents() { - if (!cast_web_view_) { - return nullptr; - } - - return cast_web_view_->web_contents(); -} - -cast_receiver::ContentWindowControls* -RuntimeApplicationServiceImpl::GetContentWindowControls() { - if (!cast_web_view_ || !cast_web_view_->window()) { - return nullptr; - } - - if (!content_window_controls_) { - content_window_controls_ = - std::make_unique(*cast_web_view_->window()); - } - - return content_window_controls_.get(); -} - -#if !BUILDFLAG(IS_CAST_DESKTOP_BUILD) -cast_receiver::StreamingConfigManager* -RuntimeApplicationServiceImpl::GetStreamingConfigManager() { - if (streaming_config_manager_) { - return streaming_config_manager_.get(); - } - - auto* message_port_service = GetMessagePortService(); - if (!message_port_service) { - return nullptr; - } - - streaming_config_manager_ = std::make_unique( - *message_port_service, - base::BindOnce( - &RuntimeApplicationServiceImpl::OnStreamingApplicationError, - weak_factory_.GetWeakPtr())); - return streaming_config_manager_.get(); -} -#endif // !BUILDFLAG(IS_CAST_DESKTOP_BUILD) - -void RuntimeApplicationServiceImpl::OnAllBindingsReceived( - GetAllBindingsCallback callback, - cast::utils::GrpcStatusOr response_or) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!response_or.ok()) { - std::move(callback).Run( - cast_receiver::Status(cast_receiver::StatusCode::kCancelled, - "Bad GrpcStatus: " + response_or.ToString()), - std::vector()); - return; - } - - const cast::bindings::GetAllResponse& response = response_or.value(); - std::vector bindings; - bindings.reserve(response.bindings_size()); - for (int i = 0; i < response.bindings_size(); ++i) { - bindings.emplace_back(response.bindings(i).before_load_script()); - } - - std::move(callback).Run(cast_receiver::OkStatus(), std::move(bindings)); -} - -base::Value::Dict RuntimeApplicationServiceImpl::GetRendererFeatures() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - const auto* entry = - FindEntry(feature::kCastCoreRendererFeatures, config_.extra_features()); - - base::Value::Dict renderer_features; - if (!entry) { - return renderer_features; - } - CHECK(entry->value().has_dictionary()); - - for (const cast::common::Dictionary::Entry& feature : - entry->value().dictionary().entries()) { - base::Value::Dict dict; - if (feature.has_value()) { - CHECK(feature.value().has_dictionary()); - for (const cast::common::Dictionary::Entry& feature_arg : - feature.value().dictionary().entries()) { - CHECK(feature_arg.has_value()); - if (feature_arg.value().value_case() == cast::common::Value::kFlag) { - dict.Set(feature_arg.key(), feature_arg.value().flag()); - } else if (feature_arg.value().value_case() == - cast::common::Value::kText) { - dict.Set(feature_arg.key(), feature_arg.value().text()); - } else { - LOG(FATAL) << "No or unsupported value was set for the feature: " - << feature.key(); - } - } - } - DVLOG(1) << "Renderer feature created: " << feature.key(); - renderer_features.Set(feature.key(), std::move(dict)); - } - - return renderer_features; -} - -bool RuntimeApplicationServiceImpl::IsAudioOnly() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return GetFlagEntry(feature::kCastCoreIsAudioOnly, config_.extra_features(), - /*default_value=*/false); -} - -bool RuntimeApplicationServiceImpl::IsEnabledForDev() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (CAST_IS_DEBUG_BUILD()) { - return true; - } - const auto* entry = - FindEntry(feature::kCastCoreRendererFeatures, config_.extra_features()); - if (!entry) { - return false; - } - CHECK(entry->value().has_dictionary()); - - return FindEntry(chromecast::feature::kEnableDevMode, - entry->value().dictionary()) != nullptr; -} - -bool RuntimeApplicationServiceImpl::IsTouchInputAllowed() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - const auto* entry = - FindEntry(feature::kCastCoreRendererFeatures, config_.extra_features()); - if (!entry) { - return false; - } - CHECK(entry->value().has_dictionary()); - const auto* enable_window_controls_entry = - FindEntry(feature::kEnableWindowControls, entry->value().dictionary()); - return enable_window_controls_entry != nullptr; -} - -bool RuntimeApplicationServiceImpl::IsFeaturePermissionsEnforced() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return GetFlagEntry(feature::kCastCoreEnforceFeaturePermissions, - config_.extra_features(), - /*default_value=*/false); -} - -void RuntimeApplicationServiceImpl::InnerContentsCreated( - CastWebContents* inner_contents, - CastWebContents* outer_contents) { - if (!config_.has_cast_web_app_config()) { - return; - } - - const std::string url = config_.cast_web_app_config().url(); - if (url.empty()) { - return; - } - -#if DCHECK_IS_ON() - base::Value::Dict features; - base::Value::Dict dev_mode_config; - dev_mode_config.Set(feature::kDevModeOrigin, url); - features.Set(feature::kEnableDevMode, std::move(dev_mode_config)); - inner_contents->AddRendererFeatures(std::move(features)); -#endif - - // Bind inner CastWebContents with the same session id and app id as the - // root CastWebContents so that the same url rewrites are applied. - inner_contents->SetAppProperties( - runtime_application_->GetAppId(), - runtime_application_->GetCastSessionId(), IsAudioOnly(), GURL(url), - IsFeaturePermissionsEnforced(), std::vector(), - std::vector()); - CastWebContents::Observer::Observe(inner_contents); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/runtime_application_service_impl.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_application_service_impl.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/runtime_application_service_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_application_service_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,178 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_SERVICE_IMPL_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_SERVICE_IMPL_H_ - -#include -#include -#include - -#include "base/task/sequenced_task_runner.h" -#include "chromecast/browser/cast_content_window.h" -#include "chromecast/browser/cast_web_view.h" -#include "chromecast/cast_core/grpc/grpc_server.h" -#include "chromecast/chromecast_buildflags.h" -#include "components/cast_receiver/browser/public/embedder_application.h" -#include "components/cast_receiver/browser/public/runtime_application.h" -#include "components/cast_receiver/common/public/status.h" -#include "third_party/cast_core/public/src/proto/common/application_state.pb.h" -#include "third_party/cast_core/public/src/proto/common/value.pb.h" -#include "third_party/cast_core/public/src/proto/runtime/runtime_service.castcore.pb.h" -#include "third_party/cast_core/public/src/proto/v2/core_application_service.castcore.pb.h" -#include "third_party/cast_core/public/src/proto/v2/core_message_port_application_service.castcore.pb.h" -#include "third_party/cast_core/public/src/proto/v2/runtime_application_service.castcore.pb.h" -#include "third_party/cast_core/public/src/proto/v2/runtime_message_port_application_service.castcore.pb.h" -#include "third_party/cast_core/public/src/proto/web/message_channel.pb.h" - -namespace cast_receiver { -class MessagePortService; -class StreamingConfigManager; -} // namespace cast_receiver - -namespace content { -class WebContents; -} // namespace content - -namespace chromecast { - -class CastContentWindow; -class MessagePortServiceGrpc; - -class RuntimeApplicationServiceImpl : public cast_receiver::EmbedderApplication, - public CastWebContents::Observer { - public: - using StatusCallback = cast_receiver::RuntimeApplication::StatusCallback; - - RuntimeApplicationServiceImpl( - std::unique_ptr runtime_application, - cast::common::ApplicationConfig config, - scoped_refptr task_runner, - CastWebService& web_service); - ~RuntimeApplicationServiceImpl() override; - - void Load(const cast::runtime::LoadApplicationRequest& request, - StatusCallback callback); - void Launch(const cast::runtime::LaunchApplicationRequest& request, - StatusCallback callback); - void Stop(const cast::runtime::StopApplicationRequest& request, - StatusCallback callback); - - const std::string& app_id() { return runtime_application_->GetAppId(); } - - // EmbedderApplication implementation: - void NotifyApplicationStarted() override; - void NotifyApplicationStopped(ApplicationStopReason stop_reason, - int32_t net_error_code) override; - void NotifyMediaPlaybackChanged(bool playing) override; - void GetAllBindings(GetAllBindingsCallback callback) override; - cast_receiver::MessagePortService* GetMessagePortService() override; - content::WebContents* GetWebContents() override; - cast_receiver::ContentWindowControls* GetContentWindowControls() override; -#if !BUILDFLAG(IS_CAST_DESKTOP_BUILD) - cast_receiver::StreamingConfigManager* GetStreamingConfigManager() override; -#endif - void NavigateToPage(const GURL& url) override; - - private: - // Gets the current |message_port_service_|, attempting to create it if it - // does not yet exist. - MessagePortServiceGrpc* GetMessagePortServiceGrpc(); - - // Creates the root CastWebView for this Cast session. - CastWebView::Scoped CreateCastWebView(); - - // Helper functions for processing proto types. - void SetTouchInput(cast::common::TouchInput::Type state); - void SetVisibility(cast::common::Visibility::Type state); - void SetMediaBlocking(cast::common::MediaState::Type state); - - // Called on an error is hit during running of cast mirroring or remoting. - void OnStreamingApplicationError(cast_receiver::Status status); - - // RuntimeApplicationService handlers: - void HandleSetUrlRewriteRules( - cast::v2::SetUrlRewriteRulesRequest request, - cast::v2::RuntimeApplicationServiceHandler::SetUrlRewriteRules::Reactor* - reactor); - void HandleSetMediaState( - cast::v2::SetMediaStateRequest request, - cast::v2::RuntimeApplicationServiceHandler::SetMediaState::Reactor* - reactor); - void HandleSetVisibility( - cast::v2::SetVisibilityRequest request, - cast::v2::RuntimeApplicationServiceHandler::SetVisibility::Reactor* - reactor); - void HandleSetTouchInput( - cast::v2::SetTouchInputRequest request, - cast::v2::RuntimeApplicationServiceHandler::SetTouchInput::Reactor* - reactor); - - // RuntimeMessagePortApplicationService handlers: - void HandlePostMessage(cast::web::Message request, - cast::v2::RuntimeMessagePortApplicationServiceHandler:: - PostMessage::Reactor* reactor); - - void OnAllBindingsReceived( - GetAllBindingsCallback callback, - cast::utils::GrpcStatusOr response_or); - - // Returns if app is audio only. - bool IsAudioOnly() const; - - // Returns if current session is enabled for dev. - bool IsEnabledForDev() const; - - // Returns if touch input is allowed. - bool IsTouchInputAllowed() const; - - // Returns renderer features. - base::Value::Dict GetRendererFeatures() const; - - // Returns whether feature permissions should be enforced. - bool IsFeaturePermissionsEnforced() const; - - // CastWebContents::Observer overrides. - void InnerContentsCreated(CastWebContents* inner_contents, - CastWebContents* outer_contents) override; - - const cast::common::ApplicationConfig config_; - scoped_refptr task_runner_; - - raw_ref web_service_; - - // The WebView associated with the window in which the Cast application is - // displayed. - CastWebView::Scoped cast_web_view_; - - // Controls for window, as a wrapper around a CastContentWindow instance. - // NOTE: Must be declared after |cast_web_view_|. - std::unique_ptr - content_window_controls_; - - // Manages access and retrieval of the StreamingConfig for a streaming session - // initiated by the owning application. - std::unique_ptr - streaming_config_manager_; - - // Shared MessagePortService implementation for this application instance to - // use. - std::unique_ptr message_port_service_; - - std::optional grpc_server_; - std::optional core_app_stub_; - std::optional - core_message_port_app_stub_; - std::optional cast_media_service_grpc_endpoint_; - - SEQUENCE_CHECKER(sequence_checker_); - - std::unique_ptr const runtime_application_; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_SERVICE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/runtime_service_impl.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_service_impl.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/runtime_service_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_service_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,547 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/runtime_service_impl.h" - -#include "base/check.h" -#include "base/command_line.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "chromecast/browser/cast_web_service.h" -#include "chromecast/cast_core/cast_core_switches.h" -#include "chromecast/cast_core/runtime/browser/core_conversions.h" -#include "chromecast/cast_core/runtime/browser/runtime_application_service_impl.h" -#include "chromecast/metrics/cast_event_builder_simple.h" -#include "components/cast_receiver/browser/public/content_browser_client_mixins.h" -#include "components/cast_receiver/browser/public/embedder_application.h" -#include "components/cast_receiver/common/public/status.h" -#include "third_party/cast_core/public/src/proto/common/application_config.pb.h" - -namespace chromecast { -namespace { - -constexpr base::TimeDelta kDefaultMetricsReportInterval = base::Seconds(60); - -} // namespace - -RuntimeServiceImpl::RuntimeServiceImpl( - cast_receiver::ContentBrowserClientMixins& browser_mixins, - CastWebService& web_service) - : application_dispatcher_( - browser_mixins - .CreateApplicationDispatcher()), - task_runner_(base::SequencedTaskRunner::GetCurrentDefault()), - web_service_(web_service), - metrics_recorder_(this) { - heartbeat_timer_.SetTaskRunner(task_runner_); - metrics_recorder_service_.emplace( - &metrics_recorder_, &action_recorder_, - base::BindRepeating(&RuntimeServiceImpl::RecordMetrics, - weak_factory_.GetWeakPtr()), - kDefaultMetricsReportInterval); -} - -RuntimeServiceImpl::~RuntimeServiceImpl() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - Stop(); -} - -cast_receiver::Status RuntimeServiceImpl::Start() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto* command_line = base::CommandLine::ForCurrentProcess(); - std::string runtime_id = - command_line->GetSwitchValueASCII(cast::core::kCastCoreRuntimeIdSwitch); - if (runtime_id.empty()) { - // This may happen during unfreeze of the browser process. Usually the cast - // service process is dead, too, but a certain condition how this happens on - // Android is not known. Most probable cause is OS reboot/update etc. - LOG(ERROR) << "Runtime id must be specified in command line with: --" - << cast::core::kCastCoreRuntimeIdSwitch; - return cast_receiver::Status( - cast_receiver::StatusCode::kFailedPrecondition); - } - - std::string runtime_service_path = - command_line->GetSwitchValueASCII(cast::core::kRuntimeServicePathSwitch); - if (runtime_service_path.empty()) { - // This may happen during unfreeze of the browser process with cast service - // process dead. - LOG(ERROR) - << "Runtime service endpoint must be specified in command line with: --" - << cast::core::kRuntimeServicePathSwitch; - return cast_receiver::Status( - cast_receiver::StatusCode::kFailedPrecondition); - } - return Start(runtime_id, runtime_service_path); -} - -cast_receiver::Status RuntimeServiceImpl::Start( - std::string_view runtime_id, - std::string_view runtime_service_endpoint) { - CHECK(!grpc_server_); - CHECK(!runtime_id.empty()); - CHECK(!runtime_service_endpoint.empty()); - - LOG(INFO) << "Starting runtime service: runtime_id=" << runtime_id - << ", endpoint=" << runtime_service_endpoint; - - grpc_server_.emplace(); - grpc_server_ - ->SetHandler( - base::BindPostTask( - task_runner_, - base::BindRepeating(&RuntimeServiceImpl::HandleLoadApplication, - weak_factory_.GetWeakPtr()))); - grpc_server_ - ->SetHandler( - base::BindPostTask( - task_runner_, - base::BindRepeating(&RuntimeServiceImpl::HandleLaunchApplication, - weak_factory_.GetWeakPtr()))); - grpc_server_ - ->SetHandler( - base::BindPostTask( - task_runner_, - base::BindRepeating(&RuntimeServiceImpl::HandleStopApplication, - weak_factory_.GetWeakPtr()))); - grpc_server_->SetHandler( - base::BindPostTask(task_runner_, base::BindRepeating( - &RuntimeServiceImpl::HandleHeartbeat, - weak_factory_.GetWeakPtr()))); - grpc_server_ - ->SetHandler( - base::BindPostTask( - task_runner_, base::BindRepeating( - &RuntimeServiceImpl::HandleStartMetricsRecorder, - weak_factory_.GetWeakPtr()))); - grpc_server_ - ->SetHandler( - base::BindPostTask(task_runner_, - base::BindRepeating( - &RuntimeServiceImpl::HandleStopMetricsRecorder, - weak_factory_.GetWeakPtr()))); - - auto status = grpc_server_->Start(std::string(runtime_service_endpoint)); - // Browser runtime must crash if the runtime service failed to start to avoid - // the process to dangle without any proper connection to the Cast Core. - if (!status.ok()) { - LOG(ERROR) << "Failed to start runtime service: status=" - << status.error_message(); - return cast_receiver::Status(cast_receiver::StatusCode::kInvalidArgument); - } - - LOG(INFO) << "Runtime service started"; - return cast_receiver::OkStatus(); -} - -void RuntimeServiceImpl::ResetGrpcServices() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (heartbeat_reactor_) { - heartbeat_timer_.Stop(); - // Reset the writes callback as we're not expecting any more responses from - // gRPC framework. - heartbeat_reactor_->SetWritesAvailableCallback(base::DoNothing()); - heartbeat_reactor_->Write(grpc::Status::OK); - heartbeat_reactor_ = nullptr; - LOG(INFO) << "Heartbeat reactor is reset"; - } - - heartbeat_timer_.Stop(); - metrics_recorder_stub_.reset(); - - LOG(INFO) << "Pending apps and Core services terminated"; -} - -cast_receiver::Status RuntimeServiceImpl::Stop() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - ResetGrpcServices(); - - if (metrics_recorder_service_) { - metrics_recorder_service_->OnCloseSoon(base::DoNothing()); - metrics_recorder_service_.reset(); - } - - if (grpc_server_) { - grpc_server_->Stop(); - grpc_server_.reset(); - } - - LOG(INFO) << "Runtime service stopped"; - return cast_receiver::OkStatus(); -} - -std::unique_ptr RuntimeServiceImpl::CreateEventBuilder() { - return std::make_unique(); -} - -void RuntimeServiceImpl::HandleLoadApplication( - cast::runtime::LoadApplicationRequest request, - cast::runtime::RuntimeServiceHandler::LoadApplication::Reactor* reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!grpc_server_) { - // gRPC server has been shut down and all reactors have been cancelled. - return; - } - - if (request.cast_session_id().empty()) { - LOG(ERROR) << "Session ID is empty"; - reactor->Write(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, - "Application session ID is missing")); - return; - } - - if (application_dispatcher_->GetApplication(request.cast_session_id())) { - reactor->Write(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, - "Application already exist")); - return; - } - - if (!request.has_application_config()) { - reactor->Write( - grpc::Status(grpc::INVALID_ARGUMENT, "Application config is missing")); - return; - } - - LOG(INFO) << "Loading application: session_id=" << request.cast_session_id(); - RuntimeApplicationServiceImpl* platform_app = - application_dispatcher_->CreateApplication( - request.cast_session_id(), - ToReceiverConfig(request.application_config()), - base::BindOnce( - [](scoped_refptr task_runner, - cast::common::ApplicationConfig config, - CastWebService& web_service, - std::unique_ptr - runtime_application) { - return std::make_unique( - std::move(runtime_application), std::move(config), - std::move(task_runner), web_service); - }, - task_runner_, std::move(request.application_config()), - std::ref(*web_service_))); - platform_app->Load( - request, - base::BindPostTask( - task_runner_, - base::BindOnce(&RuntimeServiceImpl::OnApplicationLoaded, - weak_factory_.GetWeakPtr(), request.cast_session_id(), - std::move(reactor)))); -} - -void RuntimeServiceImpl::HandleLaunchApplication( - cast::runtime::LaunchApplicationRequest request, - cast::runtime::RuntimeServiceHandler::LaunchApplication::Reactor* reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!grpc_server_) { - // gRPC server has been shut down and all reactors have been cancelled. - return; - } - - if (request.cast_session_id().empty()) { - LOG(ERROR) << "Session id is empty"; - reactor->Write(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, - "Sesssion id is missing")); - return; - } - - RuntimeApplicationServiceImpl* platform_app = - application_dispatcher_->GetApplication(request.cast_session_id()); - if (!platform_app) { - LOG(ERROR) << "Application does not exist"; - reactor->Write(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, - "Application does not exists")); - return; - } - - LOG(INFO) << "Launching application: session_id=" - << request.cast_session_id(); - platform_app->Launch( - request, - base::BindPostTask( - task_runner_, - base::BindOnce(&RuntimeServiceImpl::OnApplicationLaunching, - weak_factory_.GetWeakPtr(), request.cast_session_id(), - std::move(reactor)))); -} - -void RuntimeServiceImpl::HandleStopApplication( - cast::runtime::StopApplicationRequest request, - cast::runtime::RuntimeServiceHandler::StopApplication::Reactor* reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!grpc_server_) { - // gRPC server has been shut down and all reactors have been cancelled. - return; - } - - if (request.cast_session_id().empty()) { - LOG(ERROR) << "Session id is missing"; - reactor->Write(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, - "Sesssion id is missing")); - return; - } - - RuntimeApplicationServiceImpl* platform_app = - application_dispatcher_->GetApplication(request.cast_session_id()); - if (!platform_app) { - LOG(ERROR) << "Application doesn't exist anymore: session_id=" - << request.cast_session_id(); - reactor->Write( - grpc::Status(grpc::StatusCode::NOT_FOUND, "Application not found")); - return; - } - - LOG(INFO) << "Stopping application: session_id=" << request.cast_session_id(); - platform_app->Stop( - request, base::BindOnce(&RuntimeServiceImpl::OnApplicationStopping, - weak_factory_.GetWeakPtr(), - request.cast_session_id(), std::move(reactor))); -} - -void RuntimeServiceImpl::HandleHeartbeat( - cast::runtime::HeartbeatRequest request, - cast::runtime::RuntimeServiceHandler::Heartbeat::Reactor* reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!grpc_server_) { - // gRPC server has been shut down and all reactors have been cancelled. - return; - } - - DCHECK(!heartbeat_reactor_); - - if (!request.has_heartbeat_period() || - request.heartbeat_period().seconds() <= 0) { - LOG(ERROR) << "Failed to create a heartbeat as period is not valid"; - reactor->Write(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, - "Incorrect heartbeat period")); - return; - } - - if (heartbeat_reactor_) { - LOG(WARNING) - << "Heartbeats are requested with active heartbeat reactor: reactor=" - << heartbeat_reactor_; - heartbeat_reactor_->Write( - grpc::Status(grpc::StatusCode::ABORTED, "Duplicate heartbeat aborted")); - } - - heartbeat_period_ = base::Seconds(request.heartbeat_period().seconds()); - heartbeat_reactor_ = reactor; - // Set the write callback once for all future calls from gRPC framework. - heartbeat_reactor_->SetWritesAvailableCallback(base::BindPostTask( - task_runner_, base::BindRepeating(&RuntimeServiceImpl::OnHeartbeatSent, - weak_factory_.GetWeakPtr()))); - LOG(INFO) << "Starting heartbeat: reactor=" << heartbeat_reactor_ - << ", period=" << heartbeat_period_; - - SendHeartbeat(); -} - -void RuntimeServiceImpl::HandleStartMetricsRecorder( - cast::runtime::StartMetricsRecorderRequest request, - cast::runtime::RuntimeServiceHandler::StartMetricsRecorder::Reactor* - reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!grpc_server_) { - // gRPC server has been shut down and all reactors have been cancelled. - return; - } - - if (request.metrics_recorder_service_info().grpc_endpoint().empty()) { - reactor->Write(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, - "MetricsRecord service endpoint is missing")); - return; - } - - LOG(INFO) << "Started recording metrics"; - metrics_recorder_stub_.emplace( - request.metrics_recorder_service_info().grpc_endpoint()); - reactor->Write(cast::runtime::StartMetricsRecorderResponse()); -} - -void RuntimeServiceImpl::HandleStopMetricsRecorder( - cast::runtime::StopMetricsRecorderRequest request, - cast::runtime::RuntimeServiceHandler::StopMetricsRecorder::Reactor* - reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!grpc_server_) { - // gRPC server has been shut down and all reactors have been cancelled. - return; - } - - if (!metrics_recorder_service_) { - LOG(ERROR) << "Droping metrics recorging stop request as service is not " - "available anymore"; - reactor->Write(grpc::Status(grpc::StatusCode::UNAVAILABLE, - "Metrics recording service is not available")); - return; - } - - LOG(INFO) << "Stopped recording metrics"; - // Just reset the MetricsRecorder stub to stop sending metrics to Core. - metrics_recorder_stub_.reset(); - reactor->Write(cast::runtime::StopMetricsRecorderResponse()); -} - -void RuntimeServiceImpl::OnApplicationLoaded( - std::string session_id, - cast::runtime::RuntimeServiceHandler::LoadApplication::Reactor* reactor, - cast_receiver::Status status) { - auto* platform_app = application_dispatcher_->GetApplication(session_id); - if (!platform_app) { - LOG(ERROR) << "Application doesn't exist anymore: session_id=" - << session_id; - reactor->Write( - grpc::Status(grpc::StatusCode::NOT_FOUND, "Application not found")); - return; - } - - if (!status.ok()) { - LOG(ERROR) << "Failed to load application: session_id=" << session_id - << ", status=" << status; - platform_app->Stop(cast::runtime::StopApplicationRequest(), - base::DoNothing()); - application_dispatcher_->DestroyApplication(session_id); - reactor->Write(grpc::Status(static_cast(status.code()), - std::string(status.message()))); - return; - } - - cast::runtime::LoadApplicationResponse response; - response.mutable_message_port_info(); - reactor->Write(std::move(response)); -} - -void RuntimeServiceImpl::OnApplicationLaunching( - std::string session_id, - cast::runtime::RuntimeServiceHandler::LaunchApplication::Reactor* reactor, - cast_receiver::Status status) { - auto* platform_app = application_dispatcher_->GetApplication(session_id); - if (!platform_app) { - LOG(ERROR) << "Application doesn't exist anymore: session_id=" - << session_id; - reactor->Write( - grpc::Status(grpc::StatusCode::NOT_FOUND, "Application not found")); - return; - } - - if (!status.ok()) { - LOG(ERROR) << "Failed to launch application: session_id=" << session_id - << ", status=" << status; - platform_app->Stop(cast::runtime::StopApplicationRequest(), - base::DoNothing()); - application_dispatcher_->DestroyApplication(session_id); - reactor->Write(grpc::Status(static_cast(status.code()), - std::string(status.message()))); - return; - } - - reactor->Write(cast::runtime::LaunchApplicationResponse()); -} - -void RuntimeServiceImpl::OnApplicationStopping( - std::string session_id, - cast::runtime::RuntimeServiceHandler::StopApplication::Reactor* reactor, - cast_receiver::Status status) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - auto platform_app = application_dispatcher_->DestroyApplication(session_id); - DCHECK(platform_app); - - // Reset the app only after the response is constructed. - cast::runtime::StopApplicationResponse response; - response.set_app_id(platform_app->app_id()); - response.set_cast_session_id(session_id); - reactor->Write(std::move(response)); -} - -void RuntimeServiceImpl::SendHeartbeat() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!heartbeat_reactor_) { - LOG(WARNING) << "Heartbeat reactor has been destroyed"; - return; - } - - DVLOG(2) << "Sending heartbeat"; - heartbeat_reactor_->Write(cast::runtime::HeartbeatResponse()); -} - -void RuntimeServiceImpl::OnHeartbeatSent( - grpc::Status status, - cast::runtime::RuntimeServiceHandler::Heartbeat::Reactor* reactor) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - // There might be duplicate SendHeartbeat requests from Cast Core. The ones - // that are not associated with |heartbeat_reactor_| must be ignored. - if (reactor != heartbeat_reactor_) { - // The |reactor| was cancelled as the heartbeat response was scheduled - // for send. - LOG(WARNING) << "Ignoring heartbeat from previous request"; - return; - } - - if (!status.ok()) { - // Runtime failed to send the heartbeat to Core - assume Core has crashed - // and reset. - LOG(ERROR) << "Failed to send heartbeats: " - << cast::utils::GrpcStatusToString(status); - heartbeat_reactor_ = nullptr; - ResetGrpcServices(); - return; - } - - // Everything is ok - schedule another heartbeat. - heartbeat_timer_.Start( - FROM_HERE, heartbeat_period_, - base::BindPostTask(task_runner_, - base::BindOnce(&RuntimeServiceImpl::SendHeartbeat, - weak_factory_.GetWeakPtr()))); -} - -void RuntimeServiceImpl::RecordMetrics( - cast::metrics::RecordRequest request, - CastRuntimeMetricsRecorderService::RecordCompleteCallback - record_complete_callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!metrics_recorder_stub_) { - std::move(record_complete_callback).Run(); - return; - } - - auto call = - metrics_recorder_stub_ - ->CreateCall( - std::move(request)); - std::move(call).InvokeAsync(base::BindPostTask( - task_runner_, base::BindOnce(&RuntimeServiceImpl::OnMetricsRecorded, - weak_factory_.GetWeakPtr(), - std::move(record_complete_callback)))); -} - -void RuntimeServiceImpl::OnMetricsRecorded( - CastRuntimeMetricsRecorderService::RecordCompleteCallback - record_complete_callback, - cast::utils::GrpcStatusOr response_or) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!response_or.ok()) { - LOG(ERROR) << "Failed to record metrics: " << response_or.ToString(); - } - - std::move(record_complete_callback).Run(); -} - -void RuntimeServiceImpl::OnMetricsRecorderServiceStopped( - cast::runtime::RuntimeServiceHandler::StopMetricsRecorder::Reactor* - reactor) { - DVLOG(2) << "MetricsRecorderService stopped"; - metrics_recorder_service_.reset(); - metrics_recorder_stub_.reset(); - - reactor->Write(cast::runtime::StopMetricsRecorderResponse()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/runtime_service_impl.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_service_impl.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/runtime_service_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/runtime_service_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,142 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_SERVICE_IMPL_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_SERVICE_IMPL_H_ - -#include -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "chromecast/cast_core/grpc/grpc_server.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_action_recorder.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder.h" -#include "chromecast/cast_core/runtime/browser/cast_runtime_metrics_recorder_service.h" -#include "chromecast/cast_core/runtime/browser/runtime_application_service_impl.h" -#include "components/cast_receiver/browser/public/runtime_application_dispatcher.h" -#include "components/cast_receiver/common/public/status.h" -#include "third_party/cast_core/public/src/proto/metrics/metrics_recorder.castcore.pb.h" -#include "third_party/cast_core/public/src/proto/runtime/runtime_service.castcore.pb.h" - -namespace cast_receiver { -class ContentBrowserClientMixins; -} // namespace cast_receiver - -namespace chromecast { - -class CastWebService; - -// An implementation of the gRPC-defined RuntimeService for use with Cast Core. -class RuntimeServiceImpl final - : public CastRuntimeMetricsRecorder::EventBuilderFactory { - public: - // |application_client| and |web_service| are expected to persist for the - // lifetime of this instance. - RuntimeServiceImpl(cast_receiver::ContentBrowserClientMixins& browser_mixins, - CastWebService& web_service); - ~RuntimeServiceImpl() override; - - // Starts and stops the runtime service, including the gRPC completion queue. - cast_receiver::Status Start(); - cast_receiver::Status Start(std::string_view runtime_id, - std::string_view runtime_service_endpoint); - cast_receiver::Status Stop(); - - // CastRuntimeMetricsRecorder::EventBuilderFactory overrides: - std::unique_ptr CreateEventBuilder() override; - - private: - // RuntimeService gRPC handlers: - void HandleLoadApplication( - cast::runtime::LoadApplicationRequest request, - cast::runtime::RuntimeServiceHandler::LoadApplication::Reactor* reactor); - void HandleLaunchApplication( - cast::runtime::LaunchApplicationRequest request, - cast::runtime::RuntimeServiceHandler::LaunchApplication::Reactor* - reactor); - void HandleStopApplication( - cast::runtime::StopApplicationRequest request, - cast::runtime::RuntimeServiceHandler::StopApplication::Reactor* reactor); - void HandleHeartbeat( - cast::runtime::HeartbeatRequest request, - cast::runtime::RuntimeServiceHandler::Heartbeat::Reactor* reactor); - void HandleStartMetricsRecorder( - cast::runtime::StartMetricsRecorderRequest request, - cast::runtime::RuntimeServiceHandler::StartMetricsRecorder::Reactor* - reactor); - void HandleStopMetricsRecorder( - cast::runtime::StopMetricsRecorderRequest request, - cast::runtime::RuntimeServiceHandler::StopMetricsRecorder::Reactor* - reactor); - - // Helper methods. - void OnApplicationLoaded( - std::string session_id, - cast::runtime::RuntimeServiceHandler::LoadApplication::Reactor* reactor, - cast_receiver::Status status); - void OnApplicationLaunching( - std::string session_id, - cast::runtime::RuntimeServiceHandler::LaunchApplication::Reactor* reactor, - cast_receiver::Status status); - void OnApplicationStopping( - std::string session_id, - cast::runtime::RuntimeServiceHandler::StopApplication::Reactor* reactor, - cast_receiver::Status status); - void SendHeartbeat(); - void OnHeartbeatSent( - grpc::Status status, - cast::runtime::RuntimeServiceHandler::Heartbeat::Reactor* reactor); - void RecordMetrics(cast::metrics::RecordRequest request, - CastRuntimeMetricsRecorderService::RecordCompleteCallback - record_complete_callback); - void OnMetricsRecorded( - CastRuntimeMetricsRecorderService::RecordCompleteCallback - record_complete_callback, - cast::utils::GrpcStatusOr response_or); - void OnMetricsRecorderServiceStopped( - cast::runtime::RuntimeServiceHandler::StopMetricsRecorder::Reactor* - reactor); - - void ResetGrpcServices(); - - SEQUENCE_CHECKER(sequence_checker_); - - std::unique_ptr> - application_dispatcher_; - - scoped_refptr task_runner_; - - raw_ref const web_service_; - - // Allows metrics, histogram, action recording, which can be reported by - // CastRuntimeMetricsRecorderService if Cast Core starts it. - CastRuntimeActionRecorder action_recorder_; - CastRuntimeMetricsRecorder metrics_recorder_; - - std::optional grpc_server_; - std::optional - metrics_recorder_stub_; - std::optional metrics_recorder_service_; - - // Heartbeat period as set by Cast Core. - base::TimeDelta heartbeat_period_; - - // Heartbeat timeout timer. - base::OneShotTimer heartbeat_timer_; - - // Server streaming reactor used to send the heartbeats to Cast Core. - cast::runtime::RuntimeServiceHandler::Heartbeat::Reactor* heartbeat_reactor_ = - nullptr; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_SERVICE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/DEPS chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/DEPS --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -include_rules = [ - "+components/url_rewrite/browser", - "+components/url_rewrite/mojom", - "+mojo/public", - "+third_party/cast_core", -] diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/OWNERS chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/OWNERS --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *_type_converter*.*=set noparent -per-file *_type_converter*.*=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,233 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h" - -#include - -#include "base/strings/strcat.h" -#include "base/strings/string_util.h" - -namespace { - -std::string NormalizeHost(std::string_view host) { - return GURL(base::StrCat({url::kHttpScheme, "://", host})).host(); -} - -} // namespace - -namespace mojo { - -template <> -struct TypeConverter { - static url_rewrite::mojom::UrlRequestRewriteAddHeadersPtr Convert( - const cast::v2::UrlRequestRewriteAddHeaders& input) { - url_rewrite::mojom::UrlRequestRewriteAddHeadersPtr add_headers = - url_rewrite::mojom::UrlRequestRewriteAddHeaders::New(); - for (const auto& header : input.headers()) { - url_rewrite::mojom::UrlHeaderPtr url_header = - url_rewrite::mojom::UrlHeader::New(header.name(), header.value()); - add_headers->headers.push_back(std::move(url_header)); - } - return add_headers; - } -}; - -template <> -struct TypeConverter { - static url_rewrite::mojom::UrlRequestRewriteRemoveHeaderPtr Convert( - const cast::v2::UrlRequestRewriteRemoveHeader& input) { - url_rewrite::mojom::UrlRequestRewriteRemoveHeaderPtr remove_header = - url_rewrite::mojom::UrlRequestRewriteRemoveHeader::New(); - if (!input.query_pattern().empty()) - remove_header->query_pattern = std::make_optional(input.query_pattern()); - if (!input.header_name().empty()) - remove_header->header_name = input.header_name(); - return remove_header; - } -}; - -template <> -struct TypeConverter< - url_rewrite::mojom::UrlRequestRewriteSubstituteQueryPatternPtr, - cast::v2::UrlRequestRewriteSubstituteQueryPattern> { - static url_rewrite::mojom::UrlRequestRewriteSubstituteQueryPatternPtr Convert( - const cast::v2::UrlRequestRewriteSubstituteQueryPattern& input) { - url_rewrite::mojom::UrlRequestRewriteSubstituteQueryPatternPtr - substitute_query_pattern = - url_rewrite::mojom::UrlRequestRewriteSubstituteQueryPattern::New(); - if (!input.pattern().empty()) - substitute_query_pattern->pattern = input.pattern(); - if (!input.substitution().empty()) - substitute_query_pattern->substitution = input.substitution(); - return substitute_query_pattern; - } -}; - -template <> -struct TypeConverter { - static url_rewrite::mojom::UrlRequestRewriteReplaceUrlPtr Convert( - const cast::v2::UrlRequestRewriteReplaceUrl& input) { - url_rewrite::mojom::UrlRequestRewriteReplaceUrlPtr replace_url = - url_rewrite::mojom::UrlRequestRewriteReplaceUrl::New(); - if (!input.url_ends_with().empty()) - replace_url->url_ends_with = input.url_ends_with(); - if (!input.new_url().empty()) - replace_url->new_url = GURL(input.new_url()); - return replace_url; - } -}; - -template <> -struct TypeConverter { - static url_rewrite::mojom::UrlRequestRewriteAppendToQueryPtr Convert( - const cast::v2::UrlRequestRewriteAppendToQuery& input) { - url_rewrite::mojom::UrlRequestRewriteAppendToQueryPtr append_to_query = - url_rewrite::mojom::UrlRequestRewriteAppendToQuery::New(); - if (!input.query().empty()) - append_to_query->query = input.query(); - return append_to_query; - } -}; - -// Returns nullptr if conversion is not possible. -template <> -struct TypeConverter { - static url_rewrite::mojom::UrlRequestActionPtr Convert( - const cast::v2::UrlRequestRewriteRule::UrlRequestAction& input) { - // The converter should never get called if policy action is unspecified. - DCHECK(input != cast::v2::UrlRequestRewriteRule::ACTION_UNSPECIFIED); - switch (input) { - case cast::v2::UrlRequestRewriteRule::ALLOW: - return url_rewrite::mojom::UrlRequestAction::NewPolicy( - mojo::ConvertTo( - url_rewrite::mojom::UrlRequestAccessPolicy::kAllow)); - case cast::v2::UrlRequestRewriteRule::DENY: - return url_rewrite::mojom::UrlRequestAction::NewPolicy( - mojo::ConvertTo( - url_rewrite::mojom::UrlRequestAccessPolicy::kDeny)); - default: - // Cannot convert the gRPC policy action to a mojo counterpart. - return nullptr; - } - } -}; - -// Returns nullptr if conversion is not possible. -template <> -struct TypeConverter { - static url_rewrite::mojom::UrlRequestActionPtr Convert( - const cast::v2::UrlRequestRewrite& input) { - switch (input.action_case()) { - case cast::v2::UrlRequestRewrite::kAddHeaders: - return url_rewrite::mojom::UrlRequestAction::NewAddHeaders( - mojo::ConvertTo( - input.add_headers())); - case cast::v2::UrlRequestRewrite::kRemoveHeader: - return url_rewrite::mojom::UrlRequestAction::NewRemoveHeader( - mojo::ConvertTo< - url_rewrite::mojom::UrlRequestRewriteRemoveHeaderPtr>( - input.remove_header())); - case cast::v2::UrlRequestRewrite::kSubstituteQueryPattern: - return url_rewrite::mojom::UrlRequestAction::NewSubstituteQueryPattern( - mojo::ConvertTo< - url_rewrite::mojom::UrlRequestRewriteSubstituteQueryPatternPtr>( - input.substitute_query_pattern())); - case cast::v2::UrlRequestRewrite::kReplaceUrl: - return url_rewrite::mojom::UrlRequestAction::NewReplaceUrl( - mojo::ConvertTo( - input.replace_url())); - case cast::v2::UrlRequestRewrite::kAppendToQuery: - return url_rewrite::mojom::UrlRequestAction::NewAppendToQuery( - mojo::ConvertTo< - url_rewrite::mojom::UrlRequestRewriteAppendToQueryPtr>( - input.append_to_query())); - case cast::v2::UrlRequestRewrite::ACTION_NOT_SET: - // Cannot convert the gRPC rewrite rule to a mojo counterpart. - return nullptr; - } - } -}; - -// Returns nullptr if conversion is not possible. -template <> -struct TypeConverter { - static url_rewrite::mojom::UrlRequestRulePtr Convert( - const cast::v2::UrlRequestRewriteRule& input) { - url_rewrite::mojom::UrlRequestRulePtr rule = - url_rewrite::mojom::UrlRequestRule::New(); - - if (!input.host_filters().empty()) { - // Convert host names in case they contain non-ASCII characters. - const std::string_view kWildcard("*."); - - std::vector hosts; - for (std::string_view host : input.host_filters()) { - if (base::StartsWith(host, kWildcard, base::CompareCase::SENSITIVE)) { - hosts.push_back( - base::StrCat({kWildcard, NormalizeHost(host.substr(2))})); - } else { - hosts.push_back(NormalizeHost(host)); - } - } - rule->hosts_filter = std::move(hosts); - } - - if (!input.scheme_filters().empty()) - rule->schemes_filter.emplace(input.scheme_filters().begin(), - input.scheme_filters().end()); - - // Convert the rewrite rules. - for (const cast::v2::UrlRequestRewrite& grpc_rewrite : input.rewrites()) { - auto action = mojo::ConvertTo( - grpc_rewrite); - if (!action) { - // Conversion to Mojo failed. - return nullptr; - } - rule->actions.push_back(std::move(action)); - } - - // Convert the action policy. - if (input.action() != cast::v2::UrlRequestRewriteRule::ACTION_UNSPECIFIED) { - // Convert the action policy. - auto policy = mojo::ConvertTo( - input.action()); - if (!policy) { - // Conversion to Mojo failed. - return nullptr; - } - rule->actions.push_back(std::move(policy)); - } - - return rule; - } -}; - -url_rewrite::mojom::UrlRequestRewriteRulesPtr -TypeConverter:: - Convert(const cast::v2::UrlRequestRewriteRules& input) { - url_rewrite::mojom::UrlRequestRewriteRulesPtr rules = - url_rewrite::mojom::UrlRequestRewriteRules::New(); - for (const auto& rule : input.rules()) { - auto mojo_rule = - mojo::ConvertTo(rule); - if (!mojo_rule) { - // Conversion to Mojo failed. - return nullptr; - } - rules->rules.push_back(std::move(mojo_rule)); - } - return rules; -} - -} // namespace mojo diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_ - -#include "components/url_rewrite/mojom/url_request_rewrite.mojom.h" -#include "mojo/public/cpp/bindings/type_converter.h" -#include "third_party/cast_core/public/src/proto/v2/url_rewrite.pb.h" - -namespace mojo { - -// This conversion is done with a TypeCoverter rather than a typemap because -// it is only done one way, from the gRPC type to the Mojo type. This conversion -// is only done once, in the browser process. These rules are validated after -// they have been converted into Mojo. -// In Core Runtime, we have a one-way flow from the untrusted embedder into the -// browser process, via a gRPC API. From there, the rules are converted into -// Mojo and then validated before being sent to renderer processes. No further -// conversion is performed, the Mojo types are used as is to apply the rewrites -// on URL requests. -// Converter returns |nullptr| if conversion is not possible. -template <> -struct TypeConverter { - static url_rewrite::mojom::UrlRequestRewriteRulesPtr Convert( - const cast::v2::UrlRequestRewriteRules& input); -}; - -} // namespace mojo - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters_unittest.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters_unittest.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,288 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h" - -#include - -#include "base/run_loop.h" -#include "components/url_rewrite/browser/url_request_rewrite_rules_validation.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/cast_core/public/src/proto/v2/url_rewrite.pb.h" - -namespace chromecast { -namespace { - -using ::testing::SizeIs; - -cast::v2::UrlRequestRewrite CreateRewriteAddHeaders(std::string header_name, - std::string header_value) { - cast::v2::UrlRequestRewrite rewrite; - cast::v2::UrlHeader* url_header = - rewrite.mutable_add_headers()->mutable_headers()->Add(); - url_header->set_name(std::move(header_name)); - url_header->set_value(std::move(header_value)); - return rewrite; -} - -cast::v2::UrlRequestRewrite CreateRewriteRemoveHeader( - std::optional query_pattern, - std::string header_name) { - cast::v2::UrlRequestRewrite rewrite; - auto* remove_header = rewrite.mutable_remove_header(); - if (query_pattern) - remove_header->set_query_pattern(std::move(query_pattern).value()); - remove_header->set_header_name(std::move(header_name)); - return rewrite; -} - -cast::v2::UrlRequestRewrite CreateRewriteSubstituteQueryPattern( - std::string pattern, - std::string substitution) { - cast::v2::UrlRequestRewrite rewrite; - auto* substitute_query_pattern = rewrite.mutable_substitute_query_pattern(); - substitute_query_pattern->set_pattern(std::move(pattern)); - substitute_query_pattern->set_substitution(std::move(substitution)); - return rewrite; -} - -cast::v2::UrlRequestRewrite CreateRewriteReplaceUrl(std::string url_ends_with, - std::string new_url) { - cast::v2::UrlRequestRewrite rewrite; - auto* replace_url = rewrite.mutable_replace_url(); - replace_url->set_url_ends_with(std::move(url_ends_with)); - replace_url->set_new_url(std::move(new_url)); - return rewrite; -} - -cast::v2::UrlRequestRewrite CreateRewriteAppendToQuery(std::string query) { - cast::v2::UrlRequestRewrite rewrite; - auto* append_to_query = rewrite.mutable_append_to_query(); - append_to_query->set_query(std::move(query)); - return rewrite; -} - -class UrlRequestRewriteTypeConvertersTest : public testing::Test { - public: - UrlRequestRewriteTypeConvertersTest() = default; - - UrlRequestRewriteTypeConvertersTest( - const UrlRequestRewriteTypeConvertersTest&) = delete; - UrlRequestRewriteTypeConvertersTest& operator=( - const UrlRequestRewriteTypeConvertersTest&) = delete; - - ~UrlRequestRewriteTypeConvertersTest() override = default; - - protected: - bool UpdateRulesFromRewrite(cast::v2::UrlRequestRewrite rewrite) { - cast::v2::UrlRequestRewriteRules rules; - rules.mutable_rules()->Add()->mutable_rewrites()->Add(std::move(rewrite)); - cached_rules_ = - mojo::ConvertTo( - std::move(rules)); - return url_rewrite::ValidateRules(cached_rules_.get()); - } - - url_rewrite::mojom::UrlRequestRewriteRulesPtr cached_rules_; -}; - -// Tests AddHeaders rewrites are properly converted to their Mojo equivalent. -TEST_F(UrlRequestRewriteTypeConvertersTest, ConvertAddHeader) { - EXPECT_TRUE(UpdateRulesFromRewrite(CreateRewriteAddHeaders("Test", "Value"))); - ASSERT_THAT(cached_rules_->rules, SizeIs(1)); - ASSERT_FALSE(cached_rules_->rules[0]->hosts_filter); - ASSERT_FALSE(cached_rules_->rules[0]->schemes_filter); - ASSERT_THAT(cached_rules_->rules[0]->actions, SizeIs(1)); - ASSERT_TRUE(cached_rules_->rules[0]->actions[0]->is_add_headers()); - - const std::vector& headers = - cached_rules_->rules[0]->actions[0]->get_add_headers()->headers; - ASSERT_THAT(headers, SizeIs(1)); - ASSERT_EQ(headers[0]->name, "Test"); - ASSERT_EQ(headers[0]->value, "Value"); -} - -// Tests RemoveHeader rewrites are properly converted to their Mojo equivalent. -TEST_F(UrlRequestRewriteTypeConvertersTest, ConvertRemoveHeader) { - EXPECT_TRUE(UpdateRulesFromRewrite( - CreateRewriteRemoveHeader(std::make_optional("Test"), "Header"))); - ASSERT_THAT(cached_rules_->rules, SizeIs(1)); - ASSERT_FALSE(cached_rules_->rules[0]->hosts_filter); - ASSERT_FALSE(cached_rules_->rules[0]->schemes_filter); - ASSERT_THAT(cached_rules_->rules[0]->actions, SizeIs(1)); - ASSERT_TRUE(cached_rules_->rules[0]->actions[0]->is_remove_header()); - - const url_rewrite::mojom::UrlRequestRewriteRemoveHeaderPtr& remove_header1 = - cached_rules_->rules[0]->actions[0]->get_remove_header(); - ASSERT_TRUE(remove_header1->query_pattern); - ASSERT_EQ(remove_header1->query_pattern.value().compare("Test"), 0); - ASSERT_EQ(remove_header1->header_name.compare("Header"), 0); - - // Create a RemoveHeader rewrite with no pattern. - EXPECT_TRUE(UpdateRulesFromRewrite( - CreateRewriteRemoveHeader(std::nullopt, "Header"))); - ASSERT_THAT(cached_rules_->rules, SizeIs(1)); - ASSERT_FALSE(cached_rules_->rules[0]->hosts_filter); - ASSERT_FALSE(cached_rules_->rules[0]->schemes_filter); - ASSERT_THAT(cached_rules_->rules[0]->actions, SizeIs(1)); - ASSERT_TRUE(cached_rules_->rules[0]->actions[0]->is_remove_header()); - - const url_rewrite::mojom::UrlRequestRewriteRemoveHeaderPtr& remove_header2 = - cached_rules_->rules[0]->actions[0]->get_remove_header(); - ASSERT_FALSE(remove_header2->query_pattern); - ASSERT_EQ(remove_header2->header_name.compare("Header"), 0); -} - -// Tests SubstituteQueryPattern rewrites are properly converted to their Mojo -// equivalent. -TEST_F(UrlRequestRewriteTypeConvertersTest, ConvertSubstituteQueryPattern) { - EXPECT_TRUE(UpdateRulesFromRewrite( - CreateRewriteSubstituteQueryPattern("Pattern", "Substitution"))); - ASSERT_THAT(cached_rules_->rules, SizeIs(1)); - ASSERT_FALSE(cached_rules_->rules[0]->hosts_filter); - ASSERT_FALSE(cached_rules_->rules[0]->schemes_filter); - ASSERT_THAT(cached_rules_->rules[0]->actions, SizeIs(1)); - ASSERT_TRUE( - cached_rules_->rules[0]->actions[0]->is_substitute_query_pattern()); - - const url_rewrite::mojom::UrlRequestRewriteSubstituteQueryPatternPtr& - substitute_query_pattern = - cached_rules_->rules[0]->actions[0]->get_substitute_query_pattern(); - ASSERT_EQ(substitute_query_pattern->pattern.compare("Pattern"), 0); - ASSERT_EQ(substitute_query_pattern->substitution.compare("Substitution"), 0); -} - -// Tests ReplaceUrl rewrites are properly converted to their Mojo equivalent. -TEST_F(UrlRequestRewriteTypeConvertersTest, ConvertReplaceUrl) { - GURL url("http://site.xyz"); - EXPECT_TRUE(UpdateRulesFromRewrite( - CreateRewriteReplaceUrl("/something", url.spec()))); - ASSERT_THAT(cached_rules_->rules, SizeIs(1)); - ASSERT_FALSE(cached_rules_->rules[0]->hosts_filter); - ASSERT_FALSE(cached_rules_->rules[0]->schemes_filter); - ASSERT_THAT(cached_rules_->rules[0]->actions, SizeIs(1)); - ASSERT_TRUE(cached_rules_->rules[0]->actions[0]->is_replace_url()); - - const url_rewrite::mojom::UrlRequestRewriteReplaceUrlPtr& replace_url = - cached_rules_->rules[0]->actions[0]->get_replace_url(); - ASSERT_EQ(replace_url->url_ends_with.compare("/something"), 0); - ASSERT_EQ(replace_url->new_url.spec().compare(url.spec()), 0); -} - -// Tests AppendToQuery rewrites are properly converted to their Mojo equivalent. -TEST_F(UrlRequestRewriteTypeConvertersTest, ConvertAppendToQuery) { - EXPECT_TRUE( - UpdateRulesFromRewrite(CreateRewriteAppendToQuery("foo=bar&foo"))); - ASSERT_THAT(cached_rules_->rules, SizeIs(1)); - ASSERT_FALSE(cached_rules_->rules[0]->hosts_filter); - ASSERT_FALSE(cached_rules_->rules[0]->schemes_filter); - ASSERT_THAT(cached_rules_->rules[0]->actions, SizeIs(1)); - ASSERT_TRUE(cached_rules_->rules[0]->actions[0]->is_append_to_query()); - - const url_rewrite::mojom::UrlRequestRewriteAppendToQueryPtr& append_to_query = - cached_rules_->rules[0]->actions[0]->get_append_to_query(); - ASSERT_EQ(append_to_query->query.compare("foo=bar&foo"), 0); -} - -// Tests validation is working as expected. -TEST_F(UrlRequestRewriteTypeConvertersTest, Validation) { - // Empty rewrite. - EXPECT_FALSE(UpdateRulesFromRewrite(cast::v2::UrlRequestRewrite())); - - // Invalid AddHeaders header name. - EXPECT_FALSE( - UpdateRulesFromRewrite(CreateRewriteAddHeaders("Te\nst1", "Value"))); - - // Invalid AddHeaders header value. - EXPECT_FALSE( - UpdateRulesFromRewrite(CreateRewriteAddHeaders("Test1", "Val\nue"))); - - // Empty AddHeaders. - { - cast::v2::UrlRequestRewrite rewrite; - rewrite.mutable_add_headers(); - EXPECT_FALSE(UpdateRulesFromRewrite(std::move(rewrite))); - } - - // Invalid RemoveHeader header name. - EXPECT_FALSE( - UpdateRulesFromRewrite(CreateRewriteRemoveHeader("Query", "Head\ner"))); - - // Empty RemoveHeader. - { - cast::v2::UrlRequestRewrite rewrite; - rewrite.mutable_remove_header(); - EXPECT_FALSE(UpdateRulesFromRewrite(std::move(rewrite))); - } - - // Empty SubstituteQueryPattern. - { - cast::v2::UrlRequestRewrite rewrite; - rewrite.mutable_substitute_query_pattern(); - EXPECT_FALSE(UpdateRulesFromRewrite(std::move(rewrite))); - } - - // ReplaceURL with valid new_url. - EXPECT_TRUE(UpdateRulesFromRewrite( - CreateRewriteReplaceUrl("/something", "http://site.xyz"))); - EXPECT_TRUE(UpdateRulesFromRewrite( - CreateRewriteReplaceUrl("some%00thing", "http://site.xyz"))); - - // ReplaceURL with valid new_url including "%00" in its path. - EXPECT_TRUE(UpdateRulesFromRewrite( - CreateRewriteReplaceUrl("/something", "http://site.xyz/%00"))); - EXPECT_TRUE(UpdateRulesFromRewrite( - CreateRewriteReplaceUrl("some%00thing", "http://site.xyz/%00"))); - - // ReplaceURL with invalid new_url. - EXPECT_FALSE(UpdateRulesFromRewrite( - CreateRewriteReplaceUrl("/something", "http:site:xyz"))); - EXPECT_FALSE(UpdateRulesFromRewrite( - CreateRewriteReplaceUrl("some%00thing", "http:site:xyz"))); - - // Empty ReplaceUrl. - { - cast::v2::UrlRequestRewrite rewrite; - rewrite.mutable_replace_url(); - EXPECT_FALSE(UpdateRulesFromRewrite(std::move(rewrite))); - } - - // Empty AppendToQuery. - { - cast::v2::UrlRequestRewrite rewrite; - rewrite.mutable_append_to_query(); - EXPECT_FALSE(UpdateRulesFromRewrite(std::move(rewrite))); - } -} - -// Tests rules are properly renewed after new rules are sent. -TEST_F(UrlRequestRewriteTypeConvertersTest, RuleRenewal) { - EXPECT_TRUE( - UpdateRulesFromRewrite(CreateRewriteAddHeaders("Test1", "Value"))); - ASSERT_THAT(cached_rules_->rules, SizeIs(1)); - ASSERT_THAT(cached_rules_->rules[0]->actions, SizeIs(1)); - ASSERT_TRUE(cached_rules_->rules[0]->actions[0]->is_add_headers()); - ASSERT_THAT(cached_rules_->rules[0]->actions[0]->get_add_headers()->headers, - SizeIs(1)); - ASSERT_EQ( - cached_rules_->rules[0]->actions[0]->get_add_headers()->headers[0]->name, - "Test1"); - - EXPECT_TRUE( - UpdateRulesFromRewrite(CreateRewriteAddHeaders("Test2", "Value"))); - - // We should have the new rules. - ASSERT_THAT(cached_rules_->rules, SizeIs(1)); - ASSERT_THAT(cached_rules_->rules[0]->actions, SizeIs(1)); - ASSERT_TRUE(cached_rules_->rules[0]->actions[0]->is_add_headers()); - ASSERT_THAT(cached_rules_->rules[0]->actions[0]->get_add_headers()->headers, - SizeIs(1)); - ASSERT_EQ( - cached_rules_->rules[0]->actions[0]->get_add_headers()->headers[0]->name, - "Test2"); -} - -} // namespace -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/renderer/DEPS chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/DEPS --- chromium-132.0.6834.110/chromecast/cast_core/runtime/renderer/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -include_rules = [ - "+chromecast/cast_core/common", - "+chromecast/renderer", - "+components/cast_streaming/public", - "+components/cast_streaming/renderer/public", - "+content/public/renderer", - "+media/base", - "+third_party/blink/public/common", -] diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.h" - -#include "components/cast_streaming/renderer/public/resource_provider.h" -#include "components/cast_streaming/renderer/public/resource_provider_factory.h" - -namespace chromecast { - -CastRuntimeContentRendererClient::CastRuntimeContentRendererClient() = default; - -CastRuntimeContentRendererClient::~CastRuntimeContentRendererClient() = default; - -std::unique_ptr -CastRuntimeContentRendererClient::CreateCastStreamingResourceProvider() { - return cast_streaming::CreateResourceProvider(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.h chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.h --- chromium-132.0.6834.110/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_RENDERER_CAST_RUNTIME_CONTENT_RENDERER_CLIENT_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_RENDERER_CAST_RUNTIME_CONTENT_RENDERER_CLIENT_H_ - -#include - -#include "chromecast/renderer/cast_content_renderer_client.h" - -namespace cast_streaming { -class ResourceProvider; -} - -namespace chromecast { - -// TODO(crbug.com/1359580): Use code from //components/cast_receiver/renderer -// instead of relying on CastContentRendererClient. -class CastRuntimeContentRendererClient - : public shell::CastContentRendererClient { - public: - CastRuntimeContentRendererClient(); - CastRuntimeContentRendererClient(const CastRuntimeContentRendererClient&) = - delete; - CastRuntimeContentRendererClient(CastRuntimeContentRendererClient&&) = delete; - ~CastRuntimeContentRendererClient() override; - - CastRuntimeContentRendererClient& operator=( - const CastRuntimeContentRendererClient&) = delete; - CastRuntimeContentRendererClient& operator=( - CastRuntimeContentRendererClient&&) = delete; - - // content::ContentRendererClient overrides. - std::unique_ptr - CreateCastStreamingResourceProvider() override; - - private: - std::unique_ptr - cast_streaming_resource_provider_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_RENDERER_CAST_RUNTIME_CONTENT_RENDERER_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client_simple.cc chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client_simple.cc --- chromium-132.0.6834.110/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client_simple.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client_simple.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/cast_core/runtime/renderer/cast_runtime_content_renderer_client.h" - -#include - -#include "chromecast/renderer/cast_content_renderer_client.h" - -namespace chromecast { - -std::unique_ptr -shell::CastContentRendererClient::Create() { - return std::make_unique(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/cast_core/test/cast_core_screenshot_test.py chromium-132.0.6834.159/chromecast/cast_core/test/cast_core_screenshot_test.py --- chromium-132.0.6834.110/chromecast/cast_core/test/cast_core_screenshot_test.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/test/cast_core_screenshot_test.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,170 +0,0 @@ -# Copyright 2022 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import os -import random -import sys - -from telemetry.internal.backends.chrome import cast_browser_finder -from telemetry.internal.browser import browser_finder -from telemetry.internal.browser import browser_finder_exceptions -from telemetry.internal.platform import cast_device -from telemetry.testing import serially_executed_browser_test_case -from telemetry.util import image_util -from telemetry.util import rgba_color - - -class ScreenshotTest( - serially_executed_browser_test_case.SeriallyExecutedBrowserTestCase): - @classmethod - def Name(cls): - return 'screenshot' - - @classmethod - def SetUpProcess(cls): - super(cls, ScreenshotTest).SetUpProcess() - cls.SetBrowserOptions(cls._finder_options) - cls.StartBrowser() - cls.tab = cls.browser.tabs[0] - cls._cast_receiver_to_create.SetCastSender(cls.tab) - cls.StartCastReceiver() - cls.SetStaticServerDirs([os.path.join(os.path.dirname(__file__), 'data')]) - - @classmethod - def StartCastReceiver(cls): - """ Navigates sending tab to about:blank and cast to receiver.""" - - try: - # TODO(crbug.com/40558533): Note cls._browser_options actually is a - # FinderOptions object, and we need to access the real browser_option's - # contained inside. - cls._cast_receiver_to_create.SetUpEnvironment( - cls._browser_options.browser_options) - cls.cast_receiver = cls._cast_receiver_to_create.Create() - except Exception: - cls._cast_receiver_to_create.CleanUpEnvironment() - raise - - @classmethod - def SetBrowserOptions(cls, browser_options): - """Sets the browser option for the browser to create. - - Args: - browser_options: Browser options object for the browser we want to test. - """ - cls._browser_options = browser_options - if browser_options.local_cast: - cls._local_cast = True - else: - cls._local_cast = False - cls._browser_to_create = browser_finder.FindBrowser(browser_options) - if not cls._browser_to_create: - raise browser_finder_exceptions.BrowserFinderException( - 'Cannot find browser of type %s. \n\nAvailable browsers:\n%s\n' % ( - browser_options.browser_options.browser_type, - '\n'.join(browser_finder.GetAllAvailableBrowserTypes( - browser_options)))) - - cast_devices = cast_device.FindAllAvailableDevices(browser_options) - cast_browsers = [] - for device in cast_devices: - cast_browsers.extend( - cast_browser_finder.FindAllAvailableBrowsers( - browser_options, device)) - cls._cast_receiver_to_create = \ - cast_browser_finder.SelectDefaultBrowser(cast_browsers) - - if not cls.platform: - cls.platform = cls._browser_to_create.platform - cls.platform.network_controller.Open( - browser_options.browser_options.wpr_mode) - assert cls.platform == cls._browser_to_create.platform, ( - 'All browser launches within same test suite must use browsers on ' - 'the same platform') - - @classmethod - def TearDownProcess(cls): - """ Tear down the testing logic after running the test cases. - This is guaranteed to be called only once for all the tests after the test - suite finishes running. - """ - - if cls.browser: - cls.StopBrowser() - - if cls.cast_receiver: - cls.StopCastReceiver() - - @classmethod - def StopCastReceiver(cls): - assert cls.cast_receiver, 'Cast receiver is not started' - try: - cls.cast_receiver.Close() - cls.cast_receiver = None - finally: - cls._cast_receiver_to_create.CleanUpEnvironment() - - def TestFling(self): - """Fling a Youtube video to the Cast receiver and confirm that rendering - is correctly performed via screenshot.""" - self.cast_receiver._browser_backend.FlingVideo( - 'https://youtu.be/zBeWNaNWtIM') - self.receiver_tab = self.cast_receiver.tabs[0] - screenshot = self.receiver_tab.Screenshot(10) - logging.warning(screenshot) - pixel_value = image_util.GetPixelColor(screenshot, 100, 100) - - if self._local_cast: - # For Cast Core on Linux, no rendering is available yet so the screen - # should display the Youtube icon. - videoRGB = rgba_color.RgbaColor(40, 40, 40) - else: - videoRGB = rgba_color.RgbaColor(37, 150, 190) - - # Allow for off-by-one errors due to color conversion. - tolerance = 1 - - if not videoRGB.IsEqual(pixel_value, tolerance): - error_message = ('Color mismatch : expected (%d, %d, %d), ' + - 'got (%d, %d, %d)') % ( - videoRGB.r, videoRGB.g, videoRGB.b, - pixel_value.r, pixel_value.g, pixel_value.b) - self.fail(error_message) - - def TestMirroring(self): - """Draw a square of random color on the sending tab, take a screenshot on - the Cast receiver and confirm that the colors match.""" - - canvasRGB = rgba_color.RgbaColor( - random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), - 255) - tab = self.tab - tab.action_runner.Navigate(self.UrlOfStaticFilePath('screenshot.html')) - tab.EvaluateJavaScript('window.draw({{ red }}, {{ green }}, {{ blue }});', - red=canvasRGB.r, - green=canvasRGB.g, - blue=canvasRGB.b) - self.cast_receiver._browser_backend.MirrorTab() - self.receiver_tab = self.cast_receiver.tabs[0] - - ### TODO(crbug.com/40836534): Investigate issues grabbing a screenshot - ### with tab mirroring. - # screenshot = self.receiver_tab.Screenshot(10) - # pixel_value = image_util.GetPixelColor(screenshot, 0, 0) - - # # Allow for off-by-one errors due to color conversion. - # tolerance = 1 - - # if not canvasRGB.IsEqual(pixel_value, tolerance): - # error_message = ('Color mismatch : expected (%d, %d, %d), ' + - # 'got (%d, %d, %d)') % ( - # canvasRGB.r, canvasRGB.g, canvasRGB.b, - # pixel_value.r, pixel_value.g, pixel_value.b) - # self.fail(error_message) - - -def load_tests(loader, tests, pattern): - del loader, tests, pattern # Unused. - return serially_executed_browser_test_case \ - .LoadAllTestsInModule(sys.modules[__name__]) \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/cast_core/test/cast_project_config.py chromium-132.0.6834.159/chromecast/cast_core/test/cast_project_config.py --- chromium-132.0.6834.110/chromecast/cast_core/test/cast_project_config.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/test/cast_project_config.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -# Copyright 2022 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import os -import sys - -CHROMIUM_SRC_DIR = os.path.realpath( - os.path.join(os.path.dirname(__file__), '..', '..', '..')) - -sys.path.append(os.path.join(CHROMIUM_SRC_DIR, 'tools', 'perf')) -from chrome_telemetry_build import chromium_config - -CAST_TEST_DIR = os.path.join( - CHROMIUM_SRC_DIR, 'chromecast', 'cast_core', 'test') -CONFIG = chromium_config.ChromiumConfig(top_level_dir=CAST_TEST_DIR, - benchmark_dirs=[CAST_TEST_DIR]) \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/cast_core/test/data/screenshot.html chromium-132.0.6834.159/chromecast/cast_core/test/data/screenshot.html --- chromium-132.0.6834.110/chromecast/cast_core/test/data/screenshot.html 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/test/data/screenshot.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ - - - -Synchronized screenshot test with canvas - - - - -
- - - - diff -Nru chromium-132.0.6834.110/chromecast/cast_core/test/run_cast_integration_test.py chromium-132.0.6834.159/chromecast/cast_core/test/run_cast_integration_test.py --- chromium-132.0.6834.110/chromecast/cast_core/test/run_cast_integration_test.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/cast_core/test/run_cast_integration_test.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -#!/usr/bin/env vpython3 -# Copyright 2022 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import cast_project_config -import sys - -from telemetry.testing import browser_test_runner - -def main(): - retval = browser_test_runner.Run(cast_project_config.CONFIG, sys.argv) - return retval - - -if __name__ == '__main__': - sys.exit(main()) \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/common/DEPS chromium-132.0.6834.159/chromecast/common/DEPS --- chromium-132.0.6834.110/chromecast/common/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -include_rules = [ - "+components/cdm/common", - "+components/cast/common", - "+components/embedder_support/user_agent_utils.h", - "+components/services/heap_profiling/public/cpp", - "+components/url_matcher", - "+components/version_info", - "+content/public/common", - "+media", - "+mojo/public/cpp/bindings", - "+net/base", - "+net/http", - "+net/url_request/redirect_info.h", - "+services/network/public/cpp", - "+services/service_manager/public/cpp", - "+third_party/blink/public/common", - "+ui/base", - "+ui/gfx", -] diff -Nru chromium-132.0.6834.110/chromecast/common/OWNERS chromium-132.0.6834.159/chromecast/common/OWNERS --- chromium-132.0.6834.110/chromecast/common/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -seantopping@chromium.org - -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/common/activity_filtering_url_loader_throttle.cc chromium-132.0.6834.159/chromecast/common/activity_filtering_url_loader_throttle.cc --- chromium-132.0.6834.110/chromecast/common/activity_filtering_url_loader_throttle.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/activity_filtering_url_loader_throttle.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -// 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 "chromecast/common/activity_filtering_url_loader_throttle.h" - -#include "net/base/net_errors.h" -#include "net/url_request/redirect_info.h" -#include "services/network/public/cpp/resource_request.h" - -namespace chromecast { -namespace { - -const char kCancelReason[] = "ActivityFilteringURLLoaderThrottle"; - -} // namespace - -ActivityFilteringURLLoaderThrottle::ActivityFilteringURLLoaderThrottle( - ActivityUrlFilter* filter) - : url_filter_(filter) {} - -ActivityFilteringURLLoaderThrottle::~ActivityFilteringURLLoaderThrottle() = - default; - -void ActivityFilteringURLLoaderThrottle::WillStartRequest( - network::ResourceRequest* request, - bool* /* defer */) { - FilterURL(request->url); -} - -void ActivityFilteringURLLoaderThrottle::WillRedirectRequest( - net::RedirectInfo* redirect_info, - const network::mojom::URLResponseHead& /* response_head */, - bool* /* defer */, - std::vector* /* to_be_removed_request_headers */, - net::HttpRequestHeaders* /* modified_request_headers */, - net::HttpRequestHeaders* /* modified_cors_exempt_request_headers */) { - FilterURL(redirect_info->new_url); -} - -void ActivityFilteringURLLoaderThrottle::DetachFromCurrentSequence() {} - -void ActivityFilteringURLLoaderThrottle::FilterURL(const GURL& url) { - // Pass through allowed URLs, block otherwise. - if (!url_filter_->UrlMatchesWhitelist(url)) - delegate_->CancelWithError(net::ERR_ACCESS_DENIED, kCancelReason); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/activity_filtering_url_loader_throttle.h chromium-132.0.6834.159/chromecast/common/activity_filtering_url_loader_throttle.h --- chromium-132.0.6834.110/chromecast/common/activity_filtering_url_loader_throttle.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/activity_filtering_url_loader_throttle.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// 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. - -#ifndef CHROMECAST_COMMON_ACTIVITY_FILTERING_URL_LOADER_THROTTLE_H_ -#define CHROMECAST_COMMON_ACTIVITY_FILTERING_URL_LOADER_THROTTLE_H_ - -#include -#include - -#include "base/memory/raw_ptr.h" -#include "chromecast/common/activity_url_filter.h" -#include "third_party/blink/public/common/loader/url_loader_throttle.h" -#include "url/gurl.h" - -namespace chromecast { - -// This class monitors requests issued by third-party javascript run via -// Activities, and blocks the request based on URL whitelisting. -class ActivityFilteringURLLoaderThrottle : public blink::URLLoaderThrottle { - public: - explicit ActivityFilteringURLLoaderThrottle(ActivityUrlFilter* filter); - - ActivityFilteringURLLoaderThrottle( - const ActivityFilteringURLLoaderThrottle&) = delete; - ActivityFilteringURLLoaderThrottle& operator=( - const ActivityFilteringURLLoaderThrottle&) = delete; - - ~ActivityFilteringURLLoaderThrottle() override; - - // content::URLLoaderThrottle implementation: - void WillStartRequest(network::ResourceRequest* request, - bool* defer) override; - void WillRedirectRequest( - net::RedirectInfo* redirect_info, - const network::mojom::URLResponseHead& response_head, - bool* defer, - std::vector* to_be_removed_request_headers, - net::HttpRequestHeaders* modified_request_headers, - net::HttpRequestHeaders* modified_cors_exempt_request_headers) override; - - private: - // content::URLLoaderThrottle implementation: - void DetachFromCurrentSequence() override; - - void FilterURL(const GURL& url); - - raw_ptr url_filter_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_COMMON_ACTIVITY_FILTERING_URL_LOADER_THROTTLE_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/activity_url_filter.cc chromium-132.0.6834.159/chromecast/common/activity_url_filter.cc --- chromium-132.0.6834.110/chromecast/common/activity_url_filter.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/activity_url_filter.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// 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 "chromecast/common/activity_url_filter.h" - -namespace chromecast { - -ActivityUrlFilter::ActivityUrlFilter( - const std::vector& url_filters) - : url_matcher_(std::make_unique()) { - base::MatcherStringPattern::ID id = 0; - url_matcher::URLMatcherConditionSet::Vector condition_sets; - for (const auto& url : url_filters) { - url_matcher::URLMatcherConditionSet::Conditions conditions; - conditions.insert( - url_matcher_->condition_factory()->CreateURLMatchesCondition(url)); - scoped_refptr condition_set = - new url_matcher::URLMatcherConditionSet(id++, conditions); - condition_sets.push_back(std::move(condition_set)); - } - url_matcher_->AddConditionSets(condition_sets); -} - -ActivityUrlFilter::~ActivityUrlFilter() = default; - -bool ActivityUrlFilter::UrlMatchesWhitelist(const GURL& url) { - return !url_matcher_->MatchURL(url).empty(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/activity_url_filter.h chromium-132.0.6834.159/chromecast/common/activity_url_filter.h --- chromium-132.0.6834.110/chromecast/common/activity_url_filter.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/activity_url_filter.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// 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. - -#ifndef CHROMECAST_COMMON_ACTIVITY_URL_FILTER_H_ -#define CHROMECAST_COMMON_ACTIVITY_URL_FILTER_H_ - -#include -#include -#include - -#include "components/url_matcher/url_matcher.h" -#include "url/gurl.h" - -namespace chromecast { - -class ActivityUrlFilter { - public: - // |url_filters| are regular expressions that are allowed. - // TODO(guohuideng): This class is used by activities and regular cast apps. - // We could rename this class in future. - explicit ActivityUrlFilter(const std::vector& url_filters); - - ActivityUrlFilter(const ActivityUrlFilter&) = delete; - ActivityUrlFilter& operator=(const ActivityUrlFilter&) = delete; - - ~ActivityUrlFilter(); - - // Returns true if the given url matches to any whitelisted URL. - bool UrlMatchesWhitelist(const GURL& url); - - private: - std::unique_ptr url_matcher_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_COMMON_ACTIVITY_URL_FILTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/activity_url_filter_unittest.cc chromium-132.0.6834.159/chromecast/common/activity_url_filter_unittest.cc --- chromium-132.0.6834.110/chromecast/common/activity_url_filter_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/activity_url_filter_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// 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 "chromecast/common/activity_url_filter.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace chromecast { - -TEST(ActivityUrlFilterTest, TestWhitelistURLMatch) { - ActivityUrlFilter filter( - {"http://www.google.com/*", ".*://finance.google.com/"}); - EXPECT_TRUE(filter.UrlMatchesWhitelist( - GURL("http://www.google.com/a_test_that_matches"))); - EXPECT_FALSE(filter.UrlMatchesWhitelist( - GURL("http://www.goggles.com/i_should_not_match"))); - EXPECT_TRUE( - filter.UrlMatchesWhitelist(GURL("http://finance.google.com/mystock"))); - EXPECT_TRUE( - filter.UrlMatchesWhitelist(GURL("https://finance.google.com/mystock"))); - EXPECT_FALSE(filter.UrlMatchesWhitelist(GURL("https://www.google.com"))); - EXPECT_TRUE(filter.UrlMatchesWhitelist(GURL("http://www.google.com"))); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/cast_content_client.cc chromium-132.0.6834.159/chromecast/common/cast_content_client.cc --- chromium-132.0.6834.110/chromecast/common/cast_content_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/cast_content_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,220 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/cast_content_client.h" - -#include - -#include -#include -#include - -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/native_library.h" -#include "base/path_service.h" -#include "base/task/sequenced_task_runner.h" -#include "build/build_config.h" -#include "chromecast/base/cast_constants.h" -#include "chromecast/base/cast_paths.h" -#include "chromecast/base/version.h" -#include "chromecast/chromecast_buildflags.h" -#include "components/cast/common/constants.h" -#include "content/public/common/cdm_info.h" -#include "media/base/media_switches.h" -#include "media/cdm/cdm_type.h" -#include "media/media_buildflags.h" -#include "mojo/public/cpp/bindings/binder_map.h" -#include "third_party/widevine/cdm/buildflags.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "url/url_util.h" - -#if BUILDFLAG(IS_ANDROID) -#include - -#include "chromecast/common/media/cast_media_drm_bridge_client.h" -#include "components/cdm/common/android_cdm_registration.h" -#endif - -#if !BUILDFLAG(IS_FUCHSIA) -#include "base/no_destructor.h" -#include "components/services/heap_profiling/public/cpp/profiling_client.h" // nogncheck -#include "mojo/public/cpp/bindings/pending_receiver.h" -#endif - -#if BUILDFLAG(ENABLE_LIBRARY_CDMS) -#include "media/cdm/cdm_paths.h" // nogncheck -#endif - -#if BUILDFLAG(BUNDLE_WIDEVINE_CDM) && BUILDFLAG(IS_LINUX) -#include "base/no_destructor.h" -#include "components/cdm/common/cdm_manifest.h" -#include "media/base/cdm_capability.h" -#include "third_party/widevine/cdm/widevine_cdm_common.h" // nogncheck -// component updated CDM on all desktop platforms and remove this. -// This file is In SHARED_INTERMEDIATE_DIR. -#include "widevine_cdm_version.h" // nogncheck -#endif - -namespace chromecast { -namespace shell { - -namespace { - -#if BUILDFLAG(BUNDLE_WIDEVINE_CDM) && BUILDFLAG(IS_LINUX) -// Copied from chrome_content_client.cc -std::unique_ptr CreateWidevineCdmInfo( - const base::Version& version, - const base::FilePath& cdm_library_path, - media::CdmCapability capability) { - return std::make_unique( - kWidevineKeySystem, content::CdmInfo::Robustness::kSoftwareSecure, - std::move(capability), /*supports_sub_key_systems=*/false, - kWidevineCdmDisplayName, kWidevineCdmType, version, cdm_library_path); -} - -// On desktop Linux, given |cdm_base_path| that points to a folder containing -// the Widevine CDM and associated files, read the manifest included in that -// directory and create a CdmInfo. If that is successful, return the CdmInfo. If -// not, return nullptr. -// Copied from chrome_content_client.cc -// TODO(crbug.com/40746872): move the functions to a common file. -std::unique_ptr CreateCdmInfoFromWidevineDirectory( - const base::FilePath& cdm_base_path) { - // Library should be inside a platform specific directory. - auto cdm_library_path = - media::GetPlatformSpecificDirectory(cdm_base_path) - .Append(base::GetNativeLibraryName(kWidevineCdmLibraryName)); - if (!base::PathExists(cdm_library_path)) { - LOG(ERROR) << "cdm library path doesn't exist"; - return nullptr; - } - - // Manifest should be at the top level. - auto manifest_path = cdm_base_path.Append(FILE_PATH_LITERAL("manifest.json")); - base::Version version; - media::CdmCapability capability; - if (!ParseCdmManifestFromPath(manifest_path, &version, &capability)) - return nullptr; - - return CreateWidevineCdmInfo(version, cdm_library_path, - std::move(capability)); -} - -// This code checks to see if the Widevine CDM was bundled with Chrome. If one -// can be found and looks valid, it returns the CdmInfo for the CDM. Otherwise -// it returns nullptr. -// Copied from chrome_content_client.cc -content::CdmInfo* GetBundledWidevine() { - // We only want to do this on the first call, as if Widevine wasn't bundled - // with Chrome (or it was deleted/removed) it won't be loaded into the zygote. - static base::NoDestructor> s_cdm_info( - []() -> std::unique_ptr { - base::FilePath install_dir; - CHECK(base::PathService::Get(chromecast::DIR_BUNDLED_WIDEVINE_CDM, - &install_dir)); - - // On desktop Linux the MANIFEST is bundled with the CDM. - return CreateCdmInfoFromWidevineDirectory(install_dir); - }()); - return s_cdm_info->get(); -} -#endif // BUILDFLAG(BUNDLE_WIDEVINE_CDM) && BUILDFLAG(IS_LINUX) - -} // namespace - -CastContentClient::~CastContentClient() { -} - -void CastContentClient::SetActiveURL(const GURL& url, std::string top_origin) { - if (url.is_empty() || url == last_active_url_) - return; - LOG(INFO) << "Active URL: " << url.possibly_invalid_spec() << " for origin '" - << top_origin << "'"; - last_active_url_ = url; -} - -void CastContentClient::AddAdditionalSchemes(Schemes* schemes) { - schemes->standard_schemes.push_back(kChromeResourceScheme); -} - -std::u16string CastContentClient::GetLocalizedString(int message_id) { - return l10n_util::GetStringUTF16(message_id); -} - -std::string_view CastContentClient::GetDataResource( - int resource_id, - ui::ResourceScaleFactor scale_factor) { - return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale( - resource_id, scale_factor); -} - -base::RefCountedMemory* CastContentClient::GetDataResourceBytes( - int resource_id) { - // Chromecast loads localized resources for the home screen via this code - // path. See crbug.com/643886 for details. - return ui::ResourceBundle::GetSharedInstance().LoadLocalizedResourceBytes( - resource_id); -} - -std::string CastContentClient::GetDataResourceString(int resource_id) { - return ui::ResourceBundle::GetSharedInstance().LoadDataResourceString( - resource_id); -} - -gfx::Image& CastContentClient::GetNativeImageNamed(int resource_id) { - return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed( - resource_id); -} - -#if BUILDFLAG(IS_ANDROID) -::media::MediaDrmBridgeClient* CastContentClient::GetMediaDrmBridgeClient() { - return new media::CastMediaDrmBridgeClient(); -} -#endif // BUILDFLAG(IS_ANDROID) - -void CastContentClient::ExposeInterfacesToBrowser( - scoped_refptr io_task_runner, - mojo::BinderMap* binders) { -#if !BUILDFLAG(IS_FUCHSIA) - binders->Add( - base::BindRepeating( - [](mojo::PendingReceiver - receiver) { - static base::NoDestructor - profiling_client; - profiling_client->BindToInterface(std::move(receiver)); - }), - io_task_runner); -#endif // !BUILDFLAG(IS_FUCHSIA) -} - -void CastContentClient::AddContentDecryptionModules( - std::vector* cdms, - std::vector<::media::CdmHostFilePath>* cdm_host_file_paths) { - if (cdms) { -#if BUILDFLAG(BUNDLE_WIDEVINE_CDM) && BUILDFLAG(IS_LINUX) - // The Widevine CDM on Linux needs to be registered (and loaded) before the - // zygote is locked down. The CDM can be found from the version bundled with - // Chrome (if BUNDLE_WIDEVINE_CDM = true). - content::CdmInfo* bundled_widevine = GetBundledWidevine(); - - if (bundled_widevine) { - DVLOG(1) << "Registering bundled Widevine " << bundled_widevine->version; - cdms->push_back(*bundled_widevine); - } else { - DVLOG(1) << "Widevine enabled but no library found"; - } -#elif BUILDFLAG(IS_ANDROID) -#if BUILDFLAG(ENABLE_WIDEVINE) - cdm::AddAndroidWidevineCdm(cdms); -#endif // BUILDFLAG(ENABLE_WIDEVINE) - -#endif // BUILDFLAG(BUNDLE_WIDEVINE_CDM) && BUILDFLAG(IS_LINUX) - } -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/cast_content_client.h chromium-132.0.6834.159/chromecast/common/cast_content_client.h --- chromium-132.0.6834.110/chromecast/common/cast_content_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/cast_content_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_COMMON_CAST_CONTENT_CLIENT_H_ -#define CHROMECAST_COMMON_CAST_CONTENT_CLIENT_H_ - -#include -#include - -#include "base/task/sequenced_task_runner.h" -#include "build/build_config.h" -#include "content/public/common/content_client.h" -#include "url/gurl.h" - -namespace chromecast { -namespace shell { - -class CastContentClient : public content::ContentClient { - public: - ~CastContentClient() override; - - // content::ContentClient implementation: - void SetActiveURL(const GURL& url, std::string top_origin) override; - void AddAdditionalSchemes(Schemes* schemes) override; - std::u16string GetLocalizedString(int message_id) override; - std::string_view GetDataResource( - int resource_id, - ui::ResourceScaleFactor scale_factor) override; - base::RefCountedMemory* GetDataResourceBytes(int resource_id) override; - std::string GetDataResourceString(int resource_id) override; - gfx::Image& GetNativeImageNamed(int resource_id) override; -#if BUILDFLAG(IS_ANDROID) - ::media::MediaDrmBridgeClient* GetMediaDrmBridgeClient() override; -#endif // BUILDFLAG(IS_ANDROID) - void ExposeInterfacesToBrowser( - scoped_refptr io_task_runner, - mojo::BinderMap* binders) override; - void AddContentDecryptionModules( - std::vector* cdms, - std::vector<::media::CdmHostFilePath>* cdm_host_file_paths) override; - - private: - GURL last_active_url_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_COMMON_CAST_CONTENT_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/cast_resource_delegate.cc chromium-132.0.6834.159/chromecast/common/cast_resource_delegate.cc --- chromium-132.0.6834.110/chromecast/common/cast_resource_delegate.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/cast_resource_delegate.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/cast_resource_delegate.h" - -#include -#include - -#include "base/files/file_path.h" -#include "base/notreached.h" -#include "base/path_service.h" -#include "ui/gfx/image/image.h" - -namespace chromecast { - -namespace { - -CastResourceDelegate* g_instance = NULL; - -} // namespace - -// static -CastResourceDelegate* CastResourceDelegate::GetInstance() { - DCHECK(g_instance); - return g_instance; -} - -CastResourceDelegate::CastResourceDelegate() { - DCHECK(!g_instance) << "Cannot initialize resource bundle delegate twice."; - g_instance = this; -} - -CastResourceDelegate::~CastResourceDelegate() { - DCHECK_EQ(g_instance, this); - g_instance = NULL; -} - -base::FilePath CastResourceDelegate::GetPathForResourcePack( - const base::FilePath& pack_path, - ui::ResourceScaleFactor scale_factor) { - return pack_path; -} - -base::FilePath CastResourceDelegate::GetPathForLocalePack( - const base::FilePath& pack_path, - const std::string& locale) { - base::FilePath product_dir; - if (!base::PathService::Get(base::DIR_ASSETS, &product_dir)) { - NOTREACHED(); - } - return product_dir. - Append(FILE_PATH_LITERAL("chromecast_locales")). - Append(FILE_PATH_LITERAL(locale)). - AddExtension(FILE_PATH_LITERAL("pak")); -} - -gfx::Image CastResourceDelegate::GetImageNamed(int resource_id) { - return gfx::Image(); -} - -gfx::Image CastResourceDelegate::GetNativeImageNamed(int resource_id) { - return gfx::Image(); -} - -bool CastResourceDelegate::HasDataResource(int resource_id) const { - return false; -} - -base::RefCountedStaticMemory* CastResourceDelegate::LoadDataResourceBytes( - int resource_id, - ui::ResourceScaleFactor scale_factor) { - return NULL; -} - -std::optional CastResourceDelegate::LoadDataResourceString( - int resource_id) { - return std::nullopt; -} - -bool CastResourceDelegate::GetRawDataResource( - int resource_id, - ui::ResourceScaleFactor scale_factor, - std::string_view* value) const { - return false; -} - -bool CastResourceDelegate::GetLocalizedString(int message_id, - std::u16string* value) const { - ExtraLocaledStringMap::const_iterator it = - extra_localized_strings_.find(message_id); - if (it != extra_localized_strings_.end()) { - *value = it->second; - return true; - } - return false; -} - -void CastResourceDelegate::AddExtraLocalizedString( - int resource_id, - const std::u16string& localized) { - RemoveExtraLocalizedString(resource_id); - extra_localized_strings_.insert(std::make_pair(resource_id, localized)); -} - -void CastResourceDelegate::RemoveExtraLocalizedString(int resource_id) { - extra_localized_strings_.erase(resource_id); -} - -void CastResourceDelegate::ClearAllExtraLocalizedStrings() { - extra_localized_strings_.clear(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/cast_resource_delegate.h chromium-132.0.6834.159/chromecast/common/cast_resource_delegate.h --- chromium-132.0.6834.110/chromecast/common/cast_resource_delegate.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/cast_resource_delegate.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_COMMON_CAST_RESOURCE_DELEGATE_H_ -#define CHROMECAST_COMMON_CAST_RESOURCE_DELEGATE_H_ - -#include -#include -#include -#include - -#include "base/memory/ref_counted_memory.h" -#include "ui/base/resource/resource_bundle.h" - -namespace base { -class FilePath; -} - -namespace gfx { -class Image; -} - -namespace chromecast { - -// A singleton resource bundle delegate. Primary purpose is to indicate the -// correct locale pack file to load. -class CastResourceDelegate : public ui::ResourceBundle::Delegate { - public: - // Returns the singleton of delegate. It doesn't create an instance. - static CastResourceDelegate* GetInstance(); - - CastResourceDelegate(); - - CastResourceDelegate(const CastResourceDelegate&) = delete; - CastResourceDelegate& operator=(const CastResourceDelegate&) = delete; - - ~CastResourceDelegate() override; - - // ui:ResourceBundle::Delegate implementation: - base::FilePath GetPathForResourcePack( - const base::FilePath& pack_path, - ui::ResourceScaleFactor scale_factor) override; - base::FilePath GetPathForLocalePack( - const base::FilePath& pack_path, - const std::string& locale) override; - gfx::Image GetImageNamed(int resource_id) override; - gfx::Image GetNativeImageNamed(int resource_id) override; - bool HasDataResource(int resource_id) const override; - base::RefCountedStaticMemory* LoadDataResourceBytes( - int resource_id, - ui::ResourceScaleFactor scale_factor) override; - std::optional LoadDataResourceString(int resource_id) override; - bool GetRawDataResource(int resource_id, - ui::ResourceScaleFactor scale_factor, - std::string_view* value) const override; - bool GetLocalizedString(int message_id, std::u16string* value) const override; - - // Adds/removes/clears extra localized strings. - void AddExtraLocalizedString(int resource_id, - const std::u16string& localized); - void RemoveExtraLocalizedString(int resource_id); - void ClearAllExtraLocalizedStrings(); - - private: - using ExtraLocaledStringMap = std::unordered_map; - - ExtraLocaledStringMap extra_localized_strings_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_COMMON_CAST_RESOURCE_DELEGATE_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/cors_exempt_headers.cc chromium-132.0.6834.159/chromecast/common/cors_exempt_headers.cc --- chromium-132.0.6834.110/chromecast/common/cors_exempt_headers.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/cors_exempt_headers.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/cors_exempt_headers.h" - -#include -#include - -#include "base/containers/flat_set.h" -#include "base/no_destructor.h" -#include "base/stl_util.h" - -namespace chromecast { -namespace { - -const char* kExemptHeaders[] = { - "google_cast_bg", - "CAST-DEVICE-CAPABILITIES", - "CAST-SERIAL-NUM", - "CAST-CERT", - "CAST-CERT-CHAIN", - "CAST-SIGNATURE", - "CAST-SIGNATURE-TIME", - "CAST-APP-ID", - "CAST-SESSION-ID", - "CAST-APP-DEVICE-ID", - "CAST-PROD", - "CAST-JWT", - "CAST-PRIVATE-DATA", - "CAST-CKP-MODULUS", - "CAST-CKP-PUBLIC-EXPONENT", - "Authorization", - "X-Home-DeviceLinkedUserCreds", - "CAST-DEVICE-IN-MANAGED-MODE", - - // This header list is for legacy compatibility only. Do not add any more - // entries. -}; - -} // namespace - -base::span GetLegacyCorsExemptHeaders() { - return base::span(kExemptHeaders); -} - -bool IsCorsExemptHeader(std::string_view header) { - static const base::NoDestructor> - exempt_header_set(kExemptHeaders, - kExemptHeaders + std::size(kExemptHeaders)); - return exempt_header_set->find(header) != exempt_header_set->end(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/cors_exempt_headers.h chromium-132.0.6834.159/chromecast/common/cors_exempt_headers.h --- chromium-132.0.6834.110/chromecast/common/cors_exempt_headers.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/cors_exempt_headers.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_COMMON_CORS_EXEMPT_HEADERS_H_ -#define CHROMECAST_COMMON_CORS_EXEMPT_HEADERS_H_ - -#include - -#include "base/containers/span.h" - -namespace chromecast { - -// Returns the list of existing headers which pre-date CORS preflight check -// support in HTTP servers. -// TODO(b/154337552): Remove this list once all the servers support CORS -// preflight requests. -base::span GetLegacyCorsExemptHeaders(); - -// Returns true if |header| is CORS exempt. -bool IsCorsExemptHeader(std::string_view header); - -} // namespace chromecast - -#endif // CHROMECAST_COMMON_CORS_EXEMPT_HEADERS_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/cors_exempt_headers_unittest.cc chromium-132.0.6834.159/chromecast/common/cors_exempt_headers_unittest.cc --- chromium-132.0.6834.110/chromecast/common/cors_exempt_headers_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/cors_exempt_headers_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/cors_exempt_headers.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -TEST(CorsExemptHeadersTest, IsCorsExemptHeader) { - EXPECT_TRUE(IsCorsExemptHeader("CAST-CERT")); - EXPECT_TRUE(IsCorsExemptHeader("Authorization")); - EXPECT_FALSE(IsCorsExemptHeader("TEST-HEADER")); -} - -} // namespace -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/feature_constants.cc chromium-132.0.6834.159/chromecast/common/feature_constants.cc --- chromium-132.0.6834.110/chromecast/common/feature_constants.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/feature_constants.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/feature_constants.h" - -namespace chromecast { -namespace feature { - -const char kEnableTrackControlAppRendererFeatureUse[] = - "track_control_renderer_feature_use"; -const char kEnablePlayready[] = "playready"; -const char kEnableDevMode[] = "dev_mode"; -const char kDevModeOrigin[] = "dev_mode_origin"; -const char kEnableSystemGestures[] = "system_gestures"; -const char kEnableWindowControls[] = "enable_window_controls"; -const char kEnableSettingsUiMojo[] = "enable_settings_ui_mojo"; -const char kDisableBackgroundTabTimerThrottle[] = - "disable_background_tab_timer_throttle"; -const char kDisableBackgroundSuspend[] = "disable_background_suspend"; -const char kEnableAssistantMessagePipe[] = "enable_assistant_message_pipe"; -const char kEnableDemoStandaloneMode[] = "enable_demo_standalone_mode"; - -const char kKeyAppId[] = "app_id"; - -const char kCastCoreRendererFeatures[] = "cast_core_renderer_features"; -const char kCastCoreEnforceFeaturePermissions[] = - "cast_core_enforce_feature_permissions"; -const char kCastCoreFeaturePermissions[] = "cast_core_feature_permissions"; -const char kCastCoreFeaturePermissionOrigins[] = - "cast_core_feature_permission_origins"; -const char kCastCoreAllowMediaAccess[] = "cast_core_allow_media_access"; -const char kCastCoreForce720p[] = "cast_core_force_720p"; -const char kCastCoreIsAudioOnly[] = "cast_core_is_audio_only"; -const char kCastCoreIsRemoteControlMode[] = "cast_core_is_remote_control_mode"; -const char kCastCoreLogJsConsoleMessages[] = "cast_core_log_js_console_messages"; -const char kCastCoreTurnOnScreen[] = "cast_core_turn_on_screen"; -const char kCastCoreKeepScreenOn[] = "cast_core_keep_screen_on"; - -} // namespace feature -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/feature_constants.h chromium-132.0.6834.159/chromecast/common/feature_constants.h --- chromium-132.0.6834.110/chromecast/common/feature_constants.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/feature_constants.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_COMMON_FEATURE_CONSTANTS_H_ -#define CHROMECAST_COMMON_FEATURE_CONSTANTS_H_ - -namespace chromecast { -namespace feature { - -// TODO(b/187758538): Upstream more Feature Constants here. - -// TODO(b/187524799): Remove this feature when the related features are -// deprecated. -extern const char kEnableTrackControlAppRendererFeatureUse[]; -// The app can use playready. -extern const char kEnablePlayready[]; - -extern const char kKeyAppId[]; - -// If dev mode is enabled, kDevModeOrigin will be set with origin url -extern const char kEnableDevMode[]; -extern const char kDevModeOrigin[]; - -// Permit subscription to platform system gesture events? -extern const char kEnableSystemGestures[]; - -// Enables window APIs for the webpage (show/hide, etc.) -extern const char kEnableWindowControls[]; - -// Enable mojo connection for the settings UI. -extern const char kEnableSettingsUiMojo[]; - -// Disable blink background tab timer throttling for making sure application in -// in mini tile mode runs smoothly. -extern const char kDisableBackgroundTabTimerThrottle[]; - -// Sets RenderFrameMediaPlaybackOptions::kIsBackgroundMediaSuspendEnabled to -// false. -extern const char kDisableBackgroundSuspend[]; - -// Enable sending/receiving messages to/from libassistant -extern const char kEnableAssistantMessagePipe[]; - -// Enable a standalone demo app to control privileged features. -extern const char kEnableDemoStandaloneMode[]; - -// Cast Core constants for ApplicationConfig.extra_features. -extern const char kCastCoreRendererFeatures[]; -extern const char kCastCoreEnforceFeaturePermissions[]; -extern const char kCastCoreFeaturePermissions[]; -extern const char kCastCoreFeaturePermissionOrigins[]; -extern const char kCastCoreAllowMediaAccess[]; -extern const char kCastCoreForce720p[]; -extern const char kCastCoreIsAudioOnly[]; -extern const char kCastCoreIsRemoteControlMode[]; -extern const char kCastCoreLogJsConsoleMessages[]; -extern const char kCastCoreTurnOnScreen[]; -extern const char kCastCoreKeepScreenOn[]; - -} // namespace feature -} // namespace chromecast - -#endif // CHROMECAST_COMMON_FEATURE_CONSTANTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/global_descriptors.h chromium-132.0.6834.159/chromecast/common/global_descriptors.h --- chromium-132.0.6834.110/chromecast/common/global_descriptors.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/global_descriptors.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_COMMON_GLOBAL_DESCRIPTORS_H_ -#define CHROMECAST_COMMON_GLOBAL_DESCRIPTORS_H_ - -#include "build/build_config.h" -#include "content/public/common/content_descriptors.h" - -// This is a list of global descriptor keys to be used with the -// base::GlobalDescriptors object (see base/posix/global_descriptors.h) -enum { - // TODO(gunsch): Remove once there's a real value here. Otherwise, non-Android - // build compile fails due to empty enum. - kDummyValue = kContentIPCDescriptorMax + 1, -#if BUILDFLAG(IS_ANDROID) - kAndroidPakDescriptor, - kAndroidMinidumpDescriptor, -#endif // BUILDFLAG(IS_ANDROID) -}; - -#endif // CHROMECAST_COMMON_GLOBAL_DESCRIPTORS_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/media/DEPS chromium-132.0.6834.159/chromecast/common/media/DEPS --- chromium-132.0.6834.110/chromecast/common/media/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/media/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -include_rules = [ - "+chromecast/media", - "+components/cdm/common", - "+media/base", -] diff -Nru chromium-132.0.6834.110/chromecast/common/media/OWNERS chromium-132.0.6834.159/chromecast/common/media/OWNERS --- chromium-132.0.6834.110/chromecast/common/media/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/media/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/common/media/cast_media_drm_bridge_client.cc chromium-132.0.6834.159/chromecast/common/media/cast_media_drm_bridge_client.cc --- chromium-132.0.6834.110/chromecast/common/media/cast_media_drm_bridge_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/media/cast_media_drm_bridge_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -// 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 "chromecast/common/media/cast_media_drm_bridge_client.h" - -#include "chromecast/media/base/key_systems_common.h" - -namespace chromecast { -namespace media { - -CastMediaDrmBridgeClient::CastMediaDrmBridgeClient() {} - -CastMediaDrmBridgeClient::~CastMediaDrmBridgeClient() {} - -void CastMediaDrmBridgeClient::AddKeySystemUUIDMappings(KeySystemUuidMap* map) { -// Note: MediaDrmBridge adds the Widevine UUID mapping automatically. -} - -::media::MediaDrmBridgeDelegate* -CastMediaDrmBridgeClient::GetMediaDrmBridgeDelegate( - const ::media::UUID& scheme_uuid) { - if (scheme_uuid == widevine_delegate_.GetUUID()) - return &widevine_delegate_; - - return nullptr; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/media/cast_media_drm_bridge_client.h chromium-132.0.6834.159/chromecast/common/media/cast_media_drm_bridge_client.h --- chromium-132.0.6834.110/chromecast/common/media/cast_media_drm_bridge_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/media/cast_media_drm_bridge_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// 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. - -#ifndef CHROMECAST_COMMON_MEDIA_CAST_MEDIA_DRM_BRIDGE_CLIENT_H_ -#define CHROMECAST_COMMON_MEDIA_CAST_MEDIA_DRM_BRIDGE_CLIENT_H_ - -#include "chromecast/chromecast_buildflags.h" -#include "components/cdm/common/widevine_drm_delegate_android.h" -#include "media/base/android/media_drm_bridge_client.h" - -namespace chromecast { -namespace media { - -class CastMediaDrmBridgeClient : public ::media::MediaDrmBridgeClient { - public: - CastMediaDrmBridgeClient(); - - CastMediaDrmBridgeClient(const CastMediaDrmBridgeClient&) = delete; - CastMediaDrmBridgeClient& operator=(const CastMediaDrmBridgeClient&) = delete; - - ~CastMediaDrmBridgeClient() override; - - private: - // ::media::MediaDrmBridgeClient implementation: - void AddKeySystemUUIDMappings(KeySystemUuidMap* map) override; - ::media::MediaDrmBridgeDelegate* GetMediaDrmBridgeDelegate( - const ::media::UUID& scheme_uuid) override; - - cdm::WidevineDrmDelegateAndroid widevine_delegate_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_COMMON_MEDIA_CAST_MEDIA_DRM_BRIDGE_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/OWNERS chromium-132.0.6834.159/chromecast/common/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/common/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS -per-file *_mojom_traits*.*=set noparent -per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/activity_url_filter.mojom chromium-132.0.6834.159/chromecast/common/mojom/activity_url_filter.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/activity_url_filter.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/activity_url_filter.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// 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. - -module chromecast.mojom; - -// This struct represents a set of whitelist URL matching conditions used by -// the Activity URL filter logic. Each string is a regular expression that -// matching URL requests are passed through. If none of the condition -// matches, the URL request is blocked. -struct ActivityUrlFilterCriteria { - array criteria; -}; - -// This interface is used to configure the Activity URL filter with an -// ActivityUrlFilterCriteria. -interface ActivityUrlFilterConfiguration { - // Set the criteria used by the URL filter in the renderer. - SetFilter(ActivityUrlFilterCriteria filter); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/activity_window.mojom chromium-132.0.6834.159/chromecast/common/mojom/activity_window.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/activity_window.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/activity_window.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -// Simplified window interface to allow a web app to show/hide itself. -// -// Security: This interface is hosted by the Cast Browser. It is exposed to -// render processes via Cast App ID allow-list, which limits this API to apps -// that need the ability to dynamically show/hide themselves. This API does not -// expose any sensitive functionality. -interface ActivityWindow { - // Make the window visible. Depending on the system state, the window manager - // will decide how the activity window is composited on the screen. - Show(); - - // Hide the window. - Hide(); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/application_media_capabilities.mojom chromium-132.0.6834.159/chromecast/common/mojom/application_media_capabilities.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/application_media_capabilities.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/application_media_capabilities.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.shell.mojom; - -// Supported bitstream audio codecs and their associated properties. This is the -// corresponding mojo struct of BitstreamAudioCodecsInfo in -// chromecast/base/bitstream_audio_codecs.h -struct BitstreamAudioCodecsInfo { - // Bitmap of supported bitstream audio codecs. - int32 codecs = 0; - - // Bitmap specifying which of the corresponding codecs in |codecs| support - // spatial rendering. - int32 spatial_rendering = 0; -}; - -// Observes changes in an individual application's media capabilities. -// See chromecast/base/bitstream_audio_codecs.h for codec values. -interface ApplicationMediaCapabilitiesObserver { - // Called when bitstream audio supporting information is changed. - // |info| contains the latest supported bitstream audio codec information. - OnSupportedBitstreamAudioCodecsChanged(BitstreamAudioCodecsInfo info); -}; - -// Media capabilities for an individual application. -interface ApplicationMediaCapabilities { - AddObserver(pending_remote observer); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/application_media_capabilities_traits.h chromium-132.0.6834.159/chromecast/common/mojom/application_media_capabilities_traits.h --- chromium-132.0.6834.110/chromecast/common/mojom/application_media_capabilities_traits.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/application_media_capabilities_traits.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_COMMON_MOJOM_APPLICATION_MEDIA_CAPABILITIES_TRAITS_H_ -#define CHROMECAST_COMMON_MOJOM_APPLICATION_MEDIA_CAPABILITIES_TRAITS_H_ - -#include "chromecast/base/bitstream_audio_codecs.h" -#include "chromecast/common/mojom/application_media_capabilities.mojom-shared.h" -#include "mojo/public/cpp/bindings/struct_traits.h" - -namespace mojo { -template <> -struct StructTraits { - static int32_t codecs(const chromecast::BitstreamAudioCodecsInfo& info) { - return info.codecs; - } - - static int32_t spatial_rendering( - const chromecast::BitstreamAudioCodecsInfo& info) { - return info.spatial_rendering; - } - - static bool Read( - chromecast::shell::mojom::BitstreamAudioCodecsInfoDataView input, - chromecast::BitstreamAudioCodecsInfo* output) { - output->codecs = input.codecs(); - output->spatial_rendering = input.spatial_rendering(); - return true; - } -}; -} // namespace mojo - -#endif // CHROMECAST_COMMON_MOJOM_APPLICATION_MEDIA_CAPABILITIES_TRAITS_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/assistant_messenger.mojom chromium-132.0.6834.159/chromecast/common/mojom/assistant_messenger.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/assistant_messenger.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/assistant_messenger.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -import "mojo/public/mojom/base/values.mojom"; - -// The following APIs define a simple messaging protocol between the Assistant -// Service and a Cast App web client. All messages are either dictionary values -// or a list of dictionary values (for multiple messages). The message protocol -// is specific to each app, though the general command format uses a "className" -// key which identifies the type of command to be handled by the Assistant. - -// A handle to the Assistant message API. Returned by CreateMessagePipe(). -// Each client has unique copy. -// -// Security: See notes for AssistantMessageService. -interface AssistantMessagePipe { - // Send a message to the Assistant service. - SendMessage(mojo_base.mojom.Value message); -}; - -// The interface for clients of the Assistant message API. Clients should -// register with AssistantMessageService::CreateMessagePipe() below. -// -// Security: This interface is hosted by the render frame. It receives messages -// from the Assistant service (see notes for AssistantMessageService). -interface AssistantMessageClient { - // Receive a message from the Assistant service. - OnMessage(mojo_base.mojom.Value message); -}; - -// Assistant service messaging endpoint. -// -// Security: This interface is hosted by the Cast Service. It is exposed to a -// small set of allow-listed renderers, based on the Cast App ID. These -// renderers exclusively belong to trusted first-party apps. This interface -// allows for communication with the Assistant service using an opaque messaging -// protocol. -interface AssistantMessageService { - // Request a handle to the Assistant message API. |client|'s OnMessage will be - // called to alert the client of this interface of messages and other events. - // For JS clients, |client_id| is the Cast App ID. - CreateMessagePipe( - string client_id, - pending_remote client, - pending_receiver pipe); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/audio_socket.mojom chromium-132.0.6834.159/chromecast/common/mojom/audio_socket.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/audio_socket.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/audio_socket.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -// AudioSocketBroker is a service hosted in the browser process for delivering -// socket descriptors to renderers. The socket file descriptor can be used to -// connect to the audio output service hosted in the |cast_service| process. -interface AudioSocketBroker { - - // Gets the socket descriptor which can be used to connect to the audio output - // service. - GetSocketDescriptor() => (handle? fd); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/cast_demo.mojom chromium-132.0.6834.159/chromecast/common/mojom/cast_demo.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/cast_demo.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/cast_demo.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.shell.mojom; - -import "mojo/public/mojom/base/values.mojom"; - -// Observer interface for system volume changes. -// -// Security: This interface is hosted in a render process. -interface CastDemoVolumeChangeObserver { - // Will be called anytime the volume has been changed, including applying - // the default volume. - VolumeChanged(float level); -}; - -// Interface for the Cast Demo app to communicate with Cast platform. This -// interface is only exposed for the Cast Demo app, which is used for in-store -// retail demos. The content resources for this app are baked into the platform. -// When a device is in demo mode, its functionality is restricted to the demo -// app experience, which includes pre-baked video demos and simple smart-home -// device controls. -// -// Security: This interface is hosted by the Cast Service. Most of these methods -// expose non-sensitive capabilities. SetWifiCredentials() allows the app to -// select a WiFi network for the device, and is documented below. -interface CastDemo { - // Record a metrics event, with |data| logged with the event as JSON. - RecordEvent(string event_name, mojo_base.mojom.Value data); - - // Set a retailer name to identify the chain of this device. - SetRetailerName(string retailer_name); - - // Set a store ID to identify the location of this device. - SetStoreId(string store_id); - - // Get a retailer name to identify the chain of this device. - GetRetailerName() => (string retailer_name); - - // Get a store ID to identify the location of this device. - GetStoreId() => (string store_id); - - // Change the default volume level, with |level| in the range [0, 1]. - SetDefaultVolumeLevel(float level); - - // Get the volume level previously set through SetDefaultVolumeLevel(). - GetDefaultVolumeLevel() => (float level); - - // Set the volume to a previous level set through SetDefaultVolumeLevel(). - ApplyDefaultVolume(); - - // Set store-specific wifi credentials. - // If |psk| is present, WPA-PSK is assumed. - // If |psk| is empty, no security is assumed. - // - // Security: This allows the Cast Demo app to select a WiFi network for the - // device. Before the app enters "demonstration mode", this API allows retail - // store managers to configure the WiFi network for the device without having - // to complete the standard device setup flow. After setup, this API is - // inaccessible to customers interacting with the demo app. - SetWifiCredentials(string ssid, string psk); - - // Get the list of available WIFI networks. - // |network_list| contains a Value with the following structure: - // {"networks": [{"ssid": "", "type": ""}, ... ]} - GetAvailableWifiNetworks() => (mojo_base.mojom.Value network_list); - - // Get the current connection status. - // |status| contains a Value with the following structure: - // { "status": "", "network": "" } - GetConnectionStatus() => (mojo_base.mojom.Value status); - - // Register an observer to be notified when the volume is changed. - AddVolumeChangeObserver( - pending_remote observer); - - // Force JS LocalStorage to be persisted to disk. - PersistLocalStorage(); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/constants.mojom chromium-132.0.6834.159/chromecast/common/mojom/constants.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/constants.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/constants.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -const string kChromecastServiceName = "chromecast"; - -const string kContentBrowserServiceName = "content_browser"; - -// External service name for the standalone Cast Browser. -const string kCastBrowserServiceName = "cast_browser"; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/feature_manager.mojom chromium-132.0.6834.159/chromecast/common/mojom/feature_manager.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/feature_manager.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/feature_manager.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.shell.mojom; - -import "mojo/public/mojom/base/values.mojom"; - -// Represents one feature and stores additional data in -// DictionaryValue -struct Feature { - string name; - mojo_base.mojom.DictionaryValue config; -}; - -// Receives messages from the browser process to enable/disable Cast -// application-facing features. This interface is implemented by a -// single renderer. -interface FeatureManager { - - ConfigureFeatures(array features); - -}; - diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/feature_update.mojom chromium-132.0.6834.159/chromecast/common/mojom/feature_update.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/feature_update.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/feature_update.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -import "mojo/public/mojom/base/values.mojom"; - -// This interface is implemented by the clients of `FeatureUpdateService`. -interface FeatureUpdateObserver { - // Triggered when there is an update to base::Feature configs because a - // DCS download is completed. `features` is a dictionary which is ready to be - // persisted to disk (via PrefService). - OnFeaturesUpdated(mojo_base.mojom.DictionaryValue features); -}; - -// This interface is implemented in the Cast Service process and allows the -// observers to receive base::Feature state updates after base::Feature -// overrides are downloaded successfully from the cloud service (DCS). -interface FeatureUpdateService { - // Adds an observer to receive feature config updates. - RegisterFeatureUpdateObserver(pending_remote observer); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/gesture.mojom chromium-132.0.6834.159/chromecast/common/mojom/gesture.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/gesture.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/gesture.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -import "ui/gfx/geometry/mojom/geometry.mojom"; - -// Renderer-side system gesture handler. -// -// Security: This interface is hosted by the renderer. -interface GestureHandler { - // Invoked when the back gesture is triggered. - OnBackGesture() => (bool was_handled); - - // Invoked while the back gesture is in progress. - OnBackGestureProgress(gfx.mojom.Point touch_location); - - // Invoked while a top-drag is in progress. - OnTopDragGestureProgress(gfx.mojom.Point touch_location); - - // Invoked when a top-drag gesture completes (finger lifted). - OnTopDragGestureDone(); - - // Invoked while a right-drag is in progress. - OnRightDragGestureProgress(gfx.mojom.Point touch_location); - - // Invoked when a right-drag gesture completes (finger lifted). - OnRightDragGestureDone(); - - // Invoked when the back gesture has been cancelled (for example by the - // finger lifting before the gesture can complete. - OnBackGestureCancel(); - - // Invoked when the tap gesture is triggered. - OnTapGesture(); - - // Invoked when the tap down gesture is triggered. - OnTapDownGesture(); -}; - -// Subscription interface for a handler to receive gesture events. Subscribing -// indicates that the renderer is equipped to handle events, and expects to -// receive them. -// -// Security: This interface is hosted by the Cast Browser. It allows a renderer -// to handle special screen gestures before the system. None of these methods -// expose sensitive capabilities. This is only enabled for apps with media -// browse UIs. -interface GestureSource { - // Subscribe to events from this source. If there is already a registered - // handler, it will be replaced. - Subscribe(pending_remote handler); - - // Specify if the "back" gesture can be handled by the subscriber. If - // |can_go_back| is false, then the GestureHandler will not receive back - // gesture events. - SetCanGoBack(bool can_go_back); - - // Specify if the "top drag" gesture can be handled by the subscriber. If - // |can_top_drag| is false, then the GestureHandler will not receive top - // drag gesture events. - SetCanTopDrag(bool can_top_drag); - - // Specify if the "right drag" gesture can be handled by the subscriber. If - // |can_right_drag| is false, then the GestureHandler will not receive right - // drag gesture events. - SetCanRightDrag(bool can_top_drag); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/js_channel.mojom chromium-132.0.6834.159/chromecast/common/mojom/js_channel.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/js_channel.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/js_channel.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -// Send a message on this channel to the browser. -interface JsChannel { - // Message from javascript. - PostMessage(string message); -}; - -// Implemented on the renderer, this gets notified by the browser to -// add/remove channels as needed. -interface JsChannelClient { - // Add a new channel binding, connecting window.channel.postMessage to |pipe|. - CreateChannel(string channel, pending_remote pipe); - // Remove any existing channel binding. - RemoveChannel(string channel); -}; - -// Implemented by the browser. -interface JsChannelBindingProvider { - // The RenderFrame reports its routing ID to the browser here and provides the - // pipe to manage channels. - Register(int32 routing_id, pending_remote client); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/media_caps.mojom chromium-132.0.6834.159/chromecast/common/mojom/media_caps.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/media_caps.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/media_caps.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.media.mojom; - -struct CodecProfileLevel { - int32 codec; - int32 profile; - int32 level; -}; - -// Media capabilities that apply to all applications. -interface MediaCaps { - // Adds an `observer` to monitor media capability changes. - AddObserver(pending_remote observer); -}; - -// Observes changes in media capabilities that apply to all applications. -interface MediaCapsObserver { - // Add supported codec profiles and levels. May not be called on all - // platforms, but can be used to infer whether a video config is supported. - AddSupportedCodecProfileLevel(CodecProfileLevel codec_profile_level); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/memory_pressure.mojom chromium-132.0.6834.159/chromecast/common/mojom/memory_pressure.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/memory_pressure.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/memory_pressure.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -interface MemoryPressureController { - AddObserver(pending_remote observer); -}; - -interface MemoryPressureObserver { - // Levels defined in base::MemoryPressureListener::MemoryPressureLevel - MemoryPressureLevelChanged(int32 pressure_level); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/metrics_helper.mojom chromium-132.0.6834.159/chromecast/common/mojom/metrics_helper.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/metrics_helper.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/metrics_helper.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.metrics.mojom; - -// This interface is implemented in browser process and is called in renderer -// process so the metrics in renderer process can be collected and uploaded. -interface MetricsHelper { - // Logs application specific events. - RecordApplicationEvent(string app_id, - string session_id, - string sdk_version, - string event); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/queryable_data_store.mojom chromium-132.0.6834.159/chromecast/common/mojom/queryable_data_store.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/queryable_data_store.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/queryable_data_store.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.shell.mojom; - -import "mojo/public/mojom/base/values.mojom"; - -// This interface provides a method for browser to set renderer-frame queryable -// values at start up. It exposes read-only key/value pairs of config data to -// Cast apps through javascript. This is implemented by a single renderer. -interface QueryableDataStore { - Set(string key, mojo_base.mojom.Value value); -}; - diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/service_connector.mojom chromium-132.0.6834.159/chromecast/common/mojom/service_connector.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/service_connector.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/service_connector.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -import "mojo/public/mojom/base/generic_pending_receiver.mojom"; - -// This interface is implemented in the browser process and provides a way of -// brokering access to Cast-internal service interfaces. This is a replacement -// for Service Manager Connector, as Service Manager is effectively deprecated -// but many Cast-internal services are still built on it. As those services are -// moved off of Service Manager, uses of this interface should diminish to zero -// in favor of more strongly-typed binding interfaces. -interface ServiceConnector { - // Routes interface receivers to the Cast-internal service named by - // |service_name|. - Connect(string service_name, mojo_base.mojom.GenericPendingReceiver receiver); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/mojom/settings_ui.mojom chromium-132.0.6834.159/chromecast/common/mojom/settings_ui.mojom --- chromium-132.0.6834.110/chromecast/common/mojom/settings_ui.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/mojom/settings_ui.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -import "ui/gfx/geometry/mojom/geometry.mojom"; - -// Event phase for a single swipe gesture. -enum SideSwipeEvent { - BEGIN = 0, // Swipe has started - CONTINUE = 1, // Swipe is in progress - END = 2 // Swipe is finished -}; - -// Screen location for a side swipe gesture. -enum SideSwipeOrigin { - TOP = 0, - BOTTOM = 1, - LEFT = 2, - RIGHT = 3 -}; - -// Renderer-side client for receiving settings events. This is currently used to -// send side-swipe events. -// -// Security: This is hosted by the render process. This is only enabled for the -// built-in settings UI for smart display devices. -interface SettingsClient { - // Propagates an in-progress gesture event to the renderer. - HandleSideSwipe(SideSwipeEvent event, - SideSwipeOrigin origin, - gfx.mojom.Point touch_location); - - // Sends a platform info JSON string to the renderer. This information is - // intended to be rendered by the settings UI widget (e.g. device volume bar, - // device name, platform version info). - SendPlatformInfo(string platform_info_json); -}; - -// Interface implemented on platform to host the settings view. This is -// currently used by render process to request settings visibility. -// -// Security: This interface is hosted by the Cast Service process. This is only -// used by the built-in settings UI to receive platform information so it can be -// displayed to a user. -interface SettingsPlatform { - // Register a SettingsClient so that it can receive platform information. - Connect(pending_remote client); - - // Make the settings UI visible. - RequestVisible(bool visible); -}; diff -Nru chromium-132.0.6834.110/chromecast/common/queryable_data.cc chromium-132.0.6834.159/chromecast/common/queryable_data.cc --- chromium-132.0.6834.110/chromecast/common/queryable_data.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/queryable_data.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/queryable_data.h" - -#include - -#include "base/no_destructor.h" - -namespace chromecast { - -namespace { -QueryableData& GetQueryableData() { - static base::NoDestructor queryable_data; - return *queryable_data; -} -} // namespace - -// static -void QueryableData::RegisterQueryableValue(const std::string& query_key, - base::Value initial_value) { - DCHECK_CALLED_ON_VALID_SEQUENCE(GetQueryableData().sequence_checker_); - GetQueryableData().queryable_values_[query_key] = std::move(initial_value); -} - -// static -const base::Value* QueryableData::Query(const std::string& query_key) { - DCHECK_CALLED_ON_VALID_SEQUENCE(GetQueryableData().sequence_checker_); - const QueryableData& data = GetQueryableData(); - - auto value = data.queryable_values_.find(query_key); - if (value == data.queryable_values_.end()) - return nullptr; - return &value->second; -} - -// static -const QueryableData::ValueMap& QueryableData::GetValues() { - DCHECK_CALLED_ON_VALID_SEQUENCE(GetQueryableData().sequence_checker_); - const QueryableData& data = GetQueryableData(); - return data.queryable_values_; -} - -QueryableData::QueryableData() {} - -QueryableData::~QueryableData() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/queryable_data.h chromium-132.0.6834.159/chromecast/common/queryable_data.h --- chromium-132.0.6834.110/chromecast/common/queryable_data.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/queryable_data.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_COMMON_QUERYABLE_DATA_H_ -#define CHROMECAST_COMMON_QUERYABLE_DATA_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/no_destructor.h" -#include "base/sequence_checker.h" -#include "base/values.h" - -namespace chromecast { - -// This class is for use by both browser- and renderer-side, and tracks data -// that can be exposed directly to applications via JS APIs. The browser-side -// code uses it to expose key/value to renderer. The ipc to renderer is done by -// binding QueryableDataStorePointer on browser side to the implementation on -// the renderer side and calling the Set method. -// All methods should be accessed on the main thread. -// TODO(mdellaquila): Change the class implementation so that an instance of it -// is created for each RenderFrame -class QueryableData { - public: - using ValueMap = base::flat_map; - - QueryableData(const QueryableData&) = delete; - QueryableData& operator=(const QueryableData&) = delete; - - // Stores a value for the current process. If the key already exists, the - // value is replaced. - static void RegisterQueryableValue(const std::string& query_key, - base::Value initial_value); - - // Returns a pointer to the value for given key, if found, or null if not. - static const base::Value* Query(const std::string& query_key); - - static const ValueMap& GetValues(); - - private: - friend class base::NoDestructor; - - QueryableData(); - ~QueryableData(); - - SEQUENCE_CHECKER(sequence_checker_); - ValueMap queryable_values_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_COMMON_QUERYABLE_DATA_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/user_agent.cc chromium-132.0.6834.159/chromecast/common/user_agent.cc --- chromium-132.0.6834.110/chromecast/common/user_agent.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/user_agent.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/user_agent.h" - -#include -#include "base/strings/strcat.h" -#include "components/cast/common/constants.h" - -namespace chromecast { - -std::string GetChromeKeyString() { - std::string chrome_key = base::StrCat({"CrKey/", kFrozenCrKeyValue}); - return chrome_key; -} -std::string GetUserAgent() { - std::string chromium_user_agent = GetChromiumUserAgent(); - return base::StrCat({chromium_user_agent, " ", GetChromeKeyString(), " ", - GetDeviceUserAgentSuffix()}); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/user_agent.h chromium-132.0.6834.159/chromecast/common/user_agent.h --- chromium-132.0.6834.110/chromecast/common/user_agent.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/user_agent.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_COMMON_USER_AGENT_H_ -#define CHROMECAST_COMMON_USER_AGENT_H_ - -#include - -namespace chromecast { - -std::string GetDeviceUserAgentSuffix(); -std::string GetChromiumUserAgent(); - -std::string GetChromeKeyString(); -std::string GetUserAgent(); - -} // namespace chromecast - -#endif // CHROMECAST_COMMON_USER_AGENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/common/user_agent_android.cc chromium-132.0.6834.159/chromecast/common/user_agent_android.cc --- chromium-132.0.6834.110/chromecast/common/user_agent_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/user_agent_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -#include "chromecast/common/user_agent.h" - -#include "base/android/build_info.h" -#include "components/embedder_support/user_agent_utils.h" - -namespace chromecast { - -std::string GetDeviceUserAgentSuffix() { - auto* build_info = base::android::BuildInfo::GetInstance(); - - if (build_info->is_tv()) { - return "DeviceType/AndroidTV"; - } else { - return "DeviceType/Android"; - } -} - -std::string GetChromiumUserAgent() { - return embedder_support::GetUserAgent(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/user_agent_default.cc chromium-132.0.6834.159/chromecast/common/user_agent_default.cc --- chromium-132.0.6834.110/chromecast/common/user_agent_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/user_agent_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/user_agent.h" - -#include "chromecast/chromecast_buildflags.h" -#include "components/embedder_support/user_agent_utils.h" - -namespace chromecast { - -std::string GetDeviceUserAgentSuffix() { - return std::string(DEVICE_USER_AGENT_SUFFIX); -} - -std::string GetChromiumUserAgent() { - return embedder_support::GetUserAgent(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/common/user_agent_unittest.cc chromium-132.0.6834.159/chromecast/common/user_agent_unittest.cc --- chromium-132.0.6834.110/chromecast/common/user_agent_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/common/user_agent_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/common/user_agent.h" - -#include "base/strings/stringprintf.h" -#include "components/version_info/version_info.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -namespace { -#if BUILDFLAG(IS_ANDROID) -const char kCastAndroid[] = - "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) " - "Chrome/%s.0.0.0 " - "%sSafari/537.36 CrKey/1.56.500000 %s"; -#else -const char kCastDesktop[] = - "Mozilla/5.0 (" -#if BUILDFLAG(IS_CHROMEOS) - "X11; CrOS x86_64 14541.0.0" -#elif BUILDFLAG(IS_FUCHSIA) - "Fuchsia" -#elif BUILDFLAG(IS_LINUX) - "X11; Linux x86_64" -#elif BUILDFLAG(IS_MAC) - "Macintosh; Intel Mac OS X 10_15_7" -#elif BUILDFLAG(IS_WIN) - "Windows NT 10.0; Win64; x64" -#else -#error Unsupported platform -#endif - ") AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s.0.0.0 " - "Safari/537.36 CrKey/1.56.500000 %s"; -#endif // BUILDFLAG(IS_ANDROID) -} // namespace - -TEST(UserAgentTest, GetUserAgent) { - std::string device_suffix = GetDeviceUserAgentSuffix(); -#if BUILDFLAG(IS_ANDROID) - std::string device_compat = ""; - EXPECT_EQ(base::StringPrintf(kCastAndroid, - version_info::GetMajorVersionNumber().c_str(), - device_compat.c_str(), device_suffix.c_str()), - GetUserAgent()); -#else - EXPECT_EQ(base::StringPrintf(kCastDesktop, - version_info::GetMajorVersionNumber().c_str(), - device_suffix.c_str()), - GetUserAgent()); -#endif -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/DEPS chromium-132.0.6834.159/chromecast/crash/DEPS --- chromium-132.0.6834.110/chromecast/crash/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -include_rules = [ - "+components/crash/core/common", - "+gpu/config/gpu_crash_keys.h", - "+third_party/breakpad", -] diff -Nru chromium-132.0.6834.110/chromecast/crash/OWNERS chromium-132.0.6834.159/chromecast/crash/OWNERS --- chromium-132.0.6834.110/chromecast/crash/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -per-file cast_crash_keys*=file://components/crash/OWNERS diff -Nru chromium-132.0.6834.110/chromecast/crash/app_state_tracker.cc chromium-132.0.6834.159/chromecast/crash/app_state_tracker.cc --- chromium-132.0.6834.110/chromecast/crash/app_state_tracker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/app_state_tracker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -// 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 "chromecast/crash/app_state_tracker.h" - -#include "base/no_destructor.h" -#include "chromecast/crash/cast_crash_storage.h" - -namespace { - -struct CurrentAppState { - std::string previous_app; - std::string current_app; - std::string last_launched_app; - std::string stadia_session_id; -}; - -CurrentAppState* GetAppState() { - static base::NoDestructor app_state; - return app_state.get(); -} - -} // namespace - -namespace chromecast { - -// static -std::string AppStateTracker::GetLastLaunchedApp() { - return GetAppState()->last_launched_app; -} - -// static -std::string AppStateTracker::GetCurrentApp() { - return GetAppState()->current_app; -} - -// static -std::string AppStateTracker::GetPreviousApp() { - return GetAppState()->previous_app; -} - -// static -std::string AppStateTracker::GetStadiaSessionId() { - return GetAppState()->stadia_session_id; -} - -// static -void AppStateTracker::SetLastLaunchedApp(const std::string& app_id) { - GetAppState()->last_launched_app = app_id; - CastCrashStorage::GetInstance()->SetLastLaunchedApp(app_id); -} - -// static -void AppStateTracker::SetCurrentApp(const std::string& app_id) { - CurrentAppState* app_state = GetAppState(); - app_state->previous_app = app_state->current_app; - app_state->current_app = app_id; - - CastCrashStorage::GetInstance()->SetCurrentApp(app_id); - CastCrashStorage::GetInstance()->SetPreviousApp(app_state->previous_app); -} - -// static -void AppStateTracker::SetPreviousApp(const std::string& app_id) { - GetAppState()->previous_app = app_id; - CastCrashStorage::GetInstance()->SetPreviousApp(app_id); -} - -// static -void AppStateTracker::SetStadiaSessionId(const std::string& stadia_session_id) { - if (!stadia_session_id.empty()) { - GetAppState()->stadia_session_id = stadia_session_id; - CastCrashStorage::GetInstance()->SetStadiaSessionId(stadia_session_id); - } else { - GetAppState()->stadia_session_id.clear(); - CastCrashStorage::GetInstance()->ClearStadiaSessionId(); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/app_state_tracker.h chromium-132.0.6834.159/chromecast/crash/app_state_tracker.h --- chromium-132.0.6834.110/chromecast/crash/app_state_tracker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/app_state_tracker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_APP_STATE_TRACKER_H_ -#define CHROMECAST_CRASH_APP_STATE_TRACKER_H_ - -#include - -namespace chromecast { - -class AppStateTracker { - public: - // Record |app_id| as the last app that attempted to launch. - static void SetLastLaunchedApp(const std::string& app_id); - - // The current app becomes the previous app, |app_id| becomes the current app. - static void SetCurrentApp(const std::string& app_id); - - // Record |app_id| as the previous app. - static void SetPreviousApp(const std::string& app_id); - - // Set the Stadia session ID, when a Stadia session starts running. - // Clear the Stadia session ID by passing in an empty string - static void SetStadiaSessionId(const std::string& stadia_session_id); - - // Returns the id of the app that was last attempted to launch. - static std::string GetLastLaunchedApp(); - - // Returns the id of the active app. - static std::string GetCurrentApp(); - - // Returns the id of the app which was previously active. - static std::string GetPreviousApp(); - - // Returns the Stadia session ID, if a Stadia session is running. - static std::string GetStadiaSessionId(); -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_APP_STATE_TRACKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/build_info.cc chromium-132.0.6834.159/chromecast/crash/build_info.cc --- chromium-132.0.6834.110/chromecast/crash/build_info.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/build_info.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// 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 "chromecast/crash/build_info.h" - -#include - -#include "base/containers/contains.h" -#include "base/strings/string_util.h" -#include "chromecast/base/version.h" -namespace chromecast { -namespace { - -constexpr char kEngVariant[] = "eng"; -constexpr char kUserVariant[] = "user"; - -} // namespace - -const std::string VersionToCrashString(const std::string& cast_build_revision) { - // Incremental number for eng+user builds is too long for Crash server - // so cap it to "eng" or "user". - for (std::string infix : {kEngVariant, kUserVariant}) { - size_t index = cast_build_revision.find(infix); - if (index != std::string::npos) { - return cast_build_revision.substr( - 0, index + infix.size()); // Truncate after ".eng" / ".user". - } - } - return cast_build_revision; -} - -const std::string GetVersionString() { - return VersionToCrashString(CAST_BUILD_REVISION); -} - -const std::string GetVersionString(const std::string& cast_release_number, - const std::string& cast_incremental_number) { - if (cast_release_number.empty() || cast_incremental_number.empty()) { - return VersionToCrashString(CAST_BUILD_REVISION); - } - return VersionToCrashString( - base::JoinString({cast_release_number, cast_incremental_number}, ".")); -} - -const std::string VersionToVariant(const std::string& cast_build_revision) { - for (const std::string& variant : {kEngVariant, kUserVariant}) { - if (base::Contains(cast_build_revision, variant)) { - return variant; - } - } - return CAST_IS_DEBUG_BUILD() ? kEngVariant : kUserVariant; -} - -const std::string GetBuildVariant() { - return VersionToVariant(CAST_BUILD_REVISION); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/build_info.h chromium-132.0.6834.159/chromecast/crash/build_info.h --- chromium-132.0.6834.110/chromecast/crash/build_info.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/build_info.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_BUILD_INFO_H_ -#define CHROMECAST_CRASH_BUILD_INFO_H_ - -#include - -namespace chromecast { - -// Returns a short, readable version string. -const std::string GetVersionString(); -const std::string GetVersionString(const std::string& cast_release_number, - const std::string& cast_incremental_number); - -// Return whether build is "user", or "eng" -const std::string GetBuildVariant(); - -// Used by tests. -const std::string VersionToCrashString(const std::string& cast_build_revision); -const std::string VersionToVariant(const std::string& cast_build_revision); - - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_BUILD_INFO_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/build_info_unittest.cc chromium-132.0.6834.159/chromecast/crash/build_info_unittest.cc --- chromium-132.0.6834.110/chromecast/crash/build_info_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/build_info_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// 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 "chromecast/crash/build_info.h" - -#include - -#include "chromecast/base/version.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -constexpr char kIncrementalUserBuild[] = "1.51.user.ldap.20200813.124713"; -constexpr char kIncrementalEngBuild[] = "1.51.eng.ldap.20200813.124713"; -constexpr char kReleaseBuild[] = "1.51.224083"; - -TEST(VersionStringTest, VersionStringIsNonEmpty) { - ASSERT_FALSE(GetVersionString().empty()); -} - -TEST(VersionStringTest, VersionStringIsCorrect) { - ASSERT_EQ(GetVersionString(kReleaseBuild, kIncrementalEngBuild), - "1.51.224083.1.51.eng"); -} - -TEST(VersionStringTest, EmptyVersionStringIsCorrect) { - ASSERT_FALSE(GetVersionString("", "").empty()); -} - -TEST(VersionStringTest, ReleaseVersionUnchanged) { - ASSERT_EQ(VersionToCrashString(kReleaseBuild), kReleaseBuild); -} - -TEST(VersionStringTest, IncrementalVersionTruncated) { - ASSERT_EQ(VersionToCrashString(kIncrementalEngBuild), "1.51.eng"); - ASSERT_EQ(VersionToCrashString(kIncrementalUserBuild), "1.51.user"); -} - -TEST(GetBuildVariantTest, InfixPresent) { - ASSERT_EQ(VersionToVariant(kIncrementalEngBuild), "eng"); - ASSERT_EQ(VersionToVariant(kIncrementalUserBuild), "user"); -} - -TEST(GetBuildVariantTest, InfixAbsent) { - // If infix is absent, will use debug macro to determine variant. - bool is_eng = CAST_IS_DEBUG_BUILD(); - ASSERT_EQ(VersionToVariant(kReleaseBuild) == "eng", is_eng); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crash_keys.cc chromium-132.0.6834.159/chromecast/crash/cast_crash_keys.cc --- chromium-132.0.6834.110/chromecast/crash/cast_crash_keys.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crash_keys.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// 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 "chromecast/crash/cast_crash_keys.h" - -namespace chromecast { -namespace crash_keys { - -const char kLastApp[] = "last_app"; - -const char kCurrentApp[] = "current_app"; - -const char kPreviousApp[] = "previous_app"; - -const char kStadiaSessionId[] = "stadia_session_id"; - -} // namespace crash_keys -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crash_keys.h chromium-132.0.6834.159/chromecast/crash/cast_crash_keys.h --- chromium-132.0.6834.110/chromecast/crash/cast_crash_keys.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crash_keys.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_CAST_CRASH_KEYS_H_ -#define CHROMECAST_CRASH_CAST_CRASH_KEYS_H_ - -namespace chromecast { -namespace crash_keys { - -// Names of crash keys to be shared by multiple platforms. -extern const char kLastApp[]; - -extern const char kCurrentApp[]; - -extern const char kPreviousApp[]; - -extern const char kStadiaSessionId[]; - -} // namespace crash_keys -} // namespace chromecast - -#endif // CHROMECAST_CRASH_CAST_CRASH_KEYS_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crash_storage.cc chromium-132.0.6834.159/chromecast/crash/cast_crash_storage.cc --- chromium-132.0.6834.110/chromecast/crash/cast_crash_storage.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crash_storage.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// 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 "chromecast/crash/cast_crash_storage.h" - -#include "base/no_destructor.h" -#include "chromecast/crash/cast_crash_storage_impl.h" - -namespace chromecast { - -CastCrashStorage* CastCrashStorage::GetInstance() { - static base::NoDestructor storage; - return storage.get(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crash_storage.h chromium-132.0.6834.159/chromecast/crash/cast_crash_storage.h --- chromium-132.0.6834.110/chromecast/crash/cast_crash_storage.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crash_storage.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_CAST_CRASH_STORAGE_H_ -#define CHROMECAST_CRASH_CAST_CRASH_STORAGE_H_ - -#include - -namespace chromecast { - -// Stores crash key annotations. -// This is used to provide indirection for platform dependent storage -// implementations. -class CastCrashStorage { - public: - static CastCrashStorage* GetInstance(); - - CastCrashStorage() = default; - virtual ~CastCrashStorage() = default; - - virtual void SetLastLaunchedApp(std::string_view app_id) = 0; - virtual void ClearLastLaunchedApp() = 0; - - virtual void SetCurrentApp(std::string_view app_id) = 0; - virtual void ClearCurrentApp() = 0; - - virtual void SetPreviousApp(std::string_view app_id) = 0; - virtual void ClearPreviousApp() = 0; - - virtual void SetStadiaSessionId(std::string_view session_id) = 0; - virtual void ClearStadiaSessionId() = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_CAST_CRASH_STORAGE_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crash_storage_fuchsia.cc chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_fuchsia.cc --- chromium-132.0.6834.110/chromecast/crash/cast_crash_storage_fuchsia.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_fuchsia.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// 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 - -#include "base/fuchsia/process_context.h" -#include "base/no_destructor.h" -#include "chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.h" - -namespace chromecast { - -CastCrashStorage* CastCrashStorage::GetInstance() { - static base::NoDestructor storage( - base::ComponentContextForProcess()->svc().get()); - return storage.get(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crash_storage_impl.cc chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_impl.cc --- chromium-132.0.6834.110/chromecast/crash/cast_crash_storage_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// 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 "chromecast/crash/cast_crash_storage_impl.h" - -#include - -#include "chromecast/crash/cast_crash_keys.h" -#include "components/crash/core/common/crash_key.h" - -namespace chromecast { -namespace { - -crash_reporter::CrashKeyString<64> last_app(crash_keys::kLastApp); -crash_reporter::CrashKeyString<64> current_app(crash_keys::kCurrentApp); -crash_reporter::CrashKeyString<64> previous_app(crash_keys::kPreviousApp); -crash_reporter::CrashKeyString<64> stadia_session_id( - crash_keys::kStadiaSessionId); - -} // namespace - -CastCrashStorageImpl::CastCrashStorageImpl() = default; -CastCrashStorageImpl::~CastCrashStorageImpl() = default; - -void CastCrashStorageImpl::SetLastLaunchedApp(std::string_view app_id) { - last_app.Set(app_id); -} - -void CastCrashStorageImpl::ClearLastLaunchedApp() { - last_app.Clear(); -} - -void CastCrashStorageImpl::SetCurrentApp(std::string_view app_id) { - current_app.Set(app_id); -} - -void CastCrashStorageImpl::ClearCurrentApp() { - current_app.Clear(); -} - -void CastCrashStorageImpl::SetPreviousApp(std::string_view app_id) { - previous_app.Set(app_id); -} - -void CastCrashStorageImpl::ClearPreviousApp() { - previous_app.Clear(); -} - -void CastCrashStorageImpl::SetStadiaSessionId(std::string_view session_id) { - stadia_session_id.Set(session_id); -} - -void CastCrashStorageImpl::ClearStadiaSessionId() { - stadia_session_id.Clear(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crash_storage_impl.h chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_impl.h --- chromium-132.0.6834.110/chromecast/crash/cast_crash_storage_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crash_storage_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_CAST_CRASH_STORAGE_IMPL_H_ -#define CHROMECAST_CRASH_CAST_CRASH_STORAGE_IMPL_H_ - -#include - -#include "chromecast/crash/cast_crash_storage.h" - -namespace chromecast { - -class CastCrashStorageImpl final : public CastCrashStorage { - public: - CastCrashStorageImpl(); - ~CastCrashStorageImpl() override; - CastCrashStorageImpl& operator=(const CastCrashStorageImpl&) = delete; - CastCrashStorageImpl(const CastCrashStorageImpl&) = delete; - - // CastCrashStorage implementation: - void SetLastLaunchedApp(std::string_view app_id) override; - void ClearLastLaunchedApp() override; - void SetCurrentApp(std::string_view app_id) override; - void ClearCurrentApp() override; - void SetPreviousApp(std::string_view app_id) override; - void ClearPreviousApp() override; - void SetStadiaSessionId(std::string_view session_id) override; - void ClearStadiaSessionId() override; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_CAST_CRASH_STORAGE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crashdump_uploader.cc chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader.cc --- chromium-132.0.6834.110/chromecast/crash/cast_crashdump_uploader.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,139 +0,0 @@ -// 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 "chromecast/crash/cast_crashdump_uploader.h" - -#include - -#include - -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/logging.h" -// TODO(slan): Find a replacement for LibcurlWrapper in Chromium to remove the -// breakpad dependency. -#include "chromecast/crash/libcurl_wrapper.h" - -namespace chromecast { -namespace { - -// Keep these in sync with -// //third_party/breakpad/breakpad/src/client/mac/sender/uploader.mm -const char kProdKey[] = "prod"; -const char kVerKey[] = "ver"; -const char kGuidKey[] = "guid"; -const char kPtimeKey[] = "ptime"; -const char kCtimeKey[] = "ctime"; -const char kEmailKey[] = "email"; -const char kCommentsKey[] = "comments"; - -} // namespace - -CastCrashdumpData::CastCrashdumpData() { -} - -CastCrashdumpData::CastCrashdumpData(const CastCrashdumpData& other) = default; - -CastCrashdumpData::~CastCrashdumpData() { -} - -CastCrashdumpUploader::CastCrashdumpUploader(const CastCrashdumpData& data) - : CastCrashdumpUploader(data, std::make_unique()) {} - -CastCrashdumpUploader::CastCrashdumpUploader( - const CastCrashdumpData& data, - std::unique_ptr http_layer) - : http_layer_(std::move(http_layer)), data_(data) { - DCHECK(http_layer_); -} - -CastCrashdumpUploader::~CastCrashdumpUploader() { -} - -bool CastCrashdumpUploader::AddAttachment(const std::string& label, - const std::string& filename) { - std::optional file_size = - base::GetFileSize(base::FilePath(filename)); - if (!file_size.has_value()) { - LOG(WARNING) << "file size of " << filename << " not readable"; - return false; - } - LOG(INFO) << "file size of " << filename << ": " << file_size.value(); - attachments_[label] = filename; - return true; -} - -bool CastCrashdumpUploader::CheckRequiredParametersArePresent() { - return !(data_.product.empty() || data_.version.empty() || - data_.guid.empty() || data_.minidump_pathname.empty()); -} - -bool CastCrashdumpUploader::Upload(std::string* response) { - if (!http_layer_->Init()) { - LOG(ERROR) << "http layer Init failed"; - return false; - } - - if (!CheckRequiredParametersArePresent()) { - LOG(ERROR) << "Missing required parameters"; - return false; - } - - struct stat st; - if (0 != stat(data_.minidump_pathname.c_str(), &st)) { - LOG(ERROR) << data_.minidump_pathname << " does not exist."; - return false; - } - - std::string upload_filename = data_.upload_filename; - if (upload_filename.empty()) { - upload_filename = "upload_file_minidump"; - } - if (!http_layer_->AddFile(data_.minidump_pathname, upload_filename)) { - LOG(ERROR) << "Failed to add file: " << data_.minidump_pathname; - return false; - } - - // Populate |parameters_|. - parameters_[kProdKey] = data_.product; - parameters_[kVerKey] = data_.version; - parameters_[kGuidKey] = data_.guid; - parameters_[kPtimeKey] = data_.ptime; - parameters_[kCtimeKey] = data_.ctime; - parameters_[kEmailKey] = data_.email; - parameters_[kCommentsKey] = data_.comments; - - // Add each attachement in |attachments_|. - for (auto iter = attachments_.begin(); iter != attachments_.end(); ++iter) { - // Search for the attachment. - if (0 != stat(iter->second.c_str(), &st)) { - LOG(ERROR) << iter->second << " could not be found"; - return false; - } - - // Add the attachment - if (!http_layer_->AddFile(iter->second, iter->first)) { - LOG(ERROR) << "Failed to add file: " << iter->second - << " with label: " << iter->first; - return false; - } - } - - LOG(INFO) << "Sending request to " << data_.crash_server; - - long http_status_code; - std::string http_header_data; - return http_layer_->SendRequest(data_.crash_server, - parameters_, - &http_status_code, - &http_header_data, - response); -} - -void CastCrashdumpUploader::SetParameter(const std::string& key, - const std::string& value) { - parameters_[key] = value; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crashdump_uploader.h chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader.h --- chromium-132.0.6834.110/chromecast/crash/cast_crashdump_uploader.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,65 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_CAST_CRASHDUMP_UPLOADER_H_ -#define CHROMECAST_CRASH_CAST_CRASHDUMP_UPLOADER_H_ - -#include -#include -#include - -namespace chromecast { -class LibcurlWrapper; - -struct CastCrashdumpData { - CastCrashdumpData(); - CastCrashdumpData(const CastCrashdumpData& other); - ~CastCrashdumpData(); - - std::string product; - std::string version; - std::string guid; - std::string ptime; - std::string ctime; - std::string email; - std::string comments; - std::string minidump_pathname; - std::string crash_server; - std::string proxy_host; - std::string proxy_userpassword; - std::string upload_filename; -}; - -class CastCrashdumpUploader { - public: - CastCrashdumpUploader(const CastCrashdumpData& data, - std::unique_ptr http_layer); - explicit CastCrashdumpUploader(const CastCrashdumpData& data); - - CastCrashdumpUploader(const CastCrashdumpUploader&) = delete; - CastCrashdumpUploader& operator=(const CastCrashdumpUploader&) = delete; - - virtual ~CastCrashdumpUploader(); - - virtual bool AddAttachment(const std::string& label, - const std::string& filename); - virtual void SetParameter(const std::string& key, const std::string& value); - virtual bool Upload(std::string* response); - - private: - bool CheckRequiredParametersArePresent(); - - std::unique_ptr http_layer_; - CastCrashdumpData data_; - - // Holds the following mapping for attachments: - std::map attachments_; - - // Holds the following mapping for HTTP request params: - std::map parameters_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_CAST_CRASHDUMP_UPLOADER_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/cast_crashdump_uploader_unittest.cc chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader_unittest.cc --- chromium-132.0.6834.110/chromecast/crash/cast_crashdump_uploader_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/cast_crashdump_uploader_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,181 +0,0 @@ -// 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 - -#include "base/files/file_util.h" -#include "chromecast/base/scoped_temp_file.h" -#include "chromecast/crash/cast_crashdump_uploader.h" -#include "chromecast/crash/libcurl_wrapper.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -class MockLibcurlWrapper : public LibcurlWrapper { - public: - MOCK_METHOD0(Init, bool()); - MOCK_METHOD2(AddFile, - bool(const std::string& upload_file_path, - const std::string& basename)); - MOCK_METHOD5(SendRequest, - bool(const std::string& url, - const std::map& parameters, - long* http_status_code, - std::string* http_header_data, - std::string* http_response_data)); -}; - -// Declared for the scope of this file to increase readability. -using testing::_; -using testing::Return; - -TEST(CastCrashdumpUploaderTest, UploadFailsWhenInitFails) { - auto m = std::make_unique>(); - EXPECT_CALL(*m, Init()).Times(1).WillOnce(Return(false)); - - CastCrashdumpData data; - data.product = "foobar"; - data.version = "1.0"; - data.guid = "AAA-BBB"; - data.email = "test@test.com"; - data.comments = "none"; - data.minidump_pathname = "/tmp/foo.dmp"; - data.crash_server = "http://foo.com"; - CastCrashdumpUploader uploader(data, std::move(m)); - - ASSERT_FALSE(uploader.Upload(nullptr)); -} - -TEST(CastCrashdumpUploaderTest, UploadSucceedsWithValidParameters) { - auto m = std::make_unique>(); - - // Create a temporary file. - ScopedTempFile minidump; - - EXPECT_CALL(*m, Init()).Times(1).WillOnce(Return(true)); - EXPECT_CALL(*m, AddFile(minidump.path().value(), _)).WillOnce(Return(true)); - EXPECT_CALL(*m, SendRequest("http://foo.com", _, _, _, _)).Times(1).WillOnce( - Return(true)); - - CastCrashdumpData data; - data.product = "foobar"; - data.version = "1.0"; - data.guid = "AAA-BBB"; - data.email = "test@test.com"; - data.comments = "none"; - data.minidump_pathname = minidump.path().value(); - data.crash_server = "http://foo.com"; - CastCrashdumpUploader uploader(data, std::move(m)); - - ASSERT_TRUE(uploader.Upload(nullptr)); -} - -TEST(CastCrashdumpUploaderTest, UploadFailsWithInvalidPathname) { - auto m = std::make_unique>(); - EXPECT_CALL(*m, Init()).Times(1).WillOnce(Return(true)); - EXPECT_CALL(*m, SendRequest(_, _, _, _, _)).Times(0); - - CastCrashdumpData data; - data.product = "foobar"; - data.version = "1.0"; - data.guid = "AAA-BBB"; - data.email = "test@test.com"; - data.comments = "none"; - data.minidump_pathname = "/invalid/file/path"; - data.crash_server = "http://foo.com"; - CastCrashdumpUploader uploader(data, std::move(m)); - - ASSERT_FALSE(uploader.Upload(nullptr)); -} - -TEST(CastCrashdumpUploaderTest, UploadFailsWithoutAllRequiredParameters) { - - // Create a temporary file. - ScopedTempFile minidump; - - // Has all the require fields for a crashdump. - CastCrashdumpData data; - data.product = "foobar"; - data.version = "1.0"; - data.guid = "AAA-BBB"; - data.email = "test@test.com"; - data.comments = "none"; - data.minidump_pathname = minidump.path().value(); - data.crash_server = "http://foo.com"; - - // Test with empty product name. - data.product = ""; - auto m = std::make_unique>(); - EXPECT_CALL(*m, Init()).Times(1).WillOnce(Return(true)); - CastCrashdumpUploader uploader_no_product(data, std::move(m)); - ASSERT_FALSE(uploader_no_product.Upload(nullptr)); - data.product = "foobar"; - - // Test with empty product version. - data.version = ""; - m = std::make_unique>(); - EXPECT_CALL(*m, Init()).Times(1).WillOnce(Return(true)); - CastCrashdumpUploader uploader_no_version(data, std::move(m)); - ASSERT_FALSE(uploader_no_version.Upload(nullptr)); - data.version = "1.0"; - - // Test with empty client GUID. - data.guid = ""; - m = std::make_unique>(); - EXPECT_CALL(*m, Init()).Times(1).WillOnce(Return(true)); - CastCrashdumpUploader uploader_no_guid(data, std::move(m)); - ASSERT_FALSE(uploader_no_guid.Upload(nullptr)); -} - -TEST(CastCrashdumpUploaderTest, UploadFailsWithInvalidAttachment) { - auto m = std::make_unique>(); - - // Create a temporary file. - ScopedTempFile minidump; - - CastCrashdumpData data; - data.product = "foobar"; - data.version = "1.0"; - data.guid = "AAA-BBB"; - data.email = "test@test.com"; - data.comments = "none"; - data.minidump_pathname = minidump.path().value(); - data.crash_server = "http://foo.com"; - CastCrashdumpUploader uploader(data, std::move(m)); - - // Add a file that does not exist as an attachment. - ASSERT_FALSE(uploader.AddAttachment("label", "/path/does/not/exist")); -} - -TEST(CastCrashdumpUploaderTest, UploadSucceedsWithValidAttachment) { - auto m = std::make_unique>(); - - // Create a temporary file. - ScopedTempFile minidump; - - // Create a valid attachment. - ScopedTempFile attachment; - - EXPECT_CALL(*m, Init()).Times(1).WillOnce(Return(true)); - EXPECT_CALL(*m, AddFile(minidump.path().value(), _)).WillOnce(Return(true)); - EXPECT_CALL(*m, AddFile(attachment.path().value(), _)).WillOnce(Return(true)); - EXPECT_CALL(*m, SendRequest(_, _, _, _, _)).Times(1).WillOnce(Return(true)); - - CastCrashdumpData data; - data.product = "foobar"; - data.version = "1.0"; - data.guid = "AAA-BBB"; - data.email = "test@test.com"; - data.comments = "none"; - data.minidump_pathname = minidump.path().value(); - data.crash_server = "http://foo.com"; - CastCrashdumpUploader uploader(data, std::move(m)); - - // Add a valid file as an attachment. - uploader.AddAttachment("label", attachment.path().value()); - ASSERT_TRUE(uploader.Upload(nullptr)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.cc chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.cc --- chromium-132.0.6834.110/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,85 +0,0 @@ -// 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 "chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.h" - -#include - -#include - -#include "base/fuchsia/fuchsia_logging.h" -#include "chromecast/crash/fuchsia/constants.h" - -namespace chromecast { -namespace { - -const char kLastLaunchedApp[] = "app.last-launched"; -const char kCurrentApp[] = "app.current"; -const char kPreviousApp[] = "app.previous"; -const char kStadiaSessionId[] = "stadia-session-id"; - -fuchsia::feedback::Annotation MakeAnnotation(std::string_view key, - std::string_view value) { - fuchsia::feedback::Annotation annotation; - annotation.key = std::string(key); - annotation.value = std::string(value); - return annotation; -} - -} // namespace - -CastCrashStorageImplFuchsia::CastCrashStorageImplFuchsia( - const sys::ServiceDirectory* incoming_directory) - : incoming_directory_(incoming_directory) { - DCHECK(incoming_directory_); -} - -CastCrashStorageImplFuchsia::~CastCrashStorageImplFuchsia() = default; - -void CastCrashStorageImplFuchsia::SetLastLaunchedApp(std::string_view app_id) { - UpsertAnnotations({MakeAnnotation(kLastLaunchedApp, app_id)}); -} - -void CastCrashStorageImplFuchsia::ClearLastLaunchedApp() { - UpsertAnnotations({MakeAnnotation(kLastLaunchedApp, std::string_view())}); -} - -void CastCrashStorageImplFuchsia::SetCurrentApp(std::string_view app_id) { - UpsertAnnotations({MakeAnnotation(kCurrentApp, app_id)}); -} - -void CastCrashStorageImplFuchsia::ClearCurrentApp() { - UpsertAnnotations({MakeAnnotation(kCurrentApp, std::string_view())}); -} - -void CastCrashStorageImplFuchsia::SetPreviousApp(std::string_view app_id) { - UpsertAnnotations({MakeAnnotation(kPreviousApp, app_id)}); -} - -void CastCrashStorageImplFuchsia::ClearPreviousApp() { - UpsertAnnotations({MakeAnnotation(kPreviousApp, std::string_view())}); -} - -void CastCrashStorageImplFuchsia::SetStadiaSessionId( - std::string_view session_id) { - UpsertAnnotations({MakeAnnotation(kStadiaSessionId, session_id)}); -} - -void CastCrashStorageImplFuchsia::ClearStadiaSessionId() { - UpsertAnnotations({MakeAnnotation(kStadiaSessionId, std::string_view())}); -} - -void CastCrashStorageImplFuchsia::UpsertAnnotations( - std::vector annotations) { - fuchsia::feedback::ComponentDataRegisterPtr component_data_register; - incoming_directory_->Connect( - component_data_register.NewRequest()); - - fuchsia::feedback::ComponentData component_data; - component_data.set_namespace_(crash::kCastNamespace); - component_data.set_annotations(std::move(annotations)); - component_data_register->Upsert(std::move(component_data), []() {}); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.h chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.h --- chromium-132.0.6834.110/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_FUCHSIA_CAST_CRASH_STORAGE_IMPL_FUCHSIA_H_ -#define CHROMECAST_CRASH_FUCHSIA_CAST_CRASH_STORAGE_IMPL_FUCHSIA_H_ - -#include -#include - -#include - -#include "chromecast/crash/cast_crash_storage.h" - -namespace chromecast { - -class CastCrashStorageImplFuchsia final : public CastCrashStorage { - public: - explicit CastCrashStorageImplFuchsia( - const sys::ServiceDirectory* incoming_directory); - ~CastCrashStorageImplFuchsia() override; - CastCrashStorageImplFuchsia& operator=(const CastCrashStorageImplFuchsia&) = - delete; - CastCrashStorageImplFuchsia(const CastCrashStorageImplFuchsia&) = delete; - - // CastCrashStorage implementation: - void SetLastLaunchedApp(std::string_view app_id) override; - void ClearLastLaunchedApp() override; - void SetCurrentApp(std::string_view app_id) override; - void ClearCurrentApp() override; - void SetPreviousApp(std::string_view app_id) override; - void ClearPreviousApp() override; - void SetStadiaSessionId(std::string_view session_id) override; - void ClearStadiaSessionId() override; - - private: - void UpsertAnnotations( - std::vector annotations); - - const sys::ServiceDirectory* const incoming_directory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_FUCHSIA_CAST_CRASH_STORAGE_IMPL_FUCHSIA_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc --- chromium-132.0.6834.110/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,142 +0,0 @@ -// 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 "chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia.h" - -#include -#include -#include -#include -#include -#include - -#include - -#include "base/fuchsia/scoped_service_binding.h" -#include "base/run_loop.h" -#include "base/test/task_environment.h" -#include "chromecast/crash/fuchsia/constants.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -class MockComponentDataRegister - : public fuchsia::feedback::testing::ComponentDataRegister_TestBase { - public: - MockComponentDataRegister( - fidl::InterfaceRequest channel) { - outgoing_directory_ = std::make_unique(); - outgoing_directory_->GetOrCreateDirectory("svc")->Serve( - fuchsia::io::OpenFlags::RIGHT_READABLE | - fuchsia::io::OpenFlags::RIGHT_WRITABLE, - channel.TakeChannel()); - binding_ = std::make_unique< - base::ScopedServiceBinding>( - outgoing_directory_.get(), this); - } - - fuchsia::feedback::ComponentData GetLatest() { - return fidl::Clone(component_data_); - } - - void Upsert(fuchsia::feedback::ComponentData data, - UpsertCallback callback) final { - component_data_ = std::move(data); - callback(); - } - - void NotImplemented_(const std::string& name) final { ADD_FAILURE(); } - - private: - std::unique_ptr outgoing_directory_; - std::unique_ptr< - base::ScopedServiceBinding> - binding_; - - fuchsia::feedback::ComponentData component_data_; -}; - -class CastCrashStorageImplFuchsiaTest : public ::testing::Test { - public: - CastCrashStorageImplFuchsiaTest() { - fidl::InterfaceHandle directory; - component_data_register_ = - std::make_unique(directory.NewRequest()); - incoming_directory_ = - std::make_unique(std::move(directory)); - } - - void SetUp() final { - cast_crash_storage_ = std::make_unique( - incoming_directory_.get()); - } - - void TearDown() final { cast_crash_storage_ = nullptr; } - - void VerifyLatestAnnotation(const fuchsia::feedback::Annotation& annotation) { - fuchsia::feedback::ComponentData latest = - component_data_register_->GetLatest(); - EXPECT_EQ(latest.namespace_(), crash::kCastNamespace); - ASSERT_EQ(latest.annotations().size(), 1uL); - - fuchsia::feedback::Annotation latest_annotation = - fidl::Clone(latest.annotations()[0]); - EXPECT_EQ(annotation.key, latest_annotation.key); - EXPECT_EQ(annotation.value, latest_annotation.value); - } - - protected: - std::unique_ptr cast_crash_storage_; - - private: - base::test::TaskEnvironment task_environment_{ - base::test::TaskEnvironment::MainThreadType::IO}; - std::unique_ptr component_data_register_; - std::unique_ptr incoming_directory_; -}; - -TEST_F(CastCrashStorageImplFuchsiaTest, LastLaunchedApp) { - fuchsia::feedback::Annotation annotation; - annotation.key = "app.last-launched"; - annotation.value = "last_launched_app_id"; - - cast_crash_storage_->SetLastLaunchedApp("last_launched_app_id"); - base::RunLoop().RunUntilIdle(); - VerifyLatestAnnotation(annotation); -} - -TEST_F(CastCrashStorageImplFuchsiaTest, CurrentApp) { - fuchsia::feedback::Annotation annotation; - annotation.key = "app.current"; - annotation.value = "current_app_id"; - - cast_crash_storage_->SetCurrentApp("current_app_id"); - base::RunLoop().RunUntilIdle(); - VerifyLatestAnnotation(annotation); -} - -TEST_F(CastCrashStorageImplFuchsiaTest, PreviousApp) { - fuchsia::feedback::Annotation annotation; - annotation.key = "app.previous"; - annotation.value = "previous_app_id"; - - cast_crash_storage_->SetPreviousApp("previous_app_id"); - base::RunLoop().RunUntilIdle(); - VerifyLatestAnnotation(annotation); -} - -TEST_F(CastCrashStorageImplFuchsiaTest, StadiaSessionId) { - fuchsia::feedback::Annotation annotation; - annotation.key = "stadia-session-id"; - annotation.value = "session_id"; - - cast_crash_storage_->SetStadiaSessionId("session_id"); - base::RunLoop().RunUntilIdle(); - VerifyLatestAnnotation(annotation); -} - -} // namespace -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/fuchsia/constants.cc chromium-132.0.6834.159/chromecast/crash/fuchsia/constants.cc --- chromium-132.0.6834.110/chromecast/crash/fuchsia/constants.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/fuchsia/constants.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// 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 "chromecast/crash/fuchsia/constants.h" - -namespace chromecast { -namespace crash { - -// Namespace used when uploading annotations to the feedback service -// from Cast components. -const char kCastNamespace[] = "cast"; - -} // namespace crash -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/fuchsia/constants.h chromium-132.0.6834.159/chromecast/crash/fuchsia/constants.h --- chromium-132.0.6834.110/chromecast/crash/fuchsia/constants.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/fuchsia/constants.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_FUCHSIA_CONSTANTS_H_ -#define CHROMECAST_CRASH_FUCHSIA_CONSTANTS_H_ - -namespace chromecast { -namespace crash { - -// Namespace used when uploading annotations to the feedback service -// from Cast components. -extern const char kCastNamespace[]; - -} // namespace crash -} // namespace chromecast - -#endif // CHROMECAST_CRASH_FUCHSIA_CONSTANTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/libcurl_wrapper.cc chromium-132.0.6834.159/chromecast/crash/libcurl_wrapper.cc --- chromium-132.0.6834.110/chromecast/crash/libcurl_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/libcurl_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,227 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include -#include - -#include "chromecast/crash/libcurl_wrapper.h" - -namespace chromecast { -LibcurlWrapper::LibcurlWrapper() - : init_ok_(false), - curl_lib_(nullptr), - last_curl_error_(""), - curl_(nullptr), - formpost_(nullptr), - lastptr_(nullptr), - headerlist_(nullptr) {} - -LibcurlWrapper::~LibcurlWrapper() { - if (init_ok_) { - (*easy_cleanup_)(curl_); - dlclose(curl_lib_); - } -} - -bool LibcurlWrapper::AddFile(const std::string& upload_file_path, - const std::string& basename) { - if (!CheckInit()) - return false; - - std::cout << "Adding " << upload_file_path << " to form upload."; - // Add form file. - (*formadd_)(&formpost_, &lastptr_, CURLFORM_COPYNAME, basename.c_str(), - CURLFORM_FILE, upload_file_path.c_str(), CURLFORM_END); - - return true; -} - -// Callback to get the response data from server. -static size_t WriteCallback(void* ptr, size_t size, size_t nmemb, void* userp) { - if (!userp) - return 0; - - std::string* response = reinterpret_cast(userp); - size_t real_size = size * nmemb; - response->append(reinterpret_cast(ptr), real_size); - return real_size; -} - -bool LibcurlWrapper::SendRequest( - const std::string& url, - const std::map& parameters, - long* http_status_code, - std::string* http_header_data, - std::string* http_response_data) { - if (!CheckInit()) - return false; - - std::map::const_iterator iter = parameters.begin(); - for (; iter != parameters.end(); ++iter) - (*formadd_)(&formpost_, &lastptr_, CURLFORM_COPYNAME, iter->first.c_str(), - CURLFORM_COPYCONTENTS, iter->second.c_str(), CURLFORM_END); - - (*easy_setopt_)(curl_, CURLOPT_HTTPPOST, formpost_); - - return SendRequestInner(url, http_status_code, http_header_data, - http_response_data); -} - -bool LibcurlWrapper::Init() { - // First check to see if libcurl was statically linked: - curl_lib_ = dlopen(nullptr, RTLD_NOW); - if (curl_lib_ && (!dlsym(curl_lib_, "curl_easy_init") || - !dlsym(curl_lib_, "curl_easy_setopt"))) { - // Not statically linked, try again below. - dlerror(); // Clear dlerror before attempting to open libraries. - dlclose(curl_lib_); - curl_lib_ = nullptr; - } - if (!curl_lib_) { - curl_lib_ = dlopen("libcurl.so", RTLD_NOW); - } - if (!curl_lib_) { - curl_lib_ = dlopen("libcurl.so.4", RTLD_NOW); - } - if (!curl_lib_) { - curl_lib_ = dlopen("libcurl.so.3", RTLD_NOW); - } - if (!curl_lib_) { - std::cout << "Could not find libcurl via dlopen"; - return false; - } - - if (!SetFunctionPointers()) { - std::cout << "Could not find function pointers"; - return false; - } - - curl_ = (*easy_init_)(); - - last_curl_error_ = "No Error"; - - if (!curl_) { - dlclose(curl_lib_); - std::cout << "Curl initialization failed"; - return false; - } - - init_ok_ = true; - return true; -} - -#define SET_AND_CHECK_FUNCTION_POINTER(var, function_name, type) \ - var = reinterpret_cast(dlsym(curl_lib_, function_name)); \ - if (!var) { \ - std::cout << "Could not find libcurl function " << function_name; \ - init_ok_ = false; \ - return false; \ - } - -bool LibcurlWrapper::SetFunctionPointers() { - SET_AND_CHECK_FUNCTION_POINTER(easy_init_, "curl_easy_init", CURL * (*)()); - - SET_AND_CHECK_FUNCTION_POINTER(easy_setopt_, "curl_easy_setopt", - CURLcode(*)(CURL*, CURLoption, ...)); - - SET_AND_CHECK_FUNCTION_POINTER( - formadd_, "curl_formadd", - CURLFORMcode(*)(curl_httppost**, curl_httppost**, ...)); - - SET_AND_CHECK_FUNCTION_POINTER(slist_append_, "curl_slist_append", - curl_slist * (*)(curl_slist*, const char*)); - - SET_AND_CHECK_FUNCTION_POINTER(easy_perform_, "curl_easy_perform", - CURLcode(*)(CURL*)); - - SET_AND_CHECK_FUNCTION_POINTER(easy_cleanup_, "curl_easy_cleanup", - void (*)(CURL*)); - - SET_AND_CHECK_FUNCTION_POINTER(easy_getinfo_, "curl_easy_getinfo", - CURLcode(*)(CURL*, CURLINFO info, ...)); - - SET_AND_CHECK_FUNCTION_POINTER(easy_reset_, "curl_easy_reset", - void (*)(CURL*)); - - SET_AND_CHECK_FUNCTION_POINTER(slist_free_all_, "curl_slist_free_all", - void (*)(curl_slist*)); - - SET_AND_CHECK_FUNCTION_POINTER(formfree_, "curl_formfree", - void (*)(curl_httppost*)); - return true; -} - -bool LibcurlWrapper::SendRequestInner(const std::string& url, - long* http_status_code, - std::string* http_header_data, - std::string* http_response_data) { - std::string url_copy(url); - (*easy_setopt_)(curl_, CURLOPT_URL, url_copy.c_str()); - // Use the enum when available in the header file. - (*easy_setopt_)(curl_, CURLOPT_SSLVERSION, 6 /*CURL_SSLVERSION_TLSv1_2*/); - - // Disable 100-continue header. - char buf[] = "Expect:"; - headerlist_ = (*slist_append_)(headerlist_, buf); - (*easy_setopt_)(curl_, CURLOPT_HTTPHEADER, headerlist_); - - if (http_response_data != nullptr) { - http_response_data->clear(); - (*easy_setopt_)(curl_, CURLOPT_WRITEFUNCTION, WriteCallback); - (*easy_setopt_)(curl_, CURLOPT_WRITEDATA, - reinterpret_cast(http_response_data)); - } - if (http_header_data != nullptr) { - http_header_data->clear(); - (*easy_setopt_)(curl_, CURLOPT_HEADERFUNCTION, WriteCallback); - (*easy_setopt_)(curl_, CURLOPT_HEADERDATA, - reinterpret_cast(http_header_data)); - } - CURLcode err_code = CURLE_OK; - err_code = (*easy_perform_)(curl_); - easy_strerror_ = reinterpret_cast( - dlsym(curl_lib_, "curl_easy_strerror")); - - if (http_status_code != nullptr) { - (*easy_getinfo_)(curl_, CURLINFO_RESPONSE_CODE, http_status_code); - } - -#ifndef NDEBUG - if (err_code != CURLE_OK) - fprintf(stderr, "Failed to send http request to %s, error: %s\n", - url.c_str(), (*easy_strerror_)(err_code)); -#endif - - Reset(); - - return err_code == CURLE_OK; -} - -void LibcurlWrapper::Reset() { - if (headerlist_ != nullptr) { - (*slist_free_all_)(headerlist_); - headerlist_ = nullptr; - } - - if (formpost_ != nullptr) { - (*formfree_)(formpost_); - formpost_ = nullptr; - } - - (*easy_reset_)(curl_); -} - -bool LibcurlWrapper::CheckInit() { - if (!init_ok_) { - std::cout << "LibcurlWrapper: You must call Init(), and have it return " - "'true' before invoking any other methods.\n"; - return false; - } - - return true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/libcurl_wrapper.h chromium-132.0.6834.159/chromecast/crash/libcurl_wrapper.h --- chromium-132.0.6834.110/chromecast/crash/libcurl_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/libcurl_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CRASH_LIBCURL_WRAPPER_H_ -#define CHROMECAST_CRASH_LIBCURL_WRAPPER_H_ - -#include -#include - -#include "third_party/breakpad/breakpad/src/third_party/curl/curl.h" - -namespace chromecast { -class LibcurlWrapper { - public: - LibcurlWrapper(); - virtual ~LibcurlWrapper(); - virtual bool Init(); - virtual bool AddFile(const std::string& upload_file_path, - const std::string& basename); - virtual bool SendRequest(const std::string& url, - const std::map& parameters, - long* http_status_code, - std::string* http_header_data, - std::string* http_response_data); - - private: - // This function initializes class state corresponding to function - // pointers into the CURL library. - bool SetFunctionPointers(); - - bool SendRequestInner(const std::string& url, - long* http_status_code, - std::string* http_header_data, - std::string* http_response_data); - - void Reset(); - - bool CheckInit(); - - bool init_ok_; // Whether init succeeded - void* curl_lib_; // Pointer to result of dlopen() on - // curl library - std::string last_curl_error_; // The text of the last error when - // dealing - // with CURL. - - CURL* curl_; // Pointer for handle for CURL calls. - - CURL* (*easy_init_)(void); - - // Stateful pointers for calling into curl_formadd() - struct curl_httppost* formpost_; - struct curl_httppost* lastptr_; - struct curl_slist* headerlist_; - - // Function pointers into CURL library - CURLcode (*easy_setopt_)(CURL*, CURLoption, ...); - CURLFORMcode (*formadd_)(struct curl_httppost**, struct curl_httppost**, ...); - struct curl_slist* (*slist_append_)(struct curl_slist*, const char*); - void (*slist_free_all_)(struct curl_slist*); - CURLcode (*easy_perform_)(CURL*); - const char* (*easy_strerror_)(CURLcode); - void (*easy_cleanup_)(CURL*); - CURLcode (*easy_getinfo_)(CURL*, CURLINFO info, ...); - void (*easy_reset_)(CURL*); - void (*formfree_)(struct curl_httppost*); -}; -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LIBCURL_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/DEPS chromium-132.0.6834.159/chromecast/crash/linux/DEPS --- chromium-132.0.6834.110/chromecast/crash/linux/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -include_rules = [ - "+chromecast/system", - "+components/metrics", - "+components/prefs", - "+third_party/crashpad/crashpad/client", -] diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/crash_testing_utils.cc chromium-132.0.6834.159/chromecast/crash/linux/crash_testing_utils.cc --- chromium-132.0.6834.110/chromecast/crash/linux/crash_testing_utils.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/crash_testing_utils.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,167 +0,0 @@ -// 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 "chromecast/crash/linux/crash_testing_utils.h" - -#include - -#include "base/files/file_util.h" -#include "base/json/json_file_value_serializer.h" -#include "base/json/json_reader.h" -#include "base/json/json_writer.h" -#include "base/logging.h" -#include "base/strings/string_split.h" -#include "base/values.h" -#include "chromecast/base/path_utils.h" -#include "chromecast/crash/linux/dump_info.h" - -#define RCHECK(cond, retval, err) \ - do { \ - if (!(cond)) { \ - LOG(ERROR) << (err); \ - return (retval); \ - } \ - } while (0) - -namespace chromecast { -namespace { - -const char kRatelimitKey[] = "ratelimit"; -const char kRatelimitPeriodStartKey[] = "period_start"; -const char kRatelimitPeriodDumpsKey[] = "period_dumps"; - -std::optional ParseLockFile(const std::string& path) { - std::string lockfile_string; - RCHECK(base::ReadFileToString(base::FilePath(path), &lockfile_string), - std::nullopt, "Failed to read file"); - - std::vector lines = base::SplitString( - lockfile_string, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - - base::Value::List dumps; - - // Validate dumps - for (const std::string& line : lines) { - if (line.size() == 0) - continue; - std::optional dump_info = base::JSONReader::Read(line); - RCHECK(dump_info.has_value(), std::nullopt, "Invalid DumpInfo"); - DumpInfo info(&dump_info.value()); - RCHECK(info.valid(), std::nullopt, "Invalid DumpInfo"); - dumps.Append(std::move(dump_info.value())); - } - - return dumps; -} - -std::unique_ptr ParseMetadataFile(const std::string& path) { - base::FilePath file_path(path); - JSONFileValueDeserializer deserializer(file_path); - int error_code = -1; - std::string error_msg; - std::unique_ptr value = - deserializer.Deserialize(&error_code, &error_msg); - DLOG_IF(ERROR, !value) << "JSON error " << error_code << ":" << error_msg; - return value; -} - -int WriteLockFile(const std::string& path, const base::Value::List& contents) { - std::string lockfile; - - for (const auto& elem : contents) { - std::string dump_info; - bool ret = base::JSONWriter::Write(elem, &dump_info); - RCHECK(ret, -1, "Failed to serialize DumpInfo"); - lockfile += dump_info; - lockfile += "\n"; // Add line seperatators - } - - return WriteFile(base::FilePath(path), lockfile) ? 0 : -1; -} - -bool WriteMetadataFile(const std::string& path, - const base::Value::Dict& metadata) { - base::FilePath file_path(path); - JSONFileValueSerializer serializer(file_path); - return serializer.Serialize(metadata); -} - -} // namespace - -std::unique_ptr CreateDumpInfo(const std::string& json_string) { - std::optional value = base::JSONReader::Read(json_string); - return value.has_value() ? std::make_unique(&value.value()) - : std::make_unique(nullptr); -} - -bool FetchDumps(const std::string& lockfile_path, - std::vector>* dumps) { - DCHECK(dumps); - std::optional dump_list = ParseLockFile(lockfile_path); - RCHECK(dump_list, false, "Failed to parse lockfile"); - - dumps->clear(); - - for (const auto& elem : *dump_list) { - std::unique_ptr dump(new DumpInfo(&elem)); - RCHECK(dump->valid(), false, "Invalid DumpInfo"); - dumps->push_back(std::move(dump)); - } - - return true; -} - -bool ClearDumps(const std::string& lockfile_path) { - base::Value::List dump_list; - return WriteLockFile(lockfile_path, dump_list) == 0; -} - -bool CreateFiles(const std::string& lockfile_path, - const std::string& metadata_path) { - base::Value::Dict metadata; - - base::Value::Dict ratelimit_fields; - ratelimit_fields.Set(kRatelimitPeriodStartKey, 0.0); - ratelimit_fields.Set(kRatelimitPeriodDumpsKey, 0); - metadata.Set(kRatelimitKey, std::move(ratelimit_fields)); - - base::Value::List dumps; - - return WriteLockFile(lockfile_path, dumps) == 0 && - WriteMetadataFile(metadata_path, metadata); -} - -bool AppendLockFile(const std::string& lockfile_path, - const std::string& metadata_path, - const DumpInfo& dump) { - std::optional contents = ParseLockFile(lockfile_path); - if (!contents) { - CreateFiles(lockfile_path, metadata_path); - if (!(contents = ParseLockFile(lockfile_path))) { - return false; - } - } - - contents->Append(dump.GetAsValue()); - - return WriteLockFile(lockfile_path, *contents) == 0; -} - -bool SetRatelimitPeriodStart(const std::string& metadata_path, - const base::Time& start) { - std::unique_ptr contents = ParseMetadataFile(metadata_path); - if (!contents || !contents->is_dict()) - return false; - - base::Value::Dict* ratelimit_params = - contents->GetDict().FindDict(kRatelimitKey); - if (!ratelimit_params) - return false; - - ratelimit_params->Set(kRatelimitPeriodStartKey, - start.InSecondsFSinceUnixEpoch()); - return WriteMetadataFile(metadata_path, contents->GetDict()) == 0; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/crash_testing_utils.h chromium-132.0.6834.159/chromecast/crash/linux/crash_testing_utils.h --- chromium-132.0.6834.110/chromecast/crash/linux/crash_testing_utils.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/crash_testing_utils.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_LINUX_CRASH_TESTING_UTILS_H_ -#define CHROMECAST_CRASH_LINUX_CRASH_TESTING_UTILS_H_ - -#include -#include - -#include "base/time/time.h" - -namespace chromecast { - -class DumpInfo; - -// Creates a DumpInfo object corresponding to the deserialization of -// |json_string|. Returned DumpInfo object maybe invalid if |json_string| -// doesn't correspond to a valid DumpInfo object. -std::unique_ptr CreateDumpInfo(const std::string& json_string); - -// Populates |dumps| with all the DumpInfo entries serialized in the lockfile at -// |lockfile_path|. Returns true on success, false on error. -bool FetchDumps(const std::string& lockfile_path, - std::vector>* dumps); - -// Clear all dumps in the lockfile at |lockfile_path|. -// Returns true on success, false on error. -bool ClearDumps(const std::string& lockfile_path); - -// Creates an empty lockfile at |lockfile_path|. Creates a default initialized -// metadata file at |metadata_path|. Returns true on success, false on error. -bool CreateFiles(const std::string& lockfile_path, - const std::string& metadata_path); - -// Appends serialization of |dump| onto the lockfile at |lockfile_path|. -// Creates default initialized lockfile in |lockfile_path| and metadata file in -// |metadata_path| if they don't exist. -// Returns true on success, false on error. -bool AppendLockFile(const std::string& lockfile_path, - const std::string& metadata_path, - const DumpInfo& dump); - -// Set the ratelimit period start in the metadata file at |metadata_path| to -// |start|. Returns true on success, false on error. -bool SetRatelimitPeriodStart(const std::string& metadata_path, - const base::Time& start); - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_CRASH_TESTING_UTILS_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/crash_uploader.cc chromium-132.0.6834.159/chromecast/crash/linux/crash_uploader.cc --- chromium-132.0.6834.110/chromecast/crash/linux/crash_uploader.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/crash_uploader.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include -#include - -#include "base/at_exit.h" -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/message_loop/message_pump_type.h" -#include "base/task/single_thread_task_executor.h" -#include "base/threading/platform_thread.h" -#include "base/time/time.h" -#include "chromecast/base/cast_paths.h" -#include "chromecast/base/cast_sys_info_util.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/crash/linux/minidump_uploader.h" -#include "chromecast/public/cast_sys_info.h" -#include "chromecast/system/reboot/reboot_util.h" -#include "third_party/crashpad/crashpad/client/crashpad_info.h" - -namespace { - -// Upload crash dump for every 60 seconds. -const int kUploadRetryIntervalDefault = 60; - -} // namespace - -int main(int argc, char** argv) { - base::AtExitManager exit_manager; - base::CommandLine::Init(argc, argv); - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - chromecast::RebootUtil::Initialize(command_line->argv()); - chromecast::RegisterPathProvider(); - logging::InitLogging(logging::LoggingSettings()); - - // Allow the system crash handler to handle our own crashes. - crashpad::CrashpadInfo::GetCrashpadInfo() - ->set_system_crash_reporter_forwarding(crashpad::TriState::kEnabled); - - LOG(INFO) << "Starting crash uploader..."; - - // Nice +19. Crash uploads are not time critical and we don't want to - // interfere with user playback. - setpriority(PRIO_PROCESS, 0, 19); - - // Create the main task executor. - base::SingleThreadTaskExecutor io_task_executor(base::MessagePumpType::IO); - - std::unique_ptr sys_info = - chromecast::CreateSysInfo(); - - std::string server_url( - command_line->GetSwitchValueASCII(switches::kCrashServerUrl)); - bool daemon = - chromecast::GetSwitchValueBoolean(switches::kCrashUploaderDaemon, false); - LOG_IF(INFO, daemon) << "Running crash uploader in daemon-mode"; - - chromecast::MinidumpUploader uploader(sys_info.get(), server_url); - do { - if (!uploader.UploadAllMinidumps()) - LOG(ERROR) << "Failed to process minidumps"; - - if (uploader.reboot_scheduled()) - chromecast::RebootUtil::RebootNow( - chromecast::RebootShlib::CRASH_UPLOADER); - - if (daemon) { - base::PlatformThread::Sleep(base::Seconds(kUploadRetryIntervalDefault)); - } - } while (daemon); - - return EXIT_SUCCESS; -} diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/crash_util.cc chromium-132.0.6834.159/chromecast/crash/linux/crash_util.cc --- chromium-132.0.6834.110/chromecast/crash/linux/crash_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/crash_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,165 +0,0 @@ -// 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 "chromecast/crash/linux/crash_util.h" - -#include - -#include "base/command_line.h" -#include "base/files/file_enumerator.h" -#include "base/files/file_util.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/threading/thread_restrictions.h" -#include "base/time/time.h" -#include "build/chromecast_buildflags.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/path_utils.h" -#include "chromecast/base/process_utils.h" -#include "chromecast/base/version.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/crash/app_state_tracker.h" -#include "chromecast/crash/linux/dummy_minidump_generator.h" -#include "chromecast/crash/linux/minidump_writer.h" - -namespace chromecast { - -namespace { -const char kDumpStateSuffix[] = ".txt.gz"; -const char kMinidumpsDir[] = "minidumps"; -const size_t kMaxFilesInMinidumpsDir = 22; // 10 crashes - -#if BUILDFLAG(ENABLE_CAST_RECEIVER) -// Crash product name for Core web runtime. -constexpr const char kCoreRuntimeCrashProductName[] = "CastCoreRuntime"; -#endif // BUILDFLAG(ENABLE_CAST_RECEIVER) - -// This can be set to a callback for testing. This allows us to inject a fake -// dumpstate routine to avoid calling an executable during an automated test. -// This value should not be mutated through any other function except -// CrashUtil::SetDumpStateCbForTest(). -static base::OnceCallback* g_dumpstate_cb = nullptr; - -} // namespace - -// static -bool CrashUtil::HasSpaceToCollectCrash() { - // Normally the path is protected by a file lock, but we don't need to acquire - // that just to make an estimate of the space consumed. - base::FilePath dump_dir(GetHomePathASCII(kMinidumpsDir)); - base::FileEnumerator file_enumerator(dump_dir, false /* recursive */, - base::FileEnumerator::FILES); - size_t total = 0; - for (base::FilePath name = file_enumerator.Next(); !name.empty(); - name = file_enumerator.Next()) { - total++; - } - return total <= kMaxFilesInMinidumpsDir; -} - -// static -bool CrashUtil::CollectDumpstate(const base::FilePath& minidump_path, - base::FilePath* dumpstate_path) { - std::string dumpstate_bin_path; - base::FilePath result = - base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( - switches::kDumpstateBinPath); - - // In case of CastCore + Chrome runtime, dumpstate path is passed to runtime - // through command line. If that's missing, then it's likely not a Chromium - // runtime build and fall back to the default path. - if (!result.empty()) { - dumpstate_bin_path = result.value(); - } else { - LOG(WARNING) - << "Dumpstate path is missing in command line, using the default path"; - dumpstate_bin_path = chromecast::GetBinPathASCII("dumpstate").value(); - } - - std::vector argv = { - dumpstate_bin_path, "-w", "crash-request", "-z", "-o", - minidump_path.value() /* dumpstate appends ".txt.gz" to the filename */ - }; - - std::string log; - if (!chromecast::GetAppOutput(argv, &log)) { - LOG(ERROR) << "failed to execute dumpstate"; - return false; - } - - *dumpstate_path = minidump_path.AddExtensionASCII(kDumpStateSuffix); - return true; -} - -// static -uint64_t CrashUtil::GetCurrentTimeMs() { - return (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds(); -} - -// static -bool CrashUtil::RequestUploadCrashDump( - const std::string& existing_minidump_path, - uint64_t crashed_pid, - uint64_t crashed_process_start_time_ms, - const std::vector* attachments) { - // Remove IO restrictions from this thread. Chromium IO functions must be used - // to access the file system and upload information to the crash server. - base::ScopedAllowBlocking allow_blocking; - - LOG(INFO) << "Request to upload crash dump " << existing_minidump_path - << " for process " << crashed_pid; - - uint64_t uptime_ms = GetCurrentTimeMs() - crashed_process_start_time_ms; - MinidumpParams params( - uptime_ms, - "", // suffix - AppStateTracker::GetPreviousApp(), AppStateTracker::GetCurrentApp(), - AppStateTracker::GetLastLaunchedApp(), CAST_BUILD_RELEASE, - CAST_BUILD_INCREMENTAL, "", /* reason */ - AppStateTracker::GetStadiaSessionId()); - -// Set crash product name for Core runtime. If not set, defaults to "Eureka". -#if BUILDFLAG(ENABLE_CAST_RECEIVER) - params.crash_product_name = kCoreRuntimeCrashProductName; -#endif // BUILDFLAG(ENABLE_CAST_RECEIVER) - - DummyMinidumpGenerator minidump_generator(existing_minidump_path); - - base::FilePath filename = base::FilePath(existing_minidump_path).BaseName(); - - std::unique_ptr writer; - if (g_dumpstate_cb) { - writer.reset(new MinidumpWriter(&minidump_generator, filename.value(), - params, std::move(*g_dumpstate_cb), - attachments)); - } else { - writer.reset(new MinidumpWriter(&minidump_generator, filename.value(), - params, attachments)); - } - bool success = false; - success = (0 == writer->Write()); // error already logged. - - // In case the file is still in $TEMP, remove it. Note that DeleteFile() will - // return true if |existing_minidump_path| has already been moved. - if (!base::DeleteFile(base::FilePath(existing_minidump_path))) { - LOG(ERROR) << "Unable to delete temp minidump file " - << existing_minidump_path; - success = false; - } - - // Use std::endl to flush the log stream in case this process exits. - LOG(INFO) << "Request to upload crash dump finished. " - << "Exit now if it is main process that crashed." << std::endl; - - return success; -} - -void CrashUtil::SetDumpStateCbForTest( - base::OnceCallback cb) { - DCHECK(!g_dumpstate_cb); - g_dumpstate_cb = - new base::OnceCallback(std::move(cb)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/crash_util.h chromium-132.0.6834.159/chromecast/crash/linux/crash_util.h --- chromium-132.0.6834.110/chromecast/crash/linux/crash_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/crash_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_LINUX_CRASH_UTIL_H_ -#define CHROMECAST_CRASH_LINUX_CRASH_UTIL_H_ - -#include - -#include - -#include "base/files/file_path.h" -#include "base/functional/callback.h" - -namespace chromecast { - -struct Attachment; - -class CrashUtil { - public: - // Returns true if the filesystem has sufficient space to collect the crash. - // Performs I/O on the current thread. - static bool HasSpaceToCollectCrash(); - - // Runs the dumpstate utility and sends its output to a file - // named after the minidump, but with ".txt.gz" appended to the name. - // This blocks the current thread to perform I/O (for multiple seconds). - static bool CollectDumpstate(const base::FilePath& minidump_path, - base::FilePath* dumpstate_path); - - // Helper function to request upload an existing minidump file. Returns true - // on success, false otherwise. - static bool RequestUploadCrashDump( - const std::string& existing_minidump_path, - uint64_t crashed_pid, - uint64_t crashed_process_start_time_ms, - const std::vector* attachments = nullptr); - - // Util function to get current time in ms. This is used to record - // crashed_process_start_time_ms in client side. - static uint64_t GetCurrentTimeMs(); - - // Call this to set a callback to be used instead of invoking an executable - // in a seperate process. See MinidumpWriter::SetDumpStateCbForTest() for more - // details on this callback's signature. - static void SetDumpStateCbForTest( - base::OnceCallback cb); -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_CRASH_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/dummy_minidump_generator.cc chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator.cc --- chromium-132.0.6834.110/chromecast/crash/linux/dummy_minidump_generator.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// 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 "chromecast/crash/linux/dummy_minidump_generator.h" - -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/threading/scoped_blocking_call.h" - -namespace chromecast { - -DummyMinidumpGenerator::DummyMinidumpGenerator( - const std::string& existing_minidump_path) - : existing_minidump_path_(existing_minidump_path) { -} - -bool DummyMinidumpGenerator::Generate(const std::string& minidump_path) { - base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, - base::BlockingType::MAY_BLOCK); - - // Return false if the file does not exist. - if (!base::PathExists(base::FilePath(existing_minidump_path_))) { - LOG(ERROR) << existing_minidump_path_ << " does not exist."; - return false; - } - - LOG(INFO) << "Moving minidump from " << existing_minidump_path_ << " to " - << minidump_path << " for further uploading."; - return base::Move(base::FilePath(existing_minidump_path_), - base::FilePath(minidump_path)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/dummy_minidump_generator.h chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator.h --- chromium-132.0.6834.110/chromecast/crash/linux/dummy_minidump_generator.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_LINUX_DUMMY_MINIDUMP_GENERATOR_H_ -#define CHROMECAST_CRASH_LINUX_DUMMY_MINIDUMP_GENERATOR_H_ - -#include - -#include "chromecast/crash/linux/minidump_generator.h" - -namespace chromecast { - -class DummyMinidumpGenerator : public MinidumpGenerator { - public: - // A dummy minidump generator to move an existing minidump into - // crash_uploader's monitoring path ($HOME/minidumps). The path is monitored - // with file lock-control, so that third process should not write to it - // directly. - explicit DummyMinidumpGenerator(const std::string& existing_minidump_path); - - DummyMinidumpGenerator(const DummyMinidumpGenerator&) = delete; - DummyMinidumpGenerator& operator=(const DummyMinidumpGenerator&) = delete; - - // MinidumpGenerator implementation: - // Moves the minidump located at |existing_minidump_path_| to |minidump_path|. - // Returns true if successful, false otherwise. Note that this function MUST - // be called on a thread without IO restrictions, or it will fail fatally. - bool Generate(const std::string& minidump_path) override; - - private: - const std::string existing_minidump_path_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_DUMMY_MINIDUMP_GENERATOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/dummy_minidump_generator_unittest.cc chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator_unittest.cc --- chromium-132.0.6834.110/chromecast/crash/linux/dummy_minidump_generator_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/dummy_minidump_generator_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -// 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 - -#include - -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/rand_util.h" -#include "chromecast/base/scoped_temp_file.h" -#include "chromecast/crash/linux/dummy_minidump_generator.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -TEST(DummyMinidumpGeneratorTest, GenerateFailsWithInvalidPath) { - // Create directory in which to put minidump. - base::ScopedTempDir minidump_dir; - ASSERT_TRUE(minidump_dir.CreateUniqueTempDir()); - - // Attempt to generate a minidump from an invalid path. - DummyMinidumpGenerator generator("/path/does/not/exist/minidump.dmp"); - ASSERT_FALSE(generator.Generate( - minidump_dir.GetPath().Append("minidump.dmp").value())); -} - -TEST(DummyMinidumpGeneratorTest, GenerateSucceedsWithSmallSource) { - // Create directory in which to put minidump. - base::ScopedTempDir minidump_dir; - ASSERT_TRUE(minidump_dir.CreateUniqueTempDir()); - - // Create a fake minidump file. - ScopedTempFile fake_minidump; - const std::string data("Test contents of the minidump file.\n"); - ASSERT_TRUE(base::WriteFile(fake_minidump.path(), data)); - - DummyMinidumpGenerator generator(fake_minidump.path().value()); - base::FilePath new_minidump = minidump_dir.GetPath().Append("minidump.dmp"); - EXPECT_TRUE(generator.Generate(new_minidump.value())); - - // Original file should not exist, and new file should contain original - // contents. - std::string copied_data; - EXPECT_FALSE(base::PathExists(fake_minidump.path())); - ASSERT_TRUE(base::PathExists(new_minidump)); - EXPECT_TRUE(base::ReadFileToString(new_minidump, &copied_data)); - EXPECT_EQ(data, copied_data); -} - -TEST(DummyMinidumpGeneratorTest, GenerateSucceedsWithLargeSource) { - // Create directory in which to put minidump. - base::ScopedTempDir minidump_dir; - ASSERT_TRUE(minidump_dir.CreateUniqueTempDir()); - - // Create a large fake minidump file. - ScopedTempFile fake_minidump; - size_t str_len = 32768 * 10 + 1; - const std::string data = base::RandBytesAsString(str_len); - - // Write the string to the file. - ASSERT_TRUE(base::WriteFile(fake_minidump.path(), data)); - - base::FilePath new_minidump = minidump_dir.GetPath().Append("minidump.dmp"); - DummyMinidumpGenerator generator(fake_minidump.path().value()); - ASSERT_TRUE(generator.Generate(new_minidump.value())); - - // Original file should not exist, and new file should contain original - // contents. - std::string copied_data; - EXPECT_FALSE(base::PathExists(fake_minidump.path())); - ASSERT_TRUE(base::PathExists(new_minidump)); - EXPECT_TRUE(base::ReadFileToString(new_minidump, &copied_data)); - EXPECT_EQ(data, copied_data); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/dump_info.cc chromium-132.0.6834.159/chromecast/crash/linux/dump_info.cc --- chromium-132.0.6834.110/chromecast/crash/linux/dump_info.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/dump_info.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,229 +0,0 @@ -// 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 "chromecast/crash/linux/dump_info.h" - -#include -#include -#include - -#include - -#include "base/i18n/time_formatting.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "base/time/time.h" -#include "base/values.h" - -namespace chromecast { - -namespace { - -const int kNumRequiredParams = 4; - -const char kNameKey[] = "name"; -const char kDumpTimeKey[] = "dump_time"; -const char kDumpKey[] = "dump"; -const char kUptimeKey[] = "uptime"; -const char kLogfileKey[] = "logfile"; -const char kAttachmentsKey[] = "attachments"; -const char kSuffixKey[] = "suffix"; -const char kPrevAppNameKey[] = "prev_app_name"; -const char kCurAppNameKey[] = "cur_app_name"; -const char kLastAppNameKey[] = "last_app_name"; -const char kReleaseVersionKey[] = "release_version"; -const char kBuildNumberKey[] = "build_number"; -const char kReasonKey[] = "reason"; -const char kStadiaSessionIdKey[] = "stadia_session_id"; -const char kCrashProductNameKey[] = "crash_product_name"; -const char kExecNameKey[] = "exec_name"; -const char kSignatureKey[] = "signature"; -const char kExtraInfoKey[] = "extra_info"; - -// CastLite specific data -const char kComments[] = "comments"; -const char kJsEngine[] = "js_engine"; -const char kJsBuildLabel[] = "js_build_label"; -const char kJsExceptionCategory[] = "js_exception_category"; -const char kJsExceptionDetails[] = "js_exception_details"; -const char kJsExceptionSignature[] = "js_exception_signature"; - -// Convenience wrapper around Value::Dict::FindString(), for easier use in if -// statements. If `key` is a string in `dict`, writes it to `out` and returns -// true. Leaves `out` alone and returns false otherwise. -bool FindString(const base::Value::Dict& dict, - std::string_view key, - std::string& out) { - const std::string* value = dict.FindString(key); - if (!value) - return false; - out = *value; - return true; -} - -} // namespace - -DumpInfo::DumpInfo(const base::Value* entry) : valid_(ParseEntry(entry)) {} - -DumpInfo::DumpInfo(const std::string& crashed_process_dump, - const std::string& crashed_process_logfile, - const base::Time& dump_time, - const MinidumpParams& params, - const std::vector* attachments) - : crashed_process_dump_(crashed_process_dump), - logfile_(crashed_process_logfile), - dump_time_(dump_time), - params_(params), - valid_(true) { - if (attachments) { - attachments_ = *attachments; - } -} - -DumpInfo::~DumpInfo() {} - -base::Value DumpInfo::GetAsValue() const { - base::Value::Dict result; - - result.Set(kDumpTimeKey, base::UnlocalizedTimeFormatWithPattern( - dump_time_, "yyyy-MM-dd HH:mm:ss")); - - result.Set(kDumpKey, crashed_process_dump_); - std::string uptime = base::NumberToString(params_.process_uptime); - result.Set(kUptimeKey, uptime); - result.Set(kLogfileKey, logfile_); - - base::Value::List attachments_list; - for (const auto& attachment : attachments_) { - attachments_list.Append(attachment); - } - result.Set(kAttachmentsKey, std::move(attachments_list)); - result.Set(kSuffixKey, params_.suffix); - result.Set(kPrevAppNameKey, params_.previous_app_name); - result.Set(kCurAppNameKey, params_.current_app_name); - result.Set(kLastAppNameKey, params_.last_app_name); - result.Set(kReleaseVersionKey, params_.cast_release_version); - result.Set(kBuildNumberKey, params_.cast_build_number); - result.Set(kReasonKey, params_.reason); - result.Set(kStadiaSessionIdKey, params_.stadia_session_id); - result.Set(kExecNameKey, params_.exec_name); - result.Set(kSignatureKey, params_.signature); - result.Set(kExtraInfoKey, params_.extra_info); - result.Set(kCrashProductNameKey, params_.crash_product_name); - result.Set(kComments, params_.comments); - result.Set(kJsEngine, params_.js_engine); - result.Set(kJsBuildLabel, params_.js_build_label); - result.Set(kJsExceptionCategory, params_.js_exception_category); - result.Set(kJsExceptionDetails, params_.js_exception_details); - result.Set(kJsExceptionSignature, params_.js_exception_signature); - - return base::Value(std::move(result)); -} - -bool DumpInfo::ParseEntry(const base::Value* entry) { - valid_ = false; - - if (!entry) - return false; - - const base::Value::Dict* dict = entry->GetIfDict(); - if (!dict) - return false; - - // Extract required fields. - std::string dump_time; - if (!FindString(*dict, kDumpTimeKey, dump_time)) - return false; - if (!SetDumpTimeFromString(dump_time)) - return false; - - if (!FindString(*dict, kDumpKey, crashed_process_dump_)) - return false; - - std::string uptime; - if (!FindString(*dict, kUptimeKey, uptime)) - return false; - errno = 0; - params_.process_uptime = strtoull(uptime.c_str(), nullptr, 0); - if (errno != 0) - return false; - - if (!FindString(*dict, kLogfileKey, logfile_)) - return false; - size_t num_params = kNumRequiredParams; - - // Extract all other optional fields. - const base::Value::List* attachments_list = dict->FindList(kAttachmentsKey); - if (attachments_list) { - ++num_params; - for (const auto& attachment : *attachments_list) { - attachments_.push_back(attachment.GetString()); - } - } - - std::string unused_process_name; - if (FindString(*dict, kNameKey, unused_process_name)) - ++num_params; - if (FindString(*dict, kSuffixKey, params_.suffix)) - ++num_params; - if (FindString(*dict, kPrevAppNameKey, params_.previous_app_name)) - ++num_params; - if (FindString(*dict, kCurAppNameKey, params_.current_app_name)) - ++num_params; - if (FindString(*dict, kLastAppNameKey, params_.last_app_name)) - ++num_params; - if (FindString(*dict, kReleaseVersionKey, params_.cast_release_version)) - ++num_params; - if (FindString(*dict, kBuildNumberKey, params_.cast_build_number)) - ++num_params; - if (FindString(*dict, kReasonKey, params_.reason)) - ++num_params; - if (FindString(*dict, kStadiaSessionIdKey, params_.stadia_session_id)) - ++num_params; - if (FindString(*dict, kExecNameKey, params_.exec_name)) - ++num_params; - if (FindString(*dict, kSignatureKey, params_.signature)) - ++num_params; - if (FindString(*dict, kExtraInfoKey, params_.extra_info)) - ++num_params; - if (FindString(*dict, kCrashProductNameKey, params_.crash_product_name)) - ++num_params; - if (FindString(*dict, kComments, params_.comments)) { - ++num_params; - } - if (FindString(*dict, kJsEngine, params_.js_engine)) { - ++num_params; - } - if (FindString(*dict, kJsBuildLabel, params_.js_build_label)) { - ++num_params; - } - if (FindString(*dict, kJsExceptionCategory, params_.js_exception_category)) { - ++num_params; - } - if (FindString(*dict, kJsExceptionDetails, params_.js_exception_details)) { - ++num_params; - } - if (FindString(*dict, kJsExceptionSignature, - params_.js_exception_signature)) { - ++num_params; - } - - // Disallow extraneous params - if (dict->size() != num_params) - return false; - - valid_ = true; - return true; -} - -bool DumpInfo::SetDumpTimeFromString(const std::string& timestr) { - if (base::Time::FromString(timestr.c_str(), &dump_time_)) { - return true; - } - - LOG(INFO) << "Failed to convert dump time invalid"; - return false; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/dump_info.h chromium-132.0.6834.159/chromecast/crash/linux/dump_info.h --- chromium-132.0.6834.110/chromecast/crash/linux/dump_info.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/dump_info.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_LINUX_DUMP_INFO_H_ -#define CHROMECAST_CRASH_LINUX_DUMP_INFO_H_ - -#include -#include -#include - -#include "base/time/time.h" -#include "chromecast/crash/linux/minidump_params.h" - -namespace base { -class Value; -} - -namespace chromecast { - -// Class that encapsulates the construction and parsing of dump entries -// in the log file. -class DumpInfo { - public: - // Validate the input as a valid JSON representation of DumpInfo, then - // populate the relevant fields. - explicit DumpInfo(const base::Value* entry); - - // Attempt to construct a DumpInfo object that has the following info: - // - // -crashed_process_dump: the full path of the dump written - // -crashed_process_logfile: the full path of the logfile written - // -crashed_process_attachments: the full path of the attachments - // -dump_time: the time of the dump written - // -params: a structure containing other useful crash information - DumpInfo(const std::string& crashed_process_dump, - const std::string& crashed_process_logfile, - const base::Time& dump_time, - const MinidumpParams& params, - const std::vector* attachments = nullptr); - - DumpInfo(const DumpInfo&) = delete; - DumpInfo& operator=(const DumpInfo&) = delete; - - ~DumpInfo(); - - const std::string& crashed_process_dump() const { - return crashed_process_dump_; - } - const std::string& logfile() const { return logfile_; } - const base::Time& dump_time() const { return dump_time_; } - const std::vector& attachments() const { return attachments_; } - - // Return a deep copy of the entry's JSON representation. - // The format is: - // { - // "name": , - // "dump_time": , - // "dump": , - // "uptime": , - // "logfile": , - // "attachments": [], - // "suffix": , - // "prev_app_name": , - // "cur_app_name": , - // "last_app_name": , - // "release_version": , - // "build_number": - // "reason": - // } - base::Value GetAsValue() const; - const MinidumpParams& params() const { return params_; } - bool valid() const { return valid_; } - - private: - // Checks if parsed JSON in |value| is valid, if so populates the object's - // fields from |value|. - bool ParseEntry(const base::Value* value); - bool SetDumpTimeFromString(const std::string& timestr); - - std::string crashed_process_dump_; - std::string logfile_; - std::vector attachments_; - base::Time dump_time_; - MinidumpParams params_; - bool valid_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_DUMP_INFO_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/dump_info_unittest.cc chromium-132.0.6834.159/chromecast/crash/linux/dump_info_unittest.cc --- chromium-132.0.6834.110/chromecast/crash/linux/dump_info_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/dump_info_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,221 +0,0 @@ -// 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 - -#include "base/time/time.h" -#include "base/values.h" -#include "chromecast/crash/linux/crash_testing_utils.h" -#include "chromecast/crash/linux/dump_info.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -TEST(DumpInfoTest, EmptyStringIsNotValid) { - std::unique_ptr dump_info(CreateDumpInfo("")); - ASSERT_FALSE(dump_info->valid()); -} - -TEST(DumpInfoTest, TooFewFieldsIsNotValid) { - std::unique_ptr dump_info( - CreateDumpInfo("{" - "\"name\": \"name\"," - "\"dump_time\" : \"2001-11-12 18:31:01\"," - "\"dump\": \"dump_string\"" - "}")); - ASSERT_FALSE(dump_info->valid()); -} - -TEST(DumpInfoTest, BadTimeStringIsNotValid) { - std::unique_ptr info( - CreateDumpInfo("{" - "\"name\": \"name\"," - "\"dump_time\" : \"What up\"," - "\"dump\": \"dump_string\"," - "\"uptime\": \"123456789\"," - "\"logfile\": \"logfile.log\"" - "}")); - ASSERT_FALSE(info->valid()); -} - -TEST(DumpInfoTest, AllRequiredFieldsIsValid) { - std::unique_ptr info( - CreateDumpInfo("{" - "\"dump_time\" : \"2001-11-12 18:31:01\"," - "\"dump\": \"dump_string\"," - "\"uptime\": \"123456789\"," - "\"logfile\": \"logfile.log\"" - "}")); - static constexpr base::Time::Exploded kTime = {.year = 2001, - .month = 11, - .day_of_month = 12, - .hour = 18, - .minute = 31, - .second = 1}; - base::Time dump_time; - EXPECT_TRUE(base::Time::FromLocalExploded(kTime, &dump_time)); - - ASSERT_TRUE(info->valid()); - ASSERT_EQ(dump_time, info->dump_time()); - ASSERT_EQ("dump_string", info->crashed_process_dump()); - ASSERT_EQ(123456789u, info->params().process_uptime); - ASSERT_EQ("logfile.log", info->logfile()); -} - -TEST(DumpInfoTest, EmptyProcessNameIsValid) { - std::unique_ptr dump_info( - CreateDumpInfo("{" - "\"name\": \"\"," - "\"dump_time\" : \"2001-11-12 18:31:01\"," - "\"dump\": \"dump_string\"," - "\"uptime\": \"123456789\"," - "\"logfile\": \"logfile.log\"" - "}")); - ASSERT_TRUE(dump_info->valid()); -} - -TEST(DumpInfoTest, SomeRequiredFieldsEmptyIsValid) { - std::unique_ptr info( - CreateDumpInfo("{" - "\"name\": \"name\"," - "\"dump_time\" : \"2001-11-12 18:31:01\"," - "\"dump\": \"\"," - "\"uptime\": \"\"," - "\"logfile\": \"\"" - "}")); - static constexpr base::Time::Exploded kTime = {.year = 2001, - .month = 11, - .day_of_month = 12, - .hour = 18, - .minute = 31, - .second = 1}; - base::Time dump_time; - EXPECT_TRUE(base::Time::FromLocalExploded(kTime, &dump_time)); - - ASSERT_TRUE(info->valid()); - ASSERT_EQ(dump_time, info->dump_time()); - ASSERT_EQ("", info->crashed_process_dump()); - ASSERT_EQ(0u, info->params().process_uptime); - ASSERT_EQ("", info->logfile()); -} - -TEST(DumpInfoTest, AllOptionalFieldsIsValid) { - std::unique_ptr info( - CreateDumpInfo("{" - "\"name\": \"name\"," - "\"dump_time\" : \"2001-11-12 18:31:01\"," - "\"dump\": \"dump_string\"," - "\"uptime\": \"123456789\"," - "\"logfile\": \"logfile.log\"," - "\"attachments\": [\"file1.txt\", \"file2.img\"]," - "\"suffix\": \"suffix\"," - "\"prev_app_name\": \"previous_app\"," - "\"cur_app_name\": \"current_app\"," - "\"last_app_name\": \"last_app\"," - "\"release_version\": \"RELEASE\"," - "\"build_number\": \"BUILD_NUMBER\"," - "\"reason\": \"foo\"," - "\"comments\": \"comments\"," - "\"js_engine\": \"js_engine\"," - "\"js_build_label\": \"js_build_label\"," - "\"js_exception_category\": \"js_exception_category\"," - "\"js_exception_details\": \"js_exception_details\"," - "\"js_exception_signature\": \"js_exception_signature\"" - "}")); - static constexpr base::Time::Exploded kTime = {.year = 2001, - .month = 11, - .day_of_month = 12, - .hour = 18, - .minute = 31, - .second = 1}; - base::Time dump_time; - EXPECT_TRUE(base::Time::FromLocalExploded(kTime, &dump_time)); - - ASSERT_TRUE(info->valid()); - ASSERT_EQ(dump_time, info->dump_time()); - ASSERT_EQ("dump_string", info->crashed_process_dump()); - ASSERT_EQ(123456789u, info->params().process_uptime); - ASSERT_EQ("logfile.log", info->logfile()); - - auto attachments = info->attachments(); - ASSERT_EQ(2u, attachments.size()); - ASSERT_EQ("file1.txt", attachments[0]); - ASSERT_EQ("file2.img", attachments[1]); - ASSERT_EQ("suffix", info->params().suffix); - ASSERT_EQ("previous_app", info->params().previous_app_name); - ASSERT_EQ("current_app", info->params().current_app_name); - ASSERT_EQ("last_app", info->params().last_app_name); - ASSERT_EQ("foo", info->params().reason); - - ASSERT_EQ("comments", info->params().comments); - ASSERT_EQ("js_engine", info->params().js_engine); - ASSERT_EQ("js_build_label", info->params().js_build_label); - ASSERT_EQ("js_exception_category", info->params().js_exception_category); - ASSERT_EQ("js_exception_details", info->params().js_exception_details); - ASSERT_EQ("js_exception_signature", info->params().js_exception_signature); -} - -TEST(DumpInfoTest, SomeOptionalFieldsIsValid) { - std::unique_ptr info( - CreateDumpInfo("{" - "\"name\": \"name\"," - "\"dump_time\" : \"2001-11-12 18:31:01\"," - "\"dump\": \"dump_string\"," - "\"uptime\": \"123456789\"," - "\"logfile\": \"logfile.log\"," - "\"suffix\": \"suffix\"," - "\"prev_app_name\": \"previous_app\"," - "\"comments\": \"my comments\"," - "\"js_engine\": \"js_engine version\"," - "\"js_build_label\": \"js_build_label debug\"" - "}")); - static constexpr base::Time::Exploded kTime = {.year = 2001, - .month = 11, - .day_of_month = 12, - .hour = 18, - .minute = 31, - .second = 1}; - base::Time dump_time; - EXPECT_TRUE(base::Time::FromLocalExploded(kTime, &dump_time)); - - ASSERT_TRUE(info->valid()); - ASSERT_EQ(dump_time, info->dump_time()); - ASSERT_EQ("dump_string", info->crashed_process_dump()); - ASSERT_EQ(123456789u, info->params().process_uptime); - ASSERT_EQ("logfile.log", info->logfile()); - - ASSERT_EQ("suffix", info->params().suffix); - ASSERT_EQ("previous_app", info->params().previous_app_name); - - ASSERT_EQ("my comments", info->params().comments); - ASSERT_EQ("js_engine version", info->params().js_engine); - ASSERT_EQ("js_build_label debug", info->params().js_build_label); -} - -TEST(DumpInfoTest, ExtraFieldsIsNotValid) { - std::unique_ptr info( - CreateDumpInfo("{" - "\"name\": \"name\"," - "\"dump_time\" : \"2001-11-12 18:31:01\"," - "\"dump\": \"dump_string\"," - "\"uptime\": \"123456789\"," - "\"logfile\": \"logfile.log\"," - "\"suffix\": \"suffix\"," - "\"prev_app_name\": \"previous_app\"," - "\"cur_app_name\": \"current_app\"," - "\"last_app_name\": \"last_app\"," - "\"release_version\": \"RELEASE\"," - "\"build_number\": \"BUILD_NUMBER\"," - "\"comments\": \"comments\"," - "\"js_engine\": \"js_engine\"," - "\"js_build_label\": \"js_build_label\"," - "\"js_exception_category\": \"js_exception_category\"," - "\"js_exception_details\": \"js_exception_details\"," - "\"js_exception_signature\": \"js_exception_signature\"," - "\"hello\": \"extra_field\"" - "}")); - ASSERT_FALSE(info->valid()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_generator.h chromium-132.0.6834.159/chromecast/crash/linux/minidump_generator.h --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_generator.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_generator.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_LINUX_MINIDUMP_GENERATOR_H_ -#define CHROMECAST_CRASH_LINUX_MINIDUMP_GENERATOR_H_ - -#include - -namespace chromecast { - -// An interface to generate a minidump at a given filepath. -class MinidumpGenerator { - public: - virtual ~MinidumpGenerator() {} - - // Generates a minidump file at |minidump_path|. This method should only be - // called on a thread without IO restrictions, as non-trivial implementations - // will almost certainly require IO permissions. Returns true if minidump was - // successfully generated. - virtual bool Generate(const std::string& minidump_path) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_MINIDUMP_GENERATOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_params.cc chromium-132.0.6834.159/chromecast/crash/linux/minidump_params.cc --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_params.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_params.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// 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 "chromecast/crash/linux/minidump_params.h" - -namespace chromecast { - -MinidumpParams::MinidumpParams(const uint64_t p_process_uptime, - const std::string& p_suffix, - const std::string& p_previous_app_name, - const std::string& p_current_app_name, - const std::string& p_last_app_name, - const std::string& p_cast_release_version, - const std::string& p_cast_build_number, - const std::string& p_reason, - const std::string& p_stadia_session_id, - const std::string& p_extra_info, - const std::string& p_exec_name, - const std::string& p_signature, - const std::string& p_crash_product_name, - const std::string& p_comments, - const std::string& p_js_engine, - const std::string& p_js_build_label, - const std::string& p_js_exception_category, - const std::string& p_js_exception_details, - const std::string& p_js_exception_signature) - : process_uptime(p_process_uptime), - suffix(p_suffix), - previous_app_name(p_previous_app_name), - current_app_name(p_current_app_name), - last_app_name(p_last_app_name), - cast_release_version(p_cast_release_version), - cast_build_number(p_cast_build_number), - reason(p_reason), - stadia_session_id(p_stadia_session_id), - extra_info(p_extra_info), - exec_name(p_exec_name), - signature(p_signature), - crash_product_name(p_crash_product_name), - comments(p_comments), - js_engine(p_js_engine), - js_build_label(p_js_build_label), - js_exception_category(p_js_exception_category), - js_exception_details(p_js_exception_details), - js_exception_signature(p_js_exception_signature) {} - -MinidumpParams::MinidumpParams() : process_uptime(0) {} - -MinidumpParams::MinidumpParams(const MinidumpParams& params) = default; - -MinidumpParams::~MinidumpParams() { -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_params.h chromium-132.0.6834.159/chromecast/crash/linux/minidump_params.h --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_params.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_params.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_LINUX_MINIDUMP_PARAMS_H_ -#define CHROMECAST_CRASH_LINUX_MINIDUMP_PARAMS_H_ - -#include - -#include - -namespace chromecast { - -struct MinidumpParams { - MinidumpParams(); - MinidumpParams(const uint64_t p_process_uptime, - const std::string& p_suffix, - const std::string& p_previous_app_name, - const std::string& p_current_app_name, - const std::string& p_last_app_name, - const std::string& p_cast_release_version, - const std::string& p_cast_build_number, - const std::string& p_reason, - const std::string& p_stadia_session_id, - const std::string& p_extra_info = "", - const std::string& p_exec_name = "", - const std::string& p_signature = "", - const std::string& p_crash_product_name = "", - const std::string& p_comments = "", - const std::string& p_js_engine = "", - const std::string& p_js_build_label = "", - const std::string& p_js_exception_category = "", - const std::string& p_js_exception_details = "", - const std::string& p_js_exception_signature = ""); - MinidumpParams(const MinidumpParams& params); - ~MinidumpParams(); - - uint64_t process_uptime; - std::string suffix; - std::string previous_app_name; - std::string current_app_name; - std::string last_app_name; - // Release version is in the format of "major.minor", such as "1.15". - std::string cast_release_version; - // Build number is numerical string such as "20000". - std::string cast_build_number; - // Reason for crash, if one is available. - std::string reason; - // Stadia Session ID, if a Stadia session was running at the time of crash. - std::string stadia_session_id; - std::string extra_info; - std::string exec_name; - std::string signature; - // Crash Product name, used to identify/group crash reports in go/crash. - std::string crash_product_name; - - // CastLite specific crash report data - std::string comments; - std::string js_engine; - std::string js_build_label; - std::string js_exception_category; - std::string js_exception_details; - std::string js_exception_signature; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_MINIDUMP_PARAMS_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_uploader.cc chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader.cc --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_uploader.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,384 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/crash/linux/minidump_uploader.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "base/files/file_util.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/path_service.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/cast_paths.h" -#include "chromecast/base/pref_names.h" -#include "chromecast/base/version.h" -#include "chromecast/crash/build_info.h" -#include "chromecast/crash/cast_crashdump_uploader.h" -#include "chromecast/crash/linux/dump_info.h" -#include "chromecast/public/cast_sys_info.h" -#include "components/metrics/metrics_pref_names.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/pref_service.h" -#include "components/prefs/pref_service_factory.h" - -namespace chromecast { - -namespace { - -const char kProductName[] = "Eureka"; - -const char kCrashServerProduction[] = "https://clients2.google.com/cr/report"; - -const char kVirtualChannel[] = "virtual-channel"; - -typedef std::vector> DumpList; - -std::unique_ptr CreatePrefService() { - base::FilePath prefs_path; - CHECK(base::PathService::Get(chromecast::FILE_CAST_CONFIG, &prefs_path)); - DVLOG(1) << "Loading prefs from " << prefs_path.value(); - - PrefRegistrySimple* registry = new PrefRegistrySimple; - registry->RegisterBooleanPref(prefs::kOptInStats, true); - registry->RegisterStringPref(::metrics::prefs::kMetricsClientID, ""); - registry->RegisterStringPref(kVirtualChannel, ""); - - PrefServiceFactory prefServiceFactory; - prefServiceFactory.SetUserPrefsFile( - prefs_path, base::SingleThreadTaskRunner::GetCurrentDefault().get()); - return prefServiceFactory.Create(registry); -} - -bool IsDumpObsolete(const DumpInfo& dump) { - return dump.params().cast_release_version.empty() || - dump.params().cast_build_number.empty(); -} - -} // namespace - -MinidumpUploader::MinidumpUploader(CastSysInfo* sys_info, - const std::string& server_url, - CastCrashdumpUploader* const uploader, - PrefServiceGeneratorCallback callback) - : release_channel_(sys_info->GetSystemReleaseChannel()), - product_name_(sys_info->GetProductName()), - device_model_(sys_info->GetDeviceModel()), - board_name_(sys_info->GetBoardName()), - board_revision_(sys_info->GetBoardRevision()), - manufacturer_(sys_info->GetManufacturer()), - system_version_(sys_info->GetSystemBuildNumber()), - upload_location_(!server_url.empty() ? server_url - : kCrashServerProduction), - reboot_scheduled_(false), - filestate_initialized_(false), - uploader_(uploader), - pref_service_generator_(std::move(callback)) {} - -MinidumpUploader::MinidumpUploader(CastSysInfo* sys_info, - const std::string& server_url) - : MinidumpUploader(sys_info, - server_url, - nullptr, - base::BindRepeating(&CreatePrefService)) {} - -MinidumpUploader::~MinidumpUploader() {} - -bool MinidumpUploader::UploadAllMinidumps() { - // Create the lockfile if it doesn't exist. - if (!filestate_initialized_) - filestate_initialized_ = InitializeFileState(); - - if (HasDumps()) - return AcquireLockAndDoWork(); - - return true; -} - -bool MinidumpUploader::DoWork() { - // Read the file stream line by line into a list. As each file is uploaded, - // it is subsequently deleted from the list. If the file cannot be found - // (which is a possible scenario if the file uploaded previously, but the - // device powered off before the log could be updated), it is also deleted. - // Whenever an upload fails (due to lost connection), the remaining entries - // on the list will overwrite the log file. This way, the log file reflects - // the state of the un-uploaded dumps as best as it can. - // Note: it is also possible that a dump previously uploaded exists in the - // list, *and* can also be found. This might happen if the device powered - // off before the dump can be deleted and the log updated. This is - // unpreventable. - - DumpList dumps(GetDumps()); - - int num_uploaded = 0; - - std::unique_ptr pref_service = pref_service_generator_.Run(); - const std::string& client_id( - pref_service->GetString(::metrics::prefs::kMetricsClientID)); - std::string virtual_channel(pref_service->GetString(kVirtualChannel)); - if (virtual_channel.empty()) { - virtual_channel = release_channel_; - } - bool opt_in_stats = pref_service->GetBoolean(prefs::kOptInStats); - // Handle each dump and consume it out of the structure. - while (dumps.size()) { - const DumpInfo& dump = *(dumps.front()); - const base::FilePath dump_path(dump.crashed_process_dump()); - base::FilePath log_path(dump.logfile()); - const std::vector& attachments(dump.attachments()); - - bool ignore_and_erase_dump = false; - if (!opt_in_stats) { - LOG(INFO) << "OptInStats is false, removing crash dump"; - ignore_and_erase_dump = true; - } else if (IsDumpObsolete(dump)) { - NOTREACHED(); - } - - // Ratelimiting persists across reboots. - if (reboot_scheduled_) { - LOG(INFO) << "Already rate limited with a reboot scheduled, removing " - "crash dump"; - ignore_and_erase_dump = true; - } else if (CanUploadDump()) { - // Record dump for ratelimiting - IncrementNumDumpsInCurrentPeriod(); - } else { - LOG(INFO) << "Can't upload dump due to rate limit, will reboot"; - ResetRateLimitPeriod(); - ignore_and_erase_dump = true; - reboot_scheduled_ = true; - } - - if (ignore_and_erase_dump) { - base::DeleteFile(dump_path); - base::DeleteFile(log_path); - for (const auto& attachment : attachments) { - base::FilePath attachment_path(attachment); - if (attachment_path.DirName() == dump_path.DirName()) { - base::DeleteFile(attachment_path); - } - } - dumps.erase(dumps.begin()); - continue; - } - - LOG(INFO) << "OptInStats is true, uploading crash dump"; - - if (!dump_path.empty()) { - std::optional size = base::GetFileSize(dump_path); - if (!size.has_value()) { - // either the file does not exist, or there was an error logging its - // path, or settings its permission; regardless, we can't upload it. - for (const auto& attachment : attachments) { - base::FilePath attachment_path(attachment); - if (attachment_path.DirName() == dump_path.DirName()) { - base::DeleteFile(attachment_path); - } - } - dumps.erase(dumps.begin()); - continue; - } - } - - std::stringstream comment; - if (log_path.empty()) { - comment << "Log file not specified. "; - } else { - std::optional size = base::GetFileSize(log_path); - if (!size.has_value()) { - comment << "Can't get size of " << log_path.value() << ": " - << strerror(errno); - // if we can't find the log file, don't upload the log - log_path.clear(); - } else { - comment << "Log size is " << size.value() << ". "; - } - } - - std::stringstream uptime_stream; - uptime_stream << dump.params().process_uptime; - - // attempt to upload - LOG(INFO) << "Uploading crash to " << upload_location_; - CastCrashdumpData crashdump_data; - crashdump_data.product = kProductName; - crashdump_data.version = GetVersionString( - dump.params().cast_release_version, dump.params().cast_build_number); - crashdump_data.guid = client_id; - crashdump_data.ptime = uptime_stream.str(); - crashdump_data.comments = comment.str(); - crashdump_data.minidump_pathname = dump_path.value(); - crashdump_data.crash_server = upload_location_; - - // set upload_file parameter based on exec_name - std::string upload_filename; - if (dump.params().exec_name == "kernel") { - upload_filename = "upload_file_ramoops"; - } else { - upload_filename = "upload_file_minidump"; - } - crashdump_data.upload_filename = std::move(upload_filename); - - // Depending on if a testing CastCrashdumpUploader object has been set, - // assign |g| as a reference to the correct object. - CastCrashdumpUploader vanilla(crashdump_data); - CastCrashdumpUploader& g = (uploader_ ? *uploader_ : vanilla); - - if (!log_path.empty() && !g.AddAttachment("log_file", log_path.value())) { - LOG(ERROR) << "Could not attach log file " << log_path.value(); - // Don't fail to upload just because of this. - comment << "Could not attach log file " << log_path.value() << ". "; - } - - int attachment_count = 0; - for (const auto& attachment : attachments) { - std::string label = - "attachment_" + base::NumberToString(attachment_count++); - g.AddAttachment(label, attachment); - } - - // Dump some Android properties directly into product data. - g.SetParameter("ro.revision", board_revision_); - g.SetParameter("ro.product.release.track", release_channel_); - g.SetParameter("ro.hardware", board_name_); - g.SetParameter("ro.product.name", product_name_); - g.SetParameter("device", product_name_); - g.SetParameter("ro.product.model", device_model_); - g.SetParameter("ro.product.manufacturer", manufacturer_); - g.SetParameter("ro.system.version", system_version_); - g.SetParameter("release.virtual-channel", virtual_channel); - g.SetParameter("ro.build.type", GetBuildVariant()); - // Add app state information - if (!dump.params().previous_app_name.empty()) { - g.SetParameter("previous_app", dump.params().previous_app_name); - } - if (!dump.params().current_app_name.empty()) { - g.SetParameter("current_app", dump.params().current_app_name); - } - if (!dump.params().last_app_name.empty()) { - g.SetParameter("last_app", dump.params().last_app_name); - } - if (!dump.params().reason.empty()) { - g.SetParameter("reason", dump.params().reason); - } - if (!dump.params().exec_name.empty()) { - g.SetParameter("exec_name", dump.params().exec_name); - } - if (!dump.params().stadia_session_id.empty()) { - g.SetParameter("stadia_session_id", dump.params().stadia_session_id); - } - if (!dump.params().signature.empty()) { - g.SetParameter("signature", dump.params().signature); - } - if (!dump.params().extra_info.empty()) { - std::vector pairs = base::SplitString(dump.params().extra_info, - " ", - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY - ); - for (const auto& pair : pairs) { - std::vector key_value = - base::SplitString(pair, "=", base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - if (key_value.size() == 2) { - g.SetParameter(key_value[0], key_value[1]); - } - } - } - - // Set CastLite specific crash report data. - if (!dump.params().comments.empty()) { - g.SetParameter("comments", dump.params().comments); - } - if (!dump.params().js_engine.empty()) { - g.SetParameter("js_engine", dump.params().js_engine); - } - if (!dump.params().js_build_label.empty()) { - g.SetParameter("js_build_label", dump.params().js_build_label); - } - if (!dump.params().js_exception_category.empty()) { - g.SetParameter("js_exception_category", - dump.params().js_exception_category); - } - if (!dump.params().js_exception_details.empty()) { - g.SetParameter("js_exception_details", - dump.params().js_exception_details); - } - if (!dump.params().js_exception_signature.empty()) { - // Upload as "signature" to populate the "Stable Signature" field - g.SetParameter("signature", dump.params().js_exception_signature); - } - - std::string response; - if (!g.Upload(&response)) { - // We have failed to upload this file. - // Save our state by flushing our dumps to the lockfile - // We'll come back around later and try again. - LOG(ERROR) << "Upload report failed. response: " << response; - // The increment will happen when it retries the upload. - DecrementNumDumpsInCurrentPeriod(); - SetCurrentDumps(dumps); - return true; - } - - LOG(INFO) << "Uploaded report id " << response; - // upload succeeded, so delete the entry - dumps.erase(dumps.begin()); - // delete the dump if it exists in /data/minidumps. - // (We may use a fake dump file which should not be deleted.) - if (!dump_path.empty() && dump_path.DirName() == dump_path_ && - !base::DeleteFile(dump_path)) { - PLOG(WARNING) << "remove dump " << dump_path.value() << " failed"; - } - // delete the log if exists - if (!log_path.empty() && !base::DeleteFile(log_path)) { - PLOG(WARNING) << "remove log " << log_path.value() << " failed"; - } - // delete the attachments - if (!dump_path.empty()) { - for (const auto& attachment : attachments) { - base::FilePath attachment_path(attachment); - if (attachment_path.DirName() == dump_path.DirName() && - !base::DeleteFile(attachment_path)) { - PLOG(WARNING) << "remove attachment " << attachment << " failed"; - } - } - } - ++num_uploaded; - } - - // This will simply empty the log file. - // Entries should either be skipped/deleted or processed/deleted. - SetCurrentDumps(dumps); - - // If we reach here, then the log file should be empty, and there should - // be no more dumps to upload. However, it is possible that there are - // lingering files (for example, if the dump was written, but the log - // updating failed). Since we have no entries on these files, we cannot - // upload them. Therefore we should delete them. This is also a good way - // to make sure system resources aren't being drained. - - int num_deleted = GetNumDumps(true /* delete_all_dumps */); - if (num_deleted > 0) { - LOG(WARNING) << num_deleted << " lingering dump files deleted."; - } - - LOG(INFO) << num_uploaded << " dumps were uploaded."; - return true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_uploader.h chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader.h --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_uploader.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CRASH_LINUX_MINIDUMP_UPLOADER_H_ -#define CHROMECAST_CRASH_LINUX_MINIDUMP_UPLOADER_H_ - -#include - -#include "base/functional/callback.h" -#include "chromecast/crash/linux/synchronized_minidump_manager.h" - -class PrefService; - -namespace chromecast { - -class CastCrashdumpUploader; -class CastSysInfo; - -// Class for uploading minidumps with synchronized access to the minidumps -// directory. -class MinidumpUploader : public SynchronizedMinidumpManager { - public: - using PrefServiceGeneratorCallback = - base::RepeatingCallback()>; - - // If |server_url| is empty, a default server url will be chosen. - MinidumpUploader(CastSysInfo* sys_info, const std::string& server_url); - MinidumpUploader(CastSysInfo* sys_info, - const std::string& server_url, - CastCrashdumpUploader* const uploader, - PrefServiceGeneratorCallback callback); - - MinidumpUploader(const MinidumpUploader&) = delete; - MinidumpUploader& operator=(const MinidumpUploader&) = delete; - - ~MinidumpUploader() override; - - // Attempts to upload all minidumps in the minidumps directory. Acquires a - // mutually exclusive lock on the directory before doing work to ensure that - // access to these minidumps is synchronized between other instances of this - // class. Returns true if successful, false otherwise. - bool UploadAllMinidumps(); - - bool reboot_scheduled() const { return reboot_scheduled_; } - - private: - // SynchronizedMinidumpManager implementation: - bool DoWork() override; - - // From CastSysInfo. - const std::string release_channel_; - const std::string product_name_; - const std::string device_model_; - const std::string board_name_; - const std::string board_revision_; - const std::string manufacturer_; - const std::string system_version_; - - const std::string upload_location_; - - // Whether or not a reboot should be scheduled. - bool reboot_scheduled_; - - // True if file state has been initialized. - bool filestate_initialized_; - - // Used for injecting mocks/inducing different behavior in unittests. - CastCrashdumpUploader* const uploader_; - PrefServiceGeneratorCallback pref_service_generator_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_MINIDUMP_UPLOADER_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_uploader_unittest.cc chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader_unittest.cc --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_uploader_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_uploader_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,469 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/crash/linux/minidump_uploader.h" - -#include -#include -#include - -#include "base/base_paths.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/functional/bind.h" -#include "base/test/scoped_path_override.h" -#include "base/time/time.h" -#include "chromecast/base/cast_sys_info_dummy.h" -#include "chromecast/base/pref_names.h" -#include "chromecast/crash/cast_crashdump_uploader.h" -#include "chromecast/crash/linux/crash_testing_utils.h" -#include "chromecast/public/cast_sys_info.h" -#include "components/metrics/metrics_pref_names.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/pref_service.h" -#include "components/prefs/testing_pref_service.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -const char kLockfileName[] = "lockfile"; -const char kMetadataName[] = "metadata"; -const char kMinidumpSubdir[] = "minidumps"; -const char kVirtualChannel[] = "virtual-channel"; -const char kVirtualChannelName[] = "a-virtual-chanel"; - -typedef std::vector> DumpList; - -std::unique_ptr CreateFakePrefService(bool opt_in) { - std::unique_ptr retval( - new TestingPrefServiceSimple); - retval->registry()->RegisterBooleanPref(prefs::kOptInStats, opt_in); - retval->registry()->RegisterStringPref(::metrics::prefs::kMetricsClientID, - ""); - retval->registry()->RegisterStringPref(kVirtualChannel, kVirtualChannelName); - return std::move(retval); -} - -bool DumpsAreEqual(const DumpInfo& l, const DumpInfo& r) { - return l.crashed_process_dump() == r.crashed_process_dump() && - l.logfile() == r.logfile(); -} - -class MockCastCrashdumpUploader : public CastCrashdumpUploader { - public: - explicit MockCastCrashdumpUploader(const CastCrashdumpData& data) - : CastCrashdumpUploader(data) {} - - MOCK_METHOD2(AddAttachment, - bool(const std::string& label, const std::string& filename)); - MOCK_METHOD2(SetParameter, - void(const std::string& key, const std::string& value)); - MOCK_METHOD1(Upload, bool(std::string* response)); -}; - -using ::testing::_; -using ::testing::AtLeast; -using ::testing::Return; -using ::testing::StrictMock; - -class MinidumpUploaderTest : public testing::Test { - public: - MinidumpUploaderTest() {} - ~MinidumpUploaderTest() override {} - - protected: - void SetUp() override { - // Set up a temporary directory which will be used as our fake home dir. - ASSERT_TRUE(fake_home_dir_.CreateUniqueTempDir()); - path_override_.reset( - new base::ScopedPathOverride(base::DIR_HOME, fake_home_dir_.GetPath())); - - minidump_dir_ = fake_home_dir_.GetPath().Append(kMinidumpSubdir); - lockfile_ = minidump_dir_.Append(kLockfileName); - metadata_ = minidump_dir_.Append(kMetadataName); - - // Create minidump directory. - ASSERT_TRUE(base::CreateDirectory(minidump_dir_)); - - CastCrashdumpData data; - mock_crash_uploader_.reset(new StrictMock(data)); - } - - std::unique_ptr GenerateDumpWithFiles( - const base::FilePath& minidump_path, - const base::FilePath& logfile_path, - const std::vector* attachments = nullptr) { - // Must pass in non-empty MinidumpParams to circumvent the internal checks. - std::unique_ptr dump(new DumpInfo( - minidump_path.value(), logfile_path.value(), base::Time::Now(), - MinidumpParams(0, "_", "_", "_", "_", "_", "_", "_", "_"), - attachments)); - - CHECK(AppendLockFile(lockfile_.value(), metadata_.value(), *dump)); - base::File minidump( - minidump_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - base::File logfile(logfile_path, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - CHECK(minidump.IsValid()); - CHECK(logfile.IsValid()); - - if (attachments) { - for (const auto& attachment : *attachments) { - base::File attachment_file( - base::FilePath(attachment), - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - CHECK(attachment_file.IsValid()); - } - } - - return dump; - } - - MockCastCrashdumpUploader& mock_crash_uploader() { - return *mock_crash_uploader_; - } - - CastSysInfoDummy& sys_info_dummy() { return sys_info_dummy_; } - - base::FilePath minidump_dir_; // Path to the minidump directory. - base::FilePath lockfile_; // Path to the lockfile in |minidump_dir_|. - base::FilePath metadata_; // Path to the metadata in |minidump_dir_|. - - private: - base::ScopedTempDir fake_home_dir_; - std::unique_ptr path_override_; - - CastSysInfoDummy sys_info_dummy_; - std::unique_ptr> mock_crash_uploader_; -}; - -TEST_F(MinidumpUploaderTest, AvoidsLockingWithoutDumps) { - class LockingTest : public SynchronizedMinidumpManager { - public: - explicit LockingTest(MinidumpUploader* minidump_uploader) - : minidump_uploader_(minidump_uploader) {} - ~LockingTest() override = default; - - bool Run() { return AcquireLockAndDoWork(); } - - // SynchronizedMinidumpManager implementation: - bool DoWork() override { - // This should fail if it attempts to get the lock. - return minidump_uploader_->UploadAllMinidumps(); - } - - private: - MinidumpUploader* const minidump_uploader_; - }; - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - // Will lock for the first run to initialize file state. - ASSERT_TRUE(uploader.UploadAllMinidumps()); - - LockingTest lt(&uploader); - EXPECT_TRUE(lt.Run()); -} - -TEST_F(MinidumpUploaderTest, RemovesDumpsWithoutOptIn) { - const base::FilePath& minidump_path = minidump_dir_.Append("ayy"); - const base::FilePath& logfile_path = minidump_dir_.Append("lmao"); - - // Write a dump info entry. - GenerateDumpWithFiles(minidump_path, logfile_path); - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, false)); - - // MinidumpUploader should not call upon CastCrashdumpUploader. - ASSERT_TRUE(uploader.UploadAllMinidumps()); - - // Ensure dump files were deleted, lockfile was emptied. - ASSERT_FALSE(base::PathExists(minidump_path)); - ASSERT_FALSE(base::PathExists(logfile_path)); - - std::optional size = base::GetFileSize(lockfile_); - ASSERT_TRUE(size.has_value()); - ASSERT_EQ(size.value(), 0); -} - -TEST_F(MinidumpUploaderTest, SavesDumpInfoWithUploadFailure) { - const base::FilePath& minidump_path = minidump_dir_.Append("ayy"); - const base::FilePath& logfile_path = minidump_dir_.Append("lmao"); - - // Write one entry with appropriate files. - std::unique_ptr dump( - GenerateDumpWithFiles(minidump_path, logfile_path)); - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - - // Induce an upload failure. - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("log_file", logfile_path.value())) - .WillOnce(Return(true)); - EXPECT_CALL(mock_crash_uploader(), SetParameter(_, _)).Times(AtLeast(0)); - EXPECT_CALL(mock_crash_uploader(), Upload(_)).WillOnce(Return(false)); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - - // Ensure dump files were preserved, lockfile was not emptied. - ASSERT_TRUE(base::PathExists(minidump_path)); - ASSERT_TRUE(base::PathExists(logfile_path)); - - DumpList dumps; - ASSERT_TRUE(FetchDumps(lockfile_.value(), &dumps)); - ASSERT_TRUE(DumpsAreEqual(*dump, *dumps.front())); -} - -TEST_F(MinidumpUploaderTest, SavesRemainingDumpInfoWithMidwayUploadFailure) { - const base::FilePath& minidump_path = minidump_dir_.Append("ayy"); - const base::FilePath& logfile_path = minidump_dir_.Append("lmao"); - const base::FilePath& minidump_path2 = minidump_dir_.Append("ayy2"); - const base::FilePath& logfile_path2 = minidump_dir_.Append("lmao2"); - - // Write two entries, each with their own files. - GenerateDumpWithFiles(minidump_path, logfile_path); - std::unique_ptr dump2( - GenerateDumpWithFiles(minidump_path2, logfile_path2)); - { - MinidumpUploader uploader( - &sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - - // First allow a successful upload, then induce failure. - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("log_file", logfile_path.value())) - .WillOnce(Return(true)); - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("log_file", logfile_path2.value())) - .WillOnce(Return(true)); - EXPECT_CALL(mock_crash_uploader(), SetParameter(_, _)).Times(AtLeast(0)); - EXPECT_CALL(mock_crash_uploader(), Upload(_)) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - } - - // Info should exist in the lockfile, but should only be non-uploaded dump. - DumpList dumps; - ASSERT_TRUE(FetchDumps(lockfile_.value(), &dumps)); - ASSERT_TRUE(DumpsAreEqual(*dump2, *dumps.front())); - - // Ensure uploaded files are gone, non-uploaded files remain. - ASSERT_FALSE(base::PathExists(minidump_path)); - ASSERT_FALSE(base::PathExists(logfile_path)); - ASSERT_TRUE(base::PathExists(minidump_path2)); - ASSERT_TRUE(base::PathExists(logfile_path2)); - - { - MinidumpUploader uploader( - &sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - - // Finally, upload successfully. - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("log_file", logfile_path2.value())) - .WillOnce(Return(true)); - EXPECT_CALL(mock_crash_uploader(), SetParameter(_, _)).Times(AtLeast(0)); - EXPECT_CALL(mock_crash_uploader(), Upload(_)).WillOnce(Return(true)); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - } - - // Ensure all dump files have been removed, lockfile has been emptied. - std::optional size = base::GetFileSize(lockfile_); - ASSERT_TRUE(size.has_value()); - ASSERT_EQ(size.value(), 0); - - ASSERT_TRUE(base::DeleteFile(lockfile_)); - ASSERT_TRUE(base::DeleteFile(metadata_)); - ASSERT_TRUE(base::IsDirectoryEmpty(minidump_dir_)); -} - -TEST_F(MinidumpUploaderTest, FailsUploadWithMissingMinidumpFile) { - const base::FilePath& minidump_path = minidump_dir_.Append("ayy"); - const base::FilePath& logfile_path = minidump_dir_.Append("lmao"); - - // Write one entry with appropriate files. - GenerateDumpWithFiles(minidump_path, logfile_path); - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - - // No CastCrashdumpUploader methods should be called. - ASSERT_TRUE(base::DeleteFile(minidump_path)); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - - // Ensure dump files were deleted, lockfile was emptied. - ASSERT_FALSE(base::PathExists(minidump_path)); - ASSERT_FALSE(base::PathExists(logfile_path)); - - std::optional size = base::GetFileSize(lockfile_); - ASSERT_TRUE(size.has_value()); - ASSERT_EQ(size.value(), 0); -} - -TEST_F(MinidumpUploaderTest, UploadsWithoutMissingLogFile) { - const base::FilePath& minidump_path = minidump_dir_.Append("ayy"); - const base::FilePath& logfile_path = minidump_dir_.Append("lmao"); - - // Write one entry with appropriate files. - GenerateDumpWithFiles(minidump_path, logfile_path); - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - - // Delete logfile, crash uploader should still work as intended. - ASSERT_TRUE(base::DeleteFile(logfile_path)); - EXPECT_CALL(mock_crash_uploader(), SetParameter(_, _)).Times(AtLeast(0)); - EXPECT_CALL(mock_crash_uploader(), Upload(_)).WillOnce(Return(true)); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - - // Ensure dump files were deleted, lockfile was emptied. - ASSERT_FALSE(base::PathExists(minidump_path)); - ASSERT_FALSE(base::PathExists(logfile_path)); - - std::optional size = base::GetFileSize(lockfile_); - ASSERT_TRUE(size.has_value()); - ASSERT_EQ(size.value(), 0); -} - -TEST_F(MinidumpUploaderTest, UploadsWithMultipleAttachments) { - const base::FilePath& minidump_path = minidump_dir_.Append("ayy"); - const base::FilePath& logfile_path = minidump_dir_.Append("lmao"); - std::vector attachments = { - minidump_dir_.Append("attachment-01").value(), "/tmp/attachment-02"}; - - // Write one entry with appropriate files. - GenerateDumpWithFiles(minidump_path, logfile_path, &attachments); - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - - // Allow a successful upload. - ASSERT_TRUE(base::DeleteFile(logfile_path)); - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("attachment_0", attachments[0])) - .WillOnce(Return(true)); - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("attachment_1", attachments[1])) - .WillOnce(Return(true)); - EXPECT_CALL(mock_crash_uploader(), SetParameter(_, _)).Times(AtLeast(0)); - EXPECT_CALL(mock_crash_uploader(), Upload(_)).WillOnce(Return(true)); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - - // Ensure dump files were deleted, lockfile was emptied. - ASSERT_FALSE(base::PathExists(minidump_path)); - ASSERT_FALSE(base::PathExists(logfile_path)); - ASSERT_FALSE(base::PathExists(base::FilePath(attachments[0]))); - ASSERT_TRUE(base::PathExists(base::FilePath(attachments[1]))); - - std::optional size = base::GetFileSize(lockfile_); - ASSERT_TRUE(size.has_value()); - ASSERT_EQ(size.value(), 0); -} - -TEST_F(MinidumpUploaderTest, DeletesLingeringFiles) { - const base::FilePath& minidump_path = minidump_dir_.Append("ayy"); - const base::FilePath& logfile_path = minidump_dir_.Append("lmao"); - const base::FilePath& temp1 = minidump_dir_.Append("chrome"); - const base::FilePath& temp2 = minidump_dir_.Append("cast"); - - // Create "fake" lingering files in minidump directory. - base::File generator(temp1, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - generator.Close(); - generator.Initialize(temp2, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - generator.Close(); - ASSERT_TRUE(base::PathExists(temp1)); - ASSERT_TRUE(base::PathExists(temp2)); - - // Write a real entry. - GenerateDumpWithFiles(minidump_path, logfile_path); - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("log_file", logfile_path.value())) - .WillOnce(Return(true)); - EXPECT_CALL(mock_crash_uploader(), SetParameter(_, _)).Times(AtLeast(0)); - EXPECT_CALL(mock_crash_uploader(), Upload(_)).WillOnce(Return(true)); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - - // Ensure dump/lingering files were deleted, lockfile was emptied. - ASSERT_FALSE(base::PathExists(minidump_path)); - ASSERT_FALSE(base::PathExists(logfile_path)); - ASSERT_FALSE(base::PathExists(temp1)); - ASSERT_FALSE(base::PathExists(temp2)); - - std::optional size = base::GetFileSize(lockfile_); - ASSERT_TRUE(size.has_value()); - ASSERT_EQ(size.value(), 0); -} - -TEST_F(MinidumpUploaderTest, SchedulesRebootWhenRatelimited) { - const base::FilePath& minidump_path = minidump_dir_.Append("ayy"); - const base::FilePath& logfile_path = minidump_dir_.Append("lmao"); - - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - // Generate max dumps. - for (int i = 0; i < SynchronizedMinidumpManager::kRatelimitPeriodMaxDumps + 1; - i++) - GenerateDumpWithFiles(minidump_path, logfile_path); - - // MinidumpUploader should call CastCrashdumpUploader once (other |max| dumps - // files do not exist). Reboot should be scheduled, as this is first - // ratelimit. - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("log_file", logfile_path.value())) - .WillOnce(Return(true)) - .RetiresOnSaturation(); - EXPECT_CALL(mock_crash_uploader(), SetParameter(_, _)).Times(AtLeast(0)); - EXPECT_CALL(mock_crash_uploader(), Upload(_)) - .WillOnce(Return(true)) - .RetiresOnSaturation(); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - ASSERT_TRUE(uploader.reboot_scheduled()); - - // Ensure dump files were deleted, lockfile was emptied. - ASSERT_FALSE(base::PathExists(minidump_path)); - ASSERT_FALSE(base::PathExists(logfile_path)); - - std::optional size = base::GetFileSize(lockfile_); - ASSERT_TRUE(size.has_value()); - ASSERT_EQ(size.value(), 0); - - // Generate one dump for a second pass. - GenerateDumpWithFiles(minidump_path, logfile_path); - MinidumpUploader uploader2(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - - // Since a reboot was scheduled, the rate limit was cleared. New uploads - // should be scheduled. - EXPECT_CALL(mock_crash_uploader(), - AddAttachment("log_file", logfile_path.value())) - .WillOnce(Return(true)); - EXPECT_CALL(mock_crash_uploader(), Upload(_)).WillOnce(Return(true)); - ASSERT_TRUE(uploader2.UploadAllMinidumps()); - ASSERT_FALSE(uploader2.reboot_scheduled()); - - // Ensure dump files were deleted, lockfile was emptied. - ASSERT_FALSE(base::PathExists(minidump_path)); - ASSERT_FALSE(base::PathExists(logfile_path)); - - size = base::GetFileSize(lockfile_); - ASSERT_TRUE(size.has_value()); - ASSERT_EQ(size.value(), 0); -} - -TEST_F(MinidumpUploaderTest, UploadInitializesFileState) { - MinidumpUploader uploader(&sys_info_dummy(), "", &mock_crash_uploader(), - base::BindRepeating(&CreateFakePrefService, true)); - ASSERT_TRUE(base::IsDirectoryEmpty(minidump_dir_)); - ASSERT_TRUE(uploader.UploadAllMinidumps()); - base::File lockfile(lockfile_, base::File::FLAG_OPEN | base::File::FLAG_READ); - EXPECT_TRUE(lockfile.IsValid()); - base::File metadata(lockfile_, base::File::FLAG_OPEN | base::File::FLAG_READ); - EXPECT_TRUE(metadata.IsValid()); -} - -} // namespace -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_writer.cc chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer.cc --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_writer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// 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 "chromecast/crash/linux/minidump_writer.h" - -#include "base/files/file_util.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "chromecast/base/path_utils.h" -#include "chromecast/base/process_utils.h" -#include "chromecast/crash/linux/crash_util.h" -#include "chromecast/crash/linux/dump_info.h" -#include "chromecast/crash/linux/minidump_generator.h" - -namespace chromecast { - -namespace { - -const char kDumpStateSuffix[] = ".txt.gz"; - -// Fork and run dumpstate, saving results to minidump_name + ".txt.gz". -int DumpState(const std::string& minidump_name) { - base::FilePath dumpstate_path; - if (!CrashUtil::CollectDumpstate(base::FilePath(minidump_name), - &dumpstate_path)) { - return -1; - } - return 0; -} - -} // namespace - -MinidumpWriter::MinidumpWriter(MinidumpGenerator* minidump_generator, - const std::string& minidump_filename, - const MinidumpParams& params, - DumpStateCallback dump_state_cb, - const std::vector* attachments) - : minidump_generator_(minidump_generator), - minidump_path_(minidump_filename), - params_(params), - attachments_(attachments), - dump_state_cb_(std::move(dump_state_cb)) {} - -MinidumpWriter::MinidumpWriter(MinidumpGenerator* minidump_generator, - const std::string& minidump_filename, - const MinidumpParams& params, - const std::vector* attachments) - : MinidumpWriter(minidump_generator, - minidump_filename, - params, - base::BindOnce(&DumpState), - attachments) {} - -MinidumpWriter::~MinidumpWriter() {} - -bool MinidumpWriter::DoWork() { - // If path is not absolute, append it to |dump_path_|. - if (!minidump_path_.value().empty() && minidump_path_.value()[0] != '/') - minidump_path_ = dump_path_.Append(minidump_path_); - - // The path should be a file in the |dump_path_| directory. - if (dump_path_ != minidump_path_.DirName()) { - LOG(INFO) << "The absolute path: " << minidump_path_.value() << " is not" - << "in the correct directory: " << dump_path_.value(); - return false; - } - - // Generate a minidump at the specified |minidump_path_|. - if (!minidump_generator_->Generate(minidump_path_.value())) { - LOG(ERROR) << "Generate minidump failed " << minidump_path_.value(); - return false; - } - - // Run the dumpstate callback. - DCHECK(dump_state_cb_); - std::string dumpstate_path; - if (std::move(dump_state_cb_).Run(minidump_path_.value()) < 0) { - LOG(ERROR) << "DumpState callback failed."; - } else { - dumpstate_path = minidump_path_.value() + kDumpStateSuffix; - } - - // Add attachments to dumpinfo and copy the temporary attachments to the dump - // path. - std::unique_ptr> attachment_files; - if (attachments_) { - attachment_files = std::make_unique>(); - for (auto& attachment : *attachments_) { - base::FilePath attachment_path(attachment.file_path); - if (attachment.is_static || dump_path_ == attachment_path.DirName()) { - attachment_files->push_back(attachment.file_path); - continue; - } - - base::FilePath temporary_path = - dump_path_.Append(attachment_path.BaseName()); - if (!base::CopyFile(attachment_path, temporary_path)) { - LOG(WARNING) << "Could not copy attachment " << attachment_path.value() - << " to " << temporary_path.value(); - } else { - attachment_files->push_back(temporary_path.value()); - } - } - } - - // Add this entry to the lockfile. - const DumpInfo info(minidump_path_.value(), dumpstate_path, base::Time::Now(), - params_, attachment_files.get()); - if (!AddEntryToLockFile(info)) { - LOG(ERROR) << "lockfile logging failed"; - return false; - } - - return true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_writer.h chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer.h --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_writer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_LINUX_MINIDUMP_WRITER_H_ -#define CHROMECAST_CRASH_LINUX_MINIDUMP_WRITER_H_ - -#include "base/files/file_path.h" -#include "base/functional/callback.h" -#include "chromecast/crash/linux/minidump_params.h" -#include "chromecast/crash/linux/synchronized_minidump_manager.h" - -namespace chromecast { - -class MinidumpGenerator; - -struct Attachment { - std::string file_path; - bool is_static; -}; - -// Class for writing a minidump with synchronized access to the minidumps -// directory. -class MinidumpWriter : public SynchronizedMinidumpManager { - public: - using DumpStateCallback = base::OnceCallback; - - // Constructs a writer for a minidump. If |minidump_filename| is absolute, it - // must be a path to a file in the |dump_path_| directory. Otherwise, it - // should be a filename only, in which case, |minidump_generator| creates - // a minidump at $HOME/minidumps/|minidump_filename|. |params| describes the - // minidump metadata. |dump_state_cb| is Run() to generate a log dump. Please - // see the comments on |dump_state_cb_| below for details about this - // parameter. - // This does not take ownership of |minidump_generator|. - MinidumpWriter(MinidumpGenerator* minidump_generator, - const std::string& minidump_filename, - const MinidumpParams& params, - DumpStateCallback dump_state_cb, - const std::vector* attachments = nullptr); - - // Like the constructor above, but the default implementation of - // |dump_state_cb_| is used inside DoWork(). - MinidumpWriter(MinidumpGenerator* minidump_generator, - const std::string& minidump_filename, - const MinidumpParams& params, - const std::vector* attachments = nullptr); - - MinidumpWriter(const MinidumpWriter&) = delete; - MinidumpWriter& operator=(const MinidumpWriter&) = delete; - - ~MinidumpWriter() override; - - // Acquires exclusive access to the minidumps directory and generates a - // minidump and a log to be uploaded later. Returns 0 if successful, -1 - // otherwise. - int Write() { return AcquireLockAndDoWork() ? 0 : -1; } - - protected: - // MinidumpManager implementation: - bool DoWork() override; - - private: - MinidumpGenerator* const minidump_generator_; - base::FilePath minidump_path_; - const MinidumpParams params_; - const std::vector* attachments_; - - // This callback is Run() to dump a log to |minidump_path_|.txt.gz, taking - // |minidump_path_| as a parameter. It returns 0 on success, and a negative - // integer otherwise. If a callback is not passed in the constructor, the - // default implemementaion is used. - DumpStateCallback dump_state_cb_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_MINIDUMP_WRITER_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/minidump_writer_unittest.cc chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer_unittest.cc --- chromium-132.0.6834.110/chromecast/crash/linux/minidump_writer_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/minidump_writer_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,135 +0,0 @@ -// 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 "chromecast/crash/linux/minidump_writer.h" - -#include -#include - -#include "base/base_paths.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/functional/bind.h" -#include "base/test/scoped_path_override.h" -#include "chromecast/base/scoped_temp_file.h" -#include "chromecast/crash/linux/crash_testing_utils.h" -#include "chromecast/crash/linux/dump_info.h" -#include "chromecast/crash/linux/minidump_generator.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -const char kDumplogFile[] = "dumplog"; -const char kLockfileName[] = "lockfile"; -const char kMetadataName[] = "metadata"; -const char kMinidumpSubdir[] = "minidumps"; - -class FakeMinidumpGenerator : public MinidumpGenerator { - public: - FakeMinidumpGenerator() {} - ~FakeMinidumpGenerator() override {} - - // MinidumpGenerator implementation: - bool Generate(const std::string& minidump_path) override { return true; } -}; - -int FakeDumpState(const std::string& minidump_path) { - return 0; -} - -} // namespace - -class MinidumpWriterTest : public testing::Test { - public: - MinidumpWriterTest(const MinidumpWriterTest&) = delete; - MinidumpWriterTest& operator=(const MinidumpWriterTest&) = delete; - - protected: - MinidumpWriterTest() {} - ~MinidumpWriterTest() override {} - - void SetUp() override { - // Set up a temporary directory which will be used as our fake home dir. - ASSERT_TRUE(fake_home_dir_.CreateUniqueTempDir()); - home_.reset( - new base::ScopedPathOverride(base::DIR_HOME, fake_home_dir_.GetPath())); - - minidump_dir_ = fake_home_dir_.GetPath().Append(kMinidumpSubdir); - dumplog_file_ = minidump_dir_.Append(kDumplogFile); - lockfile_path_ = minidump_dir_.Append(kLockfileName); - metadata_path_ = minidump_dir_.Append(kMetadataName); - - // Create the minidump directory - ASSERT_TRUE(base::CreateDirectory(minidump_dir_)); - - // Lockfile will be automatically created by AppendLockFile - } - - bool AppendLockFile(const DumpInfo& dump) { - return chromecast::AppendLockFile(lockfile_path_.value(), - metadata_path_.value(), dump); - } - - FakeMinidumpGenerator fake_generator_; - base::FilePath minidump_dir_; - base::FilePath dumplog_file_; - base::FilePath lockfile_path_; - base::FilePath metadata_path_; - - private: - base::ScopedTempDir fake_home_dir_; - std::unique_ptr home_; -}; - -TEST_F(MinidumpWriterTest, Write_FailsWithIncorrectMinidumpPath) { - MinidumpWriter writer(&fake_generator_, "/path/to/wrong/dir", - MinidumpParams(), base::BindOnce(&FakeDumpState)); - - ASSERT_EQ(-1, writer.Write()); -} - -TEST_F(MinidumpWriterTest, Write_FailsWithMultiLevelRelativeMinidumpPath) { - MinidumpWriter writer(&fake_generator_, "subdir/dumplog", MinidumpParams(), - base::BindOnce(&FakeDumpState)); - - ASSERT_EQ(-1, writer.Write()); -} - -TEST_F(MinidumpWriterTest, Write_SucceedsWithSimpleFilename) { - MinidumpWriter writer(&fake_generator_, "dumplog", MinidumpParams(), - base::BindOnce(&FakeDumpState)); - - ASSERT_EQ(0, writer.Write()); -} - -TEST_F(MinidumpWriterTest, Write_SucceedsWithCorrectMinidumpPath) { - MinidumpWriter writer(&fake_generator_, dumplog_file_.value(), - MinidumpParams(), base::BindOnce(&FakeDumpState)); - - ASSERT_EQ(0, writer.Write()); -} - -TEST_F(MinidumpWriterTest, Write_SucceedsWithMultipleAttachments) { - std::vector attachments{ - {minidump_dir_.Append("attachment").value(), false}, - {"/tmp/attachment_temporary", false}, - {"/tmp/attachment_static", true}, - }; - - MinidumpWriter writer(&fake_generator_, dumplog_file_.value(), - MinidumpParams(), base::BindOnce(&FakeDumpState), - &attachments); - - ASSERT_EQ(0, writer.Write()); -} - -TEST_F(MinidumpWriterTest, Write_FailsWithSubdirInCorrectPath) { - MinidumpWriter writer(&fake_generator_, - dumplog_file_.Append("subdir/logfile").value(), - MinidumpParams(), base::BindOnce(&FakeDumpState)); - ASSERT_EQ(-1, writer.Write()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/synchronized_minidump_manager.cc chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager.cc --- chromium-132.0.6834.110/chromecast/crash/linux/synchronized_minidump_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,492 +0,0 @@ -// 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 "chromecast/crash/linux/synchronized_minidump_manager.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "base/command_line.h" -#include "base/files/dir_reader_posix.h" -#include "base/files/file_util.h" -#include "base/json/json_file_value_serializer.h" -#include "base/json/json_reader.h" -#include "base/json/json_writer.h" -#include "base/logging.h" -#include "base/posix/eintr_wrapper.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "chromecast/base/path_utils.h" -#include "chromecast/crash/linux/dump_info.h" - -// if |cond| is false, returns |retval|. -#define RCHECK(cond, retval) \ - do { \ - if (!(cond)) { \ - return (retval); \ - } \ - } while (0) - -namespace chromecast { - -namespace { - -// Allows overriding default placement of minidumps in $HOME. -const char kMinidumpPathSwitch[] = "minidump-path"; - -const char kLockfileName[] = "lockfile"; -const char kMetadataName[] = "metadata"; -const char kMinidumpsDir[] = "minidumps"; - -const char kLockfileRatelimitKey[] = "ratelimit"; -const char kLockfileRatelimitPeriodStartKey[] = "period_start"; -const char kLockfileRatelimitPeriodDumpsKey[] = "period_dumps"; -const uint64_t kLockfileNumRatelimitParams = 2; - -base::FilePath GetMinidumpPath() { - base::FilePath result = - base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( - kMinidumpPathSwitch); - if (result.empty()) { - result = GetHomePathASCII(kMinidumpsDir); - } - return result; -} - -// Gets the ratelimit parameter dictionary given a deserialized |metadata|. -// Returns nullptr if invalid. -base::Value::Dict* GetRatelimitParams( - std::optional& metadata) { - if (!metadata) - return nullptr; - return metadata->FindDict(kLockfileRatelimitKey); -} - -// Returns the time of the current ratelimit period's start in |metadata|. -// Returns base::Time() if an error occurs. -base::Time GetRatelimitPeriodStart(std::optional& metadata) { - base::Value::Dict* ratelimit_params = GetRatelimitParams(metadata); - RCHECK(ratelimit_params, base::Time()); - - std::optional seconds = - ratelimit_params->FindDouble(kLockfileRatelimitPeriodStartKey); - RCHECK(seconds, base::Time()); - - // Return value of 0 indicates "not initialized", so we need to explicitly - // check for it and return time_t = 0 equivalent. - return *seconds ? base::Time::FromSecondsSinceUnixEpoch(*seconds) - : base::Time::UnixEpoch(); -} - -// Sets the time of the current ratelimit period's start in |metadata| to -// |period_start|. Returns true on success, false on error. -bool SetRatelimitPeriodStart(std::optional& metadata, - base::Time period_start) { - DCHECK(!period_start.is_null()); - - base::Value::Dict* ratelimit_params = GetRatelimitParams(metadata); - RCHECK(ratelimit_params, false); - - ratelimit_params->Set(kLockfileRatelimitPeriodStartKey, - period_start.InSecondsFSinceUnixEpoch()); - return true; -} - -// Gets the number of dumps added to |metadata| in the current ratelimit -// period. Returns < 0 on error. -int GetRatelimitPeriodDumps(std::optional& metadata) { - base::Value::Dict* ratelimit_params = GetRatelimitParams(metadata); - if (!ratelimit_params) - return -1; - std::optional period_dumps = - ratelimit_params->FindInt(kLockfileRatelimitPeriodDumpsKey); - return period_dumps.value_or(-1); -} - -// Sets the current ratelimit period's number of dumps in |metadata| to -// |period_dumps|. Returns true on success, false on error. -bool SetRatelimitPeriodDumps(std::optional& metadata, - int period_dumps) { - DCHECK_GE(period_dumps, 0); - - base::Value::Dict* ratelimit_params = GetRatelimitParams(metadata); - RCHECK(ratelimit_params, false); - - ratelimit_params->Set(kLockfileRatelimitPeriodDumpsKey, period_dumps); - - return true; -} - -// Returns true if |metadata| contains valid metadata, false otherwise. -bool ValidateMetadata(std::optional& metadata) { - RCHECK(metadata, false); - - // Validate ratelimit params - base::Value::Dict* ratelimit_params = GetRatelimitParams(metadata); - - return ratelimit_params && - ratelimit_params->size() == kLockfileNumRatelimitParams && - !GetRatelimitPeriodStart(metadata).is_null() && - GetRatelimitPeriodDumps(metadata) >= 0; -} - -// Calls flock on valid file descriptor |fd| with flag |flag|. Returns true -// on success, false on failure. -bool CallFlockOnFileWithFlag(const int fd, int flag) { - int ret = -1; - if ((ret = HANDLE_EINTR(flock(fd, flag))) < 0) - PLOG(ERROR) << "Error locking " << fd; - - return !ret; -} - -int OpenAndLockFile(const base::FilePath& path, bool write) { - int fd = -1; - const char* file = path.value().c_str(); - - if ((fd = open(file, write ? O_RDWR : O_RDONLY)) < 0) { - PLOG(ERROR) << "Error opening " << file; - } else if (!CallFlockOnFileWithFlag(fd, LOCK_EX)) { - close(fd); - fd = -1; - } - - return fd; -} - -bool UnlockAndCloseFile(const int fd) { - if (!CallFlockOnFileWithFlag(fd, LOCK_UN)) - return false; - return !close(fd); -} - -} // namespace - -// One day -const int SynchronizedMinidumpManager::kRatelimitPeriodSeconds = 24 * 3600; -const int SynchronizedMinidumpManager::kRatelimitPeriodMaxDumps = 100; - -SynchronizedMinidumpManager::SynchronizedMinidumpManager() - : dump_path_(GetMinidumpPath()), - lockfile_path_(dump_path_.Append(kLockfileName).value()), - metadata_path_(dump_path_.Append(kMetadataName).value()), - lockfile_fd_(-1) {} - -SynchronizedMinidumpManager::~SynchronizedMinidumpManager() { - // Release the lock if held. - ReleaseLockFile(); -} - -// TODO(slan): Move some of this pruning logic to ReleaseLockFile? -int SynchronizedMinidumpManager::GetNumDumps(bool delete_all_dumps) { - int num_dumps = 0; - - base::DirReaderPosix reader(dump_path_.value().c_str()); - if (!reader.IsValid()) { - LOG(ERROR) << "Unable to open directory " << dump_path_.value(); - return 0; - } - - while (reader.Next()) { - if (strcmp(reader.name(), ".") == 0 || strcmp(reader.name(), "..") == 0) - continue; - - const base::FilePath dump_file(dump_path_.Append(reader.name())); - // If file cannot be found, skip. - if (!base::PathExists(dump_file)) - continue; - - // Do not count |lockfile_path_| and |metadata_path_|. - if (lockfile_path_ != dump_file && metadata_path_ != dump_file) { - ++num_dumps; - if (delete_all_dumps) { - LOG(INFO) << "Removing " << reader.name() - << "which was not in the lockfile"; - if (!base::DeleteFile(dump_file)) - PLOG(INFO) << "Removing " << dump_file.value() << " failed"; - } - } - } - - return num_dumps; -} - -bool SynchronizedMinidumpManager::AcquireLockAndDoWork() { - bool success = false; - if (AcquireLockFile()) { - success = DoWork(); - ReleaseLockFile(); - } - return success; -} - -bool SynchronizedMinidumpManager::AcquireLockFile() { - DCHECK_LT(lockfile_fd_, 0); - // Make the directory for the minidumps if it does not exist. - base::File::Error error; - if (!CreateDirectoryAndGetError(dump_path_, &error)) { - LOG(ERROR) << "Failed to create directory " << dump_path_.value() - << ". error = " << error; - return false; - } - - // Open the lockfile. Create it if it does not exist. - base::File lockfile(lockfile_path_, base::File::FLAG_OPEN_ALWAYS); - - // If opening or creating the lockfile failed, we don't want to proceed - // with dump writing for fear of exhausting up system resources. - if (!lockfile.IsValid()) { - LOG(ERROR) << "open lockfile failed " << lockfile_path_.value(); - return false; - } - - if ((lockfile_fd_ = OpenAndLockFile(lockfile_path_, false)) < 0) { - ReleaseLockFile(); - return false; - } - - // The lockfile is open and locked. Parse it to provide subclasses with a - // record of all the current dumps. - bool create_lockfiles = false; - if (!base::PathExists(metadata_path_)) { - LOG(INFO) << "Metadata doesn't exist."; - create_lockfiles = true; - } else if (!ParseFiles()) { - LOG(ERROR) << "Lockfile did not parse correctly. "; - create_lockfiles = true; - } - if (create_lockfiles && (!InitializeFiles() || !ParseFiles())) { - LOG(ERROR) << "Failed to create a new lock file!"; - ReleaseLockFile(); - return false; - } - - DCHECK(dumps_); - DCHECK(metadata_); - - // We successfully have acquired the lock. - return true; -} - -bool SynchronizedMinidumpManager::ParseFiles() { - DCHECK_GE(lockfile_fd_, 0); - DCHECK(!dumps_); - DCHECK(!metadata_); - - std::string lockfile; - RCHECK(ReadFileToString(lockfile_path_, &lockfile), false); - - std::vector lines = base::SplitString( - lockfile, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - - base::Value::List dumps; - - // Validate dumps - for (const std::string& line : lines) { - if (line.size() == 0) - continue; - std::optional dump_info = base::JSONReader::Read(line); - RCHECK(dump_info.has_value(), false); - DumpInfo info(&dump_info.value()); - RCHECK(info.valid(), false); - dumps.Append(std::move(dump_info.value())); - } - - JSONFileValueDeserializer deserializer(metadata_path_); - int error_code = -1; - std::string error_msg; - std::unique_ptr metadata_ptr = - deserializer.Deserialize(&error_code, &error_msg); - DLOG_IF(ERROR, !metadata_ptr) - << "JSON error " << error_code << ":" << error_msg; - RCHECK(metadata_ptr, false); - RCHECK(metadata_ptr->is_dict(), false); - std::optional metadata = - std::move(*metadata_ptr).TakeDict(); - RCHECK(ValidateMetadata(metadata), false); - - dumps_ = std::move(dumps); - metadata_ = std::move(metadata); - return true; -} - -bool SynchronizedMinidumpManager::WriteFiles( - const base::Value::List& dumps, - const base::Value::Dict& metadata) { - std::string lockfile; - - for (const auto& elem : dumps) { - std::string dump_info; - bool ret = base::JSONWriter::Write(elem, &dump_info); - RCHECK(ret, false); - lockfile += dump_info; - lockfile += "\n"; // Add line seperatators - } - - if (!WriteFile(lockfile_path_, lockfile)) { - return false; - } - - JSONFileValueSerializer serializer(metadata_path_); - return serializer.Serialize(metadata); -} - -bool SynchronizedMinidumpManager::InitializeFiles() { - base::Value::Dict metadata; - - base::Value::Dict ratelimit_fields; - ratelimit_fields.Set(kLockfileRatelimitPeriodStartKey, 0.0); - ratelimit_fields.Set(kLockfileRatelimitPeriodDumpsKey, 0); - metadata.Set(kLockfileRatelimitKey, std::move(ratelimit_fields)); - - base::Value::List dumps; - - return WriteFiles(dumps, metadata); -} - -bool SynchronizedMinidumpManager::AddEntryToLockFile( - const DumpInfo& dump_info) { - DCHECK_GE(lockfile_fd_, 0); - DCHECK(dumps_); - - // Make sure dump_info is valid. - if (!dump_info.valid()) { - LOG(ERROR) << "Entry to be added is invalid"; - return false; - } - - dumps_->Append(dump_info.GetAsValue()); - return true; -} - -bool SynchronizedMinidumpManager::RemoveEntryFromLockFile(int index) { - if (index < 0 || static_cast(index) >= dumps_->size()) - return false; - dumps_->erase(dumps_->begin() + index); - return true; -} - -void SynchronizedMinidumpManager::ReleaseLockFile() { - // flock is associated with the fd entry in the open fd table, so closing - // all fd's will release the lock. To be safe, we explicitly unlock. - if (lockfile_fd_ >= 0) { - if (dumps_ && metadata_) - WriteFiles(*dumps_, *metadata_); - - UnlockAndCloseFile(lockfile_fd_); - lockfile_fd_ = -1; - } - - dumps_.reset(); - metadata_.reset(); -} - -std::vector> SynchronizedMinidumpManager::GetDumps() { - std::vector> dumps; - - for (const auto& elem : *dumps_) { - dumps.push_back(std::unique_ptr(new DumpInfo(&elem))); - } - - return dumps; -} - -bool SynchronizedMinidumpManager::SetCurrentDumps( - const std::vector>& dumps) { - dumps_->clear(); - - for (auto& dump : dumps) { - dumps_->Append(dump->GetAsValue()); - } - - return true; -} - -bool SynchronizedMinidumpManager::IncrementNumDumpsInCurrentPeriod() { - DCHECK(metadata_); - int last_dumps = GetRatelimitPeriodDumps(metadata_); - RCHECK(last_dumps >= 0, false); - - return SetRatelimitPeriodDumps(metadata_, last_dumps + 1); -} - -bool SynchronizedMinidumpManager::DecrementNumDumpsInCurrentPeriod() { - DCHECK(metadata_); - int last_dumps = GetRatelimitPeriodDumps(metadata_); - if (last_dumps > 0) { - return SetRatelimitPeriodDumps(metadata_, last_dumps - 1); - } - return true; -} - -void SynchronizedMinidumpManager::ResetRateLimitPeriod() { - SetRatelimitPeriodStart(metadata_, base::Time::Now()); - SetRatelimitPeriodDumps(metadata_, 0); -} - -bool SynchronizedMinidumpManager::CanUploadDump() { - base::Time cur_time = base::Time::Now(); - base::Time period_start = GetRatelimitPeriodStart(metadata_); - int period_dumps_count = GetRatelimitPeriodDumps(metadata_); - - // If we're in invalid state, or we passed the period, reset the ratelimit. - // When the device reboots, |cur_time| may be incorrectly reported to be a - // very small number for a short period of time. So only consider - // |period_start| invalid when |cur_time| is less if |cur_time| is not very - // close to 0. - if (period_dumps_count < 0 || - (cur_time < period_start && - cur_time.InSecondsFSinceUnixEpoch() > kRatelimitPeriodSeconds) || - (cur_time - period_start).InSeconds() >= kRatelimitPeriodSeconds) { - ResetRateLimitPeriod(); - return true; - } - - return period_dumps_count < kRatelimitPeriodMaxDumps; -} - -bool SynchronizedMinidumpManager::HasDumps() { - // Check if lockfile has entries. - std::optional size = base::GetFileSize(lockfile_path_); - if (size.has_value() && size.value() > 0) { - return true; - } - - // Check if any files are in minidump directory - base::DirReaderPosix reader(dump_path_.value().c_str()); - if (!reader.IsValid()) { - DLOG(ERROR) << "Could not open minidump dir: " << dump_path_.value(); - return false; - } - - while (reader.Next()) { - if (strcmp(reader.name(), ".") == 0 || strcmp(reader.name(), "..") == 0) - continue; - - const base::FilePath file_path = dump_path_.Append(reader.name()); - if (file_path != lockfile_path_ && file_path != metadata_path_) - return true; - } - - return false; -} - -bool SynchronizedMinidumpManager::InitializeFileState() { - if (!AcquireLockFile()) - return false; // Error logged - - ReleaseLockFile(); - return true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/synchronized_minidump_manager.h chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager.h --- chromium-132.0.6834.110/chromecast/crash/linux/synchronized_minidump_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,155 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRASH_LINUX_SYNCHRONIZED_MINIDUMP_MANAGER_H_ -#define CHROMECAST_CRASH_LINUX_SYNCHRONIZED_MINIDUMP_MANAGER_H_ - -#include -#include - -#include "base/files/file_path.h" -#include "base/values.h" -#include "chromecast/crash/linux/dump_info.h" - -namespace chromecast { - -// Abstract base class for mutually-exclusive minidump handling. Ensures -// synchronized access among instances of this class to the minidumps directory -// using a file lock. The "lockfile" also holds serialized metadata about each -// of the minidumps in the directory. Derived classes should not access the -// lockfile directly. Instead, use protected methods to query and modify the -// metadata, but only within the implementation of DoWork(). -// -// This class holds an in memory representation of the lockfile and metadata -// file when the lockfile is held. Modifier methods work on this in memory -// representation. When the lockfile is released, the in memory representations -// are written to file -// -// The lockfile file is of the following format: -// { } -// { } -// ... -// { } -// -// Note that this isn't a valid json object. It is formatted in this way so -// that producers to this file do not need to understand json. -// -// Current external producers: -// + watchdog -// -// -// The metadata file is a separate file containing a json dictionary. -// -class SynchronizedMinidumpManager { - public: - // Length of a ratelimit period in seconds. - static const int kRatelimitPeriodSeconds; - - // Number of dumps allowed per period. - static const int kRatelimitPeriodMaxDumps; - - SynchronizedMinidumpManager(const SynchronizedMinidumpManager&) = delete; - SynchronizedMinidumpManager& operator=(const SynchronizedMinidumpManager&) = - delete; - - virtual ~SynchronizedMinidumpManager(); - - protected: - SynchronizedMinidumpManager(); - - // Acquires the lock, calls DoWork(), then releases the lock when DoWork() - // returns. Derived classes should expose a method which calls this. Returns - // the status of DoWork(), or false if the lock was not successfully acquired. - bool AcquireLockAndDoWork(); - - // Derived classes must implement this method. It will be called from - // DoWorkLocked after the lock has been successfully acquired. The lockfile - // shall be accessed and mutated only through the methods below. All other - // files shall be managed as needed by the derived class. - virtual bool DoWork() = 0; - - // Get the current dumps in the lockfile. - std::vector> GetDumps(); - - // Set |dumps| as the dumps in |lockfile_|, replacing current list of dumps. - bool SetCurrentDumps(const std::vector>& dumps); - - // Serialize |dump_info| and append it to the lockfile. Note that the child - // class must only call this inside DoWork(). This should be the only method - // used to write to the lockfile. Only call this if the minidump has been - // generated in the minidumps directory successfully. Returns true on success, - // false otherwise. - bool AddEntryToLockFile(const DumpInfo& dump_info); - - // Remove the lockfile entry at |index| in the current in memory - // representation of the lockfile. If the index is invalid returns false, - // otherwise returns true. - bool RemoveEntryFromLockFile(int index); - - // Get the number of un-uploaded dumps in the dump_path directory. - // If delete_all_dumps is true, also delete all these files, this is used to - // clean lingering dump files. - int GetNumDumps(bool delete_all_dumps); - - // Increment the number of dumps in the current ratelimit period. - // Returns true on success, false on error. - bool IncrementNumDumpsInCurrentPeriod(); - - // Decrement the number of dumps in the current ratelimit period. - // Returns true on success, false on error. - bool DecrementNumDumpsInCurrentPeriod(); - - // Start a new rate-limit period, thus allowing crash uploads to proceed. - void ResetRateLimitPeriod(); - - // Returns true when dumps uploaded in current rate limit period is less than - // |kRatelimitPeriodMaxDumps|. Resets rate limit period if period time has - // elapsed. - bool CanUploadDump(); - - // Returns true when there are dumps in the lockfile or extra files in the - // dump directory, false otherwise. - // Used to avoid unnecessary file locks in consumers. - bool HasDumps(); - - // Ensures that the lockfile and metadata are in a valid state. This requires - // obtaining the lockfile. Will fail if lockfile already held. - bool InitializeFileState(); - - // Cached path for the minidumps directory. - const base::FilePath dump_path_; - - private: - // Acquire the lock file. Blocks if another process holds it, or if called - // a second time by the same process. Returns true if successful, or false - // otherwise. - bool AcquireLockFile(); - - // Parse the lockfile and metadata file, populating |dumps_| and |metadata_| - // for modifier functions to use. Returns false if an error occurred, - // otherwise returns true. This must not be called unless |this| has acquired - // the lock. - bool ParseFiles(); - - // Write deserialized |dumps| to |lockfile_path_| and the deserialized - // |metadata| to |metadata_path_|. - bool WriteFiles(const base::Value::List& dumps, - const base::Value::Dict& metadata); - - // Creates an empty lock file and an initialized metadata file. - bool InitializeFiles(); - - // Release the lock file with the associated *fd*. - void ReleaseLockFile(); - - const base::FilePath lockfile_path_; - const base::FilePath metadata_path_; - int lockfile_fd_; - std::optional metadata_; - std::optional dumps_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRASH_LINUX_SYNCHRONIZED_MINIDUMP_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/crash/linux/synchronized_minidump_manager_unittest.cc chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager_unittest.cc --- chromium-132.0.6834.110/chromecast/crash/linux/synchronized_minidump_manager_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crash/linux/synchronized_minidump_manager_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,509 +0,0 @@ -// 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 "chromecast/crash/linux/synchronized_minidump_manager.h" - -#include -#include -#include // perror -#include -#include -#include // mkdir -#include -#include - -#include -#include -#include -#include -#include - -#include "base/base_paths.h" -#include "base/files/file.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/functional/bind.h" -#include "base/memory/ptr_util.h" -#include "base/process/launch.h" -#include "base/test/scoped_path_override.h" -#include "base/threading/platform_thread.h" -#include "base/threading/thread.h" -#include "chromecast/base/scoped_temp_file.h" -#include "chromecast/crash/linux/crash_testing_utils.h" -#include "chromecast/crash/linux/dump_info.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -const char kLockfileName[] = "lockfile"; -const char kMetadataName[] = "metadata"; -const char kMinidumpSubdir[] = "minidumps"; - -typedef std::vector> DumpList; - -// A trivial implementation of SynchronizedMinidumpManager, which does no work -// to the minidump and exposes its protected members for testing. This simply -// adds an entry to the lockfile. -class SynchronizedMinidumpManagerSimple : public SynchronizedMinidumpManager { - public: - SynchronizedMinidumpManagerSimple() - : SynchronizedMinidumpManager(), - work_done_(false), - add_entry_return_code_(false), - lockfile_path_(dump_path_.Append(kLockfileName).value()) {} - ~SynchronizedMinidumpManagerSimple() override {} - - void SetDumpInfoToWrite(std::unique_ptr dump_info) { - dump_info_ = std::move(dump_info); - } - - bool DoWorkLocked() { return AcquireLockAndDoWork(); } - - // SynchronizedMinidumpManager implementation: - bool DoWork() override { - if (dump_info_) - add_entry_return_code_ = AddEntryToLockFile(*dump_info_); - work_done_ = true; - return true; - } - - // Accessors for testing. - bool HasDumps() { return SynchronizedMinidumpManager::HasDumps(); } - bool InitializeFileState() { - return SynchronizedMinidumpManager::InitializeFileState(); - } - const std::string& dump_path() { return dump_path_.value(); } - const std::string& lockfile_path() { return lockfile_path_; } - bool work_done() { return work_done_; } - bool add_entry_return_code() { return add_entry_return_code_; } - - private: - bool work_done_; - bool add_entry_return_code_; - std::string lockfile_path_; - std::unique_ptr dump_info_; -}; - -void DoWorkLockedTask(SynchronizedMinidumpManagerSimple* manager) { - manager->DoWorkLocked(); -} - -// Simple SynchronizedMinidumpManager consumer. Checks if a dump can be uploaded -// then removes it from the lockfile. -class FakeSynchronizedMinidumpUploader : public SynchronizedMinidumpManager { - public: - FakeSynchronizedMinidumpUploader() - : SynchronizedMinidumpManager(), can_upload_return_val_(false) {} - ~FakeSynchronizedMinidumpUploader() override {} - - bool DoWorkLocked() { return AcquireLockAndDoWork(); } - - // SynchronizedMinidumpManager implementation: - bool DoWork() override { - can_upload_return_val_ = CanUploadDump(); - - if (!RemoveEntryFromLockFile(0)) - return false; - - if (!IncrementNumDumpsInCurrentPeriod()) - return false; - - return true; - } - - // Accessors for testing. - bool HasDumps() { return SynchronizedMinidumpManager::HasDumps(); } - bool can_upload_return_val() { return can_upload_return_val_; } - - private: - bool can_upload_return_val_; -}; - -class SleepySynchronizedMinidumpManagerSimple - : public SynchronizedMinidumpManagerSimple { - public: - explicit SleepySynchronizedMinidumpManagerSimple(int sleep_duration_ms) - : SynchronizedMinidumpManagerSimple(), - sleep_duration_ms_(sleep_duration_ms) {} - ~SleepySynchronizedMinidumpManagerSimple() override {} - - // SynchronizedMinidumpManager implementation: - bool DoWork() override { - // The lock has been acquired. Fall asleep for |kSleepDurationMs|, then - // write the file. - base::PlatformThread::Sleep(base::Milliseconds(sleep_duration_ms_)); - return SynchronizedMinidumpManagerSimple::DoWork(); - } - - private: - const int sleep_duration_ms_; -}; - -class SynchronizedMinidumpManagerTest : public testing::Test { - public: - SynchronizedMinidumpManagerTest() {} - ~SynchronizedMinidumpManagerTest() override {} - - void SetUp() override { - // Set up a temporary directory which will be used as our fake home dir. - ASSERT_TRUE(fake_home_dir_.CreateUniqueTempDir()); - path_override_.reset( - new base::ScopedPathOverride(base::DIR_HOME, fake_home_dir_.GetPath())); - - minidump_dir_ = fake_home_dir_.GetPath().Append(kMinidumpSubdir); - lockfile_ = minidump_dir_.Append(kLockfileName); - metadata_ = minidump_dir_.Append(kMetadataName); - - // Create a minidump directory. - ASSERT_TRUE(base::CreateDirectory(minidump_dir_)); - ASSERT_TRUE(base::IsDirectoryEmpty(minidump_dir_)); - - // Create a lockfile in that directory. - base::File lockfile( - lockfile_, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); - ASSERT_TRUE(lockfile.IsValid()); - } - - protected: - base::FilePath minidump_dir_; // Path the the minidump directory. - base::FilePath lockfile_; // Path to the lockfile in |minidump_dir_|. - base::FilePath metadata_; // Path to the metadata in |minidump_dir_|. - - private: - base::ScopedTempDir fake_home_dir_; - std::unique_ptr path_override_; -}; - -// Have |producer| generate |num_dumps| while checking there are no errors. -void produce_dumps(SynchronizedMinidumpManagerSimple* producer, int num_dumps) { - for (int i = 0; i < num_dumps; ++i) { - ASSERT_TRUE(producer->DoWorkLocked()); - ASSERT_TRUE(producer->add_entry_return_code()); - } -} - -// Have |consumer| remove and process |num_dumps| while checking there are no -// errors. -void consume_dumps(FakeSynchronizedMinidumpUploader* consumer, int num_dumps) { - for (int i = 0; i < num_dumps; ++i) { - ASSERT_TRUE(consumer->DoWorkLocked()); - ASSERT_TRUE(consumer->can_upload_return_val()); - } -} - -} // namespace - -TEST_F(SynchronizedMinidumpManagerTest, FilePathsAreCorrect) { - SynchronizedMinidumpManagerSimple manager; - - // Verify file paths for directory and lock file. - ASSERT_EQ(minidump_dir_.value(), manager.dump_path()); - ASSERT_EQ(lockfile_.value(), manager.lockfile_path()); -} - -TEST_F(SynchronizedMinidumpManagerTest, AcquireLockOnNonExistentDirectory) { - // The directory was created in SetUp(). Delete it and its contents. - ASSERT_TRUE(base::DeletePathRecursively(minidump_dir_)); - ASSERT_FALSE(base::PathExists(minidump_dir_)); - - SynchronizedMinidumpManagerSimple manager; - ASSERT_TRUE(manager.DoWorkLocked()); - ASSERT_TRUE(manager.work_done()); - - // Verify the directory and the lockfile both exist. - ASSERT_TRUE(base::DirectoryExists(minidump_dir_)); - ASSERT_TRUE(base::PathExists(lockfile_)); -} - -TEST_F(SynchronizedMinidumpManagerTest, AcquireLockOnExistingEmptyDirectory) { - // The lockfile was created in SetUp(). Delete it. - ASSERT_TRUE(base::DeleteFile(lockfile_)); - ASSERT_FALSE(base::PathExists(lockfile_)); - - SynchronizedMinidumpManagerSimple manager; - ASSERT_TRUE(manager.DoWorkLocked()); - ASSERT_TRUE(manager.work_done()); - - // Verify the directory and the lockfile both exist. - ASSERT_TRUE(base::DirectoryExists(minidump_dir_)); - ASSERT_TRUE(base::PathExists(lockfile_)); -} - -TEST_F(SynchronizedMinidumpManagerTest, - AcquireLockOnExistingDirectoryWithLockfile) { - SynchronizedMinidumpManagerSimple manager; - ASSERT_TRUE(manager.DoWorkLocked()); - ASSERT_TRUE(manager.work_done()); - - // Verify the directory and the lockfile both exist. - ASSERT_TRUE(base::DirectoryExists(minidump_dir_)); - ASSERT_TRUE(base::PathExists(lockfile_)); -} - -TEST_F(SynchronizedMinidumpManagerTest, - AddEntryToLockFile_FailsWithInvalidEntry) { - // Create invalid dump info value - base::Value val{base::Value::Dict()}; - - // Test that the manager tried to log the entry and failed. - SynchronizedMinidumpManagerSimple manager; - manager.SetDumpInfoToWrite(std::make_unique(&val)); - ASSERT_TRUE(manager.DoWorkLocked()); - ASSERT_FALSE(manager.add_entry_return_code()); - - // Verify the lockfile is untouched. - DumpList dumps; - ASSERT_TRUE(FetchDumps(lockfile_.value(), &dumps)); - ASSERT_EQ(0u, dumps.size()); -} - -TEST_F(SynchronizedMinidumpManagerTest, - AddEntryToLockFile_SucceedsWithValidEntries) { - // Sample parameters. - base::Time now = base::Time::Now(); - MinidumpParams params; - - // Write the first entry. - SynchronizedMinidumpManagerSimple manager; - manager.SetDumpInfoToWrite( - std::make_unique("dump1", "log1", now, params)); - ASSERT_TRUE(manager.DoWorkLocked()); - ASSERT_TRUE(manager.add_entry_return_code()); - - // Test that the manager was successful in logging the entry. - DumpList dumps; - ASSERT_TRUE(FetchDumps(lockfile_.value(), &dumps)); - ASSERT_EQ(1u, dumps.size()); - - // Write the second entry. - manager.SetDumpInfoToWrite( - std::make_unique("dump2", "log2", now, params)); - ASSERT_TRUE(manager.DoWorkLocked()); - ASSERT_TRUE(manager.add_entry_return_code()); - - // Test that the second entry is also valid. - ASSERT_TRUE(FetchDumps(lockfile_.value(), &dumps)); - ASSERT_EQ(2u, dumps.size()); -} - -TEST_F(SynchronizedMinidumpManagerTest, AcquireLockFile_WaitsForOtherThread) { - // Create some parameters for a minidump. - base::Time now = base::Time::Now(); - MinidumpParams params; - - // Create a manager that grabs the lock then sleeps. Post a DoWork task to - // another thread. |sleepy_manager| will grab the lock and hold it for - // |sleep_time_ms|. It will then write a dump and release the lock. - const int sleep_time_ms = 100; - SleepySynchronizedMinidumpManagerSimple sleepy_manager(sleep_time_ms); - sleepy_manager.SetDumpInfoToWrite( - std::make_unique("dump", "log", now, params)); - base::Thread sleepy_thread("sleepy"); - sleepy_thread.Start(); - sleepy_thread.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&DoWorkLockedTask, base::Unretained(&sleepy_manager))); - - // Meanwhile, this thread should wait brielfy to allow the other thread to - // grab the lock. - const int concurrency_delay = 50; - base::PlatformThread::Sleep(base::Milliseconds(concurrency_delay)); - - // |sleepy_manager| has the lock by now, but has not released it. Attempt to - // grab it. DoWorkLocked() should block until |manager| has a chance to write - // the dump. - SynchronizedMinidumpManagerSimple manager; - manager.SetDumpInfoToWrite( - std::make_unique("dump", "log", now, params)); - - EXPECT_TRUE(manager.DoWorkLocked()); - EXPECT_TRUE(manager.add_entry_return_code()); - EXPECT_TRUE(manager.work_done()); - - // Check that the other manager was also successful. - EXPECT_TRUE(sleepy_manager.add_entry_return_code()); - EXPECT_TRUE(sleepy_manager.work_done()); - - // Test that both entries were logged. - DumpList dumps; - ASSERT_TRUE(FetchDumps(lockfile_.value(), &dumps)); - EXPECT_EQ(2u, dumps.size()); -} - -// TODO(slan): These tests are passing but forking them is creating duplicates -// of all tests in this thread. Figure out how to lock the file more cleanly -// from another process. -TEST_F(SynchronizedMinidumpManagerTest, - DISABLED_AcquireLockFile_WaitsForOtherProcess) { - // Create some parameters for a minidump. - base::Time now = base::Time::Now(); - MinidumpParams params; - - // Fork the process. - pid_t pid = base::ForkWithFlags(0, nullptr, nullptr); - if (pid != 0) { - // The child process should instantiate a manager which immediately grabs - // the lock, and falls aleep for some period of time, then writes a dump, - // and finally releases the lock. - SleepySynchronizedMinidumpManagerSimple sleepy_manager(100); - sleepy_manager.SetDumpInfoToWrite( - base::WrapUnique(new DumpInfo("dump", "log", now, params))); - ASSERT_TRUE(sleepy_manager.DoWorkLocked()); - ASSERT_TRUE(sleepy_manager.work_done()); - return; - } - - // Meanwhile, this process should wait brielfy to allow the other thread to - // grab the lock. - const int concurrency_delay = 50; - base::PlatformThread::Sleep(base::Milliseconds(concurrency_delay)); - - // |sleepy_manager| has the lock by now, but has not released it. Attempt to - // grab it. DoWorkLocked() should block until |manager| has a chance to write - // the dump. - SynchronizedMinidumpManagerSimple manager; - manager.SetDumpInfoToWrite( - base::WrapUnique(new DumpInfo("dump", "log", now, params))); - - EXPECT_TRUE(manager.DoWorkLocked()); - EXPECT_TRUE(manager.add_entry_return_code()); - EXPECT_TRUE(manager.work_done()); - - // Test that both entries were logged. - DumpList dumps; - ASSERT_TRUE(FetchDumps(lockfile_.value(), &dumps)); - EXPECT_EQ(2u, dumps.size()); -} - -TEST_F(SynchronizedMinidumpManagerTest, - Upload_SucceedsWhenDumpLimitsNotExceeded) { - // Sample parameters. - base::Time now = base::Time::Now(); - MinidumpParams params; - - FakeSynchronizedMinidumpUploader uploader; - SynchronizedMinidumpManagerSimple producer; - producer.SetDumpInfoToWrite( - std::make_unique("dump1", "log1", now, params)); - - const int max_dumps = SynchronizedMinidumpManager::kRatelimitPeriodMaxDumps; - produce_dumps(&producer, max_dumps); - consume_dumps(&uploader, max_dumps); -} - -TEST_F(SynchronizedMinidumpManagerTest, Upload_FailsWhenTooManyRecentDumps) { - // Sample parameters. - base::Time now = base::Time::Now(); - MinidumpParams params; - - FakeSynchronizedMinidumpUploader uploader; - SynchronizedMinidumpManagerSimple producer; - producer.SetDumpInfoToWrite( - std::make_unique("dump1", "log1", now, params)); - - const int max_dumps = SynchronizedMinidumpManager::kRatelimitPeriodMaxDumps; - produce_dumps(&producer, max_dumps + 1); - consume_dumps(&uploader, max_dumps); - - // Should fail with too many dumps - ASSERT_TRUE(uploader.DoWorkLocked()); - ASSERT_FALSE(uploader.can_upload_return_val()); -} - -TEST_F(SynchronizedMinidumpManagerTest, UploadSucceedsAfterRateLimitPeriodEnd) { - // Sample parameters. - MinidumpParams params; - - FakeSynchronizedMinidumpUploader uploader; - SynchronizedMinidumpManagerSimple producer; - producer.SetDumpInfoToWrite( - std::make_unique("dump1", "log1", base::Time::Now(), params)); - - const int iters = 3; - const int max_dumps = SynchronizedMinidumpManager::kRatelimitPeriodMaxDumps; - - for (int i = 0; i < iters; ++i) { - produce_dumps(&producer, max_dumps + 1); - consume_dumps(&uploader, max_dumps); - - // Should fail with too many dumps - ASSERT_TRUE(uploader.DoWorkLocked()); - ASSERT_FALSE(uploader.can_upload_return_val()); - - base::TimeDelta period = - base::Seconds(SynchronizedMinidumpManager::kRatelimitPeriodSeconds); - base::Time now = base::Time::Now(); - - // Half period shouldn't trigger reset - produce_dumps(&producer, 1); - SetRatelimitPeriodStart(metadata_.value(), now - period / 2); - ASSERT_TRUE(uploader.DoWorkLocked()); - ASSERT_FALSE(uploader.can_upload_return_val()); - - // Set period starting time to trigger a reset - SetRatelimitPeriodStart(metadata_.value(), now - period); - } - - produce_dumps(&producer, 1); - consume_dumps(&uploader, 1); -} - -TEST_F(SynchronizedMinidumpManagerTest, HasDumpsWithoutDumps) { - FakeSynchronizedMinidumpUploader uploader; - ASSERT_FALSE(uploader.HasDumps()); -} - -TEST_F(SynchronizedMinidumpManagerTest, HasDumpsWithDumps) { - // Sample parameters. - base::Time now = base::Time::Now(); - MinidumpParams params; - - SynchronizedMinidumpManagerSimple producer; - FakeSynchronizedMinidumpUploader uploader; - - producer.SetDumpInfoToWrite( - std::make_unique("dump1", "log1", now, params)); - - const int kNumDumps = 3; - for (int i = 0; i < kNumDumps; ++i) { - produce_dumps(&producer, 1); - ASSERT_TRUE(uploader.HasDumps()); - } - - for (int i = 0; i < kNumDumps; ++i) { - ASSERT_TRUE(uploader.HasDumps()); - consume_dumps(&uploader, 1); - } - - ASSERT_FALSE(uploader.HasDumps()); -} - -TEST_F(SynchronizedMinidumpManagerTest, HasDumpsNotInLockFile) { - SynchronizedMinidumpManagerSimple manager; - ASSERT_FALSE(manager.HasDumps()); - - // Create file in dump path. - const base::FilePath path = - base::FilePath(manager.dump_path()).Append("hello123"); - const char kFileContents[] = "foobar"; - ASSERT_TRUE(WriteFile(path, kFileContents)); - - ASSERT_TRUE(manager.HasDumps()); -} - -TEST_F(SynchronizedMinidumpManagerTest, InitializeFileState) { - SynchronizedMinidumpManagerSimple manager; - ASSERT_TRUE(base::DeleteFile(lockfile_)); - ASSERT_TRUE(base::DeleteFile(metadata_)); - ASSERT_FALSE(base::PathExists(lockfile_)); - ASSERT_FALSE(base::PathExists(metadata_)); - EXPECT_TRUE(manager.InitializeFileState()); - base::File lockfile(lockfile_, base::File::FLAG_OPEN | base::File::FLAG_READ); - EXPECT_TRUE(lockfile.IsValid()); - base::File metadata(lockfile_, base::File::FLAG_OPEN | base::File::FLAG_READ); - EXPECT_TRUE(metadata.IsValid()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crypto/signature_cache.cc chromium-132.0.6834.159/chromecast/crypto/signature_cache.cc --- chromium-132.0.6834.110/chromecast/crypto/signature_cache.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crypto/signature_cache.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// 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 "chromecast/crypto/signature_cache.h" - - -namespace chromecast { - -namespace { -const int kSignatureCacheSize = 10; -} // namespace - -SignatureCache::SignatureCache() - : contents_(kSignatureCacheSize) {} - -SignatureCache::~SignatureCache() {} - -std::string SignatureCache::Get(const std::string& wrapped_private_key, - const std::string& hash) { - std::string result; - base::AutoLock lock(lock_); - - if (wrapped_private_key != key_) - return result; - - const auto iter = contents_.Get(hash); - if (iter != contents_.end()) - result = iter->second; - - return result; -} - -void SignatureCache::Put(const std::string& wrapped_private_key, - const std::string& hash, - const std::string& signature) { - base::AutoLock lock(lock_); - - if (wrapped_private_key != key_) { - key_ = wrapped_private_key; - contents_.Clear(); - } - - contents_.Put(hash, signature); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/crypto/signature_cache.h chromium-132.0.6834.159/chromecast/crypto/signature_cache.h --- chromium-132.0.6834.110/chromecast/crypto/signature_cache.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crypto/signature_cache.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// 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. - -#ifndef CHROMECAST_CRYPTO_SIGNATURE_CACHE_H_ -#define CHROMECAST_CRYPTO_SIGNATURE_CACHE_H_ - -#include - -#include "base/containers/lru_cache.h" -#include "base/synchronization/lock.h" - -namespace chromecast { - -// Cache the signatures of hashes corresponding to a particular private key -// (only the most recent one for which a signature was cached). We expect that -// normally the same private key will be used always, however we also -// accommodate the case where the key is changed and a new key becomes current. -// In this case we flush the cache and start over with the new key. -class SignatureCache { - public: - SignatureCache(); - - SignatureCache(const SignatureCache&) = delete; - SignatureCache& operator=(const SignatureCache&) = delete; - - ~SignatureCache(); - - std::string Get(const std::string& wrapped_private_key, - const std::string& hash); - - void Put(const std::string& wrapped_private_key, - const std::string& hash, - const std::string& signature); - - private: - std::string key_; - base::Lock lock_; - base::HashingLRUCache contents_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CRYPTO_SIGNATURE_CACHE_H_ diff -Nru chromium-132.0.6834.110/chromecast/crypto/signature_cache_unittest.cc chromium-132.0.6834.159/chromecast/crypto/signature_cache_unittest.cc --- chromium-132.0.6834.110/chromecast/crypto/signature_cache_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/crypto/signature_cache_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// 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 "chromecast/crypto/signature_cache.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -TEST(SignatureCache, Hit) { - const std::string private_key1("key1"); - const std::string hash1("hash1"); - const std::string hash2("hash2"); - const std::string signature1("signature1"); - const std::string signature2("signature2"); - SignatureCache cache; - cache.Put(private_key1, hash1, signature1); - cache.Put(private_key1, hash2, signature2); - ASSERT_EQ(signature1, cache.Get(private_key1, hash1)); - ASSERT_EQ(signature2, cache.Get(private_key1, hash2)); -} - -TEST(SignatureCache, Miss) { - const std::string private_key1("key1"); - const std::string hash1("hash1"); - const std::string hash2("hash2"); - const std::string signature1("signature1"); - SignatureCache cache; - cache.Put(private_key1, hash1, signature1); - ASSERT_EQ("", cache.Get(private_key1, hash2)); -} - -TEST(SignatureCache, NewPrivateKeyHit) { - const std::string private_key1("key1"); - const std::string private_key2("key2"); - const std::string hash1("hash1"); - const std::string signature1("signature1"); - SignatureCache cache; - cache.Put(private_key1, hash1, signature1); - cache.Put(private_key2, hash1, signature1); - ASSERT_EQ(signature1, cache.Get(private_key2, hash1)); -} - -TEST(SignatureCache, NewPrivateKeyMiss) { - const std::string private_key1("key1"); - const std::string private_key2("key2"); - const std::string hash1("hash1"); - const std::string signature1("signature1"); - SignatureCache cache; - cache.Put(private_key1, hash1, signature1); - ASSERT_EQ("", cache.Get(private_key2, hash1)); - cache.Put(private_key2, hash1, signature1); - ASSERT_NE(signature1, cache.Get(private_key1, hash1)); -} - -} // namespace -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/DEPS chromium-132.0.6834.159/chromecast/device/bluetooth/DEPS --- chromium-132.0.6834.110/chromecast/device/bluetooth/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -include_rules = [ - "+chromecast/public", -] diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/bluetooth_util.cc chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/bluetooth_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,125 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/bluetooth_util.h" - -#include "base/strings/stringprintf.h" -#include "third_party/abseil-cpp/absl/strings/ascii.h" - -namespace chromecast { -namespace bluetooth { -namespace util { - -namespace { - -const int kMacAddrStrLen = 17; -const int kUuid16bitLen = 4; -const int kUuidHexNumChars = 32; -const int kUuidNumDashes = 4; - -const char kFmtUuid[] = - "%02hhx%02hhx%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx" - "-%02hhx%02hhx-%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx"; - -const char kFmtUuidNoDashes[] = - "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx" - "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx"; - -const char kFmtAddr[] = "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx"; - -} // namespace - -// https://www.bluetooth.com/specifications/assigned-numbers/service-discovery -const bluetooth_v2_shlib::Uuid kUuidBase = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, - 0x5F, 0x9B, 0x34, 0xFB}}; - -std::string AddrToString(const bluetooth_v2_shlib::Addr& addr) { - return base::StringPrintf(kFmtAddr, addr[5], addr[4], addr[3], addr[2], - addr[1], addr[0]); -} - -std::string AddrLastByteString(const bluetooth_v2_shlib::Addr& addr) { - return base::StringPrintf("%02hhx", addr[0]); -} - -bool ParseAddr(const std::string& str, bluetooth_v2_shlib::Addr* addr) { - // sscanf will incorrectly succeed if all characters except the last one are - // correct. - if (str.size() != kMacAddrStrLen || - !absl::ascii_isxdigit(static_cast(str.back()))) { - return false; - } - - int ret = sscanf(str.c_str(), kFmtAddr, &(*addr)[5], &(*addr)[4], &(*addr)[3], - &(*addr)[2], &(*addr)[1], &(*addr)[0]); - - return ret == static_cast(addr->size()); -} - -std::string UuidToString(const bluetooth_v2_shlib::Uuid& uuid) { - return base::StringPrintf(kFmtUuid, uuid[0], uuid[1], uuid[2], uuid[3], - uuid[4], uuid[5], uuid[6], uuid[7], uuid[8], - uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], - uuid[14], uuid[15]); -} - -bool ParseUuid(const std::string& str, bluetooth_v2_shlib::Uuid* uuid) { - if (str.empty()) { - return false; - } - - for (char c : str) { - if (c != '-' && !absl::ascii_isxdigit(static_cast(c))) { - return false; - } - } - - // Check for 16-bit UUID - if (str.size() == kUuid16bitLen) { - *uuid = kUuidBase; - return sscanf(str.c_str(), "%02hhx%02hhx", &(*uuid)[2], &(*uuid)[3]) == 2; - } - - if (str.size() > kUuidHexNumChars && - str.size() != kUuidHexNumChars + kUuidNumDashes) { - return false; - } - - std::string no_dashes = str; - no_dashes.erase(std::remove(no_dashes.begin(), no_dashes.end(), '-'), - no_dashes.end()); - - if (no_dashes.size() != kUuidHexNumChars) { - return false; - } - - int ret = - sscanf(no_dashes.c_str(), kFmtUuidNoDashes, &(*uuid)[0], &(*uuid)[1], - &(*uuid)[2], &(*uuid)[3], &(*uuid)[4], &(*uuid)[5], &(*uuid)[6], - &(*uuid)[7], &(*uuid)[8], &(*uuid)[9], &(*uuid)[10], &(*uuid)[11], - &(*uuid)[12], &(*uuid)[13], &(*uuid)[14], &(*uuid)[15]); - - return ret == static_cast(uuid->size()); -} - -bluetooth_v2_shlib::Uuid UuidFromInt16(uint16_t uuid) { - bluetooth_v2_shlib::Uuid ret = kUuidBase; - ret[2] = (uuid >> 8) & 0xff; - ret[3] = uuid & 0xff; - return ret; -} - -bluetooth_v2_shlib::Uuid UuidFromInt32(uint32_t uuid) { - bluetooth_v2_shlib::Uuid ret = kUuidBase; - ret[0] = (uuid >> 24) & 0xff; - ret[1] = (uuid >> 16) & 0xff; - ret[2] = (uuid >> 8) & 0xff; - ret[3] = uuid & 0xff; - return ret; -} - -} // namespace util -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/bluetooth_util.h chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/bluetooth_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_BLUETOOTH_UTIL_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_BLUETOOTH_UTIL_H_ - -#include - -#include "chromecast/public/bluetooth/bluetooth_types.h" - -namespace chromecast { -namespace bluetooth { -namespace util { - -// https://www.bluetooth.com/specifications/assigned-numbers/service-discovery -// BASE_UUID 00000000-0000-1000-8000-00805F9B34FB -extern const bluetooth_v2_shlib::Uuid kUuidBase; - -// Format |addr| into the canonical text representation of a 48 bit mac address -// (1a:2b:3c:4e:5f:60). Hex digits are lower case. -std::string AddrToString(const bluetooth_v2_shlib::Addr& addr); - -// Get the last byte of |addr| as a hex string. This is used for logging since -// full address is PII. -std::string AddrLastByteString(const bluetooth_v2_shlib::Addr& addr); - -// Parse |str| as the canonical text representation of a 48 bit mac -// address (1a:2b:3c:4e:5f:60). Hex digits may be either upper or lower case. -// -// Returns true iff |str| is a valid mac address. -bool ParseAddr(const std::string& str, bluetooth_v2_shlib::Addr* addr); - -// Format |uuid| as the canonical big endian text format (with lowercase hex -// digits). -// 123e4567-e89b-12d3-a456-426655440000 -std::string UuidToString(const bluetooth_v2_shlib::Uuid& uuid); - -// Parses UUIDs of the following formats: -// Canonical big endian: 123e4567-e89b-12d3-a456-426655440000 -// Bluetooth SIG 16-bit UUID: FEA0 -// Big endian no dashes: 123e4567e89b12d3a456426655440000 -// -// Hex digits may be either upper or lower case. -// Returns true iff |str| is a UUID. -bool ParseUuid(const std::string& str, bluetooth_v2_shlib::Uuid* uuid); - -// Return full UUID object corresponding to 16 bit uuid. -bluetooth_v2_shlib::Uuid UuidFromInt16(uint16_t uuid); - -// Return full UUID object corresponding to 32 bit uuid. -bluetooth_v2_shlib::Uuid UuidFromInt32(uint32_t uuid); - -} // namespace util -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_BLUETOOTH_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/bluetooth_util_test.cc chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util_test.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/bluetooth_util_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/bluetooth_util_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace bluetooth { -namespace util { - -TEST(BluetoothUtilTest, AddrStringConversion) { - const char kBadAddr1[] = "foo"; - const char kBadAddr2[] = "aa:bb:cc:dd:ee:ag"; - - const char kGoodAddr1[] = "aa:bb:cc:dd:ee:ff"; - const char kGoodAddr2[] = "AA:BB:CC:DD:EE:FF"; - const char kGoodAddr3[] = "A1:B2:C3:D4:E5:F6"; - const char kGoodAddr4[] = "a1:b2:c3:d4:e5:f6"; - - const bluetooth_v2_shlib::Addr kGoodBytes1 = { - {0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa}}; - const bluetooth_v2_shlib::Addr kGoodBytes3 = { - {0xf6, 0xe5, 0xd4, 0xc3, 0xb2, 0xa1}}; - - bluetooth_v2_shlib::Addr addr; - EXPECT_FALSE(ParseAddr(kBadAddr1, &addr)); - EXPECT_FALSE(ParseAddr(kBadAddr2, &addr)); - - EXPECT_TRUE(ParseAddr(kGoodAddr1, &addr)); - EXPECT_EQ(kGoodBytes1, addr); - EXPECT_EQ(kGoodAddr1, AddrToString(addr)); - - EXPECT_TRUE(ParseAddr(kGoodAddr2, &addr)); - EXPECT_EQ(kGoodBytes1, addr); - EXPECT_EQ(kGoodAddr1, AddrToString(addr)); - - EXPECT_TRUE(ParseAddr(kGoodAddr3, &addr)); - EXPECT_EQ(kGoodBytes3, addr); - EXPECT_EQ(kGoodAddr4, AddrToString(addr)); -} - -TEST(BluetoothUtilTest, UuidStringConversion) { - const char kBadUuid1[] = "hello"; - const char kBadUuid2[] = "a822c885-af02-c780-9d4d-bd9a1fa06d9z"; - const char kBadUuid3[] = "00000000-0000-0000-0000-0x0000000000"; - const char kBadUuid4[] = "123e-567-e89b-12d3-a456-426655440000"; - const char kBadUuid5[] = "123e456--e89b-12d3-a456-426655440000"; - const char kBadUuid6[] = "123e4567--e89b-12d3-a456-426655440000"; - - const char kUuid1[] = "123e4567-e89b-12d3-a456-426655440000"; - const char kUuid2[] = "123E4567-E89B-12D3-A456-426655440000"; - const char kUuid3[] = "a822c885-af02-c780-9d4d-bd9a1fa06d93"; - const char kUuid4[] = "FE34"; - const char kUuid5[] = "a822c885af02c7809d4dbd9a1fa06d93"; - - const bluetooth_v2_shlib::Uuid kGoodBytes1 = { - {0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, - 0x55, 0x44, 0x00, 0x00}}; - const bluetooth_v2_shlib::Uuid kGoodBytes3 = { - {0xa8, 0x22, 0xc8, 0x85, 0xaf, 0x02, 0xc7, 0x80, 0x9d, 0x4d, 0xbd, 0x9a, - 0x1f, 0xa0, 0x6d, 0x93}}; - - const bluetooth_v2_shlib::Uuid kGoodBytes4 = { - {0x00, 0x00, 0xfe, 0x34, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, - 0x5F, 0x9B, 0x34, 0xFB}}; - - bluetooth_v2_shlib::Uuid uuid; - EXPECT_FALSE(ParseUuid(kBadUuid1, &uuid)); - EXPECT_FALSE(ParseUuid(kBadUuid2, &uuid)); - EXPECT_FALSE(ParseUuid(kBadUuid3, &uuid)); - EXPECT_FALSE(ParseUuid(kBadUuid4, &uuid)); - EXPECT_FALSE(ParseUuid(kBadUuid5, &uuid)); - EXPECT_FALSE(ParseUuid(kBadUuid6, &uuid)); - - EXPECT_TRUE(ParseUuid(kUuid1, &uuid)); - EXPECT_EQ(kGoodBytes1, uuid); - EXPECT_EQ(kUuid1, UuidToString(uuid)); - - EXPECT_TRUE(ParseUuid(kUuid2, &uuid)); - EXPECT_EQ(kGoodBytes1, uuid); - EXPECT_EQ(kUuid1, UuidToString(uuid)); - - EXPECT_TRUE(ParseUuid(kUuid3, &uuid)); - EXPECT_EQ(kGoodBytes3, uuid); - EXPECT_EQ(kUuid3, UuidToString(uuid)); - - EXPECT_TRUE(ParseUuid(kUuid4, &uuid)); - EXPECT_EQ(kGoodBytes4, uuid); - - EXPECT_TRUE(ParseUuid(kUuid5, &uuid)); - EXPECT_EQ(kGoodBytes3, uuid); - EXPECT_EQ(kUuid3, UuidToString(uuid)); -} - -TEST(BluetoothUtilTest, UuidFromInt16) { - static const bluetooth_v2_shlib::Uuid kExpected = { - {0x00, 0x00, 0x11, 0x0a, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, - 0x5F, 0x9B, 0x34, 0xFB}}; - EXPECT_EQ(kExpected, UuidFromInt16(0x110a)); -} - -TEST(BluetoothUtilTest, UuidFromInt32) { - static const bluetooth_v2_shlib::Uuid kExpected = { - {0x01, 0x02, 0x03, 0x04, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, - 0x5F, 0x9B, 0x34, 0xFB}}; - EXPECT_EQ(kExpected, UuidFromInt32(0x01020304)); -} - -} // namespace util -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/DEPS chromium-132.0.6834.159/chromecast/device/bluetooth/le/DEPS --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -include_rules = [ - "+third_party/re2", -] diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/ble_notification_logger.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_notification_logger.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/ble_notification_logger.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_notification_logger.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/ble_notification_logger.h" - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "chromecast/device/bluetooth/le/remote_characteristic.h" -#include "chromecast/device/bluetooth/le/remote_device.h" - -namespace chromecast { -namespace bluetooth { - -// static -constexpr base::TimeDelta BleNotificationLogger::kMinLogInterval; - -BleNotificationLogger::BleNotificationLogger(GattClientManager* gcm) - : gcm_(gcm), weak_factory_(this) { - DCHECK(gcm); - gcm_->AddObserver(this); -} - -BleNotificationLogger::~BleNotificationLogger() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - gcm_->RemoveObserver(this); -} - -void BleNotificationLogger::OnCharacteristicNotification( - scoped_refptr device, - scoped_refptr characteristic, - std::vector value) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - ++device_to_char_uuid_to_count_[device->addr()][characteristic->uuid()]; - - MaybeLogHistogramState(); -} - -void BleNotificationLogger::MaybeLogHistogramState() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (device_to_char_uuid_to_count_.empty()) { - return; - } - - auto now = base::TimeTicks::Now(); - base::TimeTicks next_time_can_log = last_log_time_ + kMinLogInterval; - if (now < next_time_can_log) { - auto time_till_next_log = next_time_can_log - now; - // Schedule a log at the next time we are allowed to. - log_timer_.Start( - FROM_HERE, time_till_next_log, - base::BindOnce(&BleNotificationLogger::MaybeLogHistogramState, - weak_factory_.GetWeakPtr())); - return; - } - - LOG(INFO) << "BLE notifications: "; - for (const auto& device : device_to_char_uuid_to_count_) { - LOG(INFO) << util::AddrLastByteString(device.first); - for (const auto& characteristic : device.second) { - LOG(INFO) << " " << util::UuidToString(characteristic.first) << " " - << characteristic.second; - } - } - - device_to_char_uuid_to_count_.clear(); - last_log_time_ = now; -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/ble_notification_logger.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_notification_logger.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/ble_notification_logger.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_notification_logger.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_BLE_NOTIFICATION_LOGGER_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_BLE_NOTIFICATION_LOGGER_H_ - -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "chromecast/device/bluetooth/le/gatt_client_manager.h" - -namespace chromecast { -namespace bluetooth { - -class BleNotificationLogger : public GattClientManager::Observer { - public: - static constexpr auto kMinLogInterval = base::Minutes(1); - - explicit BleNotificationLogger(GattClientManager* gcm); - - BleNotificationLogger(const BleNotificationLogger&) = delete; - BleNotificationLogger& operator=(const BleNotificationLogger&) = delete; - - ~BleNotificationLogger() override; - - // GattClientManager::Observer implementation: - void OnCharacteristicNotification( - scoped_refptr device, - scoped_refptr characteristic, - std::vector value) override; - - private: - using Addr = bluetooth_v2_shlib::Addr; - using Uuid = bluetooth_v2_shlib::Uuid; - - void MaybeLogHistogramState(); - - SEQUENCE_CHECKER(sequence_checker_); - - const raw_ptr gcm_; - - base::TimeTicks last_log_time_; - base::OneShotTimer log_timer_; - - // Key: Device address, Value: Map[Key: Characteristic UUID, Value: count] - std::map> device_to_char_uuid_to_count_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_BLE_NOTIFICATION_LOGGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/ble_types.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_types.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/ble_types.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/ble_types.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// 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. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_BLE_TYPES_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_BLE_TYPES_H_ - -#include - -#include "build/build_config.h" - -namespace chromecast { -namespace bluetooth { - -#if BUILDFLAG(IS_FUCHSIA) -using HandleId = uint64_t; -#else -using HandleId = uint16_t; -#endif - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_BLE_TYPES_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/gatt_client_manager.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/gatt_client_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,140 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_GATT_CLIENT_MANAGER_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_GATT_CLIENT_MANAGER_H_ - -#include -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/scoped_refptr.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/device/bluetooth/le/remote_characteristic.h" -#include "chromecast/device/bluetooth/le/remote_device.h" -#include "chromecast/device/bluetooth/le/remote_service.h" -#include "chromecast/public/bluetooth/bluetooth_types.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -namespace bluetooth_v2_shlib { -class GattClient; -} // namespace bluetooth_v2_shlib - -namespace bluetooth { - -class BluetoothManagerPlatform; -class LeScanManager; - -class GattClientManager { - public: - class Observer { - public: - // Called when the connection state changes for |device|. - virtual void OnConnectChanged(scoped_refptr device, - bool connected) {} - - // Called when the bond state changes for |device|. - virtual void OnBondChanged(scoped_refptr device, - bool bonded) {} - - // Called when the connection MTU changes for |device|. - virtual void OnMtuChanged(scoped_refptr device, int mtu) {} - - // Called when the device |device|'s service list changed. |services| is the - // new list of services, and any old ones should be considered invalidated. - virtual void OnServicesUpdated( - scoped_refptr device, - std::vector> services) {} - - // Called when |device| has a notification on |characteristic| with |value|. - virtual void OnCharacteristicNotification( - scoped_refptr device, - scoped_refptr characteristic, - std::vector value) {} - - // Called when a connection is requested. - virtual void OnConnectInitated(const bluetooth_v2_shlib::Addr& addr) {} - - virtual ~Observer() = default; - }; - - static std::unique_ptr Create( - bluetooth_v2_shlib::GattClient* gatt_client, - BluetoothManagerPlatform* bluetooth_manager, - LeScanManager* le_scan_manager); - - GattClientManager(const GattClientManager&) = delete; - GattClientManager& operator=(const GattClientManager&) = delete; - - virtual ~GattClientManager() = default; - - virtual void Initialize( - scoped_refptr io_task_runner) = 0; - virtual void Finalize() = 0; - - virtual void AddObserver(Observer* o) = 0; - virtual void RemoveObserver(Observer* o) = 0; - - // Get a RemoteDevice object corresponding to |addr| for performing GATT - // operations. |cb| will be run on the callers thread. Callbacks passed into - // methods on RemoteDevice and its subobjects (RemoteService, - // RemoteCharacteristic, RemoteDescriptor) will also be run on the thread - // which called the specific method. - virtual void GetDevice( - const bluetooth_v2_shlib::Addr& addr, - base::OnceCallback)> cb) = 0; - - // TODO(bcf): Deprecated. Replace usage with async version. - virtual scoped_refptr GetDeviceSync( - const bluetooth_v2_shlib::Addr& addr) = 0; - - // Returns the currently connected devices. - using GetConnectDevicesCallback = - base::OnceCallback>)>; - virtual void GetConnectedDevices(GetConnectDevicesCallback cb) = 0; - - // Returns the number of devices which are currently connected. - // TODO(bcf): Deprecated in favor of |GetConnectedDevices|. - virtual void GetNumConnected(base::OnceCallback cb) const = 0; - - // Called when we initiate connection to a remote device. - virtual void NotifyConnect(const bluetooth_v2_shlib::Addr& addr) = 0; - - // Used to notify |this| of currently bonded devices on initialization. - // Note that these devices might not be connected. - virtual void NotifyBonded(const bluetooth_v2_shlib::Addr& addr) = 0; - - // Returns true if |addr| corresponds to a connected BLE device. - virtual bool IsConnectedLeDevice(const bluetooth_v2_shlib::Addr& addr) = 0; - - // Enable or disable GATT client connectability. Returns |true| if successful - // otherwise |false|. - virtual bool SetGattClientConnectable(bool connectable) = 0; - - // Disconnect all connected devices. Callback will return |true| if all - // devices are disconnected, otherwise false. - // When disabling GATT client, caller should call - // SetGattClientConnectable(false) before calling DisconnectAll so that - // upcoming GATT client connections can also be blocked. - using StatusCallback = base::OnceCallback; - virtual void DisconnectAll(StatusCallback cb) = 0; - - // TODO(bcf): Deprecated. Should be removed now that this class may be used - // from any thread. - virtual scoped_refptr task_runner() = 0; - - protected: - GattClientManager() = default; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_GATT_CLIENT_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/gatt_client_manager_impl.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/gatt_client_manager_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,629 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/gatt_client_manager_impl.h" - -#include -#include - -#include "base/containers/contains.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "chromecast/device/bluetooth/le/remote_characteristic_impl.h" -#include "chromecast/device/bluetooth/le/remote_descriptor_impl.h" -#include "chromecast/device/bluetooth/le/remote_device_impl.h" -#include "chromecast/device/bluetooth/le/remote_service_impl.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -namespace { - -const int kMaxDevicesInQueue = 6; - -#define RUN_ON_IO_THREAD(method, ...) \ - io_task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&GattClientManagerImpl::method, weak_this_, \ - ##__VA_ARGS__)); - -#define MAKE_SURE_IO_THREAD(method, ...) \ - DCHECK(io_task_runner_); \ - if (!io_task_runner_->BelongsToCurrentThread()) { \ - RUN_ON_IO_THREAD(method, ##__VA_ARGS__) \ - return; \ - } - -#define CHECK_DEVICE_EXISTS_IT(it) \ - do { \ - if (it == addr_to_device_.end()) { \ - LOG(ERROR) << __func__ << ": No such device"; \ - return; \ - } \ - } while (0) - -} // namespace - -// static -constexpr base::TimeDelta GattClientManagerImpl::kConnectTimeout; -constexpr base::TimeDelta GattClientManagerImpl::kDisconnectTimeout; -constexpr base::TimeDelta GattClientManagerImpl::kReadRemoteRssiTimeout; - -// static -std::unique_ptr GattClientManager::Create( - bluetooth_v2_shlib::GattClient* gatt_client, - BluetoothManagerPlatform* bluetooth_manager, - LeScanManager* le_scan_manager) { - return std::make_unique(gatt_client); -} - -GattClientManagerImpl::GattClientManagerImpl( - bluetooth_v2_shlib::GattClient* gatt_client) - : gatt_client_(gatt_client), - observers_(new base::ObserverListThreadSafe()), - notification_logger_(this), - weak_factory_( - std::make_unique>(this)) { - weak_this_ = weak_factory_->GetWeakPtr(); -} - -GattClientManagerImpl::~GattClientManagerImpl() {} - -void GattClientManagerImpl::Initialize( - scoped_refptr io_task_runner) { - io_task_runner_ = std::move(io_task_runner); - InitializeOnIoThread(); -} - -void GattClientManagerImpl::InitializeOnIoThread() { - MAKE_SURE_IO_THREAD(InitializeOnIoThread); - gatt_client_->SetDelegate(this); -} - -void GattClientManagerImpl::Finalize() { - FinalizeOnIoThread(); -} - -void GattClientManagerImpl::AddObserver(Observer* o) { - observers_->AddObserver(o); -} - -void GattClientManagerImpl::RemoveObserver(Observer* o) { - observers_->RemoveObserver(o); -} - -void GattClientManagerImpl::GetDevice( - const bluetooth_v2_shlib::Addr& addr, - base::OnceCallback)> cb) { - MAKE_SURE_IO_THREAD(GetDevice, addr, BindToCurrentSequence(std::move(cb))); - DCHECK(cb); - std::move(cb).Run(GetDeviceSync(addr)); -} - -scoped_refptr GattClientManagerImpl::GetDeviceSync( - const bluetooth_v2_shlib::Addr& addr) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - auto it = addr_to_device_.find(addr); - if (it != addr_to_device_.end()) { - return it->second.get(); - } - - scoped_refptr new_device( - new RemoteDeviceImpl(addr, weak_this_, io_task_runner_)); - addr_to_device_[addr] = new_device; - return new_device; -} - -void GattClientManagerImpl::GetConnectedDevices(GetConnectDevicesCallback cb) { - MAKE_SURE_IO_THREAD(GetConnectedDevices, - BindToCurrentSequence(std::move(cb))); - std::vector> devices; - for (const auto& device : addr_to_device_) { - if (device.second->IsConnected()) { - devices.push_back(device.second); - } - } - - std::move(cb).Run(std::move(devices)); -} - -void GattClientManagerImpl::GetNumConnected( - base::OnceCallback cb) const { - MAKE_SURE_IO_THREAD(GetNumConnected, BindToCurrentSequence(std::move(cb))); - DCHECK(cb); - std::move(cb).Run(connected_devices_.size()); -} - -void GattClientManagerImpl::NotifyConnect( - const bluetooth_v2_shlib::Addr& addr) { - observers_->Notify(FROM_HERE, &Observer::OnConnectInitated, addr); -} - -void GattClientManagerImpl::NotifyBonded(const bluetooth_v2_shlib::Addr& addr) { - MAKE_SURE_IO_THREAD(NotifyBonded, addr); - auto device = GetDeviceSync(addr); - static_cast(device.get())->SetBonded(true); - observers_->Notify(FROM_HERE, &Observer::OnBondChanged, device, true); -} - -void GattClientManagerImpl::EnqueueConnectRequest( - const bluetooth_v2_shlib::Addr& addr, - bool is_connect, - bluetooth_v2_shlib::Gatt::Client::Transport transport) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - pending_connect_requests_.emplace_back(addr, is_connect, transport); - - // Run the request if this is the only request in the queue. Otherwise, it - // will be run when all previous requests complete. - if (pending_connect_requests_.size() == 1) { - RunQueuedConnectRequest(); - } -} - -void GattClientManagerImpl::EnqueueReadRemoteRssiRequest( - const bluetooth_v2_shlib::Addr& addr) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - - // Get the last byte because whole address is PII. - std::string addr_str = util::AddrLastByteString(addr); - - auto it = addr_to_device_.find(addr); - if (it == addr_to_device_.end()) { - LOG(ERROR) << "ReadRemoteRssi (" << addr_str << ") failed: no such device"; - return; - } - - if (pending_read_remote_rssi_requests_.size() >= kMaxDevicesInQueue) { - LOG(ERROR) << "ReadRemoteRssi (" << addr_str << ") failed: queue is full"; - it->second->OnReadRemoteRssiComplete(false, 0); - return; - } - - pending_read_remote_rssi_requests_.push_back(addr); - - // Run the request if this is the only request in the queue. Otherwise, it - // will be run when all previous requests complete. - if (pending_read_remote_rssi_requests_.size() == 1) { - RunQueuedReadRemoteRssiRequest(); - } -} - -bool GattClientManagerImpl::SetGattClientConnectable(bool connectable) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - - if (gatt_client_connectable_ == connectable) { - return false; - } - - if (connectable) { - if (disconnect_all_pending_) { - LOG(ERROR) << "Can't enable GATT client connectability while " - "DisconectAll is pending"; - return false; - } - LOG(INFO) << "Enabling GATT client connectability"; - } else { - LOG(INFO) << "Disabling GATT client connectability"; - } - - gatt_client_connectable_ = connectable; - return true; -} - -void GattClientManagerImpl::DisconnectAll(StatusCallback cb) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (disconnect_all_pending_) { - LOG(ERROR) << "Already have a pending DisconectAll request"; - std::move(cb).Run(false); - return; - } - - if (connected_devices_.empty()) { - std::move(cb).Run(true); - return; - } - - disconnect_all_pending_ = true; - disconnect_all_cb_ = std::move(cb); - for (const auto& addr : connected_devices_) { - EnqueueConnectRequest(addr, false); - } -} - -bool GattClientManagerImpl::IsConnectedLeDevice( - const bluetooth_v2_shlib::Addr& addr) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - return base::Contains(connected_devices_, addr); -} - -scoped_refptr -GattClientManagerImpl::task_runner() { - return io_task_runner_; -} - -void GattClientManagerImpl::OnConnectChanged( - const bluetooth_v2_shlib::Addr& addr, - bool status, - bool connected) { - MAKE_SURE_IO_THREAD(OnConnectChanged, addr, status, connected); - auto it = addr_to_device_.find(addr); - - // Silently ignore devices we aren't keeping track of. - if (it == addr_to_device_.end()) { - return; - } - - if (connected) { - if (!gatt_client_connectable_) { - LOG(ERROR) << "GATT client not connectable, disconnecting"; - gatt_client_->Disconnect(addr); - return; - } - // We won't declare the device connected until service discovery completes, - // so we won't start next Connect request until then. - it->second->SetConnected(true); - connected_devices_.insert(addr); - } else { - it->second->SetConnected(false); - connected_devices_.erase(addr); - if (!pending_connect_requests_.empty() && - addr == pending_connect_requests_.front().addr) { - pending_connect_requests_.pop_front(); - connect_timeout_timer_.Stop(); - disconnect_timeout_timer_.Stop(); - RunQueuedConnectRequest(); - } else { - std::erase_if(pending_connect_requests_, - [addr](const PendingRequest& request) { - return request.addr == addr; - }); - } - - std::erase(pending_read_remote_rssi_requests_, addr); - read_remote_rssi_timeout_timer_.Stop(); - - if (connected_devices_.empty()) { - DisconnectAllComplete(true); - } - } - - // We won't declare the device connected until service discovery completes. - // Only report disconnect callback if the connect callback was called ( - // service discovery completed). - if (!connected && it->second->GetServicesDiscovered()) { - it->second->SetServicesDiscovered(false); - observers_->Notify(FROM_HERE, &Observer::OnConnectChanged, it->second, - false); - } -} - -void GattClientManagerImpl::OnBondChanged(const bluetooth_v2_shlib::Addr& addr, - bool status, - bool bonded) { - MAKE_SURE_IO_THREAD(OnBondChanged, addr, status, bonded); - auto it = addr_to_device_.find(addr); - - // Silently ignore devices we aren't keeping track of. - if (it == addr_to_device_.end()) { - return; - } - - it->second->SetBonded(bonded); - - observers_->Notify(FROM_HERE, &Observer::OnBondChanged, it->second, bonded); -} - -void GattClientManagerImpl::OnNotification(const bluetooth_v2_shlib::Addr& addr, - uint16_t handle, - const std::vector& value) { - MAKE_SURE_IO_THREAD(OnNotification, addr, handle, value); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - auto characteristic = it->second->CharacteristicFromHandle(handle); - if (!characteristic) { - LOG(ERROR) << "No such characteristic"; - return; - } - - observers_->Notify(FROM_HERE, &Observer::OnCharacteristicNotification, - it->second, characteristic, value); -} - -void GattClientManagerImpl::OnCharacteristicReadResponse( - const bluetooth_v2_shlib::Addr& addr, - bool status, - uint16_t handle, - const std::vector& value) { - MAKE_SURE_IO_THREAD(OnCharacteristicReadResponse, addr, status, handle, - value); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->OnCharacteristicRead(status, handle, value); -} - -void GattClientManagerImpl::OnCharacteristicWriteResponse( - const bluetooth_v2_shlib::Addr& addr, - bool status, - uint16_t handle) { - MAKE_SURE_IO_THREAD(OnCharacteristicWriteResponse, addr, status, handle); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->OnCharacteristicWrite(status, handle); -} - -void GattClientManagerImpl::OnDescriptorReadResponse( - const bluetooth_v2_shlib::Addr& addr, - bool status, - uint16_t handle, - const std::vector& value) { - MAKE_SURE_IO_THREAD(OnDescriptorReadResponse, addr, status, handle, value); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->OnDescriptorRead(status, handle, value); -} - -void GattClientManagerImpl::OnDescriptorWriteResponse( - const bluetooth_v2_shlib::Addr& addr, - bool status, - uint16_t handle) { - MAKE_SURE_IO_THREAD(OnDescriptorWriteResponse, addr, status, handle); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->OnDescriptorWrite(status, handle); -} - -void GattClientManagerImpl::OnReadRemoteRssi( - const bluetooth_v2_shlib::Addr& addr, - bool status, - int rssi) { - MAKE_SURE_IO_THREAD(OnReadRemoteRssi, addr, status, rssi); - - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->OnReadRemoteRssiComplete(status, rssi); - - if (pending_read_remote_rssi_requests_.empty() || - addr != pending_read_remote_rssi_requests_.front()) { - // This can happen when the regular OnReadRemoteRssi is received after - // ReadRemoteRssi timed out. - LOG(ERROR) << "Unexpected call to " << __func__; - return; - } - - pending_read_remote_rssi_requests_.pop_front(); - read_remote_rssi_timeout_timer_.Stop(); - // Try to run the next ReadRemoteRssi request - RunQueuedReadRemoteRssiRequest(); -} - -void GattClientManagerImpl::OnMtuChanged(const bluetooth_v2_shlib::Addr& addr, - bool status, - int mtu) { - MAKE_SURE_IO_THREAD(OnMtuChanged, addr, status, mtu); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->SetMtu(mtu); - - observers_->Notify(FROM_HERE, &Observer::OnMtuChanged, it->second, mtu); -} - -void GattClientManagerImpl::OnGetServices( - const bluetooth_v2_shlib::Addr& addr, - const std::vector& services) { - MAKE_SURE_IO_THREAD(OnGetServices, addr, services); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->OnGetServices(services); - - if (!it->second->GetServicesDiscovered()) { - it->second->SetServicesDiscovered(true); - observers_->Notify(FROM_HERE, &Observer::OnConnectChanged, it->second, - true); - } - - observers_->Notify(FROM_HERE, &Observer::OnServicesUpdated, it->second, - it->second->GetServicesSync()); - - if (pending_connect_requests_.empty() || - addr != pending_connect_requests_.front().addr || - !pending_connect_requests_.front().is_connect) { - NOTREACHED() << "Unexpected call to " << __func__; - } - - pending_connect_requests_.pop_front(); - connect_timeout_timer_.Stop(); - // Try to run the next Connect request - RunQueuedConnectRequest(); -} - -void GattClientManagerImpl::OnServicesRemoved( - const bluetooth_v2_shlib::Addr& addr, - uint16_t start_handle, - uint16_t end_handle) { - MAKE_SURE_IO_THREAD(OnServicesRemoved, addr, start_handle, end_handle); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->OnServicesRemoved(start_handle, end_handle); - - observers_->Notify(FROM_HERE, &Observer::OnServicesUpdated, it->second, - it->second->GetServicesSync()); -} - -void GattClientManagerImpl::OnServicesAdded( - const bluetooth_v2_shlib::Addr& addr, - const std::vector& services) { - MAKE_SURE_IO_THREAD(OnServicesAdded, addr, services); - auto it = addr_to_device_.find(addr); - CHECK_DEVICE_EXISTS_IT(it); - it->second->OnServicesAdded(services); - observers_->Notify(FROM_HERE, &Observer::OnServicesUpdated, it->second, - it->second->GetServicesSync()); -} - -void GattClientManagerImpl::RunQueuedConnectRequest() { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - - while (!pending_connect_requests_.empty()) { - const PendingRequest& pending_request = pending_connect_requests_.front(); - const bluetooth_v2_shlib::Addr& addr = pending_request.addr; - const bool is_connect = pending_request.is_connect; - if (is_connect) { - if (gatt_client_connectable_) { - if (gatt_client_->Connect(addr, pending_request.transport)) { - connect_timeout_timer_.Start( - FROM_HERE, kConnectTimeout, - base::BindOnce(&GattClientManagerImpl::OnConnectTimeout, - weak_this_, addr)); - return; - } else { - LOG(ERROR) << "Connect failed"; - // Clear pending connect request to avoid device be in a bad state. - gatt_client_->ClearPendingConnect(addr); - } - } else { - LOG(ERROR) << "GATT client not connectable"; - } - auto it = addr_to_device_.find(addr); - if (it != addr_to_device_.end()) { - it->second->SetConnected(false); - } - } else { - if (gatt_client_->Disconnect(addr)) { - disconnect_timeout_timer_.Start( - FROM_HERE, kDisconnectTimeout, - base::BindOnce(&GattClientManagerImpl::OnDisconnectTimeout, - weak_this_, addr)); - return; - } - LOG(ERROR) << "Disconnect failed"; - // Clear pending disconnect request to avoid device be in a bad state. - gatt_client_->ClearPendingDisconnect(addr); - - auto it = addr_to_device_.find(addr); - if (it != addr_to_device_.end()) { - it->second->SetConnected(false); - } - - DisconnectAllComplete(false); - } - - // If current request fails, run the next request - pending_connect_requests_.pop_front(); - } -} - -void GattClientManagerImpl::RunQueuedReadRemoteRssiRequest() { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - - if (pending_read_remote_rssi_requests_.empty()) { - return; - } - - auto addr = pending_read_remote_rssi_requests_.front(); - while (!gatt_client_->ReadRemoteRssi(addr)) { - // If current request fails, run the next request - LOG(ERROR) << "ReadRemoteRssi failed"; - auto it = addr_to_device_.find(addr); - if (it != addr_to_device_.end()) { - it->second->OnReadRemoteRssiComplete(false, 0); - } - pending_read_remote_rssi_requests_.pop_front(); - - if (pending_read_remote_rssi_requests_.empty()) { - return; - } - - addr = pending_read_remote_rssi_requests_.front(); - } - - read_remote_rssi_timeout_timer_.Start( - FROM_HERE, kReadRemoteRssiTimeout, - base::BindRepeating(&GattClientManagerImpl::OnReadRemoteRssiTimeout, - weak_this_, addr)); -} - -void GattClientManagerImpl::DisconnectAllComplete(bool success) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (!disconnect_all_pending_) { - return; - } - disconnect_all_pending_ = false; - - if (disconnect_all_cb_) { - std::move(disconnect_all_cb_).Run(success); - } -} - -void GattClientManagerImpl::OnConnectTimeout( - const bluetooth_v2_shlib::Addr& addr) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - // Get the last byte because whole address is PII. - std::string addr_str = util::AddrLastByteString(addr); - - LOG(ERROR) << "Connect (" << addr_str << ")" - << " timed out. Disconnecting"; - - if (base::Contains(connected_devices_, addr)) { - // Connect times out before OnGetServices is received. - gatt_client_->Disconnect(addr); - } else { - // Connect times out before OnConnectChanged is received. - gatt_client_->ClearPendingConnect(addr); - RUN_ON_IO_THREAD(OnConnectChanged, addr, false /* status */, - false /* connected */); - } -} - -void GattClientManagerImpl::OnDisconnectTimeout( - const bluetooth_v2_shlib::Addr& addr) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - // Get the last byte because whole address is PII. - std::string addr_str = util::AddrLastByteString(addr); - - LOG(ERROR) << "Disconnect (" << addr_str << ")" - << " timed out."; - - gatt_client_->ClearPendingDisconnect(addr); - DisconnectAllComplete(false); - - // Treat device as disconnected for this unknown case. - RUN_ON_IO_THREAD(OnConnectChanged, addr, false /* status */, - false /* connected */); -} - -void GattClientManagerImpl::OnReadRemoteRssiTimeout( - const bluetooth_v2_shlib::Addr& addr) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - // Get the last byte because whole address is PII. - std::string addr_str = util::AddrLastByteString(addr); - - LOG(ERROR) << "ReadRemoteRssi (" << addr_str << ")" - << " timed out."; - - // ReadRemoteRssi times out before OnReadRemoteRssi is received. - RUN_ON_IO_THREAD(OnReadRemoteRssi, addr, false /* status */, 0 /* rssi */); -} - -void GattClientManagerImpl::FinalizeOnIoThread() { - MAKE_SURE_IO_THREAD(FinalizeOnIoThread); - weak_factory_->InvalidateWeakPtrs(); - gatt_client_->SetDelegate(nullptr); -} - -GattClientManagerImpl::PendingRequest::PendingRequest( - const bluetooth_v2_shlib::Addr& addr, - bool is_connect, - bluetooth_v2_shlib::Gatt::Client::Transport transport) - : addr(addr), is_connect(is_connect), transport(transport) {} - -GattClientManagerImpl::PendingRequest::~PendingRequest() = default; - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/gatt_client_manager_impl.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/gatt_client_manager_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,202 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_GATT_CLIENT_MANAGER_IMPL_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_GATT_CLIENT_MANAGER_IMPL_H_ - -#include -#include -#include -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/observer_list_threadsafe.h" -#include "base/task/single_thread_task_runner.h" -#include "base/timer/timer.h" -#include "chromecast/device/bluetooth/le/ble_notification_logger.h" -#include "chromecast/device/bluetooth/le/gatt_client_manager.h" -#include "chromecast/device/bluetooth/shlib/gatt_client.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -class RemoteDeviceImpl; - -class GattClientManagerImpl - : public GattClientManager, - public bluetooth_v2_shlib::Gatt::Client::Delegate { - public: - // If a Connect request takes longer than this amount of time, we will treat - // it as a failure. - static constexpr base::TimeDelta kConnectTimeout = base::Seconds(40); - // If a Disconnect request takes longer than this amount of time, we will - // treat it as a failure. - static constexpr base::TimeDelta kDisconnectTimeout = base::Seconds(10); - // If a ReadRemoteRssi request takes longer than this amount of time, we will - // treat it as a failure. - static constexpr base::TimeDelta kReadRemoteRssiTimeout = base::Seconds(10); - - explicit GattClientManagerImpl(bluetooth_v2_shlib::GattClient* gatt_client); - - GattClientManagerImpl(const GattClientManagerImpl&) = delete; - GattClientManagerImpl& operator=(const GattClientManagerImpl&) = delete; - - ~GattClientManagerImpl() override; - - void InitializeOnIoThread(); - - // GattClientManager implementation: - void Initialize( - scoped_refptr io_task_runner) override; - void Finalize() override; - void AddObserver(Observer* o) override; - void RemoveObserver(Observer* o) override; - void GetDevice( - const bluetooth_v2_shlib::Addr& addr, - base::OnceCallback)> cb) override; - scoped_refptr GetDeviceSync( - const bluetooth_v2_shlib::Addr& addr) override; - void GetConnectedDevices(GetConnectDevicesCallback cb) override; - void GetNumConnected(base::OnceCallback cb) const override; - void NotifyConnect(const bluetooth_v2_shlib::Addr& addr) override; - void NotifyBonded(const bluetooth_v2_shlib::Addr& addr) override; - bool IsConnectedLeDevice(const bluetooth_v2_shlib::Addr& addr) override; - bool SetGattClientConnectable(bool connectable) override; - void DisconnectAll(StatusCallback cb) override; - scoped_refptr task_runner() override; - - // Add a Connect or Disconnect request to the queue. |is_connect| is true for - // Connect request and false for Disconnect request. They can only be executed - // serially. |transport| need only be set if is_connect == true and you wish - // to force a BT Classic or LE connection. - void EnqueueConnectRequest( - const bluetooth_v2_shlib::Addr& addr, - bool is_connect, - bluetooth_v2_shlib::Gatt::Client::Transport transport = bluetooth_v2_shlib::Gatt::Client::Transport::kAuto); - - // Add a ReadRemoteRssi request to the queue. They can only be executed - // serially. - void EnqueueReadRemoteRssiRequest(const bluetooth_v2_shlib::Addr& addr); - - // TODO(bcf): Should be private and passed into objects which need it (e.g. - // RemoteDevice, RemoteCharacteristic). - bluetooth_v2_shlib::GattClient* gatt_client() const { return gatt_client_; } - - bool gatt_client_connectable() const { return gatt_client_connectable_; } - - private: - // bluetooth_v2_shlib::Gatt::Client::Delegate implementation: - void OnConnectChanged(const bluetooth_v2_shlib::Addr& addr, - bool status, - bool connected) override; - void OnBondChanged(const bluetooth_v2_shlib::Addr& addr, - bool status, - bool bonded) override; - void OnNotification(const bluetooth_v2_shlib::Addr& addr, - uint16_t handle, - const std::vector& value) override; - void OnCharacteristicReadResponse(const bluetooth_v2_shlib::Addr& addr, - bool status, - uint16_t handle, - const std::vector& value) override; - void OnCharacteristicWriteResponse(const bluetooth_v2_shlib::Addr& addr, - bool status, - uint16_t handle) override; - void OnDescriptorReadResponse(const bluetooth_v2_shlib::Addr& addr, - bool status, - uint16_t handle, - const std::vector& value) override; - void OnDescriptorWriteResponse(const bluetooth_v2_shlib::Addr& addr, - bool status, - uint16_t handle) override; - void OnReadRemoteRssi(const bluetooth_v2_shlib::Addr& addr, - bool status, - int rssi) override; - void OnMtuChanged(const bluetooth_v2_shlib::Addr& addr, - bool status, - int mtu) override; - void OnGetServices( - const bluetooth_v2_shlib::Addr& addr, - const std::vector& services) override; - void OnServicesRemoved(const bluetooth_v2_shlib::Addr& addr, - uint16_t start_handle, - uint16_t end_handle) override; - void OnServicesAdded( - const bluetooth_v2_shlib::Addr& addr, - const std::vector& services) override; - - void RunQueuedConnectRequest(); - void RunQueuedReadRemoteRssiRequest(); - void DisconnectAllComplete(bool success); - - void OnConnectTimeout(const bluetooth_v2_shlib::Addr& addr); - void OnDisconnectTimeout(const bluetooth_v2_shlib::Addr& addr); - void OnReadRemoteRssiTimeout(const bluetooth_v2_shlib::Addr& addr); - - void FinalizeOnIoThread(); - - const raw_ptr gatt_client_; - - scoped_refptr> observers_; - - // All bluetooth_v2_shlib calls are run on this task_runner. Following members - // must only be accessed on this task runner. - scoped_refptr io_task_runner_; - - // TODO(bcf): Need to delete on disconnect. - std::map> - addr_to_device_; - std::set connected_devices_; - - // Timer for pending Connect requests. If any Connect request times out, we - // will treat it as a failure. - base::OneShotTimer connect_timeout_timer_; - - // Timer for pending Disconnect requests. If any Disconnect request times out, - // we will treat it as a failure. - base::OneShotTimer disconnect_timeout_timer_; - - // Timer for pending ReadRemoteRssi requests. If any ReadRemoteRssi request - // times out, we will treat it as a failure. - base::OneShotTimer read_remote_rssi_timeout_timer_; - - // Queue for concurrent Connect/Disconnect requests. Each request is - // represented using a pair. |is_connect| is true for - // Connect requests and false for Disconnect requests. - struct PendingRequest { - PendingRequest(const bluetooth_v2_shlib::Addr& addr, - bool is_connect, - bluetooth_v2_shlib::Gatt::Client::Transport transport); - ~PendingRequest(); - - bluetooth_v2_shlib::Addr addr; - bool is_connect; - bluetooth_v2_shlib::Gatt::Client::Transport transport; - }; - std::deque pending_connect_requests_; - - bool disconnect_all_pending_ = false; - - // True if we are allowed connect to a remote device. This value should be set - // false when device is in GATT server mode. - bool gatt_client_connectable_ = true; - - // Callback of DisconnectAll request. - StatusCallback disconnect_all_cb_; - - // Queue for concurrent ReadRemoteRssi requests. - std::deque pending_read_remote_rssi_requests_; - - BleNotificationLogger notification_logger_; - - base::WeakPtr weak_this_; - std::unique_ptr> weak_factory_; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_GATT_CLIENT_MANAGER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/gatt_client_manager_impl_test.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl_test.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/gatt_client_manager_impl_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/gatt_client_manager_impl_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,1381 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/gatt_client_manager_impl.h" - -#include "base/functional/bind.h" -#include "base/memory/ptr_util.h" -#include "base/message_loop/message_pump_type.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/mock_callback.h" -#include "base/test/task_environment.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "chromecast/device/bluetooth/le/remote_characteristic_impl.h" -#include "chromecast/device/bluetooth/le/remote_descriptor_impl.h" -#include "chromecast/device/bluetooth/le/remote_device_impl.h" -#include "chromecast/device/bluetooth/le/remote_service.h" -#include "chromecast/device/bluetooth/shlib/mock_gatt_client.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::_; -using ::testing::Return; - -namespace chromecast { -namespace bluetooth { - -namespace { - -const bluetooth_v2_shlib::Addr kTestAddr1 = { - {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}}; -const bluetooth_v2_shlib::Addr kTestAddr2 = { - {0x10, 0x11, 0x12, 0x13, 0x14, 0x15}}; -const bluetooth_v2_shlib::Addr kTestAddr3 = { - {0x20, 0x21, 0x22, 0x23, 0x24, 0x25}}; -const bluetooth_v2_shlib::Addr kTestAddr4 = { - {0x30, 0x31, 0x32, 0x33, 0x34, 0x35}}; -const bluetooth_v2_shlib::Addr kTestAddr5 = { - {0x40, 0x41, 0x42, 0x43, 0x44, 0x45}}; - -class MockGattClientManagerObserver : public GattClientManager::Observer { - public: - MOCK_METHOD2(OnConnectChanged, - void(scoped_refptr device, bool connected)); - MOCK_METHOD2(OnMtuChanged, void(scoped_refptr device, int mtu)); - MOCK_METHOD2(OnServicesUpdated, - void(scoped_refptr device, - std::vector> services)); - MOCK_METHOD3(OnCharacteristicNotification, - void(scoped_refptr device, - scoped_refptr characteristic, - std::vector value)); -}; - -std::vector GenerateServices() { - std::vector ret; - - bluetooth_v2_shlib::Gatt::Service service; - bluetooth_v2_shlib::Gatt::Characteristic characteristic; - bluetooth_v2_shlib::Gatt::Descriptor descriptor; - - service.uuid = {{0x1}}; - service.handle = 0x1; - service.primary = true; - - // Generate a characteristic that supports notification only. - characteristic.uuid = {{0x1, 0x1}}; - characteristic.handle = 0x2; - characteristic.permissions = - static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.properties = bluetooth_v2_shlib::Gatt::PROPERTY_NOTIFY; - - descriptor.uuid = {{0x1, 0x1, 0x1}}; - descriptor.handle = 0x3; - descriptor.permissions = static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.descriptors.push_back(descriptor); - - descriptor.uuid = RemoteDescriptor::kCccdUuid; - descriptor.handle = 0x4; - descriptor.permissions = static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.descriptors.push_back(descriptor); - service.characteristics.push_back(characteristic); - - // Generate a characteristic that does not support notification or indication. - characteristic.uuid = {{0x1, 0x2}}; - characteristic.handle = 0x5; - characteristic.permissions = - static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.properties = - static_cast(0); - characteristic.descriptors.clear(); - service.characteristics.push_back(characteristic); - - // Generate a characteristic that supports indication only. - characteristic.uuid = {{0x1, 0x3}}; - characteristic.handle = 0x6; - characteristic.permissions = - static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.properties = bluetooth_v2_shlib::Gatt::PROPERTY_INDICATE; - - descriptor.uuid = {{0x1, 0x3, 0x1}}; - descriptor.handle = 0x7; - descriptor.permissions = static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.descriptors.push_back(descriptor); - - descriptor.uuid = RemoteDescriptor::kCccdUuid; - descriptor.handle = 0x8; - descriptor.permissions = static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.descriptors.push_back(descriptor); - service.characteristics.push_back(characteristic); - - // Generate a characteristic that supports both notification and indication. - characteristic.uuid = {{0x1, 0x4}}; - characteristic.handle = 0x9; - characteristic.permissions = - static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.properties = static_cast( - bluetooth_v2_shlib::Gatt::PROPERTY_NOTIFY | - bluetooth_v2_shlib::Gatt::PROPERTY_INDICATE); - characteristic.descriptors.clear(); - - descriptor.uuid = {{0x1, 0x4, 0x1}}; - descriptor.handle = 0xA; - descriptor.permissions = static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.descriptors.push_back(descriptor); - - descriptor.uuid = RemoteDescriptor::kCccdUuid; - descriptor.handle = 0xB; - descriptor.permissions = static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - characteristic.descriptors.push_back(descriptor); - service.characteristics.push_back(characteristic); - - ret.push_back(service); - - service.uuid = {{0x2}}; - service.handle = 0xC; - service.primary = true; - service.characteristics.clear(); - ret.push_back(service); - - return ret; -} - -class GattClientManagerTest : public ::testing::Test { - public: - void SetUp() override { - gatt_client_ = std::make_unique(); - gatt_client_manager_ = - std::make_unique(gatt_client_.get()); - observer_ = std::make_unique(); - - // Normally bluetooth_manager does this. - gatt_client_->SetDelegate(gatt_client_manager_.get()); - gatt_client_manager_->Initialize( - base::SingleThreadTaskRunner::GetCurrentDefault()); - gatt_client_manager_->AddObserver(observer_.get()); - } - - void TearDown() override { - gatt_client_->SetDelegate(nullptr); - gatt_client_manager_->RemoveObserver(observer_.get()); - gatt_client_manager_->Finalize(); - } - - scoped_refptr GetDevice(const bluetooth_v2_shlib::Addr& addr) { - scoped_refptr ret; - gatt_client_manager_->GetDevice( - addr, base::BindOnce( - [](scoped_refptr* ret_ptr, - scoped_refptr result) { *ret_ptr = result; }, - &ret)); - - return ret; - } - - std::vector> GetServices(RemoteDevice* device) { - std::vector> ret; - device->GetServices(base::BindOnce( - [](std::vector>* ret_ptr, - std::vector> result) { - *ret_ptr = result; - }, - &ret)); - - return ret; - } - - scoped_refptr GetServiceByUuid( - RemoteDevice* device, - const bluetooth_v2_shlib::Uuid& uuid) { - scoped_refptr ret; - device->GetServiceByUuid(uuid, base::BindOnce( - [](scoped_refptr* ret_ptr, - scoped_refptr result) { - *ret_ptr = result; - }, - &ret)); - return ret; - } - - void Connect(const bluetooth_v2_shlib::Addr& addr) { - EXPECT_CALL(*gatt_client_, - Connect(addr, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - scoped_refptr device = GetDevice(addr); - EXPECT_CALL(connect_cb_, Run(RemoteDevice::ConnectStatus::kSuccess)); - device->Connect(connect_cb_.Get()); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - EXPECT_CALL(*gatt_client_, GetServices(addr)).WillOnce(Return(true)); - delegate->OnConnectChanged(addr, true /* status */, true /* connected */); - delegate->OnGetServices(addr, {}); - ASSERT_TRUE(device->IsConnected()); - } - - base::MockCallback cb_; - base::MockCallback connect_cb_; - base::test::SingleThreadTaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; - std::unique_ptr gatt_client_manager_; - std::unique_ptr gatt_client_; - std::unique_ptr observer_; -}; - -} // namespace - -TEST_F(GattClientManagerTest, RemoteDeviceConnect) { - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - - scoped_refptr device = GetDevice(kTestAddr1); - EXPECT_FALSE(device->IsConnected()); - EXPECT_FALSE(gatt_client_manager_->IsConnectedLeDevice(kTestAddr1)); - EXPECT_EQ(kTestAddr1, device->addr()); - - // Disconnect from an already disconnected device. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(false)); - EXPECT_CALL(*gatt_client_, ClearPendingDisconnect(kTestAddr1)) - .WillOnce(Return(true)); - EXPECT_CALL(cb_, Run(true)); - device->Disconnect(cb_.Get()); - - // These should fail if we're not connected. - EXPECT_CALL(cb_, Run(false)); - device->CreateBond(cb_.Get()); - - base::MockCallback rssi_cb; - EXPECT_CALL(rssi_cb, Run(false, _)); - device->ReadRemoteRssi(rssi_cb.Get()); - - EXPECT_CALL(cb_, Run(false)); - device->RequestMtu(512, cb_.Get()); - - EXPECT_CALL(cb_, Run(false)); - device->ConnectionParameterUpdate(10, 10, 50, 100, cb_.Get()); - - // First connect request fails right away. - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr1, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(false)); - EXPECT_CALL(*gatt_client_, ClearPendingConnect(kTestAddr1)) - .WillOnce(Return(true)); - EXPECT_CALL(connect_cb_, Run(RemoteDevice::ConnectStatus::kFailure)); - device->Connect(connect_cb_.Get()); - EXPECT_FALSE(device->IsConnected()); - - // Second connect request succeeds. - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr1, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - EXPECT_CALL(connect_cb_, Run(RemoteDevice::ConnectStatus::kSuccess)); - device->Connect(connect_cb_.Get()); - EXPECT_CALL(*gatt_client_, GetServices(kTestAddr1)).WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - true /* connected */); - EXPECT_CALL(*observer_, OnConnectChanged(device, true)); - delegate->OnGetServices(kTestAddr1, {}); - - EXPECT_TRUE(device->IsConnected()); - EXPECT_TRUE(gatt_client_manager_->IsConnectedLeDevice(kTestAddr1)); - - base::MockCallback< - base::OnceCallback>)>> - get_connected_callback; - const std::vector> kExpectedDevices({device}); - EXPECT_CALL(get_connected_callback, Run(kExpectedDevices)); - gatt_client_manager_->GetConnectedDevices(get_connected_callback.Get()); - - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(true)); - device->Disconnect({}); - // Should declare device as not connected after disconnect starts - EXPECT_FALSE(device->IsConnected()); - - EXPECT_CALL(*observer_, OnConnectChanged(device, false)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - false /* connected */); - EXPECT_FALSE(device->IsConnected()); - EXPECT_FALSE(gatt_client_manager_->IsConnectedLeDevice(kTestAddr1)); - - task_environment_.RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, RemoteDeviceBond) { - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - - scoped_refptr device = GetDevice(kTestAddr1); - Connect(kTestAddr1); - EXPECT_FALSE(device->IsBonded()); - - // CreateBond fails in the initial request. - EXPECT_CALL(*gatt_client_, CreateBond(kTestAddr1)).WillOnce(Return(false)); - EXPECT_CALL(cb_, Run(false)); - device->CreateBond(cb_.Get()); - EXPECT_FALSE(device->IsBonded()); - - // CreateBond fails in the callback. - EXPECT_CALL(*gatt_client_, CreateBond(kTestAddr1)).WillOnce(Return(true)); - EXPECT_CALL(cb_, Run(false)); - device->CreateBond(cb_.Get()); - delegate->OnBondChanged(kTestAddr1, false /* status */, false /* bonded */); - EXPECT_FALSE(device->IsBonded()); - - // CreateBond succeeds. - EXPECT_CALL(*gatt_client_, CreateBond(kTestAddr1)).WillOnce(Return(true)); - device->CreateBond(cb_.Get()); - EXPECT_CALL(cb_, Run(true)); - delegate->OnBondChanged(kTestAddr1, true /* status */, true /* bonded */); - EXPECT_TRUE(device->IsBonded()); - - // Bond with an already bonded device should fail. - EXPECT_CALL(cb_, Run(false)); - device->CreateBond(cb_.Get()); - EXPECT_TRUE(device->IsBonded()); - - // RemoveBond succeeds. - EXPECT_CALL(*gatt_client_, RemoveBond(kTestAddr1)).WillOnce(Return(true)); - device->RemoveBond(cb_.Get()); - EXPECT_CALL(cb_, Run(true)); - delegate->OnBondChanged(kTestAddr1, false /* status */, false /* bonded */); - EXPECT_FALSE(device->IsBonded()); - - // RemoveBond from an unbonded device succeeds. - EXPECT_CALL(*gatt_client_, RemoveBond(kTestAddr1)).WillOnce(Return(true)); - device->RemoveBond(cb_.Get()); - EXPECT_CALL(cb_, Run(true)); - delegate->OnBondChanged(kTestAddr1, false /* status */, false /* bonded */); - EXPECT_FALSE(device->IsBonded()); - - // CreateBond again succeeds. - EXPECT_CALL(*gatt_client_, CreateBond(kTestAddr1)).WillOnce(Return(true)); - device->CreateBond(cb_.Get()); - EXPECT_CALL(cb_, Run(true)); - delegate->OnBondChanged(kTestAddr1, true /* status */, true /* bonded */); - EXPECT_TRUE(device->IsBonded()); - - // Device should remain bonded when it disconnects. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(true)); - device->Disconnect({}); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - false /* connected */); - EXPECT_FALSE(device->IsConnected()); - EXPECT_TRUE(device->IsBonded()); - - // RemoveBond from a disconnected but bonded device. - EXPECT_CALL(*gatt_client_, RemoveBond(kTestAddr1)).WillOnce(Return(true)); - device->RemoveBond(cb_.Get()); - EXPECT_CALL(cb_, Run(true)); - delegate->OnBondChanged(kTestAddr1, false /* status */, false /* bonded */); - EXPECT_FALSE(device->IsBonded()); - - task_environment_.RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, RemoteDeviceBondedOnInitialization) { - // NotifyBonded at initialization. - gatt_client_manager_->NotifyBonded(kTestAddr1); - - // Device should have updated the bonding state. - scoped_refptr device = GetDevice(kTestAddr1); - EXPECT_FALSE(device->IsConnected()); - EXPECT_TRUE(device->IsBonded()); - - Connect(kTestAddr1); - EXPECT_TRUE(device->IsConnected()); - EXPECT_TRUE(device->IsBonded()); - - task_environment_.RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, RemoteDeviceConnectConcurrent) { - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - scoped_refptr device1 = GetDevice(kTestAddr1); - scoped_refptr device2 = GetDevice(kTestAddr2); - scoped_refptr device3 = GetDevice(kTestAddr3); - scoped_refptr device4 = GetDevice(kTestAddr4); - scoped_refptr device5 = GetDevice(kTestAddr5); - - base::MockCallback cb1; - base::MockCallback cb2; - base::MockCallback cb3; - base::MockCallback cb4; - base::MockCallback cb5; - - // Device5 is already connected at the beginning. - Connect(kTestAddr5); - - // Only the 1st Connect request will be executed immediately. The rest will be - // queued. - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr1, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - device1->Connect(cb1.Get()); - device2->Connect(cb2.Get()); - device3->Connect(cb3.Get()); - device4->Connect(cb4.Get()); - device5->Disconnect(cb5.Get()); - - EXPECT_CALL(*gatt_client_, GetServices(kTestAddr1)).WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - true /* connected */); - - // Queued Connect requests will not be called until we receive OnGetServices - // of the current Connect request if it is successful. - EXPECT_CALL(cb1, Run(RemoteDevice::ConnectStatus::kSuccess)); - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr2, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(false)); - EXPECT_CALL(cb2, Run(RemoteDevice::ConnectStatus::kFailure)); - // If the Connect request fails in the initial request (not in the callback), - // the next queued request will be executed immediately. - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr3, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - delegate->OnGetServices(kTestAddr1, {}); - - EXPECT_CALL(cb3, Run(RemoteDevice::ConnectStatus::kFailure)); - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr4, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr3, true /* status */, - false /* connected */); - - EXPECT_CALL(*gatt_client_, GetServices(kTestAddr4)).WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr4, true /* status */, - true /* connected */); - - EXPECT_CALL(cb4, Run(RemoteDevice::ConnectStatus::kSuccess)); - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr5)).WillOnce(Return(true)); - delegate->OnGetServices(kTestAddr4, {}); - - EXPECT_CALL(cb5, Run(true)); - delegate->OnConnectChanged(kTestAddr5, true /* status */, - false /* connected */); - - EXPECT_TRUE(device1->IsConnected()); - EXPECT_FALSE(device2->IsConnected()); - EXPECT_FALSE(device3->IsConnected()); - EXPECT_TRUE(device4->IsConnected()); - EXPECT_FALSE(device5->IsConnected()); - - base::MockCallback> - get_num_connected_callback; - EXPECT_CALL(get_num_connected_callback, Run(2)); - gatt_client_manager_->GetNumConnected(get_num_connected_callback.Get()); - - base::RunLoop().RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, ConnectTimeout) { - scoped_refptr device = GetDevice(kTestAddr1); - - // Issue a Connect request - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr1, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - device->Connect(connect_cb_.Get()); - - // Let Connect request timeout - // We should expect to receive Connect failure message - EXPECT_CALL(*gatt_client_, ClearPendingConnect(kTestAddr1)) - .WillOnce(Return(true)); - EXPECT_CALL(connect_cb_, Run(RemoteDevice::ConnectStatus::kFailure)); - task_environment_.FastForwardBy(GattClientManagerImpl::kConnectTimeout); - EXPECT_FALSE(device->IsConnected()); -} - -TEST_F(GattClientManagerTest, GetServicesTimeout) { - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - - scoped_refptr device = GetDevice(kTestAddr1); - - // Issue a Connect request and let Connect succeed - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr1, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - device->Connect(connect_cb_.Get()); - EXPECT_CALL(*gatt_client_, GetServices(kTestAddr1)).WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - true /* connected */); - - // Let GetServices request timeout - // We should request a disconnect. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(true)); - task_environment_.FastForwardBy(GattClientManagerImpl::kConnectTimeout); - - // Make sure we issued a disconnect. - testing::Mock::VerifyAndClearExpectations(gatt_client_.get()); - - EXPECT_CALL(connect_cb_, Run(RemoteDevice::ConnectStatus::kFailure)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - false /* connected */); - - EXPECT_FALSE(device->IsConnected()); -} - -TEST_F(GattClientManagerTest, RemoteDeviceReadRssi) { - static const int kRssi = -34; - - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - scoped_refptr device = GetDevice(kTestAddr1); - - Connect(kTestAddr1); - base::MockCallback rssi_cb; - - // First ReadRemoteRssi request fails right away. - EXPECT_CALL(*gatt_client_, ReadRemoteRssi(kTestAddr1)) - .WillOnce(Return(false)); - EXPECT_CALL(rssi_cb, Run(false, 0)); - device->ReadRemoteRssi(rssi_cb.Get()); - - // Second ReadRemoteRssi request succeeds. - EXPECT_CALL(*gatt_client_, ReadRemoteRssi(kTestAddr1)).WillOnce(Return(true)); - device->ReadRemoteRssi(rssi_cb.Get()); - - EXPECT_CALL(rssi_cb, Run(true, kRssi)); - delegate->OnReadRemoteRssi(kTestAddr1, true /* status */, kRssi); -} - -TEST_F(GattClientManagerTest, DisconnectAll) { - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - base::MockCallback cb; - - // No connected devices, DisconnectAll should be successful. - EXPECT_CALL(cb, Run(true)); - gatt_client_manager_->DisconnectAll(cb.Get()); - - scoped_refptr device1 = GetDevice(kTestAddr1); - scoped_refptr device2 = GetDevice(kTestAddr2); - scoped_refptr device3 = GetDevice(kTestAddr3); - - // Connect all 3 devices. - Connect(kTestAddr1); - Connect(kTestAddr2); - Connect(kTestAddr3); - - // Disable GATT client connectability. - EXPECT_TRUE(gatt_client_manager_->SetGattClientConnectable(false)); - EXPECT_FALSE(gatt_client_manager_->gatt_client_connectable()); - - // Disconnect requests will be queued. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(true)); - gatt_client_manager_->DisconnectAll(cb.Get()); - - // cb will be run when last device got disconnected. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr2)).WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - false /* connected */); - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr3)).WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr2, true /* status */, - false /* connected */); - - // Shouldn't be able to enable connectability when DisconnectAll is pending. - EXPECT_FALSE(gatt_client_manager_->SetGattClientConnectable(true)); - EXPECT_FALSE(gatt_client_manager_->gatt_client_connectable()); - - EXPECT_CALL(cb, Run(true)); - delegate->OnConnectChanged(kTestAddr3, true /* status */, - false /* connected */); - - base::MockCallback> - get_num_connected_callback; - EXPECT_CALL(get_num_connected_callback, Run(0)); - gatt_client_manager_->GetNumConnected(get_num_connected_callback.Get()); - - // Re-enable connectability when DisconnectAll completes. - EXPECT_TRUE(gatt_client_manager_->SetGattClientConnectable(true)); - EXPECT_TRUE(gatt_client_manager_->gatt_client_connectable()); - - base::RunLoop().RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, DisconnectAllTimeout) { - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - base::MockCallback cb; - - scoped_refptr device1 = GetDevice(kTestAddr1); - scoped_refptr device2 = GetDevice(kTestAddr2); - Connect(kTestAddr1); - Connect(kTestAddr2); - - // Issue a DisconnectAll request. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(true)); - gatt_client_manager_->DisconnectAll(cb.Get()); - - // Let the fist Disconnect request timeout - EXPECT_CALL(*gatt_client_, ClearPendingDisconnect(kTestAddr1)) - .WillOnce(Return(true)); - - // We should expect to receive DisconnectAll failure message - EXPECT_CALL(cb, Run(false)); - // Run second Disconnect request in the queue. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr2)).WillOnce(Return(true)); - task_environment_.FastForwardBy(GattClientManagerImpl::kDisconnectTimeout); - - // We should treat device as disconnected for this unknown case - EXPECT_FALSE(device1->IsConnected()); - - // Second Disconnect request succeeds. - delegate->OnConnectChanged(kTestAddr2, true /* status */, - false /* connected */); - - base::MockCallback> - get_num_connected_callback; - EXPECT_CALL(get_num_connected_callback, Run(0)); - gatt_client_manager_->GetNumConnected(get_num_connected_callback.Get()); -} - -TEST_F(GattClientManagerTest, Connectability) { - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - scoped_refptr device = GetDevice(kTestAddr1); - - // By default GATT client is connectable. - EXPECT_TRUE(gatt_client_manager_->gatt_client_connectable()); - - // Start a connection. - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr1, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - device->Connect(connect_cb_.Get()); - - // Disable GATT client connectability while connection is pending. - EXPECT_TRUE(gatt_client_manager_->SetGattClientConnectable(false)); - EXPECT_FALSE(gatt_client_manager_->gatt_client_connectable()); - - // Expect to disconnect after receiving the connect callback. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - true /* connected */); - - EXPECT_CALL(connect_cb_, Run(RemoteDevice::ConnectStatus::kFailure)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - false /* connected */); - ASSERT_FALSE(device->IsConnected()); - - // Connect should fail when GATT client connectability is already disabled. - EXPECT_CALL(*gatt_client_, Connect).Times(0); - EXPECT_CALL(connect_cb_, Run(RemoteDevice::ConnectStatus::kFailure)); - device->Connect(connect_cb_.Get()); - ASSERT_FALSE(device->IsConnected()); - - // Re-enable connectability. - EXPECT_TRUE(gatt_client_manager_->SetGattClientConnectable(true)); - EXPECT_TRUE(gatt_client_manager_->gatt_client_connectable()); - - // Connect succeeds. - Connect(kTestAddr1); - - base::RunLoop().RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, ReadRemoteRssiTimeout) { - static const int kRssi = -34; - - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - scoped_refptr device = GetDevice(kTestAddr1); - - Connect(kTestAddr1); - - // Issue a ReadRemoteRssi request. - base::MockCallback rssi_cb; - EXPECT_CALL(*gatt_client_, ReadRemoteRssi(kTestAddr1)).WillOnce(Return(true)); - device->ReadRemoteRssi(rssi_cb.Get()); - - // Let ReadRemoteRssi request timeout. - // We should expect to receive ReadRemoteRssi failure message. - EXPECT_CALL(rssi_cb, Run(false, 0)); - task_environment_.FastForwardBy( - GattClientManagerImpl::kReadRemoteRssiTimeout); - - // The following callback should be ignored. - delegate->OnReadRemoteRssi(kTestAddr1, true /* status */, kRssi); - - // Device should remain connected. - EXPECT_TRUE(device->IsConnected()); -} - -TEST_F(GattClientManagerTest, RemoteDeviceReadRssiConcurrent) { - static const int kRssi1 = -34; - static const int kRssi3 = -68; - - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - scoped_refptr device1 = GetDevice(kTestAddr1); - scoped_refptr device2 = GetDevice(kTestAddr2); - scoped_refptr device3 = GetDevice(kTestAddr3); - - base::MockCallback rssi_cb1; - base::MockCallback rssi_cb2; - base::MockCallback rssi_cb3; - - // Only the 1st ReadRemoteRssi request will be executed immediately. The rest - // will be queued. - EXPECT_CALL(*gatt_client_, ReadRemoteRssi(kTestAddr1)).WillOnce(Return(true)); - device1->ReadRemoteRssi(rssi_cb1.Get()); - device2->ReadRemoteRssi(rssi_cb2.Get()); - device3->ReadRemoteRssi(rssi_cb3.Get()); - - // Queued ReadRemoteRssi requests will not be called until we receive - // OnGetServices of the current Connect request if it is successful. - EXPECT_CALL(rssi_cb1, Run(true, kRssi1)); - EXPECT_CALL(*gatt_client_, ReadRemoteRssi(kTestAddr2)) - .WillOnce(Return(false)); - EXPECT_CALL(rssi_cb2, Run(false, _)); - // If the ReadRemoteRssi request fails in the initial request (not in the - // callback), the next queued request will be executed immediately. - EXPECT_CALL(*gatt_client_, ReadRemoteRssi(kTestAddr3)).WillOnce(Return(true)); - delegate->OnReadRemoteRssi(kTestAddr1, true, kRssi1); - - EXPECT_CALL(rssi_cb3, Run(true, kRssi3)); - delegate->OnReadRemoteRssi(kTestAddr3, true, kRssi3); -} - -TEST_F(GattClientManagerTest, RemoteDeviceRequestMtu) { - static const int kMtu = 512; - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - scoped_refptr device = GetDevice(kTestAddr1); - Connect(kTestAddr1); - - EXPECT_EQ(RemoteDevice::kDefaultMtu, device->GetMtu()); - EXPECT_CALL(*gatt_client_, RequestMtu(kTestAddr1, kMtu)) - .WillOnce(Return(true)); - EXPECT_CALL(cb_, Run(true)); - device->RequestMtu(kMtu, cb_.Get()); - EXPECT_CALL(*observer_, OnMtuChanged(device, kMtu)); - delegate->OnMtuChanged(kTestAddr1, true, kMtu); - EXPECT_EQ(kMtu, device->GetMtu()); - task_environment_.RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, RemoteDeviceConnectionParameterUpdate) { - const int kMinInterval = 10; - const int kMaxInterval = 10; - const int kLatency = 50; - const int kTimeout = 100; - - Connect(kTestAddr1); - - scoped_refptr device = GetDevice(kTestAddr1); - EXPECT_CALL(*gatt_client_, - ConnectionParameterUpdate(kTestAddr1, kMinInterval, kMaxInterval, - kLatency, kTimeout)) - .WillOnce(Return(true)); - EXPECT_CALL(cb_, Run(true)); - device->ConnectionParameterUpdate(kMinInterval, kMaxInterval, kLatency, - kTimeout, cb_.Get()); -} - -TEST_F(GattClientManagerTest, RemoteDeviceServices) { - const auto kServices = GenerateServices(); - Connect(kTestAddr1); - scoped_refptr device = GetDevice(kTestAddr1); - std::vector> services; - EXPECT_EQ(0ul, GetServices(device.get()).size()); - - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, kServices); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(kServices.size(), GetServices(device.get()).size()); - for (const auto& service : kServices) { - scoped_refptr remote_service = - GetServiceByUuid(device.get(), service.uuid); - ASSERT_TRUE(remote_service); - EXPECT_EQ(service.uuid, remote_service->uuid()); - EXPECT_EQ(service.handle, remote_service->handle()); - EXPECT_EQ(service.primary, remote_service->primary()); - EXPECT_EQ(service.characteristics.size(), - remote_service->GetCharacteristics().size()); - - for (const auto& characteristic : service.characteristics) { - scoped_refptr remote_char = - remote_service->GetCharacteristicByUuid(characteristic.uuid); - ASSERT_TRUE(remote_char); - EXPECT_EQ(characteristic.uuid, remote_char->uuid()); - EXPECT_EQ(characteristic.handle, remote_char->handle()); - EXPECT_EQ(characteristic.permissions, remote_char->permissions()); - EXPECT_EQ(characteristic.properties, remote_char->properties()); - EXPECT_EQ(characteristic.descriptors.size(), - remote_char->GetDescriptors().size()); - - for (const auto& descriptor : characteristic.descriptors) { - scoped_refptr remote_desc = - remote_char->GetDescriptorByUuid(descriptor.uuid); - ASSERT_TRUE(remote_desc); - EXPECT_EQ(descriptor.uuid, remote_desc->uuid()); - EXPECT_EQ(descriptor.handle, remote_desc->handle()); - EXPECT_EQ(descriptor.permissions, remote_desc->permissions()); - } - } - } -} - -TEST_F(GattClientManagerTest, RemoteDeviceCharacteristic) { - const std::vector kTestData1 = {0x1, 0x2, 0x3}; - const std::vector kTestData2 = {0x4, 0x5, 0x6}; - const std::vector kTestData3 = {0x7, 0x8, 0x9}; - const auto kServices = GenerateServices(); - const bluetooth_v2_shlib::Gatt::Client::AuthReq kAuthReq = - bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_MITM; - const bluetooth_v2_shlib::Gatt::WriteType kWriteType = - bluetooth_v2_shlib::Gatt::WRITE_TYPE_DEFAULT; - - Connect(kTestAddr1); - scoped_refptr device = GetDevice(kTestAddr1); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, kServices); - std::vector> services = - GetServices(device.get()); - ASSERT_EQ(kServices.size(), services.size()); - - auto service = services[0]; - std::vector> characteristics = - service->GetCharacteristics(); - ASSERT_GE(characteristics.size(), 1ul); - ASSERT_TRUE(characteristics[0]); - auto* characteristic = - static_cast(characteristics[0].get()); - - EXPECT_CALL(*gatt_client_, - WriteCharacteristic(kTestAddr1, characteristic->characteristic(), - kAuthReq, kWriteType, kTestData1)) - .WillOnce(Return(true)); - - EXPECT_CALL(cb_, Run(true)); - characteristic->WriteAuth(kAuthReq, kWriteType, kTestData1, cb_.Get()); - delegate->OnCharacteristicWriteResponse(kTestAddr1, true, - characteristic->handle()); - - EXPECT_CALL(*gatt_client_, - ReadCharacteristic(kTestAddr1, characteristic->characteristic(), - kAuthReq)) - .WillOnce(Return(true)); - - base::MockCallback read_cb; - EXPECT_CALL(read_cb, Run(true, kTestData2)); - characteristic->ReadAuth(kAuthReq, read_cb.Get()); - delegate->OnCharacteristicReadResponse(kTestAddr1, true, - characteristic->handle(), kTestData2); - - EXPECT_CALL(*gatt_client_, - SetCharacteristicNotification( - kTestAddr1, characteristic->characteristic(), true)) - .WillOnce(Return(true)); - - EXPECT_CALL(cb_, Run(true)); - characteristic->SetNotification(true, cb_.Get()); - - EXPECT_CALL(*observer_, OnCharacteristicNotification( - device, characteristics[0], kTestData3)); - delegate->OnNotification(kTestAddr1, characteristic->handle(), kTestData3); - task_environment_.RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, - RemoteDeviceCharacteristicSetRegisterNotification) { - const std::vector kTestData1 = {0x1, 0x2, 0x3}; - const auto kServices = GenerateServices(); - Connect(kTestAddr1); - scoped_refptr device = GetDevice(kTestAddr1); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, kServices); - std::vector> services = - GetServices(device.get()); - ASSERT_EQ(kServices.size(), services.size()); - - scoped_refptr service = services[0]; - std::vector> characteristics = - service->GetCharacteristics(); - ASSERT_GE(characteristics.size(), 1ul); - ASSERT_TRUE(characteristics[0]); - RemoteCharacteristicImpl* characteristic = - static_cast(characteristics[0].get()); - - scoped_refptr cccd = - characteristic->GetDescriptorByUuid(RemoteDescriptor::kCccdUuid); - ASSERT_TRUE(cccd); - - EXPECT_CALL(*gatt_client_, - SetCharacteristicNotification( - kTestAddr1, characteristic->characteristic(), true)) - .WillOnce(Return(true)); - std::vector cccd_enable_notification = { - std::begin(bluetooth::RemoteDescriptor::kEnableNotificationValue), - std::end(bluetooth::RemoteDescriptor::kEnableNotificationValue)}; - EXPECT_CALL(*gatt_client_, - WriteDescriptor( - kTestAddr1, - static_cast(cccd.get())->descriptor(), - _, cccd_enable_notification)) - .WillOnce(Return(true)); - - characteristic->SetRegisterNotification(true, cb_.Get()); - EXPECT_CALL(cb_, Run(true)); - delegate->OnDescriptorWriteResponse(kTestAddr1, true, cccd->handle()); - - EXPECT_CALL(*observer_, OnCharacteristicNotification( - device, characteristics[0], kTestData1)); - delegate->OnNotification(kTestAddr1, characteristic->handle(), kTestData1); - task_environment_.RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, RemoteDeviceCharacteristicSetRegisterIndication) { - const std::vector kTestData1 = {0x1, 0x2, 0x3}; - const auto kServices = GenerateServices(); - Connect(kTestAddr1); - scoped_refptr device = GetDevice(kTestAddr1); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, kServices); - std::vector> services = - GetServices(device.get()); - ASSERT_EQ(kServices.size(), services.size()); - - scoped_refptr service = services[0]; - std::vector> characteristics = - service->GetCharacteristics(); - ASSERT_EQ(characteristics.size(), 4ul); - - // |characteristics[2]| supports indication only. - ASSERT_TRUE(characteristics[2]); - RemoteCharacteristicImpl* characteristic = - static_cast(characteristics[2].get()); - - scoped_refptr cccd = - characteristic->GetDescriptorByUuid(RemoteDescriptor::kCccdUuid); - ASSERT_TRUE(cccd); - - EXPECT_CALL(*gatt_client_, - SetCharacteristicNotification( - kTestAddr1, characteristic->characteristic(), true)) - .WillOnce(Return(true)); - std::vector cccd_enable_indication = { - std::begin(bluetooth::RemoteDescriptor::kEnableIndicationValue), - std::end(bluetooth::RemoteDescriptor::kEnableIndicationValue)}; - EXPECT_CALL(*gatt_client_, - WriteDescriptor( - kTestAddr1, - static_cast(cccd.get())->descriptor(), - _, cccd_enable_indication)) - .WillOnce(Return(true)); - - characteristic->SetRegisterNotificationOrIndication(true, cb_.Get()); - EXPECT_CALL(cb_, Run(true)); - delegate->OnDescriptorWriteResponse(kTestAddr1, true, cccd->handle()); - - EXPECT_CALL(*observer_, OnCharacteristicNotification( - device, characteristics[2], kTestData1)); - delegate->OnNotification(kTestAddr1, characteristic->handle(), kTestData1); - task_environment_.RunUntilIdle(); - - // |characteristics[3]| supports both notification and indication. - ASSERT_TRUE(characteristics[3]); - characteristic = - static_cast(characteristics[3].get()); - - cccd = characteristic->GetDescriptorByUuid(RemoteDescriptor::kCccdUuid); - ASSERT_TRUE(cccd); - - // Notification has higher priority than indication. So - // SetRegisterNotificationOrIndication will behave the same as - // SetRegisterNotification. - EXPECT_CALL(*gatt_client_, - SetCharacteristicNotification( - kTestAddr1, characteristic->characteristic(), true)) - .WillOnce(Return(true)); - std::vector cccd_enable_notification = { - std::begin(bluetooth::RemoteDescriptor::kEnableNotificationValue), - std::end(bluetooth::RemoteDescriptor::kEnableNotificationValue)}; - EXPECT_CALL(*gatt_client_, - WriteDescriptor( - kTestAddr1, - static_cast(cccd.get())->descriptor(), - _, cccd_enable_notification)) - .WillOnce(Return(true)); - - characteristic->SetRegisterNotificationOrIndication(true, cb_.Get()); - EXPECT_CALL(cb_, Run(true)); - delegate->OnDescriptorWriteResponse(kTestAddr1, true, cccd->handle()); - - EXPECT_CALL(*observer_, OnCharacteristicNotification( - device, characteristics[3], kTestData1)); - delegate->OnNotification(kTestAddr1, characteristic->handle(), kTestData1); - task_environment_.RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, RemoteDeviceDescriptor) { - const std::vector kTestData1 = {0x1, 0x2, 0x3}; - const std::vector kTestData2 = {0x4, 0x5, 0x6}; - const bluetooth_v2_shlib::Gatt::Client::AuthReq kAuthReq = - bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_MITM; - const auto kServices = GenerateServices(); - Connect(kTestAddr1); - scoped_refptr device = GetDevice(kTestAddr1); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, kServices); - std::vector> services = - GetServices(device.get()); - ASSERT_EQ(kServices.size(), services.size()); - - auto service = services[0]; - std::vector> characteristics = - service->GetCharacteristics(); - ASSERT_GE(characteristics.size(), 1ul); - auto characteristic = characteristics[0]; - - std::vector> descriptors = - characteristic->GetDescriptors(); - ASSERT_GE(descriptors.size(), 1ul); - ASSERT_TRUE(descriptors[0]); - auto* descriptor = static_cast(descriptors[0].get()); - - EXPECT_CALL(*gatt_client_, - WriteDescriptor(kTestAddr1, descriptor->descriptor(), kAuthReq, - kTestData1)) - .WillOnce(Return(true)); - - EXPECT_CALL(cb_, Run(true)); - descriptor->WriteAuth(kAuthReq, kTestData1, cb_.Get()); - delegate->OnDescriptorWriteResponse(kTestAddr1, true, descriptor->handle()); - - EXPECT_CALL(*gatt_client_, - ReadDescriptor(kTestAddr1, descriptor->descriptor(), kAuthReq)) - .WillOnce(Return(true)); - - base::MockCallback read_cb; - EXPECT_CALL(read_cb, Run(true, kTestData2)); - descriptor->ReadAuth(kAuthReq, read_cb.Get()); - delegate->OnDescriptorReadResponse(kTestAddr1, true, descriptor->handle(), - kTestData2); -} - -TEST_F(GattClientManagerTest, FakeCccd) { - std::vector input_services(1); - input_services[0].uuid = {{0x1}}; - input_services[0].handle = 0x1; - input_services[0].primary = true; - - bluetooth_v2_shlib::Gatt::Characteristic input_characteristic; - input_characteristic.uuid = {{0x1, 0x1}}; - input_characteristic.handle = 0x2; - input_characteristic.permissions = bluetooth_v2_shlib::Gatt::PERMISSION_READ; - input_characteristic.properties = bluetooth_v2_shlib::Gatt::PROPERTY_NOTIFY; - input_services[0].characteristics.push_back(input_characteristic); - - // Test indicate as well - input_characteristic.uuid = {{0x1, 0x2}}; - input_characteristic.handle = 0x3; - input_characteristic.properties = bluetooth_v2_shlib::Gatt::PROPERTY_INDICATE; - input_services[0].characteristics.push_back(input_characteristic); - - Connect(kTestAddr1); - scoped_refptr device = GetDevice(kTestAddr1); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, input_services); - std::vector> services = - GetServices(device.get()); - ASSERT_EQ(input_services.size(), services.size()); - - auto service = services[0]; - std::vector> characteristics = - service->GetCharacteristics(); - ASSERT_EQ(2u, characteristics.size()); - for (const auto& characteristic : characteristics) { - // A CCCD should have been created. - std::vector> descriptors = - characteristic->GetDescriptors(); - ASSERT_EQ(descriptors.size(), 1ul); - auto descriptor = descriptors[0]; - EXPECT_EQ(RemoteDescriptor::kCccdUuid, descriptor->uuid()); - EXPECT_EQ(static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE), - descriptor->permissions()); - } -} - -TEST_F(GattClientManagerTest, WriteType) { - const std::vector kTestData1 = {0x1, 0x2, 0x3}; - - bluetooth_v2_shlib::Gatt::Service service; - - service.uuid = {{0x1}}; - service.handle = 0x1; - service.primary = true; - - { - bluetooth_v2_shlib::Gatt::Characteristic characteristic; - characteristic.uuid = {{0x1, 0x1}}; - characteristic.handle = 0x2; - characteristic.permissions = bluetooth_v2_shlib::Gatt::PERMISSION_WRITE; - characteristic.properties = bluetooth_v2_shlib::Gatt::PROPERTY_WRITE; - service.characteristics.push_back(characteristic); - - characteristic.uuid = {{0x1, 0x2}}; - characteristic.handle = 0x3; - characteristic.permissions = bluetooth_v2_shlib::Gatt::PERMISSION_WRITE; - characteristic.properties = - bluetooth_v2_shlib::Gatt::PROPERTY_WRITE_NO_RESPONSE; - service.characteristics.push_back(characteristic); - - characteristic.uuid = {{0x1, 0x3}}; - characteristic.handle = 0x4; - characteristic.permissions = bluetooth_v2_shlib::Gatt::PERMISSION_WRITE; - characteristic.properties = bluetooth_v2_shlib::Gatt::PROPERTY_SIGNED_WRITE; - service.characteristics.push_back(characteristic); - } - - Connect(kTestAddr1); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, {service}); - - scoped_refptr device = GetDevice(kTestAddr1); - - std::vector> services = - GetServices(device.get()); - ASSERT_EQ(1u, services.size()); - - std::vector> characteristics = - services[0]->GetCharacteristics(); - ASSERT_EQ(3u, characteristics.size()); - - using WriteType = bluetooth_v2_shlib::Gatt::WriteType; - - // The current implementation of RemoteDevice will put the characteristics in - // the order reported by libcast_bluetooth. - const WriteType kWriteTypes[] = {WriteType::WRITE_TYPE_DEFAULT, - WriteType::WRITE_TYPE_NO_RESPONSE, - WriteType::WRITE_TYPE_SIGNED}; - - for (size_t i = 0; i < characteristics.size(); ++i) { - ASSERT_TRUE(characteristics[i]); - auto* characteristic = - static_cast(characteristics[i].get()); - EXPECT_CALL( - *gatt_client_, - WriteCharacteristic(kTestAddr1, characteristic->characteristic(), - bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_NONE, - kWriteTypes[i], kTestData1)) - .WillOnce(Return(true)); - - base::MockCallback write_cb; - EXPECT_CALL(write_cb, Run(true)); - characteristic->Write(kTestData1, write_cb.Get()); - delegate->OnCharacteristicWriteResponse(kTestAddr1, true, - characteristic->handle()); - } -} - -TEST_F(GattClientManagerTest, ConnectMultiple) { - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - scoped_refptr device = GetDevice(kTestAddr1); - for (size_t i = 0; i < 5; ++i) { - Connect(kTestAddr1); - EXPECT_TRUE(device->IsConnected()); - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(true)); - device->Disconnect({}); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - false /* connected */); - EXPECT_FALSE(device->IsConnected()); - } -} - -TEST_F(GattClientManagerTest, GetServicesFailOnConnect) { - scoped_refptr device = GetDevice(kTestAddr1); - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr1, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - device->Connect(connect_cb_.Get()); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - - EXPECT_CALL(connect_cb_, Run(RemoteDevice::ConnectStatus::kFailure)); - EXPECT_CALL(*gatt_client_, GetServices(kTestAddr1)).WillOnce(Return(false)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - true /* connected */); - EXPECT_FALSE(device->IsConnected()); -} - -TEST_F(GattClientManagerTest, GetServicesSuccessAfterConnectCallback) { - const auto kServices = GenerateServices(); - scoped_refptr device = GetDevice(kTestAddr1); - - // Callback that checks when Connect()'s callback returns, GetServices returns - // the correct services. - bool cb_called = false; - auto cb = base::BindOnce( - [](GattClientManagerTest* gcmt, - const std::vector* - expected_services, - bool* cb_called, RemoteDevice::ConnectStatus status) { - EXPECT_EQ(RemoteDevice::ConnectStatus::kSuccess, status); - *cb_called = true; - - auto device = gcmt->GetDevice(kTestAddr1); - auto services = gcmt->GetServices(device.get()); - EXPECT_EQ(expected_services->size(), services.size()); - }, - this, &kServices, &cb_called); - EXPECT_CALL(*gatt_client_, - Connect(kTestAddr1, bluetooth_v2_shlib::Gatt::Client::Transport::kAuto)) - .WillOnce(Return(true)); - device->Connect(std::move(cb)); - - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - EXPECT_CALL(*gatt_client_, GetServices(kTestAddr1)).WillOnce(Return(true)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - true /* connected */); - - // Connect's callback should not be called until service discovery is - // complete. - EXPECT_FALSE(cb_called); - delegate->OnGetServices(kTestAddr1, kServices); - EXPECT_TRUE(cb_called); -} - -TEST_F(GattClientManagerTest, Queuing) { - const std::vector kTestData1 = {0x1, 0x2, 0x3}; - const std::vector kTestData2 = {0x4, 0x5, 0x6}; - const std::vector kTestData3 = {0x7, 0x8, 0x9}; - const auto kServices = GenerateServices(); - const bluetooth_v2_shlib::Gatt::Client::AuthReq kAuthReq = - bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_MITM; - const bluetooth_v2_shlib::Gatt::WriteType kWriteType = - bluetooth_v2_shlib::Gatt::WRITE_TYPE_DEFAULT; - - Connect(kTestAddr1); - scoped_refptr device = GetDevice(kTestAddr1); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, kServices); - std::vector> services = - GetServices(device.get()); - ASSERT_EQ(kServices.size(), services.size()); - - auto service = services[0]; - std::vector> characteristics = - service->GetCharacteristics(); - ASSERT_GE(characteristics.size(), 2ul); - ASSERT_TRUE(characteristics[0]); - ASSERT_TRUE(characteristics[1]); - auto* characteristic1 = - static_cast(characteristics[0].get()); - auto* characteristic2 = - static_cast(characteristics[1].get()); - - // Issue a write to one characteristic. - EXPECT_CALL(*gatt_client_, - WriteCharacteristic(kTestAddr1, characteristic1->characteristic(), - kAuthReq, kWriteType, kTestData1)) - .WillOnce(Return(true)); - characteristic1->WriteAuth(kAuthReq, kWriteType, kTestData1, cb_.Get()); - - // Issue a read to another characteristic. The shlib should not get the call - // until after the read's callback. - EXPECT_CALL(*gatt_client_, - ReadCharacteristic(kTestAddr1, characteristic2->characteristic(), - kAuthReq)) - .Times(0); - base::MockCallback read_cb; - characteristic2->ReadAuth(kAuthReq, read_cb.Get()); - - EXPECT_CALL(cb_, Run(true)); - EXPECT_CALL(*gatt_client_, - ReadCharacteristic(kTestAddr1, characteristic2->characteristic(), - kAuthReq)) - .WillOnce(Return(true)); - delegate->OnCharacteristicWriteResponse(kTestAddr1, true, - characteristic1->handle()); - - EXPECT_CALL(read_cb, Run(true, kTestData2)); - delegate->OnCharacteristicReadResponse(kTestAddr1, true, - characteristic2->handle(), kTestData2); - base::RunLoop().RunUntilIdle(); -} - -TEST_F(GattClientManagerTest, CommandTimeout) { - const std::vector kTestData = {0x7, 0x8, 0x9}; - const auto kServices = GenerateServices(); - const auto kAuthReq = bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_MITM; - const auto kWriteType = bluetooth_v2_shlib::Gatt::WRITE_TYPE_DEFAULT; - - // Connect a device and get services. - Connect(kTestAddr1); - scoped_refptr device = GetDevice(kTestAddr1); - bluetooth_v2_shlib::Gatt::Client::Delegate* delegate = - gatt_client_->delegate(); - delegate->OnServicesAdded(kTestAddr1, kServices); - std::vector> services = - GetServices(device.get()); - ASSERT_EQ(kServices.size(), services.size()); - - auto service = services[0]; - std::vector> characteristics = - service->GetCharacteristics(); - ASSERT_GE(characteristics.size(), 1ul); - ASSERT_TRUE(characteristics[0]); - auto* characteristic = - static_cast(characteristics[0].get()); - - // Issue a write to one characteristic. - EXPECT_CALL(*gatt_client_, - WriteCharacteristic(kTestAddr1, characteristic->characteristic(), - kAuthReq, kWriteType, kTestData)) - .WillOnce(Return(true)); - characteristic->WriteAuth(kAuthReq, kWriteType, kTestData, cb_.Get()); - - // Let the command timeout - // We should request a disconnect. - EXPECT_CALL(*gatt_client_, Disconnect(kTestAddr1)).WillOnce(Return(true)); - task_environment_.FastForwardBy(RemoteDeviceImpl::kCommandTimeout); - - // Make sure we issued a disconnect. - testing::Mock::VerifyAndClearExpectations(gatt_client_.get()); - - // The operation should fail. - EXPECT_CALL(cb_, Run(false)); - delegate->OnConnectChanged(kTestAddr1, true /* status */, - false /* connected */); -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/instantiate_mocks.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/instantiate_mocks.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/instantiate_mocks.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/instantiate_mocks.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file just instantiates mocks to verify they can compile since no one -// uses them yet. - -#include "chromecast/device/bluetooth/le/mock_gatt_client_manager.h" -#include "chromecast/device/bluetooth/le/mock_le_scan_manager.h" -#include "chromecast/device/bluetooth/le/mock_remote_characteristic.h" -#include "chromecast/device/bluetooth/le/mock_remote_descriptor.h" -#include "chromecast/device/bluetooth/le/mock_remote_device.h" -#include "chromecast/device/bluetooth/le/mock_remote_service.h" - -namespace chromecast { -namespace bluetooth { - -namespace { - -const bluetooth_v2_shlib::Addr kAddr{}; -const bluetooth_v2_shlib::Uuid kUuid{}; - -} // namespace - -void InstantiateMocks() { - MockGattClientManager a; - MockLeScanManager b; - scoped_refptr c( - new MockRemoteCharacteristic(kUuid)); - scoped_refptr d(new MockRemoteDescriptor); - scoped_refptr e(new MockRemoteDevice(kAddr)); - scoped_refptr f(new MockRemoteService(kUuid)); -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_manager.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_MANAGER_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_MANAGER_H_ - -#include -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/scoped_refptr.h" -#include "chromecast/device/bluetooth/le/le_scan_result.h" -#include "chromecast/device/bluetooth/le/scan_filter.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -namespace bluetooth_v2_shlib { -class LeScannerImpl; -} // namespace bluetooth_v2_shlib - -namespace bluetooth { -class BluetoothManagerPlatform; - -class LeScanManager { - public: - class Observer { - public: - // Called when the scan has been enabled or disabled. - virtual void OnScanEnableChanged(bool enabled) {} - - // Called when a new scan result is ready. - virtual void OnNewScanResult(LeScanResult result) {} - - virtual ~Observer() = default; - }; - - virtual void AddObserver(Observer* o) = 0; - virtual void RemoveObserver(Observer* o) = 0; - - class ScanHandle { - public: - ScanHandle(const ScanHandle&) = delete; - ScanHandle& operator=(const ScanHandle&) = delete; - - virtual ~ScanHandle() = default; - - protected: - ScanHandle() = default; - }; - - static std::unique_ptr Create( - BluetoothManagerPlatform* bluetooth_manager, - bluetooth_v2_shlib::LeScannerImpl* le_scanner); - - LeScanManager(const LeScanManager&) = delete; - LeScanManager& operator=(const LeScanManager&) = delete; - - virtual ~LeScanManager() = default; - - virtual void Initialize( - scoped_refptr io_task_runner) = 0; - virtual void Finalize() = 0; - - // Request a handle to enable BLE scanning. Can be called on any thread. |cb| - // returns a handle. As long is there is at least one handle in existence, BLE - // scanning will be enabled. Returns nullptr if failed to enable scanning. - using RequestScanCallback = - base::OnceCallback handle)>; - virtual void RequestScan(RequestScanCallback cb) = 0; - - // Asynchronously get the most recent scan results. Can be called on any - // thread. |cb| is called on the calling thread with the results. If - // |scan_filter| is passed, only scan results matching the given |scan_filter| - // will be returned. - using GetScanResultsCallback = - base::OnceCallback)>; - virtual void GetScanResults( - GetScanResultsCallback cb, - std::optional scan_filter = std::nullopt) = 0; - - virtual void ClearScanResults() = 0; - - virtual void PauseScan() {} - - virtual void ResumeScan() {} - - virtual void SetScanParameters(int scan_interval_ms, int scan_window_ms) {} - - protected: - LeScanManager() = default; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_manager_impl.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_manager_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,264 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/le_scan_manager_impl.h" - -#include -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "chromecast/public/cast_media_shlib.h" - -#define RUN_ON_IO_THREAD(method, ...) \ - io_task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&LeScanManagerImpl::method, \ - weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); - -#define MAKE_SURE_IO_THREAD(method, ...) \ - DCHECK(io_task_runner_); \ - if (!io_task_runner_->BelongsToCurrentThread()) { \ - RUN_ON_IO_THREAD(method, ##__VA_ARGS__) \ - return; \ - } - -#define EXEC_CB_AND_RET(cb, ret, ...) \ - do { \ - if (cb) { \ - std::move(cb).Run(ret, ##__VA_ARGS__); \ - } \ - return; \ - } while (0) - -namespace chromecast { -namespace bluetooth { - -namespace { - -const int kMaxMessagesInQueue = 5; - -} // namespace - -// static -constexpr int LeScanManagerImpl::kMaxScanResultEntries; - -// static -std::unique_ptr LeScanManager::Create( - BluetoothManagerPlatform* bluetooth_manager, - bluetooth_v2_shlib::LeScannerImpl* le_scanner) { - return std::make_unique(le_scanner); -} - -class LeScanManagerImpl::ScanHandleImpl : public LeScanManager::ScanHandle { - public: - explicit ScanHandleImpl(LeScanManagerImpl* manager, int32_t id) - : on_destroyed_(BindToCurrentSequence( - base::BindOnce(&LeScanManagerImpl::NotifyScanHandleDestroyed, - manager->weak_factory_.GetWeakPtr(), - id))) {} - ~ScanHandleImpl() override { std::move(on_destroyed_).Run(); } - - private: - base::OnceClosure on_destroyed_; -}; - -LeScanManagerImpl::LeScanManagerImpl( - bluetooth_v2_shlib::LeScannerImpl* le_scanner) - : le_scanner_(le_scanner), - observers_(new base::ObserverListThreadSafe()), - weak_factory_(this) {} - -LeScanManagerImpl::~LeScanManagerImpl() = default; - -void LeScanManagerImpl::Initialize( - scoped_refptr io_task_runner) { - io_task_runner_ = std::move(io_task_runner); - InitializeOnIoThread(); -} - -void LeScanManagerImpl::Finalize() {} - -void LeScanManagerImpl::InitializeOnIoThread() { - MAKE_SURE_IO_THREAD(InitializeOnIoThread); - le_scanner_->SetDelegate(this); -} - -void LeScanManagerImpl::AddObserver(Observer* observer) { - observers_->AddObserver(observer); -} - -void LeScanManagerImpl::RemoveObserver(Observer* observer) { - observers_->RemoveObserver(observer); -} - -void LeScanManagerImpl::RequestScan(RequestScanCallback cb) { - MAKE_SURE_IO_THREAD(RequestScan, BindToCurrentSequence(std::move(cb))); - LOG(INFO) << __func__; - - if (scan_handle_ids_.empty()) { - if (!le_scanner_->StartScan()) { - LOG(ERROR) << "Failed to enable scanning"; - std::move(cb).Run(nullptr); - return; - } - LOG(INFO) << "Enabling scan"; - observers_->Notify(FROM_HERE, &Observer::OnScanEnableChanged, true); - } - - int32_t id = next_scan_handle_id_++; - auto handle = std::make_unique(this, id); - scan_handle_ids_.insert(id); - - std::move(cb).Run(std::move(handle)); -} - -void LeScanManagerImpl::GetScanResults(GetScanResultsCallback cb, - std::optional scan_filter) { - MAKE_SURE_IO_THREAD(GetScanResults, BindToCurrentSequence(std::move(cb)), - std::move(scan_filter)); - std::move(cb).Run(GetScanResultsInternal(std::move(scan_filter))); -} - -void LeScanManagerImpl::ClearScanResults() { - MAKE_SURE_IO_THREAD(ClearScanResults); - addr_to_scan_results_.clear(); -} - -void LeScanManagerImpl::PauseScan() { - MAKE_SURE_IO_THREAD(PauseScan); - if (scan_handle_ids_.empty()) { - LOG(ERROR) << "Can't pause scan, no scan handle"; - return; - } - - if (!le_scanner_->StopScan()) { - LOG(ERROR) << "Failed to pause scanning"; - } -} - -void LeScanManagerImpl::ResumeScan() { - MAKE_SURE_IO_THREAD(ResumeScan); - if (scan_handle_ids_.empty()) { - LOG(ERROR) << "Can't restart scan, no scan handle"; - return; - } - - if (!le_scanner_->StartScan()) { - LOG(ERROR) << "Failed to restart scanning"; - } -} - -void LeScanManagerImpl::SetScanParameters(int scan_interval_ms, - int scan_window_ms) { - MAKE_SURE_IO_THREAD(SetScanParameters, scan_interval_ms, scan_window_ms); - if (scan_handle_ids_.empty()) { - LOG(ERROR) << "Can't set scan parameters, no scan handle"; - return; - } - - // We could only set scan parameters when scan is paused. - if (!le_scanner_->StopScan()) { - LOG(ERROR) << "Failed to pause scanning before setting scan parameters"; - return; - } - - if (!le_scanner_->SetScanParameters(scan_interval_ms, scan_window_ms)) { - LOG(ERROR) << "Failed to set scan parameters"; - return; - } - - if (!le_scanner_->StartScan()) { - LOG(ERROR) << "Failed to restart scanning after setting scan parameters"; - return; - } - - LOG(INFO) << __func__ << " scan_interval: " << scan_interval_ms - << "ms scan_window: " << scan_window_ms << "ms"; -} - -void LeScanManagerImpl::OnScanResult( - const bluetooth_v2_shlib::LeScanner::ScanResult& scan_result_shlib) { - LeScanResult scan_result; - if (!scan_result.SetAdvData(scan_result_shlib.adv_data)) { - // Error logged. - return; - } - scan_result.addr = scan_result_shlib.addr; - scan_result.rssi = scan_result_shlib.rssi; - - auto& previous_scan_results = addr_to_scan_results_[scan_result.addr]; - if (previous_scan_results.size() > 0) { - // Remove results with the same data as the current result to avoid - // duplicate messages in the queue - previous_scan_results.remove_if( - [&scan_result](const auto& previous_result) { - return previous_result.adv_data == scan_result.adv_data; - }); - - // Remove scan_result.addr to avoid duplicate addresses in - // recent_scan_result_addr_list_. - std::erase(scan_result_addr_list_, scan_result.addr); - } - - previous_scan_results.push_front(scan_result); - if (previous_scan_results.size() > kMaxMessagesInQueue) { - previous_scan_results.pop_back(); - } - - // Update recent_scan_result_addr_list_. - scan_result_addr_list_.push_front(scan_result.addr); - while (scan_result_addr_list_.size() > kMaxScanResultEntries) { - // Remove least recently used address in recent_scan_result_addr_list_. - auto least_recently_used_addr = scan_result_addr_list_.back(); - scan_result_addr_list_.pop_back(); - addr_to_scan_results_.erase(least_recently_used_addr); - } - - // Update observers. - observers_->Notify(FROM_HERE, &Observer::OnNewScanResult, scan_result); -} - -// Returns a list of all scan results. The results are sorted by RSSI. -std::vector LeScanManagerImpl::GetScanResultsInternal( - std::optional scan_filter) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - std::vector results; - for (const auto& pair : addr_to_scan_results_) { - for (const auto& scan_result : pair.second) { - if (!scan_filter || scan_filter->Matches(scan_result)) { - results.push_back(scan_result); - } - } - } - - std::sort(results.begin(), results.end(), - [](const LeScanResult& d1, const LeScanResult& d2) { - return d1.rssi > d2.rssi; - }); - - return results; -} - -void LeScanManagerImpl::NotifyScanHandleDestroyed(int32_t id) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - - size_t num_removed = scan_handle_ids_.erase(id); - DCHECK_EQ(num_removed, 1u); - if (scan_handle_ids_.empty()) { - if (!le_scanner_->StopScan()) { - LOG(ERROR) << "Failed to disable scanning"; - } else { - LOG(INFO) << "Disabling scan"; - observers_->Notify(FROM_HERE, &Observer::OnScanEnableChanged, false); - } - } -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_manager_impl.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_manager_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_MANAGER_IMPL_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_MANAGER_IMPL_H_ - -#include -#include -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/raw_ptr.h" -#include "base/observer_list_threadsafe.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/device/bluetooth/le/le_scan_manager.h" -#include "chromecast/device/bluetooth/le/scan_filter.h" -#include "chromecast/device/bluetooth/shlib/le_scanner.h" - -namespace chromecast { -namespace bluetooth { - -class LeScanManagerImpl : public LeScanManager, - public bluetooth_v2_shlib::LeScanner::Delegate { - public: - explicit LeScanManagerImpl(bluetooth_v2_shlib::LeScannerImpl* le_scanner); - - LeScanManagerImpl(const LeScanManagerImpl&) = delete; - LeScanManagerImpl& operator=(const LeScanManagerImpl&) = delete; - - ~LeScanManagerImpl() override; - - static constexpr int kMaxScanResultEntries = 1024; - - // LeScanManager implementation: - void Initialize( - scoped_refptr io_task_runner) override; - void Finalize() override; - void AddObserver(Observer* o) override; - void RemoveObserver(Observer* o) override; - void RequestScan(RequestScanCallback cb) override; - void GetScanResults( - GetScanResultsCallback cb, - std::optional service_uuid = std::nullopt) override; - void ClearScanResults() override; - void PauseScan() override; - void ResumeScan() override; - void SetScanParameters(int scan_interval_ms, int scan_window_ms) override; - - private: - class ScanHandleImpl; - - // bluetooth_v2_shlib::LeScanner::Delegate implementation: - void OnScanResult(const bluetooth_v2_shlib::LeScanner::ScanResult& - scan_result_shlib) override; - - void InitializeOnIoThread(); - - // Returns a list of all BLE scan results. The results are sorted by RSSI. - // Must be called on |io_task_runner|. - std::vector GetScanResultsInternal( - std::optional service_uuid); - - void NotifyScanHandleDestroyed(int32_t id); - - const raw_ptr le_scanner_; - scoped_refptr io_task_runner_; - - scoped_refptr> observers_; - std::map> - addr_to_scan_results_; - - // List of addresses in scan results. Addresses are sorted from most recently - // used to least recently used. - std::deque scan_result_addr_list_; - - int32_t next_scan_handle_id_ = 0; - std::set scan_handle_ids_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_MANAGER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_manager_impl_test.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl_test.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_manager_impl_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_manager_impl_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,347 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/le_scan_manager_impl.h" - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/memory/ptr_util.h" -#include "base/task/single_thread_task_runner.h" -#include "base/task/thread_pool.h" -#include "base/test/task_environment.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "chromecast/device/bluetooth/le/remote_characteristic.h" -#include "chromecast/device/bluetooth/le/remote_descriptor.h" -#include "chromecast/device/bluetooth/le/remote_device.h" -#include "chromecast/device/bluetooth/le/remote_service.h" -#include "chromecast/device/bluetooth/shlib/mock_le_scanner.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -namespace chromecast { -namespace bluetooth { - -namespace { - -const bluetooth_v2_shlib::Addr kTestAddr1 = { - {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}}; -const bluetooth_v2_shlib::Addr kTestAddr2 = { - {0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}; - -// This hack is needed because base::BindOnce does not support capture lambdas. -template -void CopyResult(T* out, T in) { - *out = std::move(in); -} - -class MockLeScanManagerObserver : public LeScanManager::Observer { - public: - MOCK_METHOD1(OnScanEnableChanged, void(bool enabled)); - MOCK_METHOD1(OnNewScanResult, void(LeScanResult result)); -}; - -class LeScanManagerTest : public ::testing::Test { - public: - LeScanManagerTest(const LeScanManagerTest&) = delete; - LeScanManagerTest& operator=(const LeScanManagerTest&) = delete; - - protected: - LeScanManagerTest() - : io_task_runner_(base::ThreadPool::CreateSingleThreadTaskRunner( - {base::TaskPriority::BEST_EFFORT, base::MayBlock()})), - le_scan_manager_(&le_scanner_) { - le_scan_manager_.Initialize(io_task_runner_); - le_scan_manager_.AddObserver(&mock_observer_); - task_environment_.RunUntilIdle(); - } - ~LeScanManagerTest() override { - le_scan_manager_.RemoveObserver(&mock_observer_); - le_scan_manager_.Finalize(); - } - - bluetooth_v2_shlib::LeScanner::Delegate* delegate() { - return &le_scan_manager_; - } - - base::test::TaskEnvironment task_environment_; - scoped_refptr io_task_runner_; - bluetooth_v2_shlib::MockLeScanner le_scanner_; - LeScanManagerImpl le_scan_manager_; - MockLeScanManagerObserver mock_observer_; -}; - -} // namespace - -TEST_F(LeScanManagerTest, TestEnableDisableScan) { - std::unique_ptr scan_handle; - - // Enable the LE scan. We expect the observer to be updated and to get a scan - // handle. - EXPECT_CALL(le_scanner_, StartScan()).WillOnce(Return(true)); - EXPECT_CALL(mock_observer_, OnScanEnableChanged(true)); - le_scan_manager_.RequestScan(base::BindOnce( - &CopyResult>, &scan_handle)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(scan_handle); - - // After deleting the last handle, we expect scan to be disabled. - EXPECT_CALL(le_scanner_, StopScan()).WillOnce(Return(true)); - EXPECT_CALL(mock_observer_, OnScanEnableChanged(false)); - scan_handle.reset(); - task_environment_.RunUntilIdle(); -} - -TEST_F(LeScanManagerTest, TestPauseResumeScan) { - std::unique_ptr scan_handle; - - // Don't call StartScan or StopScan if there is no handle. - EXPECT_CALL(le_scanner_, StopScan()).Times(0); - le_scan_manager_.PauseScan(); - EXPECT_CALL(le_scanner_, StartScan()).Times(0); - le_scan_manager_.ResumeScan(); - task_environment_.RunUntilIdle(); - - // Create a handle. - EXPECT_CALL(le_scanner_, StartScan()).WillOnce(Return(true)); - EXPECT_CALL(mock_observer_, OnScanEnableChanged(true)); - le_scan_manager_.RequestScan(base::BindOnce( - &CopyResult>, &scan_handle)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(scan_handle); - - // Pause scan, we shouldn't declare scan is disabled. - EXPECT_CALL(mock_observer_, OnScanEnableChanged(_)).Times(0); - EXPECT_CALL(le_scanner_, StopScan()).WillOnce(Return(true)); - le_scan_manager_.PauseScan(); - task_environment_.RunUntilIdle(); - - // Resume scan. - EXPECT_CALL(mock_observer_, OnScanEnableChanged(_)).Times(0); - EXPECT_CALL(le_scanner_, StartScan()).WillOnce(Return(true)); - le_scan_manager_.ResumeScan(); - task_environment_.RunUntilIdle(); - - // Delete the handle. - EXPECT_CALL(le_scanner_, StopScan()).WillOnce(Return(true)); - EXPECT_CALL(mock_observer_, OnScanEnableChanged(false)); - scan_handle.reset(); - task_environment_.RunUntilIdle(); -} - -TEST_F(LeScanManagerTest, TestMultipleHandles) { - static constexpr int kNumHandles = 20; - - std::vector> scan_handles; - - EXPECT_CALL(le_scanner_, StartScan()).WillOnce(Return(true)); - EXPECT_CALL(mock_observer_, OnScanEnableChanged(true)); - for (int i = 0; i < kNumHandles; ++i) { - std::unique_ptr handle; - le_scan_manager_.RequestScan(base::BindOnce( - &CopyResult>, &handle)); - task_environment_.RunUntilIdle(); - ASSERT_TRUE(handle); - scan_handles.push_back(std::move(handle)); - } - - EXPECT_CALL(le_scanner_, StopScan()).Times(0); - for (int i = 0; i < kNumHandles - 1; ++i) { - scan_handles.pop_back(); - task_environment_.RunUntilIdle(); - } - - // After deleting the last handle, we expect scan to be disabled. - EXPECT_CALL(le_scanner_, StopScan()).WillOnce(Return(true)); - EXPECT_CALL(mock_observer_, OnScanEnableChanged(false)); - scan_handles.pop_back(); - task_environment_.RunUntilIdle(); -} - -TEST_F(LeScanManagerTest, TestGetScanResultsEmpty) { - std::vector results; - - // Get asynchronous scan results. The result should be empty. - le_scan_manager_.GetScanResults( - base::BindOnce(&CopyResult>, &results)); - - task_environment_.RunUntilIdle(); - ASSERT_EQ(0u, results.size()); -} - -TEST_F(LeScanManagerTest, TestEnableScanFails) { - std::unique_ptr scan_handle; - - // Observer should not be notified. - EXPECT_CALL(mock_observer_, OnScanEnableChanged(true)).Times(0); - - EXPECT_CALL(le_scanner_, StartScan()).WillOnce(Return(false)); - le_scan_manager_.RequestScan(base::BindOnce( - &CopyResult>, &scan_handle)); - task_environment_.RunUntilIdle(); - EXPECT_FALSE(scan_handle); -} - -TEST_F(LeScanManagerTest, TestGetScanResults) { - // Simulate some scan results. - bluetooth_v2_shlib::LeScanner::ScanResult raw_scan_result(kTestAddr1, {}, 1234); - - EXPECT_CALL(mock_observer_, OnNewScanResult(_)); - delegate()->OnScanResult(raw_scan_result); - task_environment_.RunUntilIdle(); - - std::vector results; - // Get asynchronous scan results. - le_scan_manager_.GetScanResults( - base::BindOnce(&CopyResult>, &results)); - - task_environment_.RunUntilIdle(); - - ASSERT_EQ(1u, results.size()); - ASSERT_EQ(kTestAddr1, results[0].addr); - ASSERT_EQ(1234, results[0].rssi); -} - -TEST_F(LeScanManagerTest, TestGetScanResultsWithService) { - EXPECT_CALL(mock_observer_, OnNewScanResult(_)).Times(2); - - // Add a scan result with service 0x4444. - bluetooth_v2_shlib::LeScanner::ScanResult raw_scan_result( - kTestAddr1, {0x03, 0x02, 0x44, 0x44}, 1234); - delegate()->OnScanResult(raw_scan_result); - - // Add a scan result with service 0x5555. - bluetooth_v2_shlib::LeScanner::ScanResult raw_scan_result_two( - kTestAddr2, {0x03, 0x02, 0x55, 0x55}, 1234); - delegate()->OnScanResult(raw_scan_result_two); - - task_environment_.RunUntilIdle(); - - // Get asynchronous scan results for results with service 0x4444. - std::vector results; - le_scan_manager_.GetScanResults( - base::BindOnce(&CopyResult>, &results), - ScanFilter::From16bitUuid(0x4444)); - task_environment_.RunUntilIdle(); - - ASSERT_EQ(1u, results.size()); - ASSERT_EQ(kTestAddr1, results[0].addr); - ASSERT_EQ(std::vector({0x44, 0x44}), - results[0].type_to_data[0x02][0]); - ASSERT_EQ(1234, results[0].rssi); - - // Get asynchronous scan results for results with service 0x5555. - le_scan_manager_.GetScanResults( - base::BindOnce(&CopyResult>, &results), - ScanFilter::From16bitUuid(0x5555)); - task_environment_.RunUntilIdle(); - - ASSERT_EQ(1u, results.size()); - ASSERT_EQ(kTestAddr2, results[0].addr); - ASSERT_EQ(std::vector({0x55, 0x55}), - results[0].type_to_data[0x02][0]); - ASSERT_EQ(1234, results[0].rssi); - - // Get asynchronous scan results for results with service 0x6666. - le_scan_manager_.GetScanResults( - base::BindOnce(&CopyResult>, &results), - ScanFilter::From16bitUuid(0x6666)); - task_environment_.RunUntilIdle(); - - ASSERT_EQ(0u, results.size()); -} - -TEST_F(LeScanManagerTest, TestGetScanResultsSortedByRssi) { - EXPECT_CALL(mock_observer_, OnNewScanResult(_)).Times(3); - - // Add a scan result with service 0x4444. - bluetooth_v2_shlib::LeScanner::ScanResult raw_scan_result( - kTestAddr1, {0x03, 0x02, 0x44, 0x44}, 1); - delegate()->OnScanResult(raw_scan_result); - - // Add a scan result with service 0x5555. - bluetooth_v2_shlib::LeScanner::ScanResult raw_scan_result_two( - kTestAddr2, {0x03, 0x02, 0x55, 0x55}, 3); - delegate()->OnScanResult(raw_scan_result_two); - - // Add a scan result with service 0x5555. - bluetooth_v2_shlib::LeScanner::ScanResult raw_scan_result_three( - kTestAddr1, {0x03, 0x02, 0x55, 0x55}, 2); - delegate()->OnScanResult(raw_scan_result_three); - - task_environment_.RunUntilIdle(); - - std::vector results; - // Get asynchronous scan results. - le_scan_manager_.GetScanResults( - base::BindOnce(&CopyResult>, &results)); - - task_environment_.RunUntilIdle(); - - ASSERT_EQ(3u, results.size()); - EXPECT_EQ(kTestAddr2, results[0].addr); - EXPECT_EQ(3, results[0].rssi); - EXPECT_EQ(kTestAddr1, results[1].addr); - EXPECT_EQ(2, results[1].rssi); - EXPECT_EQ(kTestAddr1, results[2].addr); - EXPECT_EQ(1, results[2].rssi); -} - -TEST_F(LeScanManagerTest, TestOnNewScanResult) { - LeScanResult result; - ON_CALL(mock_observer_, OnNewScanResult(_)) - .WillByDefault( - Invoke([&result](LeScanResult result_in) { result = result_in; })); - - // Add a scan result with service 0x4444. - bluetooth_v2_shlib::LeScanner::ScanResult raw_scan_result( - kTestAddr1, {0x03, 0x02, 0x44, 0x44}, 1); - delegate()->OnScanResult(raw_scan_result); - task_environment_.RunUntilIdle(); - - // Ensure that the observer was notified. - ASSERT_EQ(kTestAddr1, result.addr); - ASSERT_EQ(std::vector({0x44, 0x44}), result.type_to_data[0x02][0]); - ASSERT_EQ(1, result.rssi); -} - -TEST_F(LeScanManagerTest, TestMaxScanResultEntries) { - EXPECT_CALL(mock_observer_, OnNewScanResult(_)) - .Times(LeScanManagerImpl::kMaxScanResultEntries + 5); - - // Add scan results with different addrs. - for (int i = 0; i < LeScanManagerImpl::kMaxScanResultEntries + 5; ++i) { - uint8_t addr_bit0 = i & 0xFF; - uint8_t addr_bit1 = (i & 0xFF00) >> 8; - bluetooth_v2_shlib::LeScanner::ScanResult raw_scan_result( - {{addr_bit0, addr_bit1, 0xFF, 0xFF, 0xFF, 0xFF}}, {0x03, 0x02, 0x44, 0x44}, -i); - delegate()->OnScanResult(raw_scan_result); - } - - task_environment_.RunUntilIdle(); - - std::vector results; - // Get asynchronous scan results. - le_scan_manager_.GetScanResults( - base::BindOnce(&CopyResult>, &results)); - - task_environment_.RunUntilIdle(); - - // First 5 addresses should have been kicked out. - ASSERT_EQ(1024u, results.size()); - bluetooth_v2_shlib::Addr test_addr; - for (int i = 0; i < LeScanManagerImpl::kMaxScanResultEntries; ++i) { - uint8_t addr_bit0 = (i + 5) & 0xFF; - uint8_t addr_bit1 = ((i + 5) & 0xFF00) >> 8; - test_addr = {{addr_bit0, addr_bit1, 0xFF, 0xFF, 0xFF, 0xFF}}; - EXPECT_EQ(test_addr, results[i].addr); - EXPECT_EQ(-(i + 5), results[i].rssi); - } -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_result.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_result.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,314 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/le_scan_result.h" - -#include - -#include "base/logging.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" - -namespace chromecast { -namespace bluetooth { - -namespace { - -template -std::optional GetUuidsFromShort( - const std::map>>& type_to_data, - uint8_t type) { - auto it = type_to_data.find(type); - if (it == type_to_data.end()) { - return std::nullopt; - } - - LeScanResult::UuidList ret; - for (const auto& field : it->second) { - if (field.size() % sizeof(T)) { - LOG(ERROR) << "Invalid length, expected multiple of " << sizeof(T); - return std::nullopt; - } - - for (size_t i = 0; i < field.size(); i += sizeof(T)) { - // Uuids are transmitted in little endian byte order. (Bluetooth Core - // Specification v4.0 Vol 3 Part C Section 11.1). - T value = 0; - for (size_t j = 0; j < sizeof(T); ++j) { - value |= field[i + j] << 8 * j; - } - - ret.push_back(converter(value)); - } - } - - return ret; -} - -std::optional GetUuidsAsUuid( - const std::map>>& type_to_data, - uint8_t type) { - auto it = type_to_data.find(type); - if (it == type_to_data.end()) { - return std::nullopt; - } - - LeScanResult::UuidList ret; - for (const auto& field : it->second) { - if (field.size() % sizeof(bluetooth_v2_shlib::Uuid)) { - LOG(ERROR) << "Invalid length, expected multiple of " - << sizeof(bluetooth_v2_shlib::Uuid); - return std::nullopt; - } - - for (size_t i = 0; i < field.size(); - i += sizeof(bluetooth_v2_shlib::Uuid)) { - ret.emplace_back(); - // GAP UUIDs are little endian and bluetooth_v2_shlib::Uuid is big endian. - std::reverse_copy(field.begin() + i, - field.begin() + i + sizeof(bluetooth_v2_shlib::Uuid), - ret.back().begin()); - } - } - - return ret; -} - -} // namespace - -LeScanResult::LeScanResult() = default; -LeScanResult::LeScanResult(const LeScanResult& other) = default; -LeScanResult::~LeScanResult() = default; - -bool LeScanResult::SetAdvData(base::span advertisement_data) { - std::map>> new_type_to_data; - - size_t i = 0; - while (i < advertisement_data.size()) { - if (i + 1 == advertisement_data.size()) { - LOG(ERROR) << "Malformed BLE packet"; - return false; - } - - // http://www.argenox.com/bluetooth-low-energy-ble-v4-0-development/library/a-ble-advertising-primer/ - // Format: - // [size][type][payload ] - // [i ][i+1 ][i+2:i+1+size] - // - // Note: size does not include its own byte - uint8_t size = advertisement_data[i]; - uint8_t type = advertisement_data[i + 1]; - - // Avoid infinite loop if invalid data - if (size == 0 || i + 1 + size > advertisement_data.size()) { - LOG(ERROR) << "Invalid size"; - return false; - } - - base::span data = - advertisement_data.subspan(i + 2, size - 1); - new_type_to_data[type].emplace_back(data.begin(), data.end()); - - i += (size + 1); - } - - adv_data.assign(advertisement_data.begin(), advertisement_data.end()); - type_to_data.swap(new_type_to_data); - return true; -} - -std::optional LeScanResult::Name() const { - auto it = type_to_data.find(kGapCompleteName); - if (it != type_to_data.end()) { - DCHECK_GE(it->second.size(), 1u); - return std::string(reinterpret_cast(it->second[0].data()), - it->second[0].size()); - } - - it = type_to_data.find(kGapShortName); - if (it != type_to_data.end()) { - DCHECK_GE(it->second.size(), 1u); - return std::string(reinterpret_cast(it->second[0].data()), - it->second[0].size()); - } - - return std::nullopt; -} - -std::optional LeScanResult::Flags() const { - auto it = type_to_data.find(kGapFlags); - if (it == type_to_data.end()) { - return std::nullopt; - } - - DCHECK_GE(it->second.size(), 1u); - if (it->second[0].size() != 1) { - LOG(ERROR) << "Invalid length for flags"; - return std::nullopt; - } - - return it->second[0][0]; -} - -std::optional LeScanResult::AllServiceUuids() const { - bool any_exist = false; - UuidList ret; - auto insert_if_exists = [&ret, &any_exist](std::optional list) { - if (list) { - any_exist = true; - ret.insert(ret.end(), list->begin(), list->end()); - } - }; - - insert_if_exists(IncompleteListOf16BitServiceUuids()); - insert_if_exists(CompleteListOf16BitServiceUuids()); - insert_if_exists(IncompleteListOf32BitServiceUuids()); - insert_if_exists(CompleteListOf32BitServiceUuids()); - insert_if_exists(IncompleteListOf128BitServiceUuids()); - insert_if_exists(CompleteListOf128BitServiceUuids()); - - if (!any_exist) { - return std::nullopt; - } - - return ret; -} - -std::optional -LeScanResult::IncompleteListOf16BitServiceUuids() const { - return GetUuidsFromShort( - type_to_data, kGapIncomplete16BitServiceUuids); -} - -std::optional -LeScanResult::CompleteListOf16BitServiceUuids() const { - return GetUuidsFromShort( - type_to_data, kGapComplete16BitServiceUuids); -} - -std::optional -LeScanResult::IncompleteListOf32BitServiceUuids() const { - return GetUuidsFromShort( - type_to_data, kGapIncomplete32BitServiceUuids); -} - -std::optional -LeScanResult::CompleteListOf32BitServiceUuids() const { - return GetUuidsFromShort( - type_to_data, kGapComplete32BitServiceUuids); -} - -std::optional -LeScanResult::IncompleteListOf128BitServiceUuids() const { - return GetUuidsAsUuid(type_to_data, kGapIncomplete128BitServiceUuids); -} - -std::optional -LeScanResult::CompleteListOf128BitServiceUuids() const { - return GetUuidsAsUuid(type_to_data, kGapComplete128BitServiceUuids); -} - -LeScanResult::ServiceDataMap LeScanResult::AllServiceData() const { - ServiceDataMap ret; - - auto sd16 = ServiceData16Bit(); - ret.insert(sd16.begin(), sd16.end()); - - auto sd32 = ServiceData32Bit(); - ret.insert(sd32.begin(), sd32.end()); - - auto sd128 = ServiceData128Bit(); - ret.insert(sd128.begin(), sd128.end()); - - return ret; -} - -LeScanResult::ServiceDataMap LeScanResult::ServiceData16Bit() const { - ServiceDataMap ret; - auto it = type_to_data.find(kGapServicesData16bit); - if (it == type_to_data.end()) { - return ret; - } - - for (const auto& data : it->second) { - uint16_t uuid = 0; - if (data.size() < sizeof(uuid)) { - LOG(ERROR) << "Invalid service data, too short"; - ret.clear(); - return ret; - } - uuid = data[1] << 8 | data[0]; - ret[util::UuidFromInt16(uuid)] = - std::vector(data.begin() + sizeof(uuid), data.end()); - } - - return ret; -} - -LeScanResult::ServiceDataMap LeScanResult::ServiceData32Bit() const { - ServiceDataMap ret; - auto it = type_to_data.find(kGapServicesData32bit); - if (it == type_to_data.end()) { - return ret; - } - - for (const auto& data : it->second) { - uint32_t uuid = 0; - if (data.size() < sizeof(uuid)) { - LOG(ERROR) << "Invalid service data, too short"; - ret.clear(); - return ret; - } - uuid = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; - ret[util::UuidFromInt32(uuid)].assign(data.begin() + sizeof(uuid), - data.end()); - } - - return ret; -} - -LeScanResult::ServiceDataMap LeScanResult::ServiceData128Bit() const { - ServiceDataMap ret; - auto it = type_to_data.find(kGapServicesData128bit); - if (it == type_to_data.end()) { - return ret; - } - - for (const auto& data : it->second) { - bluetooth_v2_shlib::Uuid uuid; - if (data.size() < sizeof(uuid)) { - LOG(ERROR) << "Invalid service data, too short"; - ret.clear(); - return ret; - } - std::reverse_copy(data.begin(), data.begin() + sizeof(uuid), uuid.begin()); - ret[uuid].assign(data.begin() + sizeof(uuid), data.end()); - } - - return ret; -} - -std::map> LeScanResult::ManufacturerData() - const { - std::map> ret; - auto it = type_to_data.find(kGapManufacturerData); - if (it == type_to_data.end()) { - return ret; - } - - for (const auto& data : it->second) { - uint16_t id = 0; - if (data.size() < sizeof(id)) { - LOG(ERROR) << "Invalid manufacturer data, too short"; - ret.clear(); - return ret; - } - id = data[1] << 8 | data[0]; - ret[id].assign(data.begin() + sizeof(id), data.end()); - } - - return ret; -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_result.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_result.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_RESULT_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_RESULT_H_ - -#include -#include -#include -#include - -#include "base/containers/span.h" -#include "chromecast/public/bluetooth/bluetooth_types.h" - -namespace chromecast { -namespace bluetooth { - -struct LeScanResult { - // https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile - enum : uint8_t { - kGapFlags = 0x01, - kGapIncomplete16BitServiceUuids = 0x02, - kGapComplete16BitServiceUuids = 0x03, - kGapIncomplete32BitServiceUuids = 0x04, - kGapComplete32BitServiceUuids = 0x05, - kGapIncomplete128BitServiceUuids = 0x06, - kGapComplete128BitServiceUuids = 0x07, - kGapShortName = 0x08, - kGapCompleteName = 0x09, - kGapTxPowerLevel = 0x0a, - kGap128bitServiceSolicitations = 0x15, - kGapServicesData16bit = 0x16, - kGapAppearance = 0x19, - kGapServicesData32bit = 0x20, - kGapServicesData128bit = 0x21, - kGapManufacturerData = 0xff, - }; - - LeScanResult(); - LeScanResult(const LeScanResult& other); - ~LeScanResult(); - - bool SetAdvData(base::span adv_data); - - std::optional Name() const; - - std::optional Flags() const; - - using UuidList = std::vector; - std::optional AllServiceUuids() const; - std::optional IncompleteListOf16BitServiceUuids() const; - std::optional CompleteListOf16BitServiceUuids() const; - std::optional IncompleteListOf32BitServiceUuids() const; - std::optional CompleteListOf32BitServiceUuids() const; - std::optional IncompleteListOf128BitServiceUuids() const; - std::optional CompleteListOf128BitServiceUuids() const; - - using ServiceDataMap = - std::map>; - ServiceDataMap AllServiceData() const; - ServiceDataMap ServiceData16Bit() const; - ServiceDataMap ServiceData32Bit() const; - ServiceDataMap ServiceData128Bit() const; - - std::map> ManufacturerData() const; - - bluetooth_v2_shlib::Addr addr; - std::vector adv_data; - int rssi = -255; - - std::map>> type_to_data; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_LE_SCAN_RESULT_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_result_fuzzer.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result_fuzzer.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_result_fuzzer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result_fuzzer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/le_scan_result.h" - -// Entry point for LibFuzzer. -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - base::span adv_data(data, size); - chromecast::bluetooth::LeScanResult res; - res.SetAdvData(adv_data); - return 0; -} diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_result_test.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result_test.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/le_scan_result_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/le_scan_result_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,406 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/le_scan_result.h" - -#include "base/containers/contains.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace bluetooth { - -TEST(LeScanResultTest, SetAdvData) { - static const uint8_t kBadData[] = {0x3, 0x2}; - - LeScanResult scan_result; - - // Setting invalid data should not change the object. - EXPECT_FALSE(scan_result.SetAdvData({kBadData})); - EXPECT_TRUE(scan_result.adv_data.empty()); - EXPECT_TRUE(scan_result.type_to_data.empty()); - - const std::vector kFlags = {0x47}; - const std::vector kName = {0x41, 0x42, 0x43}; - const std::vector kService = {0x12, 0x34}; - - std::vector adv_data; - adv_data.push_back(kFlags.size() + 1); - adv_data.push_back(LeScanResult::kGapFlags); - adv_data.insert(adv_data.end(), kFlags.begin(), kFlags.end()); - adv_data.push_back(kName.size() + 1); - adv_data.push_back(LeScanResult::kGapCompleteName); - adv_data.insert(adv_data.end(), kName.begin(), kName.end()); - adv_data.push_back(kService.size() + 1); - adv_data.push_back(LeScanResult::kGapComplete16BitServiceUuids); - adv_data.insert(adv_data.end(), kService.begin(), kService.end()); - - EXPECT_TRUE(scan_result.SetAdvData(adv_data)); - EXPECT_EQ(adv_data, scan_result.adv_data); - ASSERT_EQ(1ul, scan_result.type_to_data[LeScanResult::kGapFlags].size()); - EXPECT_EQ(kFlags, scan_result.type_to_data[LeScanResult::kGapFlags][0]); - ASSERT_EQ(1ul, - scan_result.type_to_data[LeScanResult::kGapCompleteName].size()); - EXPECT_EQ(kName, scan_result.type_to_data[LeScanResult::kGapCompleteName][0]); - ASSERT_EQ( - 1ul, scan_result.type_to_data[LeScanResult::kGapComplete16BitServiceUuids] - .size()); - EXPECT_EQ( - kService, - scan_result.type_to_data[LeScanResult::kGapComplete16BitServiceUuids][0]); -} - -TEST(LeScanResultTest, Name) { - LeScanResult scan_result; - EXPECT_FALSE(scan_result.Name()); - - static const char kName1[] = "foo"; - static const char kName2[] = "foobar"; - - scan_result.type_to_data[LeScanResult::kGapShortName].push_back( - std::vector( - reinterpret_cast(kName1), - reinterpret_cast(kName1) + strlen(kName1))); - std::optional name = scan_result.Name(); - ASSERT_TRUE(name); - EXPECT_EQ(kName1, *name); - - scan_result.type_to_data[LeScanResult::kGapCompleteName].push_back( - std::vector( - reinterpret_cast(kName2), - reinterpret_cast(kName2) + strlen(kName2))); - - name = scan_result.Name(); - ASSERT_TRUE(name); - EXPECT_EQ(kName2, *name); -} - -TEST(LeScanResultTest, Flags) { - static const uint8_t kFlags = 0x42; - - LeScanResult scan_result; - EXPECT_FALSE(scan_result.Flags()); - scan_result.type_to_data[LeScanResult::kGapFlags].push_back({kFlags}); - auto flags = scan_result.Flags(); - ASSERT_TRUE(flags); - EXPECT_EQ(kFlags, *flags); -} - -TEST(LeScanResultTest, AllUuids) { - static const uint16_t kIncompleteUuid16 = 0x1234; - const std::vector kIncompleteUuid16Bytes = {0x34, 0x12}; - static const uint16_t kCompleteUuid16 = 0x5678; - const std::vector kCompleteUuid16Bytes = {0x78, 0x56}; - static const uint32_t kIncompleteUuid32 = 0x12345678; - const std::vector kIncompleteUuid32Bytes = {0x78, 0x56, 0x34, 0x12}; - static const uint32_t kCompleteUuid32 = 0xabcdef01; - const std::vector kCompleteUuid32Bytes = {0x1, 0xef, 0xcd, 0xab}; - static const bluetooth_v2_shlib::Uuid kIncompleteUuid128 = { - {0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, - 0x55, 0x44, 0x00, 0x00}}; - static const bluetooth_v2_shlib::Uuid kCompleteUuid128 = { - {0xa8, 0x22, 0xc8, 0x85, 0xaf, 0x02, 0xc7, 0x80, 0x9d, 0x4d, 0xbd, 0x9a, - 0x1f, 0xa0, 0x6d, 0x93}}; - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapIncomplete16BitServiceUuids] - .push_back(kIncompleteUuid16Bytes); - scan_result.type_to_data[LeScanResult::kGapComplete16BitServiceUuids] - .push_back(kCompleteUuid16Bytes); - scan_result.type_to_data[LeScanResult::kGapIncomplete32BitServiceUuids] - .push_back(kIncompleteUuid32Bytes); - scan_result.type_to_data[LeScanResult::kGapComplete32BitServiceUuids] - .push_back(kCompleteUuid32Bytes); - scan_result.type_to_data[LeScanResult::kGapIncomplete128BitServiceUuids] - .emplace_back(kIncompleteUuid128.rbegin(), kIncompleteUuid128.rend()); - scan_result.type_to_data[LeScanResult::kGapComplete128BitServiceUuids] - .emplace_back(kCompleteUuid128.rbegin(), kCompleteUuid128.rend()); - - auto all_uuids = scan_result.AllServiceUuids(); - ASSERT_TRUE(all_uuids); - ASSERT_EQ(6ul, all_uuids->size()); - - auto exists = [&all_uuids](const bluetooth_v2_shlib::Uuid& uuid) { - return base::Contains(*all_uuids, uuid); - }; - - EXPECT_TRUE(exists(util::UuidFromInt16(kIncompleteUuid16))); - EXPECT_TRUE(exists(util::UuidFromInt16(kCompleteUuid16))); - EXPECT_TRUE(exists(util::UuidFromInt32(kIncompleteUuid32))); - EXPECT_TRUE(exists(util::UuidFromInt32(kCompleteUuid32))); - EXPECT_TRUE(exists(kIncompleteUuid128)); - EXPECT_TRUE(exists(kCompleteUuid128)); -} - -TEST(LeScanResultTest, IncompleteListOf16BitServiceUuid) { - static const uint16_t kUuid1 = 0x1234; - const std::vector kUuid1Bytes = {0x34, 0x12}; - - static const uint16_t kUuid2 = 0x5678; - const std::vector kUuid2Bytes = {0x78, 0x56}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapIncomplete16BitServiceUuids] - .push_back(kUuid1Bytes); - scan_result.type_to_data[LeScanResult::kGapIncomplete16BitServiceUuids] - .push_back(kUuid2Bytes); - - auto uuids = scan_result.IncompleteListOf16BitServiceUuids(); - ASSERT_TRUE(uuids); - ASSERT_EQ(2ul, uuids->size()); - EXPECT_EQ(util::UuidFromInt16(kUuid1), (*uuids)[0]); - EXPECT_EQ(util::UuidFromInt16(kUuid2), (*uuids)[1]); -} - -TEST(LeScanResultTest, CompleteListOf16BitServiceUuid) { - static const uint16_t kUuid1 = 0x1234; - const std::vector kUuid1Bytes = {0x34, 0x12}; - - static const uint16_t kUuid2 = 0x5678; - const std::vector kUuid2Bytes = {0x78, 0x56}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapComplete16BitServiceUuids] - .push_back(kUuid1Bytes); - scan_result.type_to_data[LeScanResult::kGapComplete16BitServiceUuids] - .push_back(kUuid2Bytes); - - auto uuids = scan_result.CompleteListOf16BitServiceUuids(); - ASSERT_TRUE(uuids); - ASSERT_EQ(2ul, uuids->size()); - EXPECT_EQ(util::UuidFromInt16(kUuid1), (*uuids)[0]); - EXPECT_EQ(util::UuidFromInt16(kUuid2), (*uuids)[1]); -} - -TEST(LeScanResultTest, IncompleteListOf32BitServiceUuid) { - static const uint32_t kUuid1 = 0x12345678; - const std::vector kUuid1Bytes = {0x78, 0x56, 0x34, 0x12}; - - static const uint32_t kUuid2 = 0xabcdef01; - const std::vector kUuid2Bytes = {0x1, 0xef, 0xcd, 0xab}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapIncomplete32BitServiceUuids] - .push_back(kUuid1Bytes); - scan_result.type_to_data[LeScanResult::kGapIncomplete32BitServiceUuids] - .push_back(kUuid2Bytes); - - auto uuids = scan_result.IncompleteListOf32BitServiceUuids(); - ASSERT_TRUE(uuids); - ASSERT_EQ(2ul, uuids->size()); - EXPECT_EQ(util::UuidFromInt32(kUuid1), (*uuids)[0]); - EXPECT_EQ(util::UuidFromInt32(kUuid2), (*uuids)[1]); -} - -TEST(LeScanResultTest, CompleteListOf32BitServiceUuid) { - static const uint32_t kUuid1 = 0x12345678; - const std::vector kUuid1Bytes = {0x78, 0x56, 0x34, 0x12}; - - static const uint32_t kUuid2 = 0xabcdef01; - const std::vector kUuid2Bytes = {0x1, 0xef, 0xcd, 0xab}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapComplete32BitServiceUuids] - .push_back(kUuid1Bytes); - scan_result.type_to_data[LeScanResult::kGapComplete32BitServiceUuids] - .push_back(kUuid2Bytes); - - auto uuids = scan_result.CompleteListOf32BitServiceUuids(); - ASSERT_TRUE(uuids); - ASSERT_EQ(2ul, uuids->size()); - EXPECT_EQ(util::UuidFromInt32(kUuid1), (*uuids)[0]); - EXPECT_EQ(util::UuidFromInt32(kUuid2), (*uuids)[1]); -} - -TEST(LeScanResultTest, IncompleteListOf128BitServiceUuid) { - static const bluetooth_v2_shlib::Uuid kUuid1 = { - {0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, - 0x55, 0x44, 0x00, 0x00}}; - static const bluetooth_v2_shlib::Uuid kUuid2 = { - {0xa8, 0x22, 0xc8, 0x85, 0xaf, 0x02, 0xc7, 0x80, 0x9d, 0x4d, 0xbd, 0x9a, - 0x1f, 0xa0, 0x6d, 0x93}}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapIncomplete128BitServiceUuids] - .emplace_back(kUuid1.rbegin(), kUuid1.rend()); - scan_result.type_to_data[LeScanResult::kGapIncomplete128BitServiceUuids] - .emplace_back(kUuid2.rbegin(), kUuid2.rend()); - - auto uuids = scan_result.IncompleteListOf128BitServiceUuids(); - ASSERT_TRUE(uuids); - ASSERT_EQ(2ul, uuids->size()); - EXPECT_EQ(kUuid1, (*uuids)[0]); - EXPECT_EQ(kUuid2, (*uuids)[1]); -} - -TEST(LeScanResultTest, CompleteListOf128BitServiceUuid) { - static const bluetooth_v2_shlib::Uuid kUuid1 = { - {0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, - 0x55, 0x44, 0x00, 0x00}}; - static const bluetooth_v2_shlib::Uuid kUuid2 = { - {0xa8, 0x22, 0xc8, 0x85, 0xaf, 0x02, 0xc7, 0x80, 0x9d, 0x4d, 0xbd, 0x9a, - 0x1f, 0xa0, 0x6d, 0x93}}; - static const bluetooth_v2_shlib::Uuid kUuid3 = { - {0xaa, 0x22, 0xc8, 0x85, 0xaf, 0x02, 0xc7, 0x80, 0x9d, 0x4d, 0xbd, 0x9a, - 0x1f, 0xa0, 0x6d, 0x93}}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapComplete128BitServiceUuids] - .emplace_back(kUuid1.rbegin(), kUuid1.rend()); - scan_result.type_to_data[LeScanResult::kGapComplete128BitServiceUuids] - .emplace_back(kUuid2.rbegin(), kUuid2.rend()); - auto& end = - scan_result.type_to_data[LeScanResult::kGapComplete128BitServiceUuids] - .back(); - end.insert(end.end(), kUuid3.rbegin(), kUuid3.rend()); - - auto uuids = scan_result.CompleteListOf128BitServiceUuids(); - ASSERT_TRUE(uuids); - ASSERT_EQ(3ul, uuids->size()); - EXPECT_EQ(kUuid1, (*uuids)[0]); - EXPECT_EQ(kUuid2, (*uuids)[1]); - EXPECT_EQ(kUuid3, (*uuids)[2]); -} - -TEST(LeScanResultTest, AllServiceData) { - static const uint16_t kUuid16 = 0x1234; - const std::vector kUuid16Bytes = {0x34, 0x12, 0xab, 0xcd, 0xef}; - - static const uint32_t kUuid32 = 0x12345678; - const std::vector kUuid32Bytes = {0x78, 0x56, 0x34, 0x12, - 0xab, 0xcd, 0xef}; - - static const bluetooth_v2_shlib::Uuid kUuid128 = { - {0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, - 0x55, 0x44, 0x00, 0x00}}; - const std::vector kUuid128Data = {0x78, 0x56, 0x34, 0x12, - 0xab, 0xcd, 0xef}; - std::vector uuid128_bytes(kUuid128.rbegin(), kUuid128.rend()); - uuid128_bytes.insert(uuid128_bytes.end(), kUuid128Data.begin(), - kUuid128Data.end()); - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapServicesData16bit].push_back( - kUuid16Bytes); - scan_result.type_to_data[LeScanResult::kGapServicesData32bit].push_back( - kUuid32Bytes); - scan_result.type_to_data[LeScanResult::kGapServicesData128bit].push_back( - uuid128_bytes); - - auto sd = scan_result.AllServiceData(); - EXPECT_EQ(3ul, sd.size()); - EXPECT_EQ(sd[util::UuidFromInt16(kUuid16)], - std::vector(kUuid16Bytes.begin() + sizeof(kUuid16), - kUuid16Bytes.end())); - EXPECT_EQ(sd[util::UuidFromInt32(kUuid32)], - std::vector(kUuid32Bytes.begin() + sizeof(kUuid32), - kUuid32Bytes.end())); - EXPECT_EQ(sd[kUuid128], kUuid128Data); -} - -TEST(LeScanResultTest, ServiceData16Bit) { - static const uint16_t kUuid1 = 0x1234; - const std::vector kUuid1Bytes = {0x34, 0x12, 0xab, 0xcd, 0xef}; - - static const uint16_t kUuid2 = 0x5678; - const std::vector kUuid2Bytes = {0x78, 0x56, 0xa1, 0x0d, 0xe1}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapServicesData16bit].push_back( - kUuid1Bytes); - scan_result.type_to_data[LeScanResult::kGapServicesData16bit].push_back( - kUuid2Bytes); - - auto sd = scan_result.ServiceData16Bit(); - ASSERT_EQ(2ul, sd.size()); - EXPECT_EQ(sd[util::UuidFromInt16(kUuid1)], - std::vector(kUuid1Bytes.begin() + sizeof(kUuid1), - kUuid1Bytes.end())); - EXPECT_EQ(sd[util::UuidFromInt16(kUuid2)], - std::vector(kUuid2Bytes.begin() + sizeof(kUuid2), - kUuid2Bytes.end())); -} - -TEST(LeScanResultTest, ServiceData32Bit) { - static const uint32_t kUuid1 = 0x12345678; - const std::vector kUuid1Bytes = {0x78, 0x56, 0x34, 0x12, - 0xab, 0xcd, 0xef}; - - static const uint32_t kUuid2 = 0xabcdef01; - const std::vector kUuid2Bytes = {0x01, 0xef, 0xcd, 0xab, - 0xa1, 0x0d, 0xe1}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapServicesData32bit].push_back( - kUuid1Bytes); - scan_result.type_to_data[LeScanResult::kGapServicesData32bit].push_back( - kUuid2Bytes); - - auto sd = scan_result.ServiceData32Bit(); - ASSERT_EQ(2ul, sd.size()); - EXPECT_EQ(sd[util::UuidFromInt32(kUuid1)], - std::vector(kUuid1Bytes.begin() + sizeof(kUuid1), - kUuid1Bytes.end())); - EXPECT_EQ(sd[util::UuidFromInt32(kUuid2)], - std::vector(kUuid2Bytes.begin() + sizeof(kUuid2), - kUuid2Bytes.end())); -} - -TEST(LeScanResultTest, ServiceData128Bit) { - static const bluetooth_v2_shlib::Uuid kUuid1 = { - {0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, - 0x55, 0x44, 0x00, 0x00}}; - const std::vector kUuid1Data = {0x78, 0x56, 0x34, 0x12, - 0xab, 0xcd, 0xef}; - std::vector uuid1_bytes(kUuid1.rbegin(), kUuid1.rend()); - uuid1_bytes.insert(uuid1_bytes.end(), kUuid1Data.begin(), kUuid1Data.end()); - - static const bluetooth_v2_shlib::Uuid kUuid2 = { - {0xa8, 0x22, 0xc8, 0x85, 0xaf, 0x02, 0xc7, 0x80, 0x9d, 0x4d, 0xbd, 0x9a, - 0x1f, 0xa0, 0x6d, 0x93}}; - const std::vector kUuid2Data = {0x01, 0xef, 0xcd, 0xab, - 0xa1, 0x0d, 0xe1}; - std::vector uuid2_bytes(kUuid2.rbegin(), kUuid2.rend()); - uuid2_bytes.insert(uuid2_bytes.end(), kUuid2Data.begin(), kUuid2Data.end()); - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapServicesData128bit].push_back( - uuid1_bytes); - scan_result.type_to_data[LeScanResult::kGapServicesData128bit].push_back( - uuid2_bytes); - - auto sd = scan_result.ServiceData128Bit(); - ASSERT_EQ(2ul, sd.size()); - EXPECT_EQ(sd[kUuid1], kUuid1Data); - EXPECT_EQ(sd[kUuid2], kUuid2Data); -} - -TEST(LeScanResultTest, ManufacturerData) { - static const uint16_t kManufacturer1 = 0x1234; - const std::vector kManufacturer1Bytes = {0x34, 0x12, 0xab, 0xcd, - 0xef}; - - static const uint16_t kManufacturer2 = 0x5678; - const std::vector kManufacturer2Bytes = {0x78, 0x56, 0xa1, 0x0d, - 0xe1}; - - LeScanResult scan_result; - scan_result.type_to_data[LeScanResult::kGapManufacturerData].push_back( - kManufacturer1Bytes); - scan_result.type_to_data[LeScanResult::kGapManufacturerData].push_back( - kManufacturer2Bytes); - - auto md = scan_result.ManufacturerData(); - ASSERT_EQ(2ul, md.size()); - EXPECT_EQ( - md[kManufacturer1], - std::vector(kManufacturer1Bytes.begin() + sizeof(kManufacturer1), - kManufacturer1Bytes.end())); - EXPECT_EQ( - md[kManufacturer2], - std::vector(kManufacturer2Bytes.begin() + sizeof(kManufacturer2), - kManufacturer2Bytes.end())); -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_gatt_client_manager.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_gatt_client_manager.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_gatt_client_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_gatt_client_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/mock_gatt_client_manager.h" - -#include "chromecast/device/bluetooth/le/remote_characteristic.h" - -namespace chromecast { -namespace bluetooth { - -MockGattClientManager::MockGattClientManager() = default; -MockGattClientManager::~MockGattClientManager() = default; - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_gatt_client_manager.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_gatt_client_manager.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_gatt_client_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_gatt_client_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_GATT_CLIENT_MANAGER_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_GATT_CLIENT_MANAGER_H_ - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/observer_list.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/device/bluetooth/le/gatt_client_manager.h" -#include "chromecast/device/bluetooth/le/mock_remote_device.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace bluetooth { - -class MockGattClientManager : public GattClientManager { - public: - MockGattClientManager(); - ~MockGattClientManager() override; - - void AddObserver(Observer* o) override { observers_.AddObserver(o); } - void RemoveObserver(Observer* o) override { observers_.RemoveObserver(o); } - - MOCK_METHOD(scoped_refptr, - GetDevice, - (const bluetooth_v2_shlib::Addr& addr)); - void GetDevice( - const bluetooth_v2_shlib::Addr& addr, - base::OnceCallback)> cb) override { - std::move(cb).Run(GetDevice(addr)); - } - - MOCK_METHOD(scoped_refptr, - GetDeviceSync, - (const bluetooth_v2_shlib::Addr& addr), - (override)); - - MOCK_METHOD(std::vector>, - GetConnectedDevices, - ()); - void GetConnectedDevices(GetConnectDevicesCallback cb) override { - std::move(cb).Run(GetConnectedDevices()); - } - - MOCK_METHOD(void, - Initialize, - (scoped_refptr io_task_runner), - (override)); - MOCK_METHOD(void, Finalize, (), (override)); - MOCK_METHOD(void, - GetNumConnected, - (base::OnceCallback cb), - (const, override)); - MOCK_METHOD(void, - NotifyConnect, - (const bluetooth_v2_shlib::Addr& addr), - (override)); - MOCK_METHOD(void, - NotifyBonded, - (const bluetooth_v2_shlib::Addr& addr), - (override)); - MOCK_METHOD(scoped_refptr, - task_runner, - (), - (override)); - MOCK_METHOD(bool, - IsConnectedLeDevice, - (const bluetooth_v2_shlib::Addr& addr), - (override)); - MOCK_METHOD(bool, SetGattClientConnectable, (bool connectable), (override)); - MOCK_METHOD(void, DisconnectAll, (StatusCallback cb), (override)); - - base::ObserverList::Unchecked observers_; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_GATT_CLIENT_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_le_scan_manager.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_le_scan_manager.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_le_scan_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_le_scan_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/mock_le_scan_manager.h" - -namespace chromecast { -namespace bluetooth { - -MockLeScanManager::MockLeScanManager() = default; -MockLeScanManager::~MockLeScanManager() = default; - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_le_scan_manager.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_le_scan_manager.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_le_scan_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_le_scan_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,65 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_LE_SCAN_MANAGER_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_LE_SCAN_MANAGER_H_ - -#include - -#include "base/memory/raw_ptr.h" -#include "base/memory/scoped_refptr.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/device/bluetooth/le/le_scan_manager.h" -#include "chromecast/device/bluetooth/le/scan_filter.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace bluetooth { - -class MockLeScanManager : public LeScanManager { - public: - class MockScanHandle : public ScanHandle { - public: - MockScanHandle() = default; - ~MockScanHandle() override = default; - }; - - MockLeScanManager(); - ~MockLeScanManager() override; - - void AddObserver(Observer* o) override { - DCHECK(o && !observer_); - observer_ = o; - } - void RemoveObserver(Observer* o) override { - DCHECK(o && o == observer_); - observer_ = nullptr; - } - - MOCK_METHOD(void, - Initialize, - (scoped_refptr io_task_runner), - (override)); - MOCK_METHOD(void, Finalize, (), (override)); - MOCK_METHOD(std::unique_ptr, RequestScan, ()); - void RequestScan(RequestScanCallback cb) override { - std::move(cb).Run(RequestScan()); - } - - MOCK_METHOD(std::vector, - GetScanResults, - (std::optional scan_filter)); - void GetScanResults(GetScanResultsCallback cb, - std::optional scan_filter) override { - std::move(cb).Run(GetScanResults(std::move(scan_filter))); - } - MOCK_METHOD(void, ClearScanResults, (), (override)); - - raw_ptr observer_ = nullptr; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_LE_SCAN_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_characteristic.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_characteristic.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_characteristic.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_characteristic.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/mock_remote_characteristic.h" - -namespace chromecast { -namespace bluetooth { - -MockRemoteCharacteristic::MockRemoteCharacteristic( - const bluetooth_v2_shlib::Uuid& uuid) - : uuid_(uuid) {} - -MockRemoteCharacteristic::~MockRemoteCharacteristic() = default; - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_characteristic.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_characteristic.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_characteristic.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_characteristic.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_CHARACTERISTIC_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_CHARACTERISTIC_H_ - -#include -#include - -#include "chromecast/device/bluetooth/le/remote_characteristic.h" -#include "chromecast/device/bluetooth/le/remote_descriptor.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace bluetooth { - -class MockRemoteCharacteristic : public RemoteCharacteristic { - public: - explicit MockRemoteCharacteristic(const bluetooth_v2_shlib::Uuid& uuid); - - MOCK_METHOD0(GetDescriptors, std::vector>()); - MOCK_METHOD1( - GetDescriptorByUuid, - scoped_refptr(const bluetooth_v2_shlib::Uuid& uuid)); - - MOCK_METHOD1(SetRegisterNotification, bool(bool)); - void SetRegisterNotification(bool enable, StatusCallback cb) override { - std::move(cb).Run(SetRegisterNotification(enable)); - } - - MOCK_METHOD1(SetRegisterNotificationOrIndication, bool(bool)); - void SetRegisterNotificationOrIndication(bool enable, - StatusCallback cb) override { - std::move(cb).Run(SetRegisterNotificationOrIndication(enable)); - } - - void SetNotification(bool enable, StatusCallback cb) override {} - void ReadAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - ReadCallback callback) override {} - - MOCK_METHOD0(Read, std::pair>()); - void Read(ReadCallback callback) override { - auto res = Read(); - std::move(callback).Run(res.first, std::move(res.second)); - } - - MOCK_METHOD3(WriteAuth, - bool(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - const std::vector& value)); - void WriteAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - const std::vector& value, - StatusCallback callback) override { - std::move(callback).Run(WriteAuth(auth_req, write_type, value)); - } - - MOCK_METHOD1(Write, bool(const std::vector& value)); - void Write(const std::vector& value, - StatusCallback callback) override { - std::move(callback).Run(Write(value)); - } - - MOCK_METHOD0(NotificationEnabled, bool()); - const bluetooth_v2_shlib::Uuid& uuid() const override { return uuid_; } - MOCK_CONST_METHOD0(handle, HandleId()); - MOCK_CONST_METHOD0(permissions, bluetooth_v2_shlib::Gatt::Permissions()); - MOCK_CONST_METHOD0(properties, bluetooth_v2_shlib::Gatt::Properties()); - - const bluetooth_v2_shlib::Uuid uuid_; - - private: - friend testing::StrictMock; - - ~MockRemoteCharacteristic() override; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_CHARACTERISTIC_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_descriptor.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_descriptor.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_descriptor.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_descriptor.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/mock_remote_descriptor.h" - -namespace chromecast { -namespace bluetooth { - -MockRemoteDescriptor::MockRemoteDescriptor() = default; -MockRemoteDescriptor::~MockRemoteDescriptor() = default; - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_descriptor.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_descriptor.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_descriptor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_descriptor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_DESCRIPTOR_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_DESCRIPTOR_H_ - -#include - -#include "chromecast/device/bluetooth/le/remote_descriptor.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace bluetooth { - -class MockRemoteDescriptor : public RemoteDescriptor { - public: - MockRemoteDescriptor(); - - void ReadAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - ReadCallback callback) override {} - void Read(ReadCallback callback) override {} - void WriteAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - const std::vector& value, - StatusCallback callback) override {} - void Write(const std::vector& value, - StatusCallback callback) override {} - MOCK_CONST_METHOD0(uuid, const bluetooth_v2_shlib::Uuid()); - MOCK_CONST_METHOD0(handle, HandleId()); - MOCK_CONST_METHOD0(permissions, bluetooth_v2_shlib::Gatt::Permissions()); - - private: - ~MockRemoteDescriptor() override; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_DESCRIPTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_device.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_device.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_device.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_device.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/mock_remote_device.h" - -namespace chromecast { -namespace bluetooth { - -MockRemoteDevice::MockRemoteDevice(const bluetooth_v2_shlib::Addr& addr) - : addr_(addr) {} - -MockRemoteDevice::~MockRemoteDevice() = default; - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_device.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_device.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_device.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_device.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_DEVICE_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_DEVICE_H_ - -#include - -#include "chromecast/device/bluetooth/le/remote_device.h" -#include "chromecast/device/bluetooth/le/remote_service.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace bluetooth { - -class MockRemoteDevice : public RemoteDevice { - public: - explicit MockRemoteDevice(const bluetooth_v2_shlib::Addr& addr); - - MOCK_METHOD0(Connect, ConnectStatus()); - void Connect(ConnectCallback cb, - bluetooth_v2_shlib::Gatt::Client::Transport /* transport */) override { - std::move(cb).Run(Connect()); - } - - MOCK_METHOD0(Disconnect, bool()); - void Disconnect(StatusCallback cb) override { - std::move(cb).Run(Disconnect()); - } - - MOCK_METHOD0(CreateBond, bool()); - void CreateBond(StatusCallback cb) override { - std::move(cb).Run(CreateBond()); - } - - MOCK_METHOD0(RemoveBond, bool()); - void RemoveBond(StatusCallback cb) override { - std::move(cb).Run(RemoveBond()); - } - - MOCK_METHOD1(ReadRemoteRssi, void(RssiCallback cb)); - - MOCK_METHOD1(RequestMtu, bool(int mtu)); - void RequestMtu(int mtu, StatusCallback cb) override { - std::move(cb).Run(RequestMtu(mtu)); - } - - MOCK_METHOD4( - ConnectionParameterUpdate, - bool(int min_interval, int max_interval, int latency, int timeout)); - void ConnectionParameterUpdate(int min_interval, - int max_interval, - int latency, - int timeout, - StatusCallback cb) override { - std::move(cb).Run(ConnectionParameterUpdate(min_interval, max_interval, - latency, timeout)); - } - - MOCK_METHOD0(IsConnected, bool()); - - MOCK_METHOD0(IsBonded, bool()); - - MOCK_METHOD0(GetMtu, int()); - - MOCK_METHOD0(GetServices, std::vector>()); - void GetServices( - base::OnceCallback>)> cb) - override { - std::move(cb).Run(GetServices()); - } - - MOCK_METHOD0(GetServicesSync, std::vector>()); - - MOCK_METHOD1( - GetServiceByUuid, - scoped_refptr(const bluetooth_v2_shlib::Uuid& uuid)); - void GetServiceByUuid( - const bluetooth_v2_shlib::Uuid& uuid, - base::OnceCallback)> cb) override { - std::move(cb).Run(GetServiceByUuid(uuid)); - } - - MOCK_METHOD1( - GetServiceByUuidSync, - scoped_refptr(const bluetooth_v2_shlib::Uuid& uuid)); - - const bluetooth_v2_shlib::Addr& addr() const override { return addr_; } - - const bluetooth_v2_shlib::Addr addr_; - - private: - friend testing::StrictMock; - - ~MockRemoteDevice() override; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_DEVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_service.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_service.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_service.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_service.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/mock_remote_service.h" - -namespace chromecast { -namespace bluetooth { - -MockRemoteService::MockRemoteService(const bluetooth_v2_shlib::Uuid& uuid) - : uuid_(uuid) {} - -MockRemoteService::~MockRemoteService() = default; - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_service.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_service.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/mock_remote_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/mock_remote_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_SERVICE_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_SERVICE_H_ - -#include - -#include "chromecast/device/bluetooth/le/remote_characteristic.h" -#include "chromecast/device/bluetooth/le/remote_device.h" -#include "chromecast/device/bluetooth/le/remote_service.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace bluetooth { - -class MockRemoteService : public RemoteService { - public: - explicit MockRemoteService(const bluetooth_v2_shlib::Uuid& uuid); - - MOCK_METHOD0(GetCharacteristics, - std::vector>()); - MOCK_METHOD1(GetCharacteristicByUuid, - scoped_refptr( - const bluetooth_v2_shlib::Uuid& uuid)); - const bluetooth_v2_shlib::Uuid& uuid() const override { return uuid_; } - MOCK_CONST_METHOD0(handle, HandleId()); - MOCK_CONST_METHOD0(primary, bool()); - - const bluetooth_v2_shlib::Uuid uuid_; - - private: - friend testing::StrictMock; - - ~MockRemoteService() override; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_MOCK_REMOTE_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_characteristic.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_characteristic.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,99 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_CHARACTERISTIC_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_CHARACTERISTIC_H_ - -#include -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_refptr.h" -#include "chromecast/device/bluetooth/le/ble_types.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -class RemoteDescriptor; - -// A proxy for a remote characteristic on a RemoteDevice. Unless otherwise -// specified, all callbacks are run on the caller's thread. -class RemoteCharacteristic - : public base::RefCountedThreadSafe { - public: - using ReadCallback = - base::OnceCallback&)>; - using StatusCallback = base::OnceCallback; - - RemoteCharacteristic(const RemoteCharacteristic&) = delete; - RemoteCharacteristic& operator=(const RemoteCharacteristic&) = delete; - - // Return a list of all descriptors. - virtual std::vector> GetDescriptors() = 0; - - // Retrieves the descriptor with |uuid|, or nullptr if it doesn't exist. - virtual scoped_refptr GetDescriptorByUuid( - const bluetooth_v2_shlib::Uuid& uuid) = 0; - - // Register or deregister from a notification. Calls |SetNotification| and - // writes the CCCD. For indication support, see method - // |SetRegisterNotificationOrIndication|. - virtual void SetRegisterNotification(bool enable, StatusCallback cb) = 0; - - // Enable notifications for this characteristic. Client must still write to - // the CCCD seperately (or use |SetRegisterNotification| instead). - virtual void SetNotification(bool enable, StatusCallback cb) = 0; - - // If notification is supported, then register or deregister notification. - // If indication is supported, then register or deregister indication. - // Note that notification has higher priority over indication. - // Calls |SetNotification| and writes the CCCD. - virtual void SetRegisterNotificationOrIndication(bool enable, - StatusCallback cb) = 0; - - // Read the characteristic with |auth_req|. When completed, |callback| will be - // called. - virtual void ReadAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - ReadCallback callback) = 0; - - // Read the characteristic. Will retry if auth_req isn't met. When completed, - // |callback| will be called. - virtual void Read(ReadCallback callback) = 0; - - // Write |value| to the characteristic with |auth_req| and |write_type|. When - // completed, |callback| will be called. - virtual void WriteAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - const std::vector& value, - StatusCallback callback) = 0; - - // Write |value| to the characteristic inferring write_type from - // |permissions()|. Will retry if auth_req isn't met. When completed, - // |callback| will be called. - virtual void Write(const std::vector& value, - StatusCallback callback) = 0; - - // Returns true if notifications are enabled. - virtual bool NotificationEnabled() = 0; - - virtual const bluetooth_v2_shlib::Uuid& uuid() const = 0; - virtual HandleId handle() const = 0; - virtual bluetooth_v2_shlib::Gatt::Permissions permissions() const = 0; - virtual bluetooth_v2_shlib::Gatt::Properties properties() const = 0; - - protected: - friend class base::RefCountedThreadSafe; - - RemoteCharacteristic() = default; - virtual ~RemoteCharacteristic() = default; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_CHARACTERISTIC_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_characteristic_impl.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic_impl.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_characteristic_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,347 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/remote_characteristic_impl.h" - -#include "base/containers/contains.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/not_fatal_until.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "chromecast/device/bluetooth/le/gatt_client_manager_impl.h" -#include "chromecast/device/bluetooth/le/remote_descriptor_impl.h" -#include "chromecast/device/bluetooth/le/remote_device_impl.h" - -#define EXEC_CB_AND_RET(cb, ret, ...) \ - do { \ - if (cb) { \ - std::move(cb).Run(ret, ##__VA_ARGS__); \ - } \ - return; \ - } while (0) - -#define RUN_ON_IO_THREAD(method, ...) \ - io_task_runner_->PostTask( \ - FROM_HERE, \ - base::BindOnce(&RemoteCharacteristicImpl::method, this, ##__VA_ARGS__)); - -#define MAKE_SURE_IO_THREAD(method, ...) \ - DCHECK(io_task_runner_); \ - if (!io_task_runner_->BelongsToCurrentThread()) { \ - RUN_ON_IO_THREAD(method, ##__VA_ARGS__) \ - return; \ - } - -namespace chromecast { -namespace bluetooth { - -namespace { - -std::vector GetDescriptorNotificationValue(bool notification_enable) { - if (notification_enable) { - return std::vector( - std::begin(bluetooth::RemoteDescriptor::kEnableNotificationValue), - std::end(bluetooth::RemoteDescriptor::kEnableNotificationValue)); - } - - return std::vector( - std::begin(bluetooth::RemoteDescriptor::kDisableNotificationValue), - std::end(bluetooth::RemoteDescriptor::kDisableNotificationValue)); -} - -std::vector GetDescriptorIndicationValue(bool indication_enable) { - if (indication_enable) { - return std::vector( - std::begin(bluetooth::RemoteDescriptor::kEnableIndicationValue), - std::end(bluetooth::RemoteDescriptor::kEnableIndicationValue)); - } - - return std::vector( - std::begin(bluetooth::RemoteDescriptor::kDisableNotificationValue), - std::end(bluetooth::RemoteDescriptor::kDisableNotificationValue)); -} - -bool CharacteristicHasNotify( - const bluetooth_v2_shlib::Gatt::Characteristic* characteristic) { - return characteristic->properties & bluetooth_v2_shlib::Gatt::PROPERTY_NOTIFY; -} - -bool CharacteristicHasIndication( - const bluetooth_v2_shlib::Gatt::Characteristic* characteristic) { - return characteristic->properties & - bluetooth_v2_shlib::Gatt::PROPERTY_INDICATE; -} - -std::unique_ptr MaybeCreateFakeCccd( - const bluetooth_v2_shlib::Gatt::Characteristic* characteristic) { - if (!CharacteristicHasNotify(characteristic) && - !CharacteristicHasIndication(characteristic)) { - return nullptr; - } - - for (const auto& descriptor : characteristic->descriptors) { - if (descriptor.uuid == RemoteDescriptor::kCccdUuid) { - return nullptr; - } - } - - auto cccd = std::make_unique(); - cccd->uuid = RemoteDescriptor::kCccdUuid; - cccd->permissions = static_cast( - bluetooth_v2_shlib::Gatt::PERMISSION_READ | - bluetooth_v2_shlib::Gatt::PERMISSION_WRITE); - return cccd; -} - -} // namespace - -RemoteCharacteristicImpl::RemoteCharacteristicImpl( - RemoteDeviceImpl* device, - base::WeakPtr gatt_client_manager, - const bluetooth_v2_shlib::Gatt::Characteristic* characteristic, - scoped_refptr io_task_runner) - : device_(device), - gatt_client_manager_(gatt_client_manager), - characteristic_(characteristic), - io_task_runner_(io_task_runner), - fake_cccd_(MaybeCreateFakeCccd(characteristic)), - uuid_to_descriptor_(CreateDescriptorMap()) { - DCHECK(gatt_client_manager); - DCHECK(characteristic); - DCHECK(io_task_runner_->BelongsToCurrentThread()); -} - -RemoteCharacteristicImpl::~RemoteCharacteristicImpl() = default; - -std::map> -RemoteCharacteristicImpl::CreateDescriptorMap() { - std::map> ret; - for (const auto& descriptor : characteristic_->descriptors) { - ret[descriptor.uuid] = new RemoteDescriptorImpl( - device_, gatt_client_manager_, &descriptor, io_task_runner_); - } - - if (fake_cccd_) { - DCHECK(!base::Contains(ret, RemoteDescriptor::kCccdUuid)); - ret[fake_cccd_->uuid] = new RemoteDescriptorImpl( - device_, gatt_client_manager_, fake_cccd_.get(), io_task_runner_); - } - - return ret; -} - -std::vector> -RemoteCharacteristicImpl::GetDescriptors() { - std::vector> ret; - ret.reserve(uuid_to_descriptor_.size()); - for (const auto& pair : uuid_to_descriptor_) { - ret.push_back(pair.second); - } - - return ret; -} - -scoped_refptr RemoteCharacteristicImpl::GetDescriptorByUuid( - const bluetooth_v2_shlib::Uuid& uuid) { - auto it = uuid_to_descriptor_.find(uuid); - if (it == uuid_to_descriptor_.end()) { - return nullptr; - } - - return it->second; -} - -void RemoteCharacteristicImpl::SetRegisterNotification(bool enable, - StatusCallback cb) { - MAKE_SURE_IO_THREAD(SetRegisterNotification, enable, - BindToCurrentSequence(std::move(cb))); - - SetRegisterNotificationOrIndicationInternal(false, enable, std::move(cb)); -} - -void RemoteCharacteristicImpl::SetNotification(bool enable, StatusCallback cb) { - MAKE_SURE_IO_THREAD(SetNotification, enable, - BindToCurrentSequence(std::move(cb))); - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, false); - } - if (!gatt_client_manager_->gatt_client()->SetCharacteristicNotification( - device_->addr(), *characteristic_, enable)) { - LOG(ERROR) << "Set characteristic notification failed"; - EXEC_CB_AND_RET(cb, false); - } - - notification_enabled_ = enable; - EXEC_CB_AND_RET(cb, true); -} - -void RemoteCharacteristicImpl::SetRegisterNotificationOrIndication( - bool enable, - RemoteCharacteristic::StatusCallback cb) { - MAKE_SURE_IO_THREAD(SetRegisterNotificationOrIndication, enable, - BindToCurrentSequence(std::move(cb))); - - if (CharacteristicHasNotify(characteristic_)) { - SetRegisterNotificationOrIndicationInternal(false, enable, std::move(cb)); - } else if (CharacteristicHasIndication(characteristic_)) { - SetRegisterNotificationOrIndicationInternal(true, enable, std::move(cb)); - } else { - LOG(ERROR) << __func__ - << " failed: Characteristic doesn't support notification or " - "indication"; - EXEC_CB_AND_RET(cb, false); - } -} - -void RemoteCharacteristicImpl::SetRegisterNotificationOrIndicationInternal( - bool indication, - bool enable, - RemoteCharacteristic::StatusCallback cb) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, false); - } - - if (indication) { - if (!CharacteristicHasIndication(characteristic_)) { - LOG(ERROR) << __func__ - << " failed: Characteristic doesn't support indication"; - EXEC_CB_AND_RET(cb, false); - } - } else { - if (!CharacteristicHasNotify(characteristic_)) { - LOG(ERROR) << __func__ - << " failed: Characteristic doesn't support notifications"; - EXEC_CB_AND_RET(cb, false); - } - } - - if (notification_enabled_ == enable) { - EXEC_CB_AND_RET(cb, true); - } - - if (!gatt_client_manager_->gatt_client()->SetCharacteristicNotification( - device_->addr(), *characteristic_, enable)) { - LOG(ERROR) << "Set characteristic notification failed"; - EXEC_CB_AND_RET(cb, false); - } - - notification_enabled_ = enable; - - // If device has no CCCD and we needed to create a fake one, just return - // success. - if (fake_cccd_) { - EXEC_CB_AND_RET(cb, true); - } - - auto it = uuid_to_descriptor_.find(RemoteDescriptor::kCccdUuid); - CHECK(it != uuid_to_descriptor_.end(), base::NotFatalUntil::M130); - - // CCCD must exist. |fake_cccd_| should have been created if it doesn't exist. - std::vector write_val = indication - ? GetDescriptorIndicationValue(enable) - : GetDescriptorNotificationValue(enable); - it->second->WriteAuth(bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_NONE, - write_val, std::move(cb)); -} - -void RemoteCharacteristicImpl::ReadAuth( - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - ReadCallback callback) { - MAKE_SURE_IO_THREAD(ReadAuth, auth_req, - BindToCurrentSequence(std::move(callback))); - DCHECK(callback); - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(callback, false, {}); - } - - device_->ReadCharacteristic(this, auth_req, std::move(callback)); -} - -void RemoteCharacteristicImpl::Read(ReadCallback callback) { - ReadAuth(bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_INVALID, - std::move(callback)); -} - -void RemoteCharacteristicImpl::WriteAuth( - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - const std::vector& value, - StatusCallback callback) { - MAKE_SURE_IO_THREAD(WriteAuth, auth_req, write_type, value, - BindToCurrentSequence(std::move(callback))); - DCHECK(callback); - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(callback, false); - } - - device_->WriteCharacteristic(this, auth_req, write_type, value, - std::move(callback)); -} - -void RemoteCharacteristicImpl::Write(const std::vector& value, - StatusCallback callback) { - using WriteType = bluetooth_v2_shlib::Gatt::WriteType; - using Properties = bluetooth_v2_shlib::Gatt::Properties; - - WriteType write_type = WriteType::WRITE_TYPE_NONE; - if (properties() & Properties::PROPERTY_WRITE) { - write_type = WriteType::WRITE_TYPE_DEFAULT; - } else if (properties() & Properties::PROPERTY_WRITE_NO_RESPONSE) { - write_type = WriteType::WRITE_TYPE_NO_RESPONSE; - } else if (properties() & Properties::PROPERTY_SIGNED_WRITE) { - write_type = WriteType::WRITE_TYPE_SIGNED; - } else { - LOG(ERROR) << "Write not supported. Properties: " - << static_cast(properties()); - EXEC_CB_AND_RET(callback, false); - } - - WriteAuth(bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_NONE, write_type, value, - std::move(callback)); -} - -bool RemoteCharacteristicImpl::NotificationEnabled() { - return notification_enabled_; -} - -const bluetooth_v2_shlib::Gatt::Characteristic& -RemoteCharacteristicImpl::characteristic() const { - return *characteristic_; -} - -const bluetooth_v2_shlib::Uuid& RemoteCharacteristicImpl::uuid() const { - return characteristic_->uuid; -} - -HandleId RemoteCharacteristicImpl::handle() const { - return characteristic_->handle; -} - -bluetooth_v2_shlib::Gatt::Permissions RemoteCharacteristicImpl::permissions() - const { - return characteristic_->permissions; -} - -bluetooth_v2_shlib::Gatt::Properties RemoteCharacteristicImpl::properties() - const { - return characteristic_->properties; -} - -void RemoteCharacteristicImpl::Invalidate() { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - for (auto& item : uuid_to_descriptor_) { - static_cast(item.second.get())->Invalidate(); - } - gatt_client_manager_.reset(); -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_characteristic_impl.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic_impl.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_characteristic_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_characteristic_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_CHARACTERISTIC_IMPL_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_CHARACTERISTIC_IMPL_H_ - -#include -#include -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/device/bluetooth/le/remote_characteristic.h" - -namespace chromecast { -namespace bluetooth { - -class GattClientManagerImpl; -class RemoteDescriptor; -class RemoteDescriptorImpl; -class RemoteDeviceImpl; - -// A proxy for a remote characteristic on a RemoteDevice. Unless otherwise -// specified, all callbacks are run on the caller's thread. -class RemoteCharacteristicImpl : public RemoteCharacteristic { - public: - RemoteCharacteristicImpl(const RemoteCharacteristicImpl&) = delete; - RemoteCharacteristicImpl& operator=(const RemoteCharacteristicImpl&) = delete; - - // RemoteCharacteristic impl: - std::vector> GetDescriptors() override; - scoped_refptr GetDescriptorByUuid( - const bluetooth_v2_shlib::Uuid& uuid) override; - void SetRegisterNotification(bool enable, StatusCallback cb) override; - void SetNotification(bool enable, StatusCallback cb) override; - void SetRegisterNotificationOrIndication(bool enable, - StatusCallback cb) override; - void ReadAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - ReadCallback callback) override; - void Read(ReadCallback callback) override; - void WriteAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - const std::vector& value, - StatusCallback callback) override; - void Write(const std::vector& value, - StatusCallback callback) override; - bool NotificationEnabled() override; - const bluetooth_v2_shlib::Uuid& uuid() const override; - HandleId handle() const override; - bluetooth_v2_shlib::Gatt::Permissions permissions() const override; - bluetooth_v2_shlib::Gatt::Properties properties() const override; - - const bluetooth_v2_shlib::Gatt::Characteristic& characteristic() const; - - // Mark the object as out of scope. - void Invalidate(); - - private: - friend class GattClientManagerImpl; - friend class RemoteDeviceImpl; - friend class RemoteServiceImpl; - - RemoteCharacteristicImpl( - RemoteDeviceImpl* device, - base::WeakPtr gatt_client_manager, - const bluetooth_v2_shlib::Gatt::Characteristic* characteristic, - scoped_refptr io_task_runner); - ~RemoteCharacteristicImpl() override; - - std::map> - CreateDescriptorMap(); - - // If |indication| is true, register or deregister indication. - // If |indication| is false, register or deregister notification. - void SetRegisterNotificationOrIndicationInternal(bool indication, - bool enable, - StatusCallback cb); - - // Weak reference to avoid refcount loop. - const raw_ptr device_; - base::WeakPtr gatt_client_manager_; - const raw_ptr characteristic_; - - // All bluetooth_v2_shlib calls are run on this task_runner. All members must - // be accessed on this task_runner. - const scoped_refptr io_task_runner_; - - // Work around http://crbug/831878. This allows notifications on - // characteristics which do not have a CCCD. - const std::unique_ptr fake_cccd_; - - const std::map> - uuid_to_descriptor_; - - std::atomic notification_enabled_{false}; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_CHARACTERISTIC_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_descriptor.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_descriptor.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/remote_descriptor.h" - -namespace chromecast { -namespace bluetooth { - -// static -constexpr uint8_t RemoteDescriptor::kEnableNotificationValue[]; -// static -constexpr uint8_t RemoteDescriptor::kEnableIndicationValue[]; -// static -constexpr uint8_t RemoteDescriptor::kDisableNotificationValue[]; -// static -const bluetooth_v2_shlib::Uuid RemoteDescriptor::kCccdUuid = { - {0x00, 0x00, 0x29, 0x02, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, - 0x5f, 0x9b, 0x34, 0xfb}}; - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_descriptor.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_descriptor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DESCRIPTOR_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DESCRIPTOR_H_ - -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "chromecast/device/bluetooth/le/ble_types.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -class RemoteDevice; -class RemoteDescriptor; - -// A proxy for a remote descriptor on a RemoteDevice. Unless otherwise -// specified, all callbacks are run on the caller's thread. -class RemoteDescriptor : public base::RefCountedThreadSafe { - public: - static constexpr uint8_t kEnableNotificationValue[] = {0x01, 0x00}; - static constexpr uint8_t kEnableIndicationValue[] = {0x02, 0x00}; - static constexpr uint8_t kDisableNotificationValue[] = {0x00, 0x00}; - static const bluetooth_v2_shlib::Uuid kCccdUuid; - - using ReadCallback = - base::OnceCallback&)>; - using StatusCallback = base::OnceCallback; - - RemoteDescriptor(const RemoteDescriptor&) = delete; - RemoteDescriptor& operator=(const RemoteDescriptor&) = delete; - - // Read the descriptor with |auth_req|. When completed, |callback| will be - // called. - virtual void ReadAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - ReadCallback callback) = 0; - - // Read the descriptor. When completed, |callback| will be called. - virtual void Read(ReadCallback callback) = 0; - - // Write |value| to the descriptor with |auth_req|. When completed, |callback| - // will be called. - virtual void WriteAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - const std::vector& value, - StatusCallback callback) = 0; - - // Write |value| to the descriptor. Will retry if auth_req isn't met. When - // completed, |callback| will be called. - virtual void Write(const std::vector& value, - StatusCallback callback) = 0; - - virtual const bluetooth_v2_shlib::Uuid uuid() const = 0; - virtual HandleId handle() const = 0; - virtual bluetooth_v2_shlib::Gatt::Permissions permissions() const = 0; - - protected: - friend class base::RefCountedThreadSafe; - - RemoteDescriptor() = default; - virtual ~RemoteDescriptor() = default; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DESCRIPTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_descriptor_impl.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor_impl.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_descriptor_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/remote_descriptor_impl.h" - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "chromecast/device/bluetooth/le/gatt_client_manager_impl.h" -#include "chromecast/device/bluetooth/le/remote_device_impl.h" - -#define EXEC_CB_AND_RET(cb, ret, ...) \ - do { \ - if (cb) { \ - std::move(cb).Run(ret, ##__VA_ARGS__); \ - } \ - return; \ - } while (0) - -#define RUN_ON_IO_THREAD(method, ...) \ - io_task_runner_->PostTask( \ - FROM_HERE, \ - base::BindOnce(&RemoteDescriptorImpl::method, this, ##__VA_ARGS__)); - -#define MAKE_SURE_IO_THREAD(method, ...) \ - DCHECK(io_task_runner_); \ - if (!io_task_runner_->BelongsToCurrentThread()) { \ - RUN_ON_IO_THREAD(method, ##__VA_ARGS__) \ - return; \ - } - -namespace chromecast { -namespace bluetooth { - -RemoteDescriptorImpl::RemoteDescriptorImpl( - RemoteDeviceImpl* device, - base::WeakPtr gatt_client_manager, - const bluetooth_v2_shlib::Gatt::Descriptor* descriptor, - scoped_refptr io_task_runner) - : device_(device), - gatt_client_manager_(std::move(gatt_client_manager)), - descriptor_(descriptor), - io_task_runner_(std::move(io_task_runner)) { - DCHECK(device); - DCHECK(gatt_client_manager_); - DCHECK(descriptor); - DCHECK(io_task_runner_->BelongsToCurrentThread()); -} - -RemoteDescriptorImpl::~RemoteDescriptorImpl() = default; - -void RemoteDescriptorImpl::ReadAuth( - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - ReadCallback callback) { - MAKE_SURE_IO_THREAD(ReadAuth, auth_req, - BindToCurrentSequence(std::move(callback))); - DCHECK(callback); - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(callback, false, {}); - } - - device_->ReadDescriptor(this, auth_req, std::move(callback)); -} - -void RemoteDescriptorImpl::Read(ReadCallback callback) { - ReadAuth(bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_INVALID, - std::move(callback)); -} - -void RemoteDescriptorImpl::WriteAuth( - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - const std::vector& value, - StatusCallback callback) { - MAKE_SURE_IO_THREAD(WriteAuth, auth_req, value, - BindToCurrentSequence(std::move(callback))); - DCHECK(callback); - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(callback, false); - } - - device_->WriteDescriptor(this, auth_req, value, std::move(callback)); -} - -void RemoteDescriptorImpl::Write(const std::vector& value, - StatusCallback callback) { - WriteAuth(bluetooth_v2_shlib::Gatt::Client::AUTH_REQ_INVALID, value, - std::move(callback)); -} - -const bluetooth_v2_shlib::Gatt::Descriptor& RemoteDescriptorImpl::descriptor() - const { - return *descriptor_; -} - -const bluetooth_v2_shlib::Uuid RemoteDescriptorImpl::uuid() const { - return descriptor_->uuid; -} - -HandleId RemoteDescriptorImpl::handle() const { - return descriptor_->handle; -} - -bluetooth_v2_shlib::Gatt::Permissions RemoteDescriptorImpl::permissions() - const { - return descriptor_->permissions; -} - -void RemoteDescriptorImpl::Invalidate() { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - gatt_client_manager_.reset(); -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_descriptor_impl.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor_impl.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_descriptor_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_descriptor_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DESCRIPTOR_IMPL_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DESCRIPTOR_IMPL_H_ - -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/device/bluetooth/le/remote_descriptor.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -class GattClientManagerImpl; -class RemoteDeviceImpl; - -class RemoteDescriptorImpl : public RemoteDescriptor { - public: - RemoteDescriptorImpl(const RemoteDescriptorImpl&) = delete; - RemoteDescriptorImpl& operator=(const RemoteDescriptorImpl&) = delete; - - // RemoteDescriptor implementation: - void ReadAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - ReadCallback callback) override; - void Read(ReadCallback callback) override; - void WriteAuth(bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - const std::vector& value, - StatusCallback callback) override; - void Write(const std::vector& value, - StatusCallback callback) override; - const bluetooth_v2_shlib::Uuid uuid() const override; - HandleId handle() const override; - bluetooth_v2_shlib::Gatt::Permissions permissions() const override; - - const bluetooth_v2_shlib::Gatt::Descriptor& descriptor() const; - - // Mark the object as out of scope. - void Invalidate(); - - private: - friend class GattClientManagerImpl; - friend class RemoteCharacteristicImpl; - friend class RemoteDeviceImpl; - - RemoteDescriptorImpl( - RemoteDeviceImpl* device, - base::WeakPtr gatt_client_manager, - const bluetooth_v2_shlib::Gatt::Descriptor* descriptor, - scoped_refptr io_task_runner); - ~RemoteDescriptorImpl() override; - - const raw_ptr device_; - base::WeakPtr gatt_client_manager_; - const raw_ptr descriptor_; - - // All bluetooth_v2_shlib calls are run on this task_runner. All members must - // be accessed on this task_runner. - const scoped_refptr io_task_runner_; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DESCRIPTOR_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_device.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_device.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DEVICE_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DEVICE_H_ - -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -class RemoteService; - -// A proxy to for a remote GATT server device. -class RemoteDevice : public base::RefCountedThreadSafe { - public: - enum : int { - kDefaultMtu = 20, - }; - - enum class ConnectStatus { - kUndefined, - kGattClientManagerDestroyed, - kConnectPending, - kFailure, - kSuccess, - }; - - using StatusCallback = base::OnceCallback; - using ConnectCallback = base::OnceCallback; - - RemoteDevice(const RemoteDevice&) = delete; - RemoteDevice& operator=(const RemoteDevice&) = delete; - - // Initiate a connection to this device. Callback will return |true| if - // connected successfully, otherwise false. Only one pending call is allowed - // at a time. - virtual void Connect( - ConnectCallback cb, - bluetooth_v2_shlib::Gatt::Client::Transport transport = bluetooth_v2_shlib::Gatt::Client::Transport::kAuto) = 0; - - // Disconnect from this device. Callback will return |true| if disconnected - // successfully, otherwise false. Only one pending call is allowed at a time. - virtual void Disconnect(StatusCallback cb) = 0; - - // Create bond to this device. Callback will return |true| if - // bonded successfully, otherwise false. Device must be connected. - virtual void CreateBond(StatusCallback cb) = 0; - - // Remove bond to this device. Callback will return |true| if - // bond is removed, otherwise false. - virtual void RemoveBond(StatusCallback cb) = 0; - - // Read this device's RSSI. The result will be sent in |callback|. Only one - // pending call is allowed at a time. - using RssiCallback = base::OnceCallback; - virtual void ReadRemoteRssi(RssiCallback cb) = 0; - - // Request an MTU update to |mtu|. Callback will return |true| if MTU is - // updated successfully, otherwise false. Only one pending call is allowed at - // a time. - virtual void RequestMtu(int mtu, StatusCallback cb) = 0; - - // Request an update to connection parameters. - virtual void ConnectionParameterUpdate(int min_interval, - int max_interval, - int latency, - int timeout, - StatusCallback cb) = 0; - - // Returns true if this device is connected. - virtual bool IsConnected() = 0; - - // Returns true if this device is bonded. - virtual bool IsBonded() = 0; - - // Returns the current MTU of the connection with this device. - virtual int GetMtu() = 0; - - // Returns a list of all discovered services on this device. After - // GattClientManager::Observer::OnServicesUpdated is called, these may point - // to old services, so services need to be reobtained. - virtual void GetServices( - base::OnceCallback>)> - cb) = 0; - - // TODO(bcf): Deprecated. Replace usage with async version. - virtual std::vector> GetServicesSync() = 0; - - // Returns the service corresponding to |uuid|, or nullptr if none exist. - virtual void GetServiceByUuid( - const bluetooth_v2_shlib::Uuid& uuid, - base::OnceCallback)> cb) = 0; - - // TODO(bcf): Deprecated. Replace usage with async version. - virtual scoped_refptr GetServiceByUuidSync( - const bluetooth_v2_shlib::Uuid& uuid) = 0; - - virtual const bluetooth_v2_shlib::Addr& addr() const = 0; - - protected: - friend base::RefCountedThreadSafe; - - RemoteDevice() = default; - virtual ~RemoteDevice() = default; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DEVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_device_impl.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device_impl.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_device_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,729 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/remote_device_impl.h" - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/not_fatal_until.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "chromecast/device/bluetooth/le/gatt_client_manager_impl.h" -#include "chromecast/device/bluetooth/le/remote_characteristic_impl.h" -#include "chromecast/device/bluetooth/le/remote_descriptor_impl.h" -#include "chromecast/device/bluetooth/le/remote_service_impl.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -#define RUN_ON_IO_THREAD(method, ...) \ - io_task_runner_->PostTask( \ - FROM_HERE, \ - base::BindOnce(&RemoteDeviceImpl::method, this, ##__VA_ARGS__)); - -#define MAKE_SURE_IO_THREAD(method, ...) \ - DCHECK(io_task_runner_); \ - if (!io_task_runner_->BelongsToCurrentThread()) { \ - RUN_ON_IO_THREAD(method, ##__VA_ARGS__) \ - return; \ - } - -#define EXEC_CB_AND_RET(cb, ret, ...) \ - do { \ - if (cb) { \ - std::move(cb).Run(ret, ##__VA_ARGS__); \ - } \ - return; \ - } while (0) - -#define CHECK_CONNECTED(cb) \ - do { \ - if (!connected_) { \ - LOG(ERROR) << __func__ << "failed: Not connected"; \ - EXEC_CB_AND_RET(cb, false); \ - } \ - } while (0) - -#define LOG_EXEC_CB_AND_RET(cb, ret) \ - do { \ - if (!ret) { \ - LOG(ERROR) << __func__ << "failed"; \ - } \ - EXEC_CB_AND_RET(cb, ret); \ - } while (0) - -// static -constexpr base::TimeDelta RemoteDeviceImpl::kCommandTimeout; - -RemoteDeviceImpl::RemoteDeviceImpl( - const bluetooth_v2_shlib::Addr& addr, - base::WeakPtr gatt_client_manager, - scoped_refptr io_task_runner) - : gatt_client_manager_(gatt_client_manager), - addr_(addr), - io_task_runner_(io_task_runner) { - DCHECK(gatt_client_manager); - DCHECK(io_task_runner_->BelongsToCurrentThread()); -} - -RemoteDeviceImpl::~RemoteDeviceImpl() = default; - -void RemoteDeviceImpl::Connect(ConnectCallback cb, - bluetooth_v2_shlib::Gatt::Client::Transport transport) { - MAKE_SURE_IO_THREAD(Connect, BindToCurrentSequence(std::move(cb)), transport); - LOG(INFO) << "Connect(" << util::AddrLastByteString(addr_) << ")"; - - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, ConnectStatus::kGattClientManagerDestroyed); - } - - if (connect_cb_) { - LOG(ERROR) << __func__ << " failed: Connection pending"; - EXEC_CB_AND_RET(cb, ConnectStatus::kConnectPending); - } - - gatt_client_manager_->NotifyConnect(addr_); - connect_cb_ = std::move(cb); - gatt_client_manager_->EnqueueConnectRequest(addr_, true, transport); -} - -void RemoteDeviceImpl::Disconnect(StatusCallback cb) { - MAKE_SURE_IO_THREAD(Disconnect, BindToCurrentSequence(std::move(cb))); - LOG(INFO) << "Disconnect(" << util::AddrLastByteString(addr_) << ")"; - - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, false); - } - - disconnect_pending_ = true; - disconnect_cb_ = std::move(cb); - gatt_client_manager_->EnqueueConnectRequest(addr_, false); -} - -void RemoteDeviceImpl::CreateBond(StatusCallback cb) { - MAKE_SURE_IO_THREAD(CreateBond, BindToCurrentSequence(std::move(cb))); - LOG(INFO) << "CreateBond(" << util::AddrLastByteString(addr_) << ")"; - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, false); - } - - if (!connected_) { - LOG(ERROR) << "Not connected"; - EXEC_CB_AND_RET(cb, false); - } - - if (create_bond_pending_ || remove_bond_pending_) { - // TODO(tiansong): b/120489954 Implement queuing and timeout logic. - LOG(ERROR) << __func__ << " failed: waiting for pending bond command"; - EXEC_CB_AND_RET(cb, false); - } - - if (bonded_) { - LOG(ERROR) << "Already bonded"; - EXEC_CB_AND_RET(cb, false); - } - - if (!gatt_client_manager_->gatt_client()->CreateBond(addr_)) { - LOG(ERROR) << __func__ << " failed"; - EXEC_CB_AND_RET(cb, false); - } - - create_bond_pending_ = true; - create_bond_cb_ = std::move(cb); -} - -void RemoteDeviceImpl::RemoveBond(StatusCallback cb) { - MAKE_SURE_IO_THREAD(RemoveBond, BindToCurrentSequence(std::move(cb))); - LOG(INFO) << "RemoveBond(" << util::AddrLastByteString(addr_) << ")"; - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, false); - } - - if (create_bond_pending_ || remove_bond_pending_) { - // TODO(tiansong): b/120489954 Implement queuing and timeout logic. - LOG(ERROR) << __func__ << " failed: waiting for pending bond command"; - EXEC_CB_AND_RET(cb, false); - } - - if (!bonded_) { - LOG(WARNING) << "Not bonded"; - } - - if (!gatt_client_manager_->gatt_client()->RemoveBond(addr_)) { - LOG(ERROR) << __func__ << " failed"; - EXEC_CB_AND_RET(cb, false); - } - - remove_bond_pending_ = true; - remove_bond_cb_ = std::move(cb); -} - -void RemoteDeviceImpl::ReadRemoteRssi(RssiCallback cb) { - MAKE_SURE_IO_THREAD(ReadRemoteRssi, BindToCurrentSequence(std::move(cb))); - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, false, 0); - } - - if (rssi_pending_) { - LOG(ERROR) << "Read remote RSSI already pending"; - EXEC_CB_AND_RET(cb, false, 0); - } - - rssi_pending_ = true; - rssi_cb_ = std::move(cb); - gatt_client_manager_->EnqueueReadRemoteRssiRequest(addr_); -} - -void RemoteDeviceImpl::RequestMtu(int mtu, StatusCallback cb) { - MAKE_SURE_IO_THREAD(RequestMtu, mtu, BindToCurrentSequence(std::move(cb))); - LOG(INFO) << "RequestMtu(" << util::AddrLastByteString(addr_) << ", " << mtu - << ")"; - DCHECK(cb); - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, false); - } - CHECK_CONNECTED(cb); - mtu_callbacks_.push(std::move(cb)); - EnqueueOperation( - __func__, base::BindOnce(&RemoteDeviceImpl::RequestMtuImpl, this, mtu)); -} - -void RemoteDeviceImpl::ConnectionParameterUpdate(int min_interval, - int max_interval, - int latency, - int timeout, - StatusCallback cb) { - MAKE_SURE_IO_THREAD(ConnectionParameterUpdate, min_interval, max_interval, - latency, timeout, BindToCurrentSequence(std::move(cb))); - LOG(INFO) << "ConnectionParameterUpdate(" << util::AddrLastByteString(addr_) - << ", " << min_interval << ", " << max_interval << ", " << latency - << ", " << timeout << ")"; - if (!gatt_client_manager_) { - LOG(ERROR) << __func__ << " failed: Destroyed"; - EXEC_CB_AND_RET(cb, false); - } - CHECK_CONNECTED(cb); - bool ret = gatt_client_manager_->gatt_client()->ConnectionParameterUpdate( - addr_, min_interval, max_interval, latency, timeout); - LOG_EXEC_CB_AND_RET(cb, ret); -} - -bool RemoteDeviceImpl::IsConnected() { - return connected_ && !disconnect_pending_; -} - -bool RemoteDeviceImpl::IsBonded() { - return bonded_; -} - -int RemoteDeviceImpl::GetMtu() { - return mtu_; -} - -void RemoteDeviceImpl::GetServices( - base::OnceCallback>)> cb) { - MAKE_SURE_IO_THREAD(GetServices, BindToCurrentSequence(std::move(cb))); - auto ret = GetServicesSync(); - EXEC_CB_AND_RET(cb, std::move(ret)); -} - -std::vector> RemoteDeviceImpl::GetServicesSync() { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - std::vector> services; - services.reserve(uuid_to_service_.size()); - for (const auto& pair : uuid_to_service_) - services.push_back(pair.second); - - return services; -} - -void RemoteDeviceImpl::GetServiceByUuid( - const bluetooth_v2_shlib::Uuid& uuid, - base::OnceCallback)> cb) { - MAKE_SURE_IO_THREAD(GetServiceByUuid, uuid, - BindToCurrentSequence(std::move(cb))); - auto ret = GetServiceByUuidSync(uuid); - EXEC_CB_AND_RET(cb, std::move(ret)); -} - -const bluetooth_v2_shlib::Addr& RemoteDeviceImpl::addr() const { - return addr_; -} - -void RemoteDeviceImpl::ReadCharacteristic( - scoped_refptr characteristic, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - RemoteCharacteristic::ReadCallback cb) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - handle_to_characteristic_read_cbs_[characteristic->handle()].push( - std::move(cb)); - - EnqueueOperation( - __func__, base::BindOnce(&RemoteDeviceImpl::ReadCharacteristicImpl, this, - std::move(characteristic), auth_req)); -} - -void RemoteDeviceImpl::WriteCharacteristic( - scoped_refptr characteristic, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - std::vector value, - RemoteCharacteristic::StatusCallback cb) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - handle_to_characteristic_write_cbs_[characteristic->handle()].push( - std::move(cb)); - EnqueueOperation( - __func__, base::BindOnce(&RemoteDeviceImpl::WriteCharacteristicImpl, this, - std::move(characteristic), auth_req, write_type, - std::move(value))); -} - -void RemoteDeviceImpl::ReadDescriptor( - scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - RemoteDescriptor::ReadCallback cb) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - handle_to_descriptor_read_cbs_[descriptor->handle()].push(std::move(cb)); - - EnqueueOperation(__func__, - base::BindOnce(&RemoteDeviceImpl::ReadDescriptorImpl, this, - std::move(descriptor), auth_req)); -} - -void RemoteDeviceImpl::WriteDescriptor( - scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - std::vector value, - RemoteDescriptor::StatusCallback cb) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - handle_to_descriptor_write_cbs_[descriptor->handle()].push(std::move(cb)); - EnqueueOperation( - __func__, - base::BindOnce(&RemoteDeviceImpl::WriteDescriptorImpl, this, - std::move(descriptor), auth_req, std::move(value))); -} - -scoped_refptr RemoteDeviceImpl::GetServiceByUuidSync( - const bluetooth_v2_shlib::Uuid& uuid) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - auto it = uuid_to_service_.find(uuid); - if (it == uuid_to_service_.end()) - return nullptr; - - return it->second; -} - -void RemoteDeviceImpl::SetConnected(bool connected) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - // We only set connected = true and call the callback after services are - // discovered. - if (!connected) { - connected_ = false; - ConnectComplete(false); - } - - if (disconnect_pending_) { - disconnect_pending_ = false; - if (disconnect_cb_) { - std::move(disconnect_cb_).Run(!connected); - } - } - - if (!connected && rssi_pending_) { - LOG(ERROR) << "Read remote RSSI failed: disconnected"; - if (rssi_cb_) { - std::move(rssi_cb_).Run(false, 0); - } - rssi_pending_ = false; - } - - if (connected) { - if (!gatt_client_manager_) { - LOG(ERROR) << "Couldn't discover services: Destroyed"; - return; - } - - if (!gatt_client_manager_->gatt_client()->GetServices(addr_)) { - LOG(ERROR) << "Couldn't discover services, disconnecting"; - Disconnect({}); - ConnectComplete(false); - } - } else { - // Reset state after disconnection - mtu_ = kDefaultMtu; - ClearServices(); - } -} - -void RemoteDeviceImpl::SetBonded(bool bonded) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - - bonded_ = bonded; - - if (create_bond_pending_) { - create_bond_pending_ = false; - if (create_bond_cb_) { - std::move(create_bond_cb_).Run(bonded); - } - } - - if (remove_bond_pending_) { - remove_bond_pending_ = false; - if (remove_bond_cb_) { - std::move(remove_bond_cb_).Run(!bonded); - } - } -} - -void RemoteDeviceImpl::SetServicesDiscovered(bool discovered) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - services_discovered_ = discovered; - if (!discovered) { - return; - } - connected_ = true; - ConnectComplete(true); -} - -bool RemoteDeviceImpl::GetServicesDiscovered() { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - return services_discovered_; -} - -void RemoteDeviceImpl::SetMtu(int mtu) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - mtu_ = mtu; - if (!mtu_callbacks_.empty()) { - std::move(mtu_callbacks_.front()).Run(true); - mtu_callbacks_.pop(); - NotifyQueueOperationComplete(); - } -} - -scoped_refptr RemoteDeviceImpl::CharacteristicFromHandle( - uint16_t handle) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - auto it = handle_to_characteristic_.find(handle); - if (it == handle_to_characteristic_.end()) - return nullptr; - - return it->second; -} - -void RemoteDeviceImpl::OnCharacteristicRead(bool status, - uint16_t handle, - const std::vector& value) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - auto it = handle_to_characteristic_read_cbs_.find(handle); - if (it == handle_to_characteristic_read_cbs_.end() || it->second.empty()) { - LOG(ERROR) << "No such characteristic read"; - } else { - std::move(it->second.front()).Run(status, value); - it->second.pop(); - } - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::OnCharacteristicWrite(bool status, uint16_t handle) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - auto it = handle_to_characteristic_write_cbs_.find(handle); - if (it == handle_to_characteristic_write_cbs_.end() || it->second.empty()) { - LOG(ERROR) << "No such characteristic write"; - } else { - std::move(it->second.front()).Run(status); - it->second.pop(); - } - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::OnDescriptorRead(bool status, - uint16_t handle, - const std::vector& value) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - auto it = handle_to_descriptor_read_cbs_.find(handle); - if (it == handle_to_descriptor_read_cbs_.end() || it->second.empty()) { - LOG(ERROR) << "No such descriptor read"; - } else { - std::move(it->second.front()).Run(status, value); - it->second.pop(); - } - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::OnDescriptorWrite(bool status, uint16_t handle) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - auto it = handle_to_descriptor_write_cbs_.find(handle); - if (it == handle_to_descriptor_write_cbs_.end() || it->second.empty()) { - LOG(ERROR) << "No such descriptor write"; - } else { - std::move(it->second.front()).Run(status); - it->second.pop(); - } - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::OnGetServices( - const std::vector& services) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - ClearServices(); - OnServicesAdded(services); -} - -void RemoteDeviceImpl::OnServicesRemoved(uint16_t start_handle, - uint16_t end_handle) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - for (auto it = uuid_to_service_.begin(); it != uuid_to_service_.end();) { - if (it->second->handle() >= start_handle && - it->second->handle() <= end_handle) { - for (auto& characteristic : it->second->GetCharacteristics()) { - handle_to_characteristic_.erase(characteristic->handle()); - } - it = uuid_to_service_.erase(it); - } else { - ++it; - } - } -} - -void RemoteDeviceImpl::OnServicesAdded( - const std::vector& services) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - for (const auto& service : services) { - uuid_to_service_[service.uuid] = new RemoteServiceImpl( - this, gatt_client_manager_, service, io_task_runner_); - } - - for (const auto& pair : uuid_to_service_) { - for (auto& characteristic : pair.second->GetCharacteristics()) { - handle_to_characteristic_.emplace( - characteristic->handle(), - static_cast(characteristic.get())); - } - } -} - -void RemoteDeviceImpl::OnReadRemoteRssiComplete(bool status, int rssi) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - rssi_pending_ = false; - if (rssi_cb_) { - std::move(rssi_cb_).Run(status, rssi); - } -} - -void RemoteDeviceImpl::ConnectComplete(bool success) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (connect_cb_) { - std::move(connect_cb_) - .Run(success ? ConnectStatus::kSuccess : ConnectStatus::kFailure); - } -} - -void RemoteDeviceImpl::EnqueueOperation(const std::string& name, - base::OnceClosure op) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - command_queue_.emplace_back(name, std::move(op)); - - // Run the operation if this is the only operation in the queue. Otherwise, it - // will be executed when the current operation completes. - if (command_queue_.size() == 1) { - RunNextOperation(); - } -} - -void RemoteDeviceImpl::NotifyQueueOperationComplete() { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (command_queue_.empty()) { - LOG(ERROR) << "Command queue is empty, device might be disconnected"; - return; - } - command_queue_.pop_front(); - command_timeout_timer_.Stop(); - - // Run the next operation if there is one in the queue. - if (!command_queue_.empty()) { - RunNextOperation(); - } -} - -void RemoteDeviceImpl::RunNextOperation() { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (command_queue_.empty()) { - LOG(ERROR) << "Command queue is empty, device might be disconnected"; - return; - } - auto& front = command_queue_.front(); - command_timeout_timer_.Start( - FROM_HERE, kCommandTimeout, - base::BindRepeating(&RemoteDeviceImpl::OnCommandTimeout, this, - front.first)); - std::move(front.second).Run(); -} - -void RemoteDeviceImpl::RequestMtuImpl(int mtu) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (gatt_client_manager_->gatt_client()->RequestMtu(addr_, mtu)) { - return; - } - - LOG(ERROR) << __func__ << " failed"; - DCHECK(!mtu_callbacks_.empty()); - std::move(mtu_callbacks_.front()).Run(false); - mtu_callbacks_.pop(); - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::ReadCharacteristicImpl( - scoped_refptr characteristic, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (gatt_client_manager_->gatt_client()->ReadCharacteristic( - addr(), characteristic->characteristic(), auth_req)) { - return; - } - - LOG(ERROR) << __func__ << " failed"; - auto it = handle_to_characteristic_read_cbs_.find(characteristic->handle()); - CHECK(it != handle_to_characteristic_read_cbs_.end(), - base::NotFatalUntil::M130); - DCHECK(!it->second.empty()); - std::move(it->second.front()).Run(false, {}); - it->second.pop(); - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::WriteCharacteristicImpl( - scoped_refptr characteristic, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - std::vector value) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (gatt_client_manager_->gatt_client()->WriteCharacteristic( - addr(), characteristic->characteristic(), auth_req, write_type, - value)) { - return; - } - - LOG(ERROR) << __func__ << " failed"; - auto it = handle_to_characteristic_write_cbs_.find(characteristic->handle()); - CHECK(it != handle_to_characteristic_write_cbs_.end(), - base::NotFatalUntil::M130); - DCHECK(!it->second.empty()); - std::move(it->second.front()).Run(false); - it->second.pop(); - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::ReadDescriptorImpl( - scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (gatt_client_manager_->gatt_client()->ReadDescriptor( - addr(), descriptor->descriptor(), auth_req)) { - return; - } - - LOG(ERROR) << __func__ << " failed"; - auto it = handle_to_descriptor_read_cbs_.find(descriptor->handle()); - CHECK(it != handle_to_descriptor_read_cbs_.end(), base::NotFatalUntil::M130); - DCHECK(!it->second.empty()); - std::move(it->second.front()).Run(false, {}); - it->second.pop(); - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::WriteDescriptorImpl( - scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - std::vector value) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - if (gatt_client_manager_->gatt_client()->WriteDescriptor( - addr(), descriptor->descriptor(), auth_req, value)) { - return; - } - - LOG(ERROR) << __func__ << " failed"; - auto it = handle_to_descriptor_write_cbs_.find(descriptor->handle()); - CHECK(it != handle_to_descriptor_write_cbs_.end(), base::NotFatalUntil::M130); - DCHECK(!it->second.empty()); - std::move(it->second.front()).Run(false); - it->second.pop(); - NotifyQueueOperationComplete(); -} - -void RemoteDeviceImpl::ClearServices() { - for (auto& item : handle_to_characteristic_) { - item.second->Invalidate(); - } - - uuid_to_service_.clear(); - handle_to_characteristic_.clear(); - command_queue_.clear(); - command_timeout_timer_.Stop(); - - while (!mtu_callbacks_.empty()) { - LOG(ERROR) << "RequestMtu failed: disconnected"; - std::move(mtu_callbacks_.front()).Run(false); - mtu_callbacks_.pop(); - } - - for (auto& item : handle_to_characteristic_read_cbs_) { - auto& queue = item.second; - while (!queue.empty()) { - LOG(ERROR) << "Characteristic read failed: disconnected"; - std::move(queue.front()).Run(false, {}); - queue.pop(); - } - } - handle_to_characteristic_read_cbs_.clear(); - - for (auto& item : handle_to_characteristic_write_cbs_) { - auto& queue = item.second; - while (!queue.empty()) { - LOG(ERROR) << "Characteristic write failed: disconnected"; - std::move(queue.front()).Run(false); - queue.pop(); - } - } - handle_to_characteristic_write_cbs_.clear(); - - for (auto& item : handle_to_descriptor_read_cbs_) { - auto& queue = item.second; - while (!queue.empty()) { - LOG(ERROR) << "Descriptor read failed: disconnected"; - std::move(queue.front()).Run(false, {}); - queue.pop(); - } - } - handle_to_descriptor_read_cbs_.clear(); - - for (auto& item : handle_to_descriptor_write_cbs_) { - auto& queue = item.second; - while (!queue.empty()) { - LOG(ERROR) << "Descriptor write failed: disconnected"; - std::move(queue.front()).Run(false); - queue.pop(); - } - } - handle_to_descriptor_write_cbs_.clear(); -} - -void RemoteDeviceImpl::OnCommandTimeout(const std::string& name) { - DCHECK(io_task_runner_->BelongsToCurrentThread()); - LOG(ERROR) << name << "(" << util::AddrLastByteString(addr_) << ")" - << " timed out. Disconnecting"; - Disconnect(base::DoNothing()); -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_device_impl.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device_impl.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_device_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_device_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DEVICE_IMPL_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DEVICE_IMPL_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/task/single_thread_task_runner.h" -#include "base/threading/thread_checker.h" -#include "base/timer/timer.h" -#include "chromecast/device/bluetooth/le/remote_characteristic.h" -#include "chromecast/device/bluetooth/le/remote_descriptor.h" -#include "chromecast/device/bluetooth/le/remote_device.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -class GattClientManagerImpl; -class RemoteCharacteristicImpl; -class RemoteDescriptorImpl; -class RemoteService; -class RemoteServiceImpl; - -class RemoteDeviceImpl : public RemoteDevice { - public: - // If commands take longer than this amount of time, we will disconnect the - // device. - static constexpr base::TimeDelta kCommandTimeout = base::Seconds(30); - - RemoteDeviceImpl(const RemoteDeviceImpl&) = delete; - RemoteDeviceImpl& operator=(const RemoteDeviceImpl&) = delete; - - // RemoteDevice implementation - void Connect(ConnectCallback cb, bluetooth_v2_shlib::Gatt::Client::Transport transport) override; - void Disconnect(StatusCallback cb) override; - void CreateBond(StatusCallback cb) override; - void RemoveBond(StatusCallback cb) override; - void ReadRemoteRssi(RssiCallback cb) override; - void RequestMtu(int mtu, StatusCallback cb) override; - void ConnectionParameterUpdate(int min_interval, - int max_interval, - int latency, - int timeout, - StatusCallback cb) override; - bool IsConnected() override; - bool IsBonded() override; - int GetMtu() override; - void GetServices( - base::OnceCallback>)> cb) - override; - std::vector> GetServicesSync() override; - void GetServiceByUuid( - const bluetooth_v2_shlib::Uuid& uuid, - base::OnceCallback)> cb) override; - scoped_refptr GetServiceByUuidSync( - const bluetooth_v2_shlib::Uuid& uuid) override; - const bluetooth_v2_shlib::Addr& addr() const override; - - void ReadCharacteristic( - scoped_refptr characteristic, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - RemoteCharacteristic::ReadCallback cb); - void WriteCharacteristic( - scoped_refptr characteristic, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - std::vector value, - RemoteCharacteristic::StatusCallback cb); - void ReadDescriptor(scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - RemoteDescriptor::ReadCallback cb); - void WriteDescriptor(scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - std::vector value, - RemoteDescriptor::StatusCallback cb); - - private: - friend class GattClientManagerImpl; - - RemoteDeviceImpl(const bluetooth_v2_shlib::Addr& addr, - base::WeakPtr gatt_client_manager, - scoped_refptr io_task_runner); - ~RemoteDeviceImpl() override; - - // Friend methods for GattClientManagerImpl - void SetConnected(bool connected); - void SetBonded(bool bonded); - void SetServicesDiscovered(bool discovered); - bool GetServicesDiscovered(); - void SetMtu(int mtu); - - scoped_refptr CharacteristicFromHandle(uint16_t handle); - - void OnCharacteristicRead(bool status, - uint16_t handle, - const std::vector& value); - void OnCharacteristicWrite(bool status, uint16_t handle); - void OnDescriptorRead(bool status, - uint16_t handle, - const std::vector& value); - void OnDescriptorWrite(bool status, uint16_t handle); - void OnGetServices( - const std::vector& services); - void OnServicesRemoved(uint16_t start_handle, uint16_t end_handle); - void OnServicesAdded( - const std::vector& services); - void OnReadRemoteRssiComplete(bool status, int rssi); - // end Friend methods for GattClientManagerImpl - - void ConnectComplete(bool success); - - // Add an operation to the queue. Certain operations can only be executed - // serially. - void EnqueueOperation(const std::string& name, base::OnceClosure op); - - // Notify that the currently queued operation has completed. - void NotifyQueueOperationComplete(); - - // Run the next queued operation. - void RunNextOperation(); - - void RequestMtuImpl(int mtu); - void ReadCharacteristicImpl( - scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req); - void WriteCharacteristicImpl( - scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - bluetooth_v2_shlib::Gatt::WriteType write_type, - std::vector value); - void ReadDescriptorImpl(scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req); - void WriteDescriptorImpl(scoped_refptr descriptor, - bluetooth_v2_shlib::Gatt::Client::AuthReq auth_req, - std::vector value); - void ClearServices(); - - void OnCommandTimeout(const std::string& command_name); - - const base::WeakPtr gatt_client_manager_; - const bluetooth_v2_shlib::Addr addr_; - - // All bluetooth_v2_shlib calls are run on this task_runner. Below members - // should only be accessed on this task_runner. - const scoped_refptr io_task_runner_; - - bool services_discovered_ = false; - - ConnectCallback connect_cb_; - - bool disconnect_pending_ = false; - StatusCallback disconnect_cb_; - - bool create_bond_pending_ = false; - StatusCallback create_bond_cb_; - - bool remove_bond_pending_ = false; - StatusCallback remove_bond_cb_; - - bool rssi_pending_ = false; - RssiCallback rssi_cb_; - - std::atomic connected_{false}; - std::atomic bonded_{false}; - std::atomic mtu_{kDefaultMtu}; - std::map> - uuid_to_service_; - std::map> - handle_to_characteristic_; - - // Timer for commands on |command_queue_|. If any command times out, we will - // force disconnect of this device. - base::OneShotTimer command_timeout_timer_; - - // Queue of operation name and the operation itself. - std::deque> command_queue_; - std::queue mtu_callbacks_; - std::map> - handle_to_characteristic_read_cbs_; - std::map> - handle_to_characteristic_write_cbs_; - std::map> - handle_to_descriptor_read_cbs_; - std::map> - handle_to_descriptor_write_cbs_; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_DEVICE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_service.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_SERVICE_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_SERVICE_H_ - -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "chromecast/device/bluetooth/le/ble_types.h" -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth { - -class RemoteCharacteristic; -class RemoteDevice; - -// A proxy for a remote service on a RemoteDevice. Unless otherwise -// specified, all callbacks are run on the caller's thread. -class RemoteService : public base::RefCountedThreadSafe { - public: - RemoteService(const RemoteService&) = delete; - RemoteService& operator=(const RemoteService&) = delete; - - // Returns a list of characteristics in this service. - virtual std::vector> - GetCharacteristics() = 0; - - virtual scoped_refptr GetCharacteristicByUuid( - const bluetooth_v2_shlib::Uuid& uuid) = 0; - - virtual const bluetooth_v2_shlib::Uuid& uuid() const = 0; - virtual HandleId handle() const = 0; - virtual bool primary() const = 0; - - protected: - friend class base::RefCountedThreadSafe; - - RemoteService() = default; - virtual ~RemoteService() = default; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_service_impl.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service_impl.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_service_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/remote_service_impl.h" - -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "chromecast/device/bluetooth/le/remote_characteristic_impl.h" - -namespace chromecast { -namespace bluetooth { - -// static -std::map> -RemoteServiceImpl::CreateCharMap( - RemoteDeviceImpl* remote_device, - base::WeakPtr gatt_client_manager, - const bluetooth_v2_shlib::Gatt::Service& service, - scoped_refptr io_task_runner) { - std::map> - ret; - for (const auto& characteristic : service.characteristics) { - ret[characteristic.uuid] = new RemoteCharacteristicImpl( - remote_device, gatt_client_manager, &characteristic, io_task_runner); - } - return ret; -} - -RemoteServiceImpl::RemoteServiceImpl( - RemoteDeviceImpl* remote_device, - base::WeakPtr gatt_client_manager, - const bluetooth_v2_shlib::Gatt::Service& service, - scoped_refptr io_task_runner) - : service_(service), - uuid_to_characteristic_(CreateCharMap(remote_device, - gatt_client_manager, - service_, - io_task_runner)) { - DCHECK(gatt_client_manager); - DCHECK(io_task_runner); - DCHECK(io_task_runner->BelongsToCurrentThread()); -} - -RemoteServiceImpl::~RemoteServiceImpl() = default; - -std::vector> -RemoteServiceImpl::GetCharacteristics() { - std::vector> ret; - ret.reserve(uuid_to_characteristic_.size()); - for (const auto& pair : uuid_to_characteristic_) { - ret.push_back(pair.second); - } - - return ret; -} - -scoped_refptr RemoteServiceImpl::GetCharacteristicByUuid( - const bluetooth_v2_shlib::Uuid& uuid) { - auto it = uuid_to_characteristic_.find(uuid); - if (it == uuid_to_characteristic_.end()) - return nullptr; - return it->second; -} - -const bluetooth_v2_shlib::Uuid& RemoteServiceImpl::uuid() const { - return service_.uuid; -} -HandleId RemoteServiceImpl::handle() const { - return service_.handle; -} -bool RemoteServiceImpl::primary() const { - return service_.primary; -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_service_impl.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service_impl.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/remote_service_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/remote_service_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_SERVICE_IMPL_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_SERVICE_IMPL_H_ - -#include -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/device/bluetooth/le/remote_service.h" - -namespace chromecast { -namespace bluetooth { - -class GattClientManagerImpl; -class RemoteCharacteristic; -class RemoteCharacteristicImpl; -class RemoteDeviceImpl; - -class RemoteServiceImpl : public RemoteService { - public: - RemoteServiceImpl(const RemoteServiceImpl&) = delete; - RemoteServiceImpl& operator=(const RemoteServiceImpl&) = delete; - - // RemoteService implementation: - std::vector> GetCharacteristics() - override; - scoped_refptr GetCharacteristicByUuid( - const bluetooth_v2_shlib::Uuid& uuid) override; - const bluetooth_v2_shlib::Uuid& uuid() const override; - HandleId handle() const override; - bool primary() const override; - - private: - friend class RemoteDeviceImpl; - - static std::map> - CreateCharMap(RemoteDeviceImpl* remote_device, - base::WeakPtr gatt_client_manager, - const bluetooth_v2_shlib::Gatt::Service& service, - scoped_refptr io_task_runner); - - // May only be constructed by RemoteDevice. - explicit RemoteServiceImpl( - RemoteDeviceImpl* remote_device, - base::WeakPtr gatt_client_manager, - const bluetooth_v2_shlib::Gatt::Service& service, - scoped_refptr io_task_runner); - ~RemoteServiceImpl() override; - - const bluetooth_v2_shlib::Gatt::Service service_; - - const std::map> - uuid_to_characteristic_; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_REMOTE_SERVICE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/scan_filter.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/scan_filter.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/scan_filter.h" - -#include "base/containers/contains.h" -#include "chromecast/device/bluetooth/bluetooth_util.h" -#include "third_party/re2/src/re2/re2.h" - -namespace chromecast { -namespace bluetooth { - -// static -ScanFilter ScanFilter::From16bitUuid(uint16_t service_uuid) { - ScanFilter filter; - filter.service_uuid = util::UuidFromInt16(service_uuid); - return filter; -} - -ScanFilter::ScanFilter() = default; -ScanFilter::ScanFilter(const ScanFilter& other) = default; -ScanFilter::ScanFilter(ScanFilter&& other) = default; -ScanFilter::~ScanFilter() = default; - -bool ScanFilter::Matches(const LeScanResult& scan_result) const { - if (name && name != scan_result.Name()) { - return false; - } - - if (service_uuid) { - std::optional all_uuids = - scan_result.AllServiceUuids(); - if (!all_uuids) { - return false; - } - - if (!base::Contains(*all_uuids, *service_uuid)) { - return false; - } - } - - if (!name && regex_name) { - std::optional scan_name = scan_result.Name(); - if (!scan_name || !RE2::PartialMatch(*scan_name, *regex_name)) { - return false; - } - } - - return true; -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/scan_filter.h chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/scan_filter.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_LE_SCAN_FILTER_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_LE_SCAN_FILTER_H_ - -#include -#include - -#include "chromecast/device/bluetooth/le/le_scan_result.h" -#include "chromecast/public/bluetooth/bluetooth_types.h" - -namespace chromecast { -namespace bluetooth { - -struct ScanFilter { - // Helper function to get ScanFilter which matches 16 bit |service_uuid|. - static ScanFilter From16bitUuid(uint16_t service_uuid); - - ScanFilter(); - ScanFilter(const ScanFilter& other); - ScanFilter(ScanFilter&& other); - ~ScanFilter(); - - bool Matches(const LeScanResult& scan_result) const; - - // Exact name. - std::optional name; - - // RE2 partial match on name. This is ignored if |name| is specified. - // https://github.com/google/re2 - std::optional regex_name; - - std::optional service_uuid; -}; - -} // namespace bluetooth -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_LE_SCAN_FILTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/le/scan_filter_test.cc chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter_test.cc --- chromium-132.0.6834.110/chromecast/device/bluetooth/le/scan_filter_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/le/scan_filter_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,122 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/device/bluetooth/le/scan_filter.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace bluetooth { - -namespace { - -const char kName[] = "foo"; -const bluetooth_v2_shlib::Uuid kUuid = {{0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, - 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, - 0x55, 0x44, 0x00, 0x00}}; - -} // namespace - -TEST(ScanFilterTest, Name) { - ScanFilter filter; - LeScanResult result; - EXPECT_TRUE(filter.Matches(result)); - - filter.name = kName; - EXPECT_FALSE(filter.Matches(result)); - - result.type_to_data[LeScanResult::kGapShortName].emplace_back( - reinterpret_cast(kName), - reinterpret_cast(kName) + strlen(kName)); - EXPECT_TRUE(filter.Matches(result)); - - ++result.type_to_data[LeScanResult::kGapShortName][0][0]; - EXPECT_FALSE(filter.Matches(result)); -} - -TEST(ScanFilterTest, Uuid) { - ScanFilter filter; - filter.service_uuid = kUuid; - - LeScanResult result; - EXPECT_FALSE(filter.Matches(result)); - - result.type_to_data[LeScanResult::kGapIncomplete128BitServiceUuids] - .emplace_back(kUuid.rbegin(), kUuid.rend()); - EXPECT_TRUE(filter.Matches(result)); - - ++result.type_to_data[LeScanResult::kGapIncomplete128BitServiceUuids][0][0]; - EXPECT_FALSE(filter.Matches(result)); -} - -TEST(ScanFilterTest, NameAndUuid) { - ScanFilter filter; - filter.name = kName; - filter.service_uuid = kUuid; - - LeScanResult result; - EXPECT_FALSE(filter.Matches(result)); - - result.type_to_data[LeScanResult::kGapShortName].emplace_back( - reinterpret_cast(kName), - reinterpret_cast(kName) + strlen(kName)); - EXPECT_FALSE(filter.Matches(result)); - - result.type_to_data[LeScanResult::kGapIncomplete128BitServiceUuids] - .emplace_back(kUuid.rbegin(), kUuid.rend()); - EXPECT_TRUE(filter.Matches(result)); - - // Unmatching name shouldn't work. - --result.type_to_data[LeScanResult::kGapShortName][0][0]; - EXPECT_FALSE(filter.Matches(result)); - - // Unmatching uuid shouldn't work. - ++result.type_to_data[LeScanResult::kGapIncomplete128BitServiceUuids][0][0]; - ++result.type_to_data[LeScanResult::kGapShortName][0][0]; - EXPECT_FALSE(filter.Matches(result)); - - --result.type_to_data[LeScanResult::kGapIncomplete128BitServiceUuids][0][0]; - EXPECT_TRUE(filter.Matches(result)); -} - -TEST(ScanFilterTest, RegexName) { - const char kHello[] = "hello"; - - // Just test some basic regular experssions, we don't want this to be testing - // RE2. - ScanFilter filter; - filter.regex_name = "ell"; - - LeScanResult result; - EXPECT_FALSE(filter.Matches(result)); - - result.type_to_data[LeScanResult::kGapShortName].emplace_back( - reinterpret_cast(kHello), - reinterpret_cast(kHello) + strlen(kHello)); - EXPECT_TRUE(filter.Matches(result)); - - filter.regex_name = "g"; - EXPECT_FALSE(filter.Matches(result)); - - filter.regex_name = "h.*o"; - EXPECT_TRUE(filter.Matches(result)); -} - -TEST(ScanFilterTest, RegexNameIgnoredIfNameSet) { - ScanFilter filter; - filter.regex_name = "."; // Match any string. - filter.name = "bar"; - - LeScanResult result; - result.type_to_data[LeScanResult::kGapShortName].emplace_back( - reinterpret_cast(kName), - reinterpret_cast(kName) + strlen(kName)); - EXPECT_FALSE(filter.Matches(result)); - - filter.name = kName; - EXPECT_TRUE(filter.Matches(result)); -} - -} // namespace bluetooth -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/shlib/gatt_client.h chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/gatt_client.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/shlib/gatt_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/gatt_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_SHLIB_GATT_CLIENT_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_SHLIB_GATT_CLIENT_H_ - -#include - -#include "chromecast/public/bluetooth/gatt.h" - -namespace chromecast { -namespace bluetooth_v2_shlib { - -class GattClient { - public: - virtual ~GattClient() = default; - virtual bool IsSupported() = 0; - virtual void SetDelegate(Gatt::Client::Delegate* delegate) = 0; - virtual bool Connect(const Addr& addr, Gatt::Client::Transport transport) = 0; - virtual bool Disconnect(const Addr& addr) = 0; - virtual bool CreateBond(const Addr& addr) = 0; - virtual bool RemoveBond(const Addr& addr) = 0; - virtual bool ReadCharacteristic(const Addr& addr, - const Gatt::Characteristic& characteristic, - Gatt::Client::AuthReq auth_req) = 0; - virtual bool WriteCharacteristic(const Addr& addr, - const Gatt::Characteristic& characteristic, - Gatt::Client::AuthReq auth_req, - Gatt::WriteType write_type, - const std::vector& value) = 0; - virtual bool ReadDescriptor(const Addr& addr, - const Gatt::Descriptor& descriptor, - Gatt::Client::AuthReq auth_req) = 0; - virtual bool WriteDescriptor(const Addr& addr, - const Gatt::Descriptor& descriptor, - Gatt::Client::AuthReq auth_req, - const std::vector& value) = 0; - virtual bool SetCharacteristicNotification( - const Addr& addr, - const Gatt::Characteristic& characteristic, - bool enable) = 0; - virtual bool ReadRemoteRssi(const Addr& addr) = 0; - virtual bool RequestMtu(const Addr& addr, int mtu) = 0; - virtual bool ConnectionParameterUpdate(const Addr& addr, - int min_interval, - int max_interval, - int latency, - int timeout) = 0; - virtual bool GetServices(const Addr& addr) = 0; - virtual bool ClearPendingConnect(const Addr& addr) = 0; - virtual bool ClearPendingDisconnect(const Addr& addr) = 0; -}; - -} // namespace bluetooth_v2_shlib -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_SHLIB_GATT_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/shlib/le_scanner.h chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/le_scanner.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/shlib/le_scanner.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/le_scanner.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_SHLIB_LE_SCANNER_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_SHLIB_LE_SCANNER_H_ - -#include "chromecast/public/bluetooth/le_scanner.h" - -namespace chromecast { -namespace bluetooth_v2_shlib { - -class LeScannerImpl { - public: - virtual ~LeScannerImpl() = default; - virtual bool IsSupported() = 0; - virtual void SetDelegate(LeScanner::Delegate* delegate) = 0; - virtual bool StartScan() = 0; - virtual bool StopScan() = 0; - virtual bool SetScanParameters(int scan_interval_ms, int scan_window_ms) = 0; -}; - -} // namespace bluetooth_v2_shlib -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_SHLIB_LE_SCANNER_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/shlib/mock_gatt_client.h chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/mock_gatt_client.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/shlib/mock_gatt_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/mock_gatt_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_SHLIB_MOCK_GATT_CLIENT_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_SHLIB_MOCK_GATT_CLIENT_H_ - -#include - -#include "base/memory/raw_ptr.h" -#include "chromecast/device/bluetooth/shlib/gatt_client.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace bluetooth_v2_shlib { - -class MockGattClient : public GattClient { - public: - MockGattClient(); - ~MockGattClient() override; - MOCK_METHOD0(IsSupported, bool()); - MOCK_METHOD2(Connect, bool(const Addr&, Gatt::Client::Transport transport)); - MOCK_METHOD1(SetDelegate, void(Gatt::Client::Delegate*)); - MOCK_METHOD0(Enable, bool()); - MOCK_METHOD0(Disable, bool()); - MOCK_METHOD1(Disconnect, bool(const Addr&)); - MOCK_METHOD1(CreateBond, bool(const Addr&)); - MOCK_METHOD1(RemoveBond, bool(const Addr&)); - MOCK_METHOD3(ReadCharacteristic, - bool(const Addr&, - const Gatt::Characteristic&, - Gatt::Client::AuthReq)); - MOCK_METHOD5(WriteCharacteristic, - bool(const Addr&, - const Gatt::Characteristic&, - Gatt::Client::AuthReq, - Gatt::WriteType, - const std::vector&)); - MOCK_METHOD3(ReadDescriptor, - bool(const Addr&, - const Gatt::Descriptor&, - Gatt::Client::AuthReq)); - MOCK_METHOD4(WriteDescriptor, - bool(const Addr&, - const Gatt::Descriptor&, - Gatt::Client::AuthReq, - const std::vector&)); - MOCK_METHOD3(SetCharacteristicNotification, - bool(const Addr&, const Gatt::Characteristic&, bool)); - MOCK_METHOD1(ReadRemoteRssi, bool(const Addr&)); - MOCK_METHOD2(RequestMtu, bool(const Addr&, int mtu)); - MOCK_METHOD5(ConnectionParameterUpdate, - bool(const Addr&, int, int, int, int)); - MOCK_METHOD1(GetServices, bool(const Addr&)); - MOCK_METHOD1(ClearPendingConnect, bool(const Addr&)); - MOCK_METHOD1(ClearPendingDisconnect, bool(const Addr&)); - - Gatt::Client::Delegate* delegate() const { return delegate_; } - - private: - raw_ptr delegate_ = nullptr; -}; - -inline MockGattClient::MockGattClient() { - ON_CALL(*this, SetDelegate(::testing::_)) - .WillByDefault( - [this](Gatt::Client::Delegate* delegate) { delegate_ = delegate; }); -} -inline MockGattClient::~MockGattClient() = default; - -} // namespace bluetooth_v2_shlib -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_SHLIB_MOCK_GATT_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/device/bluetooth/shlib/mock_le_scanner.h chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/mock_le_scanner.h --- chromium-132.0.6834.110/chromecast/device/bluetooth/shlib/mock_le_scanner.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/device/bluetooth/shlib/mock_le_scanner.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_DEVICE_BLUETOOTH_SHLIB_MOCK_LE_SCANNER_H_ -#define CHROMECAST_DEVICE_BLUETOOTH_SHLIB_MOCK_LE_SCANNER_H_ - -#include "chromecast/device/bluetooth/shlib/le_scanner.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace bluetooth_v2_shlib { - -class MockLeScanner : public LeScannerImpl { - public: - MockLeScanner(); - ~MockLeScanner() override; - MOCK_METHOD0(IsSupported, bool()); - MOCK_METHOD1(SetDelegate, void(LeScanner::Delegate* delegate)); - MOCK_METHOD0(StartScan, bool()); - MOCK_METHOD0(StopScan, bool()); - MOCK_METHOD2(SetScanParameters, bool(int, int)); -}; - -inline MockLeScanner::MockLeScanner() = default; -inline MockLeScanner::~MockLeScanner() = default; - -} // namespace bluetooth_v2_shlib -} // namespace chromecast - -#endif // CHROMECAST_DEVICE_BLUETOOTH_SHLIB_MOCK_LE_SCANNER_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/DEPS chromium-132.0.6834.159/chromecast/external_mojo/DEPS --- chromium-132.0.6834.110/chromecast/external_mojo/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -include_rules = [ - "+chromecast/base", - "+chromecast/mojo", - "+mojo/public", - "+services/service_manager/public", -] diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/OWNERS chromium-132.0.6834.159/chromecast/external_mojo/OWNERS --- chromium-132.0.6834.110/chromecast/external_mojo/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -kmackay@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/README.md chromium-132.0.6834.159/chromecast/external_mojo/README.md --- chromium-132.0.6834.110/chromecast/external_mojo/README.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -# External Mojo services - -This directory contains code that allows Mojo services in processes outside of -cast_shell to communicate with Mojo services within cast_shell. - -## broker_service -This contains the service_manager::Service that runs inside cast_shell and -brokers communication between Mojo services in external processes and services -within cast_shell. This service is automatically started when the -'enable_external_mojo_services' GN arg is true. - -## external_service_support -This directory contains utilities to ease development of Mojo services that run -in processes outside of Chromium/cast_shell. - -## common -This contains code that is shared between cast_shell and external services. diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/broker_service/broker_service.cc chromium-132.0.6834.159/chromecast/external_mojo/broker_service/broker_service.cc --- chromium-132.0.6834.110/chromecast/external_mojo/broker_service/broker_service.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/broker_service/broker_service.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,157 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/external_mojo/broker_service/broker_service.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/message_loop/message_pump_type.h" -#include "base/no_destructor.h" -#include "base/task/sequenced_task_runner.h" -#include "base/threading/thread.h" -#include "chromecast/external_mojo/public/cpp/common.h" -#include "chromecast/external_mojo/public/cpp/external_mojo_broker.h" -#include "chromecast/external_mojo/public/mojom/connector.mojom.h" -#include "services/service_manager/public/cpp/manifest_builder.h" - -namespace chromecast { -namespace external_mojo { - -namespace { - -BrokerService* g_instance = nullptr; - -std::vector& GetExternalManifests() { - static std::vector manifests; - return manifests; -} - -service_manager::Manifest MakePackagedServices( - std::vector manifests) { - service_manager::Manifest packaged; - for (auto& manifest : manifests) { - // External services can only access what the external Mojo broker service - // can access, so require all services that external services require. - for (const auto& capability_entry : manifest.required_capabilities) { - const auto& service_name = capability_entry.first; - const auto& capability_names = capability_entry.second; - for (const auto& capability_name : capability_names) { - packaged.required_capabilities[service_name].insert(capability_name); - } - } - - // External services that expose capabilities have an internal proxy service - // registered with ServiceManager. - if (!manifest.exposed_capabilities.empty()) { - // The external Mojo broker service needs to require a capability from - // each external service in order to register the internal proxy service - // for it. - packaged.required_capabilities[manifest.service_name].insert( - manifest.exposed_capabilities.begin()->first); - packaged.packaged_services.emplace_back(std::move(manifest)); - } - } - return packaged; -} - -} // namespace - -BrokerService::BrokerService(service_manager::Connector* connector) { - DCHECK(!g_instance); - g_instance = this; - io_thread_ = std::make_unique("external_mojo"); - io_thread_->StartWithOptions( - base::Thread::Options(base::MessagePumpType::IO, 0)); - - std::vector external_services_to_proxy; - const service_manager::Manifest& manifest = GetManifest(); - for (const auto& sub_manifest : manifest.packaged_services) { - external_services_to_proxy.push_back(sub_manifest.service_name); - } - bundle_.AddBinder(base::BindRepeating(&BrokerService::BindConnector, - base::Unretained(this))); - broker_ = base::SequenceBound(io_thread_->task_runner(), - GetBrokerPath()); - broker_.AsyncCall(&ExternalMojoBroker::InitializeChromium) - .WithArgs(connector->Clone(), external_services_to_proxy); -} - -BrokerService::~BrokerService() { - broker_.Reset(); - io_thread_.reset(); - g_instance = nullptr; -} - -// static -BrokerService* BrokerService::GetInstance() { - return g_instance; -} - -// static -void BrokerService::ServiceRequestHandler( - mojo::PendingReceiver receiver) { - if (!g_instance) { - return; - } - g_instance->BindServiceRequest(std::move(receiver)); -} - -// static -void BrokerService::AddExternalServiceManifest( - service_manager::Manifest manifest) { - GetExternalManifests().push_back(std::move(manifest)); -} - -// static -const service_manager::Manifest& BrokerService::GetManifest() { - static base::NoDestructor manifest{ - service_manager::ManifestBuilder() - .WithServiceName(BrokerService::kServiceName) - .WithDisplayName("External Mojo Broker Service") - .WithOptions(service_manager::ManifestOptionsBuilder() - .WithSandboxType("none") - .CanRegisterOtherServiceInstances(true) - .Build()) - .ExposeCapability( - "connector_factory", - std::set{ - "chromecast.external_mojo.mojom.ExternalConnector", - }) - .Build() - .Amend(MakePackagedServices(GetExternalManifests()))}; - return *manifest; -} - -void BrokerService::OnConnect(const service_manager::BindSourceInfo& source, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) { - bundle_.BindInterface(interface_name, std::move(interface_pipe)); -} - -void BrokerService::BindConnector( - mojo::PendingReceiver receiver) { - broker_.AsyncCall(&ExternalMojoBroker::BindConnector) - .WithArgs(std::move(receiver)); -} - -mojo::PendingRemote BrokerService::CreateConnector() { - mojo::PendingRemote connector_remote; - BindConnector(connector_remote.InitWithNewPipeAndPassReceiver()); - return connector_remote; -} - -void BrokerService::BindServiceRequest( - mojo::PendingReceiver receiver) { - if (service_receiver_.is_bound()) { - LOG(INFO) << "BrokerService is re-binding to the Service Manager."; - service_receiver_.Close(); - } - service_receiver_.Bind(std::move(receiver)); -} - -} // namespace external_mojo -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/broker_service/broker_service.h chromium-132.0.6834.159/chromecast/external_mojo/broker_service/broker_service.h --- chromium-132.0.6834.110/chromecast/external_mojo/broker_service/broker_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/broker_service/broker_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_BROKER_SERVICE_BROKER_SERVICE_H_ -#define CHROMECAST_EXTERNAL_MOJO_BROKER_SERVICE_BROKER_SERVICE_H_ - -#include -#include - -#include "base/memory/ref_counted.h" -#include "base/threading/sequence_bound.h" -#include "chromecast/external_mojo/public/mojom/connector.mojom.h" -#include "chromecast/mojo/interface_bundle.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "services/service_manager/public/cpp/manifest.h" -#include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/public/cpp/service_receiver.h" -#include "services/service_manager/public/mojom/service.mojom.h" - -namespace base { -class SequencedTaskRunner; -class Thread; -} // namespace base - -namespace service_manager { -class Connector; -} // namespace service_manager - -namespace chromecast { -namespace external_mojo { -class ExternalMojoBroker; - -// A Mojo service (intended to run within cast_shell or some other Chromium -// ServiceManager environment) that allows Mojo services built into external -// processes to interoperate with the Mojo services within cast_shell. -class BrokerService : public ::service_manager::Service { - public: - static BrokerService* GetInstance(); - static void ServiceRequestHandler( - mojo::PendingReceiver receiver); - - static constexpr char const* kServiceName = "external_mojo_broker"; - - // Adds a manifest for an external Mojo service (ie, one that is running in - // a non-Chromium process). A manifest is only needed for external services - // that bind to Mojo services within cast_shell, or for external services that - // are bound to (used) by internal Mojo services. All external manifests must - // be added before GetExternalMojoBrokerManifest() is called (otherwise they - // will not be included in the broker manifest, and so the relevant - // permissions will not be set correctly). - static void AddExternalServiceManifest(service_manager::Manifest manifest); - - // Returns the manifest for this service. - static const service_manager::Manifest& GetManifest(); - - explicit BrokerService(service_manager::Connector* connector); - - BrokerService(const BrokerService&) = delete; - BrokerService& operator=(const BrokerService&) = delete; - - ~BrokerService() override; - - // ::service_manager::Service implementation: - void OnConnect(const service_manager::BindSourceInfo& source, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) override; - - // Dispenses a connector for use in a remote process. The remote process must - // already belong to the same process network as the BrokerService. - mojo::PendingRemote CreateConnector(); - - private: - void BindServiceRequest( - mojo::PendingReceiver receiver); - - void BindConnector(mojo::PendingReceiver receiver); - - service_manager::ServiceReceiver service_receiver_{this}; - - std::unique_ptr io_thread_; - scoped_refptr io_task_runner_; - - InterfaceBundle bundle_; - - base::SequenceBound broker_; -}; - -} // namespace external_mojo -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_BROKER_SERVICE_BROKER_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/DEPS chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/DEPS --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -include_rules = [ - "+chromecast/crash", - "+components/crash/core/app", - "+mojo/core/embedder", - "+services/tracing", - "+third_party/crashpad/crashpad/client", - "+third_party/perfetto/include/perfetto", -] diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/README.md chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/README.md --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/README.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -# External Mojo service support - -This directory contains utilities to ease development of Mojo services that run -in processes outside of Chromium/cast_shell. The simplest model is to create a -subclass of 'ServiceProcess' (and implement 'ServiceProcess::Create()' that -returns an instance of that subclass), and link with 'standalone_service_main' -to create the executable. In your 'ServiceProcess' implementation, you can bind -to Mojo interfaces using the provided 'Connector' pointer, and/or register your -own Mojo services for use by other processes. - -The 'ChromiumServiceWrapper' class is intended to allow Mojo services that were -intended to be embedded into cast_shell (or other ServiceManager embedder) to -be moved into a completely separate process. It forwards 'BindInterface()' -calls to the 'service_manager::Service' API. You can use -'CreateChromiumServiceReceiver()' to create a -'mojo::PendingReceiver' to emulate the normal service -creation flow; the 'service_manager::Service::OnStart()' method will be called -automatically. - -The 'standalone_mojo_broker' is intended for use on platforms where there is no -cast_shell running; this allows Mojo services outside of cast_shell to -communicate with each other without any Chromium embedder on the system. diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/chromium_service.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/chromium_service.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/chromium_service.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/chromium_service.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,97 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/external_mojo/external_service_support/chromium_service.h" - -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/token.h" -#include "chromecast/external_mojo/external_service_support/external_connector.h" -#include "mojo/public/cpp/bindings/pending_associated_receiver.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "services/service_manager/public/cpp/bind_source_info.h" -#include "services/service_manager/public/cpp/connector.h" -#include "services/service_manager/public/mojom/connector.mojom.h" -#include "services/service_manager/public/mojom/service_control.mojom.h" - -namespace chromecast { -namespace external_service_support { - -namespace { - -void OnStartCallback( - ExternalConnector* connector, - mojo::PendingReceiver connector_receiver, - mojo::PendingAssociatedReceiver - control_receiver) { - DCHECK(connector); - if (connector_receiver.is_valid()) { - connector->SendChromiumConnectorRequest(connector_receiver.PassPipe()); - } -} - -} // namespace - -ChromiumServiceWrapper::ChromiumServiceWrapper( - ExternalConnector* connector, - mojo::Remote service_remote, - std::unique_ptr chromium_service, - const std::string& service_name) - : service_remote_(std::move(service_remote)), - chromium_service_(std::move(chromium_service)) { - DCHECK(connector); - DCHECK(chromium_service_); - - connector->RegisterService(service_name, - service_receiver_.BindNewPipeAndPassRemote()); -} - -ChromiumServiceWrapper::~ChromiumServiceWrapper() = default; - -void ChromiumServiceWrapper::OnBindInterface( - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) { - chromium_service_->OnBindInterface( - service_manager::BindSourceInfo( - service_manager::Identity("unique", base::Token::CreateRandom(), - base::Token::CreateRandom(), - base::Token::CreateRandom()), - service_manager::CapabilitySet()), - interface_name, std::move(interface_pipe)); -} - -mojo::PendingReceiver -CreateChromiumServiceReceiver( - ExternalConnector* connector, - mojo::Remote* service_remote, - service_manager::Identity identity) { - DCHECK(connector); - - if (identity.name().empty()) { - identity = service_manager::Identity( - "unspecified", base::Token::CreateRandom(), base::Token::CreateRandom(), - base::Token::CreateRandom()); - } - - auto receiver = service_remote->BindNewPipeAndPassReceiver(); - (*service_remote) - ->OnStart(identity, base::BindOnce(&OnStartCallback, connector)); - return receiver; -} - -std::unique_ptr CreateChromiumConnector( - ExternalConnector* connector) { - mojo::MessagePipe pipe; - connector->SendChromiumConnectorRequest(std::move(pipe.handle1)); - return std::make_unique( - mojo::Remote( - mojo::PendingRemote( - std::move(pipe.handle0), 0))); -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/chromium_service.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/chromium_service.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/chromium_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/chromium_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_CHROMIUM_SERVICE_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_CHROMIUM_SERVICE_H_ - -#include -#include - -#include "chromecast/external_mojo/public/mojom/connector.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "mojo/public/cpp/system/message_pipe.h" -#include "services/service_manager/public/cpp/identity.h" -#include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/public/mojom/service.mojom.h" - -namespace service_manager { -class Connector; -class Service; -} // namespace service_manager - -namespace chromecast { -namespace external_service_support { -class ExternalConnector; - -// Provides a wrapper for a Chromium ServiceManager-based service to run in -// an external (non-Chromium) process. -class ChromiumServiceWrapper : public external_mojo::mojom::ExternalService { - public: - ChromiumServiceWrapper( - ExternalConnector* connector, - mojo::Remote service_remote, - std::unique_ptr chromium_service, - const std::string& service_name); - - ChromiumServiceWrapper(const ChromiumServiceWrapper&) = delete; - ChromiumServiceWrapper& operator=(const ChromiumServiceWrapper&) = delete; - - ~ChromiumServiceWrapper() override; - - private: - // external_mojo::mojom::ExternalService implementation: - void OnBindInterface(const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) override; - - const mojo::Remote service_remote_; - const std::unique_ptr chromium_service_; - - mojo::Receiver service_receiver_{this}; -}; - -// Creates a ServiceRequest (analogous to one created by Chromium -// ServiceManager) for use in creating Chromium Mojo services in an external -// process. |service_remote| will be filled in with a pointer for the service, -// which should be bassed to ChromiumServiceWrapper's constructor. |identity| is -// the desired identity of the service to be created (ie, what will be returned -// from ServiceBinding::identity() once the service binding is created). If you -// don't care about the identity, just use the default. -mojo::PendingReceiver -CreateChromiumServiceReceiver( - ExternalConnector* connector, - mojo::Remote* service_remote, - service_manager::Identity identity = service_manager::Identity()); - -// Creates a service_manager::Connector instance from an external service -// ExternalConnector. -std::unique_ptr CreateChromiumConnector( - ExternalConnector* connector); - -// Convenience helper for services that only take a ServiceRequest param in the -// constructor. The |name| is the desired service name. -template -std::unique_ptr CreateChromiumService( - ExternalConnector* connector, - const std::string& name) { - mojo::Remote service_remote; - auto receiver = CreateChromiumServiceReceiver(connector, &service_remote); - return std::make_unique( - connector, std::move(service_remote), - std::make_unique(std::move(receiver)), name); -} - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_CHROMIUM_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/crash_reporter_builtin.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_builtin.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/crash_reporter_builtin.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_builtin.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// 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 "base/debug/stack_trace.h" -#include "base/no_destructor.h" -#include "base/time/time.h" -#include "build/build_config.h" -#include "chromecast/crash/linux/crash_util.h" -#include "chromecast/external_mojo/external_service_support/crash_reporter_client.h" -#include "components/crash/core/app/breakpad_linux.h" -#include "components/crash/core/app/crash_reporter_client.h" - -namespace chromecast { -namespace external_service_support { - -namespace { - -class CrashReporterBuiltin : public crash_reporter::CrashReporterClient { - public: - CrashReporterBuiltin() - : start_time_ms_(base::TimeTicks::Now().since_origin().InMilliseconds()) { - } - - ~CrashReporterBuiltin() override = default; - - CrashReporterBuiltin(const CrashReporterBuiltin&) = delete; - CrashReporterBuiltin& operator=(const CrashReporterBuiltin&) = delete; - - // crash_reporter::CrashReporterClient implementation: - bool EnableBreakpadForProcess(const std::string& process_type) override { - return true; - } - bool HandleCrashDump(const char* crashdump_filename, - uint64_t crash_pid) override { - chromecast::CrashUtil::RequestUploadCrashDump(crashdump_filename, crash_pid, - start_time_ms_); - // Always return true to indicate that this crash dump has been processed, - // so that it won't fallback to Chrome's default uploader. - return true; - } - bool GetCollectStatsConsent() override { - // Returning true allows writing the crash dump to disk, but not to - // upload. The uploader will check whether the device has opted in to crash - // uploading. It would be more optimal to avoid writing the crash dump if - // the device is opted out, but the complexity of checking that flag would - // increase the probability of a crash within the crash handler. - return true; - } - - private: - const uint64_t start_time_ms_; -}; - -CrashReporterBuiltin* GetCrashReporterClient() { - static base::NoDestructor crash_reporter_client; - return crash_reporter_client.get(); -} -} // namespace - -// static -void CrashReporterClient::Init() { -#if !defined(OFFICIAL_BUILD) - base::debug::EnableInProcessStackDumping(); -#endif // !defined(OFFICIAL_BUILD) - - crash_reporter::SetCrashReporterClient(GetCrashReporterClient()); - breakpad::InitCrashReporter(/*process_type=*/""); -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/crash_reporter_client.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_client.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/crash_reporter_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_CRASH_REPORTER_CLIENT_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_CRASH_REPORTER_CLIENT_H_ - -namespace chromecast { -namespace external_service_support { - -class CrashReporterClient { - public: - static void Init(); -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_CRASH_REPORTER_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/crash_reporter_system.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_system.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/crash_reporter_system.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/crash_reporter_system.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -// 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 "base/command_line.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/external_mojo/external_service_support/crash_reporter_client.h" -#include "third_party/crashpad/crashpad/client/crashpad_info.h" - -namespace chromecast { -namespace external_service_support { - -// static -void CrashReporterClient::Init() { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - crashpad::CrashpadInfo* crashpad_info = - crashpad::CrashpadInfo::GetCrashpadInfo(); - if (command_line->HasSwitch(switches::kDisableCrashpadForwarding)) { - LOG(INFO) << "Crashpad forwarding disabled"; - crashpad_info->set_system_crash_reporter_forwarding( - crashpad::TriState::kDisabled); - } else { - crashpad_info->set_system_crash_reporter_forwarding( - crashpad::TriState::kEnabled); - } -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_connector.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_connector.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,126 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_H_ - -#include -#include -#include -#include - -#include "base/callback_list.h" -#include "chromecast/external_mojo/public/mojom/connector.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/system/message_pipe.h" - -namespace service_manager { -class Connector; -} // namespace service_manager - -namespace chromecast { -namespace external_service_support { -class ExternalService; - -// Interface to the Mojo broker, allowing services to be registered and other -// processes to bind to registered services. Once any public methods are called -// on an instance of this class, that instance is bound to the calling thread. -// -// To use the same interface on another thread, call Clone() and pass the new -// instance to the desired thread before calling any public methods on it. -class ExternalConnector { - public: - static void Connect( - const std::string& broker_path, - base::OnceCallback)> callback); - - static std::unique_ptr Create( - const std::string& broker_path); - - static std::unique_ptr Create( - mojo::PendingRemote remote); - - // Acquires a connector from the BrokerService via the Chromium service - // manager. - static std::unique_ptr Create( - ::service_manager::Connector* connector); - - virtual ~ExternalConnector() = default; - - // Adds a callback that will be called if this class loses its connection to - // the Mojo broker. The calling class must retain the returned subscription - // until it intends to unregister. By the time |callback| is executed, a new - // attempt at connecting will be started, and this object is valid. Note that - // some prior messages may be lost. - [[nodiscard]] virtual base::CallbackListSubscription - AddConnectionErrorCallback(base::RepeatingClosure callback) = 0; - - // Registers a service that other Mojo processes/services can bind to. Others - // can call BindInterface(|service_name|, interface_name) to bind to this - // |service|. - // If registering multiple services, consider using RegisterServices(). - virtual void RegisterService(const std::string& service_name, - ExternalService* service) = 0; - virtual void RegisterService( - const std::string& service_name, - mojo::PendingRemote - service_remote) = 0; - - // Registers multiple services that other Mojo processes/services can bind to. - // Others can call BindInterface(|service_names[i]|, interface_name) to bind - // to this |service[i]|. - // This function is more efficient than using multiple times RegisterService() - // because it only does a single Mojo call. - virtual void RegisterServices( - const std::vector& service_names, - const std::vector& services) = 0; - virtual void RegisterServices( - std::vector - service_instances_info) = 0; - - // Asks the Mojo broker to bind to a matching interface on the service with - // the given |service_name|. If the service does not yet exist, the binding - // will remain in progress until the service is registered. If |async| is - // |false|, then the bind will execute synchronously; otherwise, it will - // execute asynchronously on the same sequence (see b/146508043). - template - void BindInterface(const std::string& service_name, - mojo::PendingReceiver receiver, - bool async = true) { - BindInterface(service_name, Interface::Name_, receiver.PassPipe(), async); - } - - virtual void BindInterface(const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe, - bool async = true) = 0; - - // Creates a new instance of this class which may be passed to another thread. - // The returned object may be passed across sequences until any of its public - // methods are called, at which point it becomes bound to the calling - // sequence. - virtual std::unique_ptr Clone() = 0; - - // Requests a PendingRemote for an ExternalConnector which can be passed to a - // different process. - virtual mojo::PendingRemote - RequestConnector() = 0; - - // Sends a request for a Chromium ServiceManager connector. - virtual void SendChromiumConnectorRequest( - mojo::ScopedMessagePipeHandle request) = 0; - - // Query the list of available services from this connector. - virtual void QueryServiceList( - base::OnceCallback< - void(std::vector< - chromecast::external_mojo::mojom::ExternalServiceInfoPtr>)> - callback) = 0; -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_connector_impl.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector_impl.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_connector_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,327 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/external_mojo/external_service_support/external_connector_impl.h" - -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_refptr.h" -#include "base/synchronization/lock.h" -#include "base/task/sequenced_task_runner.h" -#include "base/thread_annotations.h" -#include "base/time/time.h" -#include "chromecast/external_mojo/broker_service/broker_service.h" -#include "chromecast/external_mojo/external_service_support/external_service.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/platform/named_platform_channel.h" -#include "mojo/public/cpp/platform/platform_channel_endpoint.h" -#include "mojo/public/cpp/system/invitation.h" -#include "services/service_manager/public/cpp/connector.h" - -namespace chromecast { -namespace external_service_support { - -namespace { -constexpr base::TimeDelta kConnectRetryDelay = base::Milliseconds(500); -} // namespace - -// Since we are only allowed to make a single underlying connection to the -// broker, we share the underlying connection between all ExternalConnector -// instances. The ExternalConnectors use clones of the underlying connection. -// -// Since connection error callbacks are called in some arbitrary order, we need -// to be careful to handle disconnection correctly. Each underlying connection -// has a unique token (int64_t) associated with it, which is propagated to all -// clones. If any clone receives a disconnect callback, it tries to reconnect by -// calling ConnectClone(), passing in the previous token (associated with the -// broken connection). BrokerConnection then attempts to reconnect the -// underlying connection if the broken connection token matches the token for -// the current connection; if it doesn't match, the connection was already -// recreated, so nothing needs to be done. -class ExternalConnectorImpl::BrokerConnection - : public base::RefCountedThreadSafe { - public: - explicit BrokerConnection(std::string broker_path) - : broker_path_(std::move(broker_path)), - task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) { - Connect(); - } - - int64_t ConnectClone( - int64_t dead_connection_token, - mojo::PendingReceiver receiver) { - int64_t token; - { - base::AutoLock lock(lock_); - if (dead_connection_token == connection_token_) { - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&BrokerConnection::Connect, this)); - ++connection_token_; - } - token = connection_token_; - } - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&BrokerConnection::AttachClone, this, - std::move(receiver))); - return token; - } - - private: - friend class base::RefCountedThreadSafe; - ~BrokerConnection() = default; - - void Connect() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - connector_.reset(); - pending_receiver_ = connector_.BindNewPipeAndPassReceiver(); - AttemptBrokerConnection(); - } - - void AttachClone( - mojo::PendingReceiver receiver) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - connector_->Clone(std::move(receiver)); - } - - void AttemptBrokerConnection() { - mojo::NamedPlatformChannel::Options channel_options; - channel_options.server_name = broker_path_; -#if BUILDFLAG(IS_ANDROID) - // On Android, use the abstract namespace to avoid filesystem access. - channel_options.use_abstract_namespace = true; -#endif - mojo::PlatformChannelEndpoint endpoint = - mojo::NamedPlatformChannel::ConnectToServer(channel_options); - if (!endpoint.is_valid()) { - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce(&BrokerConnection::AttemptBrokerConnection, - weak_factory_.GetWeakPtr()), - kConnectRetryDelay); - return; - } - - auto invitation = mojo::IncomingInvitation::Accept(std::move(endpoint)); - auto remote_pipe = invitation.ExtractMessagePipe(0); - if (!remote_pipe) { - LOG(ERROR) << "Invalid message pipe"; - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce(&BrokerConnection::AttemptBrokerConnection, - weak_factory_.GetWeakPtr()), - kConnectRetryDelay); - return; - } - - mojo::FuseMessagePipes(pending_receiver_.PassPipe(), - std::move(remote_pipe)); - } - - const std::string broker_path_; - const scoped_refptr task_runner_; - - mojo::Remote connector_; - mojo::PendingReceiver - pending_receiver_; - - base::Lock lock_; - int64_t connection_token_ GUARDED_BY(lock_) = 1; - - base::WeakPtrFactory weak_factory_{this}; -}; - -// static -void ExternalConnector::Connect( - const std::string& broker_path, - base::OnceCallback)> callback) { - DCHECK(callback); - std::move(callback).Run(Create(broker_path)); -} - -// static -std::unique_ptr ExternalConnector::Create( - const std::string& broker_path) { - return std::make_unique(broker_path); -} - -// static -std::unique_ptr ExternalConnector::Create( - mojo::PendingRemote remote) { - return std::make_unique(std::move(remote)); -} - -// static -std::unique_ptr ExternalConnector::Create( - service_manager::Connector* connector) { - mojo::PendingRemote pending_remote; - connector->BindInterface(external_mojo::BrokerService::kServiceName, - pending_remote.InitWithNewPipeAndPassReceiver()); - return std::make_unique(std::move(pending_remote)); -} - -ExternalConnectorImpl::ExternalConnectorImpl(const std::string& broker_path) - : broker_connection_(base::MakeRefCounted(broker_path)) { - DETACH_FROM_SEQUENCE(sequence_checker_); - Connect(); -} - -ExternalConnectorImpl::ExternalConnectorImpl( - scoped_refptr broker_connection) - : broker_connection_(broker_connection) { - DETACH_FROM_SEQUENCE(sequence_checker_); - Connect(); -} - -ExternalConnectorImpl::ExternalConnectorImpl( - mojo::PendingRemote pending_remote) - : pending_remote_(std::move(pending_remote)) { - DETACH_FROM_SEQUENCE(sequence_checker_); -} - -ExternalConnectorImpl::~ExternalConnectorImpl() = default; - -base::CallbackListSubscription -ExternalConnectorImpl::AddConnectionErrorCallback( - base::RepeatingClosure callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return error_closures_.Add(std::move(callback)); -} - -void ExternalConnectorImpl::RegisterService(const std::string& service_name, - ExternalService* service) { - RegisterService(service_name, service->GetReceiver()); -} - -void ExternalConnectorImpl::RegisterService( - const std::string& service_name, - mojo::PendingRemote service_remote) { - BindConnectorIfNecessary(); - auto service_instance_info = - chromecast::external_mojo::mojom::ServiceInstanceInfo::New( - service_name, std::move(service_remote)); - std::vector v; - v.emplace_back(std::move(service_instance_info)); - connector_->RegisterServiceInstances(std::move(v)); -} - -void ExternalConnectorImpl::RegisterServices( - const std::vector& service_names, - const std::vector& services) { - CHECK(service_names.size() == services.size()); - std::vector - service_instances_info; - service_instances_info.reserve(services.size()); - for (size_t i = 0; i < services.size(); ++i) { - service_instances_info.emplace_back( - chromecast::external_mojo::mojom::ServiceInstanceInfo::New( - service_names[i], services[i]->GetReceiver())); - } - - RegisterServices(std::move(service_instances_info)); -} - -void ExternalConnectorImpl::RegisterServices( - std::vector - service_instances_info) { - BindConnectorIfNecessary(); - connector_->RegisterServiceInstances(std::move(service_instances_info)); -} - -void ExternalConnectorImpl::QueryServiceList( - base::OnceCallback)> - callback) { - BindConnectorIfNecessary(); - connector_->QueryServiceList(std::move(callback)); -} - -void ExternalConnectorImpl::BindInterface( - const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe, - bool async) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!async) { - BindInterfaceImmediately(service_name, interface_name, - std::move(interface_pipe)); - return; - } - base::SequencedTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&ExternalConnectorImpl::BindInterfaceImmediately, - weak_factory_.GetWeakPtr(), service_name, interface_name, - std::move(interface_pipe))); -} - -void ExternalConnectorImpl::BindInterfaceImmediately( - const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) { - BindConnectorIfNecessary(); - connector_->BindInterface(service_name, interface_name, - std::move(interface_pipe)); -} - -std::unique_ptr ExternalConnectorImpl::Clone() { - if (broker_connection_) { - return std::make_unique(broker_connection_); - } - // Bind to the current sequence since this is a public method. - BindConnectorIfNecessary(); - return std::make_unique(RequestConnector()); -} - -mojo::PendingRemote -ExternalConnectorImpl::RequestConnector() { - // Bind to the current sequence since this is a public method. - BindConnectorIfNecessary(); - mojo::PendingRemote remote; - connector_->Clone(remote.InitWithNewPipeAndPassReceiver()); - return remote; -} - -void ExternalConnectorImpl::SendChromiumConnectorRequest( - mojo::ScopedMessagePipeHandle request) { - BindConnectorIfNecessary(); - connector_->BindChromiumConnector(std::move(request)); -} - -void ExternalConnectorImpl::Connect() { - DCHECK(broker_connection_); - connection_token_ = broker_connection_->ConnectClone( - connection_token_, pending_remote_.InitWithNewPipeAndPassReceiver()); -} - -void ExternalConnectorImpl::OnMojoDisconnect() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - connector_.reset(); - pending_remote_.reset(); - if (broker_connection_) { - Connect(); - BindConnectorIfNecessary(); - } - error_closures_.Notify(); -} - -void ExternalConnectorImpl::BindConnectorIfNecessary() { - // Bind the message pipe and SequenceChecker to the current thread the first - // time it is used to connect. - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (connector_.is_bound()) { - return; - } - - DCHECK(pending_remote_.is_valid()); - - connector_.Bind(std::move(pending_remote_)); - connector_.set_disconnect_handler(base::BindOnce( - &ExternalConnectorImpl::OnMojoDisconnect, base::Unretained(this))); -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_connector_impl.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector_impl.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_connector_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_connector_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,93 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_IMPL_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_IMPL_H_ - -#include -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "chromecast/external_mojo/external_service_support/external_connector.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { -namespace external_service_support { - -class ExternalConnectorImpl : public ExternalConnector { - class BrokerConnection; - - public: - explicit ExternalConnectorImpl(const std::string& broker_path); - explicit ExternalConnectorImpl( - scoped_refptr broker_connection); - // For in-process connectors only. - explicit ExternalConnectorImpl( - mojo::PendingRemote - pending_remote); - - ExternalConnectorImpl(const ExternalConnectorImpl&) = delete; - ExternalConnectorImpl& operator=(const ExternalConnectorImpl&) = delete; - - ~ExternalConnectorImpl() override; - - // ExternalConnector implementation: - base::CallbackListSubscription AddConnectionErrorCallback( - base::RepeatingClosure callback) override; - void RegisterService(const std::string& service_name, - ExternalService* service) override; - void RegisterService( - const std::string& service_name, - mojo::PendingRemote service_remote) - override; - void RegisterServices(const std::vector& service_names, - const std::vector& services) override; - void RegisterServices( - std::vector - service_instances_info) override; - void BindInterface(const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe, - bool async = true) override; - std::unique_ptr Clone() override; - mojo::PendingRemote - RequestConnector() override; - void SendChromiumConnectorRequest( - mojo::ScopedMessagePipeHandle request) override; - void QueryServiceList( - base::OnceCallback< - void(std::vector< - chromecast::external_mojo::mojom::ExternalServiceInfoPtr>)> - callback) override; - - private: - void BindInterfaceImmediately(const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe); - void Connect(); - void OnMojoDisconnect(); - void BindConnectorIfNecessary(); - - const scoped_refptr broker_connection_; - - int64_t connection_token_ = 0; - mojo::PendingRemote pending_remote_; - mojo::Remote connector_; - - base::RepeatingClosureList error_closures_; - - SEQUENCE_CHECKER(sequence_checker_); - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_service.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_service.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_service.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_service.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/external_mojo/external_service_support/external_service.h" - -#include "base/logging.h" - -namespace chromecast { -namespace external_service_support { - -ExternalService::ExternalService() = default; - -ExternalService::~ExternalService() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -mojo::PendingRemote -ExternalService::GetReceiver() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - service_receiver_.reset(); - return service_receiver_.BindNewPipeAndPassRemote(); -} - -void ExternalService::OnBindInterface( - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) { - bundle_.BindInterface(interface_name, std::move(interface_pipe)); -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_service.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_service.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/external_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/external_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_SERVICE_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_SERVICE_H_ - -#include -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/sequence_checker.h" -#include "chromecast/external_mojo/public/mojom/connector.mojom.h" -#include "chromecast/mojo/interface_bundle.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/system/message_pipe.h" - -namespace chromecast { -namespace external_service_support { - -// API for external (non-Chromium process) Mojo services. -class ExternalService : public external_mojo::mojom::ExternalService { - public: - ExternalService(); - - ExternalService(const ExternalService&) = delete; - ExternalService& operator=(const ExternalService&) = delete; - - ~ExternalService() override; - - // Returns the Mojo receiver for this service. - mojo::PendingRemote GetReceiver(); - - // Adds an interface that users of this service may bind to. To avoid races - // where the service is registered but interfaces cannot be bound by other - // processes/services, add all interfaces before registering this service. - // The |bind_callback| will be called once for each bind attempt. The callback - // will not be called after this ExternalService instance is destroyed. - template - void AddInterface( - base::RepeatingCallback)> - bind_callback) { - RemoveInterface(); - bundle_.AddBinder(std::move(bind_callback)); - } - - // Convenience method for exposing an interface. The implementation must - // outlive the service or be explicitly removed before the implementation is - // destroyed. - template - void AddInterface(Interface* interface) { - RemoveInterface(); - bundle_.AddInterface(interface); - } - - // Removes an interface, preventing new bindings from being created. Does not - // affect existing bindings. - template - void RemoveInterface() { - bundle_.RemoveInterface(); - } - - InterfaceBundle* bundle() { return &bundle_; } - - private: - // external_mojo::mojom::ExternalService implementation: - void OnBindInterface(const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) override; - - InterfaceBundle bundle_; - mojo::Receiver service_receiver_{this}; - - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/fake_external_connector.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/fake_external_connector.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/fake_external_connector.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/fake_external_connector.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,105 +0,0 @@ -// 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 "chromecast/external_mojo/external_service_support/fake_external_connector.h" - -#include - -#include "chromecast/external_mojo/external_service_support/external_service.h" - -namespace chromecast { -namespace external_service_support { - -FakeExternalConnector::FakeExternalConnector() { - DETACH_FROM_SEQUENCE(sequence_checker_); -} - -FakeExternalConnector::FakeExternalConnector( - mojo::PendingRemote remote) - : parent_(std::move(remote)) {} - -FakeExternalConnector::~FakeExternalConnector() = default; - -base::CallbackListSubscription -FakeExternalConnector::AddConnectionErrorCallback( - base::RepeatingClosure callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return base::CallbackListSubscription(); -} - -void FakeExternalConnector::RegisterService(const std::string& service_name, - ExternalService* service) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - RegisterService(service_name, service->GetReceiver()); -} - -void FakeExternalConnector::RegisterService( - const std::string& service_name, - mojo::PendingRemote service_remote) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - services_.emplace(service_name, std::move(service_remote)); -} - -void FakeExternalConnector::RegisterServices( - const std::vector& service_names, - const std::vector& services) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(service_names.size() == services.size()); - for (size_t i = 0; i < services.size(); ++i) { - RegisterService(service_names[i], services[i]); - } -} - -void FakeExternalConnector::RegisterServices( - std::vector - service_instances_info) {} - -void FakeExternalConnector::QueryServiceList( - base::OnceCallback)> - callback) {} - -void FakeExternalConnector::BindInterface( - const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe, - bool async) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (parent_.is_bound()) { - parent_->BindInterfaceInternal(service_name, interface_name, - std::move(interface_pipe)); - return; - } - if (!services_.count(service_name)) { - return; - } - services_[service_name]->OnBindInterface(interface_name, - std::move(interface_pipe)); -} - -std::unique_ptr -FakeExternalConnector::Clone() { - mojo::PendingRemote remote; - child_receivers_.Add(this, remote.InitWithNewPipeAndPassReceiver()); - return std::make_unique(std::move(remote)); -} - -mojo::PendingRemote -FakeExternalConnector::RequestConnector() { - return mojo::PendingRemote(); -} - -void FakeExternalConnector::SendChromiumConnectorRequest( - mojo::ScopedMessagePipeHandle request) {} - -void FakeExternalConnector::BindInterfaceInternal( - const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) { - BindInterface(service_name, interface_name, std::move(interface_pipe)); -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/fake_external_connector.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/fake_external_connector.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/fake_external_connector.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/fake_external_connector.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,87 +0,0 @@ -// 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. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_FAKE_EXTERNAL_CONNECTOR_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_FAKE_EXTERNAL_CONNECTOR_H_ - -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/sequence_checker.h" -#include "chromecast/external_mojo/external_service_support/external_connector.h" -#include "chromecast/external_mojo/public/mojom/test_connector.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { -namespace external_service_support { - -// Local, single-process ExternalConnector for testing. Clients can register -// mock services with FakeExternalConnector and verify that tested code makes -// the expected service requests. -class FakeExternalConnector - : public external_service_support::ExternalConnector, - public external_mojo::mojom::TestExternalConnector { - public: - FakeExternalConnector(); - explicit FakeExternalConnector( - mojo::PendingRemote remote); - FakeExternalConnector(const FakeExternalConnector&) = delete; - FakeExternalConnector& operator=(const FakeExternalConnector&) = delete; - ~FakeExternalConnector() override; - - // external_service_support::ExternalConnector implementation: - void RegisterService(const std::string& service_name, - ExternalService* service) override; - void RegisterService( - const std::string& service_name, - mojo::PendingRemote service_remote) - override; - void RegisterServices(const std::vector& service_names, - const std::vector& services) override; - void BindInterface(const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe, - bool async = true) override; - // Note: These methods are unimplemented. - base::CallbackListSubscription AddConnectionErrorCallback( - base::RepeatingClosure callback) override; - void RegisterServices( - std::vector - service_instances_info) override; - std::unique_ptr Clone() override; - mojo::PendingRemote - RequestConnector() override; - void SendChromiumConnectorRequest( - mojo::ScopedMessagePipeHandle request) override; - void QueryServiceList( - base::OnceCallback< - void(std::vector< - chromecast::external_mojo::mojom::ExternalServiceInfoPtr>)> - callback) override; - - private: - // external_mojo::mojom::TestExternalConnector implementation: - void BindInterfaceInternal( - const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) override; - - mojo::Remote parent_; - base::flat_map> - services_; - mojo::ReceiverSet - child_receivers_; - - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_FAKE_EXTERNAL_CONNECTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/perfetto_tracing_client.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/perfetto_tracing_client.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/perfetto_tracing_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/perfetto_tracing_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#include "chromecast/external_mojo/external_service_support/perfetto_tracing_client.h" - -namespace chromecast { -namespace external_service_support { - -const char TracingClient::kTracingServiceName[] = "perfetto"; - -// Initializes perfetto tracing. -// -// If this is called more than once, it will not cause problems because -// because perfetto::Tracing::Initialize() handles this internally. -void InitializePerfettoTracing(base::tracing::PerfettoPlatform* platform) { - perfetto::TracingInitArgs args; - args.backends = perfetto::kSystemBackend; - args.platform = platform; - perfetto::Tracing::Initialize(args); -} - -PerfettoTracingClient::~PerfettoTracingClient() = default; - -PerfettoTracingClient::PerfettoTracingClient() - : perfetto_platform_(std::make_unique( - base::tracing::PerfettoPlatform::TaskRunnerType::kBuiltin)) { - InitializePerfettoTracing(perfetto_platform_.get()); -} - -std::unique_ptr TracingClient::Create( - ExternalConnector* connector) { - return std::make_unique(); -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/perfetto_tracing_client.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/perfetto_tracing_client.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/perfetto_tracing_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/perfetto_tracing_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_PERFETTO_TRACING_CLIENT_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_PERFETTO_TRACING_CLIENT_H_ - -#include - -#include "base/tracing/perfetto_platform.h" -#include "chromecast/external_mojo/external_service_support/tracing_client.h" -#include "third_party/perfetto/include/perfetto/tracing/string_helpers.h" -#include "third_party/perfetto/include/perfetto/tracing/tracing.h" -#include "third_party/perfetto/include/perfetto/tracing/track_event.h" - -namespace chromecast { -namespace external_service_support { -class ExternalConnector; - -// TracingClient implementation for using Perfetto tracing. -class PerfettoTracingClient : public TracingClient { - public: - PerfettoTracingClient(); - - ~PerfettoTracingClient() override; - - PerfettoTracingClient(const PerfettoTracingClient&) = delete; - PerfettoTracingClient& operator=(const PerfettoTracingClient&) = delete; - - private: - const std::unique_ptr perfetto_platform_; -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_PERFETTO_TRACING_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/process_setup.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/process_setup.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/process_setup.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/process_setup.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/external_mojo/external_service_support/process_setup.h" - -#include -#include - -#include "base/base_switches.h" -#include "base/command_line.h" -#include "base/feature_list.h" -#include "base/logging.h" -#include "build/build_config.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/chromecast_buildflags.h" - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) -#include "chromecast/external_mojo/external_service_support/crash_reporter_client.h" -#endif - -namespace chromecast { -namespace external_service_support { - -void CommonProcessInitialization(int argc, const char* const* argv) { -#if !BUILDFLAG(IS_ANDROID) - // Set C library locale to make sure CommandLine can parse argument values - // in the correct encoding. - setlocale(LC_ALL, ""); - setlocale(LC_NUMERIC, "C"); -#endif - - base::CommandLine::Init(argc, argv); - - logging::LoggingSettings settings; - settings.logging_dest = - logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR; - logging::InitLogging(settings); - -#if BUILDFLAG(IS_CAST_DESKTOP_BUILD) - logging::SetLogItems(true, true, true, false); -#else - // Timestamp available through logcat -v time. - logging::SetLogItems(true, true, false, false); -#endif // BUILDFLAG(IS_CAST_DESKTOP_BUILD) - - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (!command_line->HasSwitch(switches::kDeferFeatureList)) { - base::FeatureList::InitInstance( - command_line->GetSwitchValueASCII(switches::kEnableFeatures), - command_line->GetSwitchValueASCII(switches::kDisableFeatures)); - } - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - CrashReporterClient::Init(); -#endif - - CHECK_NE(SIG_ERR, signal(SIGPIPE, SIG_IGN)); -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/process_setup.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/process_setup.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/process_setup.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/process_setup.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_PROCESS_SETUP_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_PROCESS_SETUP_H_ - -namespace chromecast { -namespace external_service_support { - -// Common initialization code for external Mojo processes. Should be called -// early in main(). -void CommonProcessInitialization(int argc, const char* const* argv); - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_PROCESS_SETUP_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/reconnecting_remote.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/reconnecting_remote.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/reconnecting_remote.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/reconnecting_remote.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_RECONNECTING_REMOTE_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_RECONNECTING_REMOTE_H_ - -#include -#include -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "chromecast/external_mojo/external_service_support/external_connector.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { - -// A class which wraps a mojo::Remote with automatic reconnection logic. -// -// Two reconnection methods are supported: (1) Provide a service name and an -// ExternalConnector to reconnect, or (2) provide a callback to rebind the -// remote. -// -// Clients can register observer callbacks to be notified of reconnect events so -// that they can re-initialize some state in the remote process. Observers are -// notified in the same order they were registered. Observers should use WeakPtr -// if they expect to outlive the ReconnectingRemote. -// -// This class can also be used to wrap a local implementation. This can be used -// for (1) Client code which can exist in both in and out-of-process, and (2) -// Injecting a mock implementation. Since the impl is called directly, this -// allows for synchronous method call validation, as opposed to asynchronously -// posting mojo calls which require a base::RunLoop to verify in unit tests. -// -template -class ReconnectingRemote { - public: - // Reconnect option 1: Provide an ExternalConnector to request the interface - // from a named service. - ReconnectingRemote(const std::string& service_name, - external_service_support::ExternalConnector* connector) - : service_name_(service_name), connector_(connector) { - DCHECK(connector_); - Connect(); - } - - // Reconnect option 2: Provide a callback to re-bind |remote_|. |remote_| is - // always in an unbound state before |connect_callback_| is run. - explicit ReconnectingRemote( - base::RepeatingCallback* remote)> - connect_callback) - : connect_callback_(std::move(connect_callback)) { - Connect(); - } - - // Option 3: Inject an implementation directly to wrap a local implementation. - // Reconnection is not necessary since a local instance will always exist. - explicit ReconnectingRemote(Interface* impl) : remote_proxy_(impl) {} - - ReconnectingRemote(const ReconnectingRemote&) = delete; - ReconnectingRemote& operator=(const ReconnectingRemote&) = delete; - ~ReconnectingRemote() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } - - Interface* get() const { return remote_proxy_; } - Interface* operator->() const { return get(); } - Interface& operator*() const { return *get(); } - - void OnReconnect(base::RepeatingClosure callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - observer_callbacks_.push_back(std::move(callback)); - } - - private: - void Connect() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - remote_.reset(); - if (connector_) { - connector_->BindInterface(service_name_, - remote_.BindNewPipeAndPassReceiver()); - } else { - connect_callback_.Run(&remote_); - } - DCHECK(remote_.is_bound()); - remote_proxy_ = remote_.get(); - remote_.set_disconnect_handler( - base::BindOnce(&ReconnectingRemote::Connect, base::Unretained(this))); - for (auto& callback : observer_callbacks_) { - callback.Run(); - } - } - - const std::string service_name_; - external_service_support::ExternalConnector* const connector_ = nullptr; - - base::RepeatingCallback* remote)> - connect_callback_; - - mojo::Remote remote_; - Interface* remote_proxy_ = nullptr; - std::vector observer_callbacks_; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_RECONNECTING_REMOTE_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/service_process.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/service_process.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/service_process.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/service_process.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_SERVICE_PROCESS_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_SERVICE_PROCESS_H_ - -#include - -namespace chromecast { -namespace external_service_support { - -class ExternalConnector; - -// Provides an entrypoint for external processes that are using Mojo with -// standalone_service_main.cc. -class ServiceProcess { - public: - virtual ~ServiceProcess() = default; - - // Entrypoint from standalone_service_main.cc. - static std::unique_ptr Create(ExternalConnector* connector); -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_SERVICE_PROCESS_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/standalone_mojo_broker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "base/at_exit.h" -#include "base/message_loop/message_pump_for_io.h" -#include "base/message_loop/message_pump_type.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_executor.h" -#include "base/task/thread_pool/thread_pool_instance.h" -#include "chromecast/external_mojo/external_service_support/external_connector_impl.h" -#include "chromecast/external_mojo/external_service_support/process_setup.h" -#include "chromecast/external_mojo/external_service_support/tracing_client.h" -#include "chromecast/external_mojo/public/cpp/common.h" -#include "chromecast/external_mojo/public/cpp/external_mojo_broker.h" -#include "mojo/core/embedder/embedder.h" -#include "mojo/core/embedder/scoped_ipc_support.h" - -// Standalone Mojo broker process. - -int main(int argc, char** argv) { - base::AtExitManager exit_manager; - chromecast::external_service_support::CommonProcessInitialization(argc, argv); - - base::SingleThreadTaskExecutor io_task_executor(base::MessagePumpType::IO); - base::RunLoop run_loop; - - mojo::core::Configuration mojo_config; - mojo_config.is_broker_process = true; - mojo::core::Init(mojo_config); - - mojo::core::ScopedIPCSupport ipc_support( - io_task_executor.task_runner(), - mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); - - base::ThreadPoolInstance::CreateAndStartWithDefaultParams( - "StandaloneMojoBroker"); - - chromecast::external_mojo::ExternalMojoBroker broker( - chromecast::external_mojo::GetBrokerPath()); - - chromecast::external_service_support::ExternalConnectorImpl tracing_connector( - broker.CreateConnector()); - auto tracing_client = - chromecast::external_service_support::TracingClient::Create( - &tracing_connector); - - run_loop.Run(); - base::ThreadPoolInstance::Get()->Shutdown(); - - return 0; -} diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/standalone_service_main.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/standalone_service_main.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/standalone_service_main.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/standalone_service_main.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include - -#include "base/at_exit.h" -#include "base/command_line.h" -#include "base/files/file_descriptor_watcher_posix.h" -#include "base/functional/bind.h" -#include "base/message_loop/message_pump_for_io.h" -#include "base/message_loop/message_pump_type.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_executor.h" -#include "base/task/thread_pool/thread_pool_instance.h" -#include "base/threading/sequence_bound.h" -#include "base/threading/thread.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/external_mojo/external_service_support/external_connector.h" -#include "chromecast/external_mojo/external_service_support/process_setup.h" -#include "chromecast/external_mojo/external_service_support/service_process.h" -#include "chromecast/external_mojo/external_service_support/tracing_client.h" -#include "chromecast/external_mojo/public/cpp/common.h" -#include "chromecast/external_mojo/public/cpp/external_mojo_broker.h" -#include "mojo/core/embedder/embedder.h" -#include "mojo/core/embedder/scoped_ipc_support.h" -#include "mojo/public/cpp/bindings/pending_remote.h" - -// Simple process entrypoint for standalone Mojo services. - -struct GlobalState { - std::unique_ptr - service_process; - std::unique_ptr - connector; - std::unique_ptr - tracing_client; -}; - -void OnConnected( - GlobalState* state, - std::unique_ptr - connector) { - state->connector = std::move(connector); - state->tracing_client = - chromecast::external_service_support::TracingClient::Create( - state->connector.get()); - state->service_process = - chromecast::external_service_support::ServiceProcess::Create( - state->connector.get()); -} - -int main(int argc, char** argv) { - base::AtExitManager exit_manager; - chromecast::external_service_support::CommonProcessInitialization(argc, argv); - - base::SingleThreadTaskExecutor io_task_executor(base::MessagePumpType::IO); - base::FileDescriptorWatcher file_descriptor_watcher(io_task_executor.task_runner()); - base::RunLoop run_loop; - - mojo::core::Init(); - - mojo::core::ScopedIPCSupport ipc_support( - io_task_executor.task_runner(), - mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); - - base::ThreadPoolInstance::CreateAndStartWithDefaultParams( - "StandaloneService"); - - GlobalState state; - // State for in-process Mojo broker. - auto broker_thread = std::make_unique("external_mojo"); - base::SequenceBound broker; - - if (chromecast::GetSwitchValueBoolean(switches::kInProcessBroker, false)) { - // Set up the external Mojo Broker. - broker_thread->StartWithOptions( - base::Thread::Options(base::MessagePumpType::IO, 0)); - broker = base::SequenceBound( - broker_thread->task_runner(), - chromecast::external_mojo::GetBrokerPath()); - mojo::PendingRemote - connector_remote; - broker - .AsyncCall( - &chromecast::external_mojo::ExternalMojoBroker::BindConnector) - .WithArgs(connector_remote.InitWithNewPipeAndPassReceiver()); - OnConnected(&state, - chromecast::external_service_support::ExternalConnector::Create( - std::move(connector_remote))); - } else { - // Connect to existing Mojo broker. - chromecast::external_service_support::ExternalConnector::Connect( - chromecast::external_mojo::GetBrokerPath(), - base::BindOnce(&OnConnected, &state)); - } - - run_loop.Run(); - base::ThreadPoolInstance::Get()->Shutdown(); - - return 0; -} diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/tracing_client.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/tracing_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// 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. -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_TRACING_CLIENT_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_TRACING_CLIENT_H_ - -#include - -namespace chromecast { -namespace external_service_support { -class ExternalConnector; - -// TracingClient Supports the tracing of processes that connect to a central -// tracing service through an ExternalConnector. -class TracingClient { - public: - TracingClient() = default; - virtual ~TracingClient() = default; - - static const char kTracingServiceName[]; - - static std::unique_ptr Create(ExternalConnector* connector); - - private: - TracingClient(const TracingClient&) = delete; - TracingClient& operator=(const TracingClient&) = delete; -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_TRACING_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/tracing_client_dummy.cc chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client_dummy.cc --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/tracing_client_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// 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 "chromecast/external_mojo/external_service_support/tracing_client_dummy.h" - -namespace chromecast { -namespace external_service_support { - -// static -const char TracingClient::kTracingServiceName[] = "unknown"; - -// static -std::unique_ptr TracingClient::Create( - ExternalConnector* connector) { - return std::make_unique(); -} - -} // namespace external_service_support -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/tracing_client_dummy.h chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client_dummy.h --- chromium-132.0.6834.110/chromecast/external_mojo/external_service_support/tracing_client_dummy.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/external_service_support/tracing_client_dummy.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// 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. -#ifndef CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_TRACING_CLIENT_DUMMY_H_ -#define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_TRACING_CLIENT_DUMMY_H_ - -#include "chromecast/external_mojo/external_service_support/tracing_client.h" - -namespace chromecast { -namespace external_service_support { - -// Dummy implementation for build configurations that do not enable tracing. -class TracingClientDummy : public TracingClient { - public: - TracingClientDummy() = default; - ~TracingClientDummy() override = default; - - private: - TracingClientDummy(const TracingClientDummy&) = delete; - TracingClientDummy& operator=(const TracingClientDummy&) = delete; -}; - -} // namespace external_service_support -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_TRACING_CLIENT_DUMMY_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/public/cpp/common.cc chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/common.cc --- chromium-132.0.6834.110/chromecast/external_mojo/public/cpp/common.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/common.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/external_mojo/public/cpp/common.h" - -#include - -#include "base/check.h" -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/path_service.h" -#include "build/build_config.h" -#include "chromecast/base/chromecast_switches.h" - -namespace chromecast { -namespace external_mojo { - -namespace { - -#if !BUILDFLAG(IS_ANDROID) -// Default path for Unix domain socket used by external Mojo services to connect -// to Mojo services within cast_shell. -constexpr std::string_view kDefaultBrokerPath("/tmp/cast_mojo_broker"); -#endif // !BUILDFLAG(IS_ANDROID) - -} // namespace - -std::string GetBrokerPath() { - std::string broker_path; - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kCastMojoBrokerPath)) { - broker_path = - command_line->GetSwitchValueASCII(switches::kCastMojoBrokerPath); - } else { -#if BUILDFLAG(IS_ANDROID) - // Android apps don't have access to `/tmp` folder. Use app's data folder - // instead to store the socket file. - base::FilePath socket_path; - CHECK(base::PathService::Get(base::DIR_ANDROID_APP_DATA, &socket_path)); - socket_path = socket_path.AppendASCII(FILE_PATH_LITERAL("cast_mojo_broker")); - broker_path = socket_path.MaybeAsASCII(); -#else - broker_path = std::string(kDefaultBrokerPath); -#endif // BUILDFLAG(IS_ANDROID) - } - return broker_path; -} - -} // namespace external_mojo -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/public/cpp/common.h chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/common.h --- chromium-132.0.6834.110/chromecast/external_mojo/public/cpp/common.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/common.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_PUBLIC_CPP_COMMON_H_ -#define CHROMECAST_EXTERNAL_MOJO_PUBLIC_CPP_COMMON_H_ - -#include - -namespace chromecast { -namespace external_mojo { - -// Returns the Unix domain socket path to use to connect to the Mojo broker. -// You can set the path on the command line with --mojo_broker_path=. -std::string GetBrokerPath(); - -} // namespace external_mojo -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_PUBLIC_CPP_COMMON_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/public/cpp/external_mojo_broker.cc chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/external_mojo_broker.cc --- chromium-132.0.6834.110/chromecast/external_mojo/public/cpp/external_mojo_broker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/external_mojo_broker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,481 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/external_mojo/public/cpp/external_mojo_broker.h" - -#include -#include -#include - -#include "base/containers/contains.h" -#include "build/build_config.h" - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -#include -#endif - -#include - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/message_loop/message_pump_for_io.h" -#include "base/task/current_thread.h" -#include "base/token.h" -#include "base/trace_event/trace_event.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/external_mojo/public/cpp/common.h" -#include "chromecast/external_mojo/public/mojom/connector.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "mojo/public/cpp/platform/named_platform_channel.h" -#include "mojo/public/cpp/platform/platform_channel_endpoint.h" -#include "mojo/public/cpp/platform/platform_handle.h" -#include "mojo/public/cpp/platform/socket_utils_posix.h" -#include "mojo/public/cpp/system/invitation.h" -#include "services/service_manager/public/cpp/connector.h" -#include "services/service_manager/public/cpp/constants.h" -#include "services/service_manager/public/cpp/identity.h" -#include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/public/cpp/service_filter.h" -#include "services/service_manager/public/cpp/service_receiver.h" -#include "services/service_manager/public/mojom/connector.mojom.h" -#include "services/service_manager/public/mojom/service.mojom.h" - -#if BUILDFLAG(IS_ANDROID) -#include "base/android/bundle_utils.h" -#endif - -namespace chromecast { -namespace external_mojo { - -namespace { - -void OnRegisterServiceResult(const std::string& service_name, - service_manager::mojom::ConnectResult result) { - // RegisterServiceInstance() currently returns INVALID_ARGUMENT on success. - if (result == service_manager::mojom::ConnectResult::ACCESS_DENIED) { - LOG(WARNING) << "Failed to register external service proxy for " - << service_name; - } -} - -void OnInternalBindResult( - const std::string& service_name, - const std::string& interface_name, - service_manager::mojom::ConnectResult result, - const std::optional& identity) { - if (result != service_manager::mojom::ConnectResult::SUCCEEDED) { - LOG(ERROR) << "Failed to bind " << service_name << ":" << interface_name - << ", result = " << result; - } -} - -} // namespace - -class ExternalMojoBroker::ConnectorImpl : public mojom::ExternalConnector { - public: - ConnectorImpl() : connector_facade_(this) {} - - ConnectorImpl(const ConnectorImpl&) = delete; - ConnectorImpl& operator=(const ConnectorImpl&) = delete; - - void InitializeChromium( - std::unique_ptr connector, - const std::vector& external_services_to_proxy) { - DCHECK(connector); - connector_ = std::move(connector); - RegisterExternalServices(external_services_to_proxy); - } - - void AddReceiver(mojo::PendingReceiver receiver) { - receivers_.Add(this, std::move(receiver)); - } - - private: - class ExternalServiceProxy : public ::service_manager::Service { - public: - ExternalServiceProxy( - ConnectorImpl* connector, - std::string service_name, - mojo::PendingReceiver<::service_manager::mojom::Service> receiver) - : connector_(connector), - service_name_(std::move(service_name)), - service_receiver_(this, std::move(receiver)) { - DCHECK(connector_); - } - - ExternalServiceProxy(const ExternalServiceProxy&) = delete; - ExternalServiceProxy& operator=(const ExternalServiceProxy&) = delete; - - private: - void OnBindInterface( - const service_manager::BindSourceInfo& source, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) override { - connector_->BindExternalInterface(service_name_, interface_name, - std::move(interface_pipe)); - } - - ConnectorImpl* const connector_; - const std::string service_name_; - service_manager::ServiceReceiver service_receiver_; - }; - - class ServiceManagerConnectorFacade - : public service_manager::mojom::Connector { - public: - explicit ServiceManagerConnectorFacade( - ExternalMojoBroker::ConnectorImpl* connector) - : connector_(connector) { - DCHECK(connector_); - } - - void AddReceiver( - mojo::PendingReceiver receiver) { - receivers_.Add(this, std::move(receiver)); - } - - private: - void BindInterface(const ::service_manager::ServiceFilter& filter, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe, - service_manager::mojom::BindInterfacePriority priority, - BindInterfaceCallback callback) override { - connector_->BindInterface(filter.service_name(), interface_name, - std::move(interface_pipe)); - std::move(callback).Run(service_manager::mojom::ConnectResult::SUCCEEDED, - std::nullopt); - } - - void QueryService(const std::string& service_name, - QueryServiceCallback callback) override { - // TODO(kmackay) Could add a wrapper as needed. - NOTIMPLEMENTED(); - } - - void WarmService(const ::service_manager::ServiceFilter& filter, - WarmServiceCallback callback) override { - std::move(callback).Run(service_manager::mojom::ConnectResult::SUCCEEDED, - std::nullopt); - } - - void RegisterServiceInstance( - const ::service_manager::Identity& identity, - mojo::ScopedMessagePipeHandle service, - mojo::PendingReceiver - metadata_receiver, - RegisterServiceInstanceCallback callback) override { - // TODO(kmackay) Could add a wrapper as needed. - NOTIMPLEMENTED(); - } - - void Clone(mojo::PendingReceiver - receiver) override { - AddReceiver(std::move(receiver)); - } - - ExternalMojoBroker::ConnectorImpl* const connector_; - - mojo::ReceiverSet receivers_; - }; - - struct PendingBindRequest { - PendingBindRequest(const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) - : interface_name(interface_name), - interface_pipe(std::move(interface_pipe)) {} - - const std::string interface_name; - mojo::ScopedMessagePipeHandle interface_pipe; - }; - - void RegisterExternalServices( - const std::vector& external_services_to_proxy) { - if (external_services_to_proxy.empty()) { - return; - } - - external_services_to_proxy_.insert(external_services_to_proxy.begin(), - external_services_to_proxy.end()); - - for (const auto& service_name : external_services_to_proxy) { - LOG(INFO) << "Register proxy for external " << service_name; - mojo::PendingRemote service_remote; - registered_external_services_[service_name] = - std::make_unique( - this, service_name, - service_remote.InitWithNewPipeAndPassReceiver()); - - connector_->RegisterServiceInstance( - service_manager::Identity(service_name, - service_manager::kSystemInstanceGroup, - base::Token{}, base::Token::CreateRandom()), - std::move(service_remote), - mojo::NullReceiver() /* metadata_receiver */, - base::BindOnce(&OnRegisterServiceResult, service_name)); - } - } - - // Helper for ExternalServiceProxy. - void BindExternalInterface(const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) { - LOG(INFO) << "Internal request for " << service_name << ":" - << interface_name; - auto it = services_.find(service_name); - if (it != services_.end()) { - it->second->OnBindInterface(interface_name, std::move(interface_pipe)); - return; - } - - ServiceNotFound(service_name, interface_name, std::move(interface_pipe)); - } - - void RegisterServiceInstance( - const std::string& service_name, - mojo::PendingRemote service_remote) { - if (base::Contains(services_, service_name)) { - LOG(ERROR) << "Duplicate service " << service_name; - return; - } - TRACE_EVENT_INSTANT1("mojom", "RegisterService", TRACE_EVENT_SCOPE_THREAD, - "service", service_name); - LOG(INFO) << "Register service " << service_name; - mojo::Remote service(std::move(service_remote)); - service.set_disconnect_handler(base::BindOnce( - &ConnectorImpl::OnServiceLost, base::Unretained(this), service_name)); - auto it = services_.emplace(service_name, std::move(service)).first; - - auto p = pending_bind_requests_.find(service_name); - if (p != pending_bind_requests_.end()) { - for (auto& request : p->second) { - it->second->OnBindInterface(request.interface_name, - std::move(request.interface_pipe)); - } - pending_bind_requests_.erase(p); - } - - auto& info_entry = services_info_[service_name]; - info_entry.name = service_name; - info_entry.connect_time = base::TimeTicks::Now(); - info_entry.disconnect_time = base::TimeTicks(); - } - - // standalone::mojom::Connector implementation: - void RegisterServiceInstances( - std::vector - service_instances_info) override { - for (auto& instance_info_ptr : service_instances_info) { - RegisterServiceInstance(instance_info_ptr->service_name, - std::move(instance_info_ptr->service_remote)); - } - } - - void BindInterface(const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) override { - LOG(INFO) << "Request for " << service_name << ":" << interface_name; - TRACE_EVENT_INSTANT1("mojom", "BindToService", TRACE_EVENT_SCOPE_THREAD, - "service", service_name); - auto it = services_.find(service_name); - if (it != services_.end()) { - LOG(INFO) << "Found externally-registered " << service_name; - it->second->OnBindInterface(interface_name, std::move(interface_pipe)); - return; - } - - auto service_proxy_it = external_services_to_proxy_.find(service_name); - - if (!connector_ || service_proxy_it != external_services_to_proxy_.end()) { - ServiceNotFound(service_name, interface_name, std::move(interface_pipe)); - return; - } - - connector_->QueryService( - service_name, - base::BindOnce(&ConnectorImpl::OnQueryResult, base::Unretained(this), - service_name, interface_name, - std::move(interface_pipe))); - } - - void Clone( - mojo::PendingReceiver receiver) override { - AddReceiver(std::move(receiver)); - } - - void BindChromiumConnector( - mojo::ScopedMessagePipeHandle interface_pipe) override { - if (!connector_) { - connector_facade_.AddReceiver( - mojo::PendingReceiver( - std::move(interface_pipe))); - return; - } - - connector_->BindConnectorReceiver( - mojo::PendingReceiver( - std::move(interface_pipe))); - } - - void QueryServiceList(QueryServiceListCallback callback) override { - std::vector infos; - for (const auto& it : services_info_) { - infos.emplace_back(it.second.Clone()); - } - std::move(callback).Run(std::move(infos)); - } - - void OnQueryResult(const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe, - service_manager::mojom::ServiceInfoPtr info) { - if (!info) { - ServiceNotFound(service_name, interface_name, std::move(interface_pipe)); - return; - } - - LOG(INFO) << "Found internal " << service_name; - connector_->BindInterface( - service_manager::ServiceFilter::ByName(service_name), interface_name, - std::move(interface_pipe), - service_manager::mojom::BindInterfacePriority::kImportant, - base::BindOnce(&OnInternalBindResult, service_name, interface_name)); - } - - void ServiceNotFound(const std::string& service_name, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) { - LOG(INFO) << service_name << " not found"; - // Assume the service will be registered later, and wait until then. - pending_bind_requests_[service_name].emplace_back( - interface_name, std::move(interface_pipe)); - } - - void OnServiceLost(const std::string& service_name) { - LOG(INFO) << service_name << " disconnected"; - TRACE_EVENT_INSTANT1("mojom", "ServiceDisconnected", - TRACE_EVENT_SCOPE_THREAD, "service", service_name); - services_.erase(service_name); - services_info_[service_name].disconnect_time = base::TimeTicks::Now(); - } - - ServiceManagerConnectorFacade connector_facade_; - std::unique_ptr connector_; - - mojo::ReceiverSet receivers_; - std::set external_services_to_proxy_; - std::map> - registered_external_services_; - - std::map> services_; - std::map> pending_bind_requests_; - std::map services_info_; -}; - -class ExternalMojoBroker::ReadWatcher - : public base::MessagePumpForIO::FdWatcher { - public: - ReadWatcher(ConnectorImpl* connector, mojo::PlatformHandle listen_handle) - : connector_(connector), - listen_handle_(std::move(listen_handle)), - watch_controller_(FROM_HERE) { - DCHECK(listen_handle_.is_valid()); - base::CurrentIOThread::Get().WatchFileDescriptor( - listen_handle_.GetFD().get(), true /* persistent */, - base::MessagePumpForIO::WATCH_READ, &watch_controller_, this); - } - - ReadWatcher(const ReadWatcher&) = delete; - ReadWatcher& operator=(const ReadWatcher&) = delete; - - // base::MessagePumpForIO::FdWatcher implementation: - void OnFileCanReadWithoutBlocking(int fd) override { - base::ScopedFD accepted_fd; - if (mojo::AcceptSocketConnection(fd, &accepted_fd, - false /* check_peer_user */) && - accepted_fd.is_valid()) { - mojo::OutgoingInvitation invitation; - auto pipe = invitation.AttachMessagePipe(0); - mojo::OutgoingInvitation::Send( - std::move(invitation), base::kNullProcessHandle, - mojo::PlatformChannelEndpoint( - mojo::PlatformHandle(std::move(accepted_fd)))); - connector_->AddReceiver( - mojo::PendingReceiver(std::move(pipe))); - } - } - - void OnFileCanWriteWithoutBlocking(int /* fd */) override {} - - private: - ConnectorImpl* const connector_; - const mojo::PlatformHandle listen_handle_; - base::MessagePumpForIO::FdWatchController watch_controller_; -}; - -ExternalMojoBroker::ExternalMojoBroker(const std::string& broker_path) { - connector_ = std::make_unique(); - - // For external service support, we expose a channel endpoint on the - // |broker_path|. Otherwise, only services in the same process network can - // make use of the broker. -#if BUILDFLAG(ENABLE_EXTERNAL_MOJO_SERVICES) -#if BUILDFLAG(IS_ANDROID) - // Monolithic MediaShell can just access the service broker directly in the - // same process, so there's no need to stand up a server. - if (!base::android::BundleUtils::IsBundle()) { - return; - } - // On Android, use the abstract namespace to avoid filesystem access. - bool use_abstract_namespace = true; -#else - bool use_abstract_namespace = false; -#endif // BUILDFLAG(IS_ANDROID) - - LOG(INFO) << "Initializing external mojo broker at: " << broker_path; - - mojo::NamedPlatformChannel::Options channel_options; - channel_options.server_name = broker_path; - channel_options.use_abstract_namespace = use_abstract_namespace; - mojo::NamedPlatformChannel named_channel(channel_options); - - mojo::PlatformChannelServerEndpoint server_endpoint = - named_channel.TakeServerEndpoint(); - DCHECK(server_endpoint.is_valid()); - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - chmod(broker_path.c_str(), 0770); -#endif - - read_watcher_ = std::make_unique( - connector_.get(), server_endpoint.TakePlatformHandle()); -#endif // BUILDFLAG(ENABLE_EXTERNAL_MOJO_SERVICES) -} - -void ExternalMojoBroker::InitializeChromium( - std::unique_ptr connector, - const std::vector& external_services_to_proxy) { - connector_->InitializeChromium(std::move(connector), - external_services_to_proxy); -} - -mojo::PendingRemote -ExternalMojoBroker::CreateConnector() { - mojo::PendingRemote remote; - connector_->AddReceiver(remote.InitWithNewPipeAndPassReceiver()); - return remote; -} - -void ExternalMojoBroker::BindConnector( - mojo::PendingReceiver receiver) { - connector_->AddReceiver(std::move(receiver)); -} - -ExternalMojoBroker::~ExternalMojoBroker() = default; - -} // namespace external_mojo -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/public/cpp/external_mojo_broker.h chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/external_mojo_broker.h --- chromium-132.0.6834.110/chromecast/external_mojo/public/cpp/external_mojo_broker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/public/cpp/external_mojo_broker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_EXTERNAL_MOJO_PUBLIC_CPP_EXTERNAL_MOJO_BROKER_H_ -#define CHROMECAST_EXTERNAL_MOJO_PUBLIC_CPP_EXTERNAL_MOJO_BROKER_H_ - -#include -#include -#include - -#include "chromecast/external_mojo/public/mojom/connector.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" - -namespace service_manager { -class Connector; -} // namespace service_manager - -namespace chromecast { -namespace external_mojo { - -// Manages connections from Mojo services in external processes. May be used -// either in a standalone broker process, or embedded into a Chromium process. -class ExternalMojoBroker { - public: - explicit ExternalMojoBroker(const std::string& broker_path); - - ExternalMojoBroker(const ExternalMojoBroker&) = delete; - ExternalMojoBroker& operator=(const ExternalMojoBroker&) = delete; - - ~ExternalMojoBroker(); - - // Initializes the embedded into a Chromium process (eg in cast_shell). - // |connector| is the ServiceManager connector within the Chromium process. - // |external_services_to_proxy| is a list of the names of external services - // that should be made accessible to Mojo services running within Chromium. - void InitializeChromium( - std::unique_ptr connector, - const std::vector& external_services_to_proxy); - - mojo::PendingRemote CreateConnector(); - - void BindConnector(mojo::PendingReceiver receiver); - - private: - class ConnectorImpl; - class ReadWatcher; - - std::unique_ptr connector_; - std::unique_ptr read_watcher_; -}; - -} // namespace external_mojo -} // namespace chromecast - -#endif // CHROMECAST_EXTERNAL_MOJO_PUBLIC_CPP_EXTERNAL_MOJO_BROKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/public/mojom/OWNERS chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/external_mojo/public/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/public/mojom/connector.mojom chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/connector.mojom --- chromium-132.0.6834.110/chromecast/external_mojo/public/mojom/connector.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/connector.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.external_mojo.mojom; - -import "mojo/public/mojom/base/time.mojom"; - -// Struct for information provided when calling QueryServiceList(). -struct ExternalServiceInfo { - // Service name provided to RegisterServiceInstance. - string name; - // TimeTicks value when the service was last registered. - mojo_base.mojom.TimeTicks connect_time; - // TimeTicks value when the service was disconnected. - // This value is set to TimeTicks() if the service is currently connected. - mojo_base.mojom.TimeTicks disconnect_time; -}; - -// Interface for external (non-Chromium process) Mojo services to receive Mojo -// binding requests from other processes/services. -interface ExternalService { - // Called when another service/process wants to bind to the interface with the - // given |interface_name| on this service. - OnBindInterface(string interface_name, - handle interface_pipe); -}; - -struct ServiceInstanceInfo { - string service_name; - pending_remote service_remote; -}; - -// Interface to register external Mojo services to the broker, and bind to -// registered Mojo services. This provides functionality similar to Chromium's -// service manager, but avoids any dependency on the service manager since this -// is intended for use by code outside of the Chrome repository. -interface ExternalConnector { - // Registers services with the broker. - RegisterServiceInstances(array instances_info); - - // Asks the broker to pass the |interface_pipe| to the registered service with - // the given |service_name| to be bound to the appropriate interface. If the - // |service_name| is not registered yet, the request will remain pending until - // the service is registered. - BindInterface(string service_name, - string interface_name, - handle interface_pipe); - - // Binds a new receiver to the Connector implementation, to allow clients to - // clone Connector pointers for use on other threads. - Clone(pending_receiver receiver); - - // Binds to a Chromium service_manager::Connector instance, if possible. - BindChromiumConnector(handle interface_pipe); - - // Query services that are available from this connector. - QueryServiceList() => (array services); -}; diff -Nru chromium-132.0.6834.110/chromecast/external_mojo/public/mojom/test_connector.mojom chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/test_connector.mojom --- chromium-132.0.6834.110/chromecast/external_mojo/public/mojom/test_connector.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/external_mojo/public/mojom/test_connector.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.external_mojo.mojom; - -// Helper interface to bind to registered Mojo services in unittests where -// clients clone the FakeExternalConnector instance before using it. -interface TestExternalConnector { - // Directs the call to FakeExternalConnector::BindInterface - BindInterfaceInternal(string service_name, string interface_name, - handle interface_pipe); -}; diff -Nru chromium-132.0.6834.110/chromecast/fuchsia/DEPS chromium-132.0.6834.159/chromecast/fuchsia/DEPS --- chromium-132.0.6834.110/chromecast/fuchsia/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/fuchsia/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+chromecast/activity", - "+chromecast/common", -] diff -Nru chromium-132.0.6834.110/chromecast/fuchsia/queryable_data_host_fuchsia.cc chromium-132.0.6834.159/chromecast/fuchsia/queryable_data_host_fuchsia.cc --- chromium-132.0.6834.110/chromecast/fuchsia/queryable_data_host_fuchsia.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/fuchsia/queryable_data_host_fuchsia.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/fuchsia/queryable_data_host_fuchsia.h" - -#include "base/values.h" -#include "chromecast/common/queryable_data.h" - -namespace chromecast { - -QueryableDataHostFuchsia::QueryableDataHostFuchsia() {} - -QueryableDataHostFuchsia::~QueryableDataHostFuchsia() {} - -void QueryableDataHostFuchsia::SendQueryableValue(const std::string& key, - const base::Value& value) { - // TODO(b/169167391): async call to update queryable values when runner fidl - // exists. - LOG(ERROR) << "Not Implemented: SendQueryableValue" << key << " " << value; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/fuchsia/queryable_data_host_fuchsia.h chromium-132.0.6834.159/chromecast/fuchsia/queryable_data_host_fuchsia.h --- chromium-132.0.6834.110/chromecast/fuchsia/queryable_data_host_fuchsia.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/fuchsia/queryable_data_host_fuchsia.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_FUCHSIA_QUERYABLE_DATA_HOST_FUCHSIA_H_ -#define CHROMECAST_FUCHSIA_QUERYABLE_DATA_HOST_FUCHSIA_H_ - -#include - -#include "base/values.h" -#include "chromecast/activity/queryable_data_host.h" - -namespace chromecast { - -// Sends queryable data through FIDL to the Cast Runner (Fuchsia). -class QueryableDataHostFuchsia : public QueryableDataHost { - public: - QueryableDataHostFuchsia(); - - QueryableDataHostFuchsia(const QueryableDataHostFuchsia&) = delete; - QueryableDataHostFuchsia& operator=(const QueryableDataHostFuchsia&) = delete; - - ~QueryableDataHostFuchsia() override; - - // chromecast::QueryableDataHost implementation: - void SendQueryableValue(const std::string& key, - const base::Value& value) override; -}; - -} // namespace chromecast - -#endif // CHROMECAST_FUCHSIA_QUERYABLE_DATA_HOST_FUCHSIA_H_ diff -Nru chromium-132.0.6834.110/chromecast/gpu/DEPS chromium-132.0.6834.159/chromecast/gpu/DEPS --- chromium-132.0.6834.110/chromecast/gpu/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/gpu/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -# Copyright 2019 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -include_rules = [ - "+chromecast/media/service/mojom", - "+components/viz/common", - "+components/viz/service", - "+content/public/child", - "+content/public/gpu", -] diff -Nru chromium-132.0.6834.110/chromecast/gpu/cast_content_gpu_client.cc chromium-132.0.6834.159/chromecast/gpu/cast_content_gpu_client.cc --- chromium-132.0.6834.110/chromecast/gpu/cast_content_gpu_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/gpu/cast_content_gpu_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/gpu/cast_content_gpu_client.h" - -#include "base/memory/ptr_util.h" -#include "base/task/single_thread_task_runner.h" -#include "components/viz/service/display/overlay_strategy_underlay_cast.h" -#include "content/public/child/child_thread.h" - -namespace chromecast { -namespace shell { - -CastContentGpuClient::CastContentGpuClient() = default; -CastContentGpuClient::~CastContentGpuClient() = default; - -// static -std::unique_ptr CastContentGpuClient::Create() { - return base::WrapUnique(new CastContentGpuClient()); -} - -void CastContentGpuClient::PostCompositorThreadCreated( - base::SingleThreadTaskRunner* task_runner) { - DCHECK(task_runner); - mojo::PendingRemote - video_geometry_setter; - content::ChildThread::Get()->BindHostReceiver( - video_geometry_setter.InitWithNewPipeAndPassReceiver()); - - task_runner->PostTask( - FROM_HERE, - base::BindOnce( - &viz::OverlayStrategyUnderlayCast::ConnectVideoGeometrySetter, - std::move(video_geometry_setter))); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/gpu/cast_content_gpu_client.h chromium-132.0.6834.159/chromecast/gpu/cast_content_gpu_client.h --- chromium-132.0.6834.110/chromecast/gpu/cast_content_gpu_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/gpu/cast_content_gpu_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GPU_CAST_CONTENT_GPU_CLIENT_H_ -#define CHROMECAST_GPU_CAST_CONTENT_GPU_CLIENT_H_ - -#include - -#include "base/task/single_thread_task_runner.h" -#include "content/public/gpu/content_gpu_client.h" - -namespace chromecast { -namespace shell { - -class CastContentGpuClient : public content::ContentGpuClient { - public: - static std::unique_ptr Create(); - - CastContentGpuClient(const CastContentGpuClient&) = delete; - CastContentGpuClient& operator=(const CastContentGpuClient&) = delete; - - ~CastContentGpuClient() override; - - // content::ContentGpuClient: - void PostCompositorThreadCreated( - base::SingleThreadTaskRunner* task_runner) override; - - protected: - CastContentGpuClient(); -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_GPU_CAST_CONTENT_GPU_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/DEPS chromium-132.0.6834.159/chromecast/graphics/DEPS --- chromium-132.0.6834.110/chromecast/graphics/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -include_rules = [ - "+chromecast/starboard/chromecast/events", - "+chromecast/ui", - "+components/viz/common/frame_sinks", - "+ui/accessibility/platform", - "+ui/aura", - "+ui/base", - "+ui/base/ime", - "+ui/compositor", - "+ui/display", - "+ui/events", - "+ui/events/test", - "+ui/gfx", - "+ui/gl/test", - "+ui/ozone/public", - "+ui/platform_window", - "+ui/touch_selection", - "+ui/views", - "+ui/wm/core", - "+ui/wm/public", - "+third_party/skia", -] - -specific_include_rules = { - "run_all_unittests\.cc": [ - "+mojo/core/embedder", - ] -} diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_display_util.cc chromium-132.0.6834.159/chromecast/graphics/cast_display_util.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_display_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_display_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_display_util.h" - -#include -#include - -namespace chromecast { - -float GetDeviceScaleFactor(const gfx::Size& display_resolution) { - int smaller_dimension = - std::min(display_resolution.width(), display_resolution.height()); - float ratio = smaller_dimension / 720.f; - if (ratio >= 2.f) - return floorf(ratio); - if (ratio >= 1.5f) - return 1.5f; - return 1.f; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_display_util.h chromium-132.0.6834.159/chromecast/graphics/cast_display_util.h --- chromium-132.0.6834.110/chromecast/graphics/cast_display_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_display_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_CAST_DISPLAY_UTIL_H_ -#define CHROMECAST_GRAPHICS_CAST_DISPLAY_UTIL_H_ - -#include "ui/gfx/geometry/size.h" - -namespace chromecast { - -// Computes the default scale factor for display with given resolution. -// -// Cast applications target 720p; larger resolutions will be scaled up so -// that content fills the screen. -float GetDeviceScaleFactor(const gfx::Size& display_resolution); - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_DISPLAY_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_display_util_unittest.cc chromium-132.0.6834.159/chromecast/graphics/cast_display_util_unittest.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_display_util_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_display_util_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_display_util.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -TEST(CastDisplayScaleTest, StandardResolutions_16x9) { - const gfx::Size kResolution720p(1280, 720); - const gfx::Size kResolution1080p(1920, 1080); - const gfx::Size kResolution1440p(2560, 1440); - const gfx::Size kResolution2160p(3840, 2160); - const gfx::Size kResolution4320p(7680, 4320); - - EXPECT_EQ(1.f, GetDeviceScaleFactor(kResolution720p)); - EXPECT_EQ(1.5f, GetDeviceScaleFactor(kResolution1080p)); - EXPECT_EQ(2.f, GetDeviceScaleFactor(kResolution1440p)); - EXPECT_EQ(3.f, GetDeviceScaleFactor(kResolution2160p)); - EXPECT_EQ(6.f, GetDeviceScaleFactor(kResolution4320p)); -} - -TEST(CastDisplayScaleTest, NonstandardResolutions) { - const gfx::Size kResolutionHomeHub(600, 1024); - EXPECT_EQ(1.f, GetDeviceScaleFactor(kResolutionHomeHub)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_egl_platform_default.cc chromium-132.0.6834.159/chromecast/graphics/cast_egl_platform_default.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_egl_platform_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_egl_platform_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#include "chromecast/public/cast_egl_platform.h" -#include "chromecast/public/cast_egl_platform_shlib.h" - -namespace chromecast { -namespace { - -// Default/stub CastEglPlatform implementation so that we can link -// successfully. -class EglPlatformDefault : public CastEglPlatform { - public: - ~EglPlatformDefault() override {} - const int* GetEGLSurfaceProperties(const int* desired) override { - return desired; - } - bool InitializeHardware() override { return true; } - void* GetEglLibrary() override { return nullptr; } - void* GetGles2Library() override { return nullptr; } - GLGetProcAddressProc GetGLProcAddressProc() override { return nullptr; } - NativeDisplayType CreateDisplayType(const Size& size) override { - return nullptr; - } - NativeWindowType CreateWindow(NativeDisplayType display_type, - const Size& size) override { - return nullptr; - } -}; - -} // namespace - -CastEglPlatform* CastEglPlatformShlib::Create( - const std::vector& argv) { - return new EglPlatformDefault(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_focus_client_aura.cc chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_focus_client_aura.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,254 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_focus_client_aura.h" - -#include "base/containers/contains.h" -#include "base/logging.h" -#include "base/ranges/algorithm.h" -#include "ui/aura/window.h" - -#define LOG_WINDOW_INFO(top_level, window) \ - "top-level: " << (top_level)->GetId() << ": '" << (top_level)->GetName() \ - << "', window: " << (window)->GetId() << ": '" \ - << (window)->GetName() << "'" - -namespace chromecast { - -CastFocusClientAura::CastFocusClientAura() : focused_window_(nullptr) {} - -CastFocusClientAura::~CastFocusClientAura() { - focused_window_ = nullptr; - for (aura::Window* window : focusable_windows_) { - window->RemoveObserver(this); - } - focusable_windows_.clear(); -} - -aura::Window* CastFocusClientAura::GetFocusedWindow() { - return focused_window_; -} - -void CastFocusClientAura::AddObserver( - aura::client::FocusChangeObserver* observer) { - focus_observers_.AddObserver(observer); -} - -void CastFocusClientAura::RemoveObserver( - aura::client::FocusChangeObserver* observer) { - focus_observers_.RemoveObserver(observer); -} - -void CastFocusClientAura::OnWindowVisibilityChanged(aura::Window* window, - bool visible) { - if (!visible && (window == focused_window_)) { - // The focused window just lost visibility, so de-focus it. - UpdateWindowFocus(); - } else if (visible) { - // The window that just became visible might be the most appropriate window - // to have focus. - UpdateWindowFocus(); - } -} - -// One of our observed windows is being destroyed. -// We observe each window that has the potential for being focused, -// so this window needs to be removed from the list of focusable windows. -void CastFocusClientAura::OnWindowDestroying(aura::Window* window) { - aura::Window* top_level = GetZOrderWindow(window); - DCHECK(top_level); - DLOG(INFO) << "Removing window, " << LOG_WINDOW_INFO(top_level, window); - - auto iter = base::ranges::find(focusable_windows_, window); - if (iter != focusable_windows_.end()) { - focusable_windows_.erase(iter); - window->RemoveObserver(this); - } - if (window == focused_window_) { - // De-focus the window that is being destroyed. - UpdateWindowFocus(); - } -} - -// Update focus if a window is entering or leaving our hierarchy. -void CastFocusClientAura::OnWindowHierarchyChanging( - const HierarchyChangeParams& params) { - if (params.new_parent && - (aura::client::GetFocusClient(params.new_parent) == this)) { - if (params.old_parent == params.new_parent) { - // A window is moving within our hierarchy. - return; - } else { - // A window is entering our hierarchy, so we need to consider - // focusing it. - FocusWindow(params.target); - return; - } - } - - // The window is leaving our hierarchy, so stop tracking it. - // It could contain multiple windows that were focused, so lets stop tracking - // them all. - auto iter = focusable_windows_.begin(); - bool was_focused = false; - while (iter != focusable_windows_.end()) { - aura::Window* window = *iter; - if (params.target == window || params.target->Contains(window)) { - window->RemoveObserver(this); - was_focused |= window == focused_window_; - iter = focusable_windows_.erase(iter); - - aura::Window* top_level = GetZOrderWindow(window); - DCHECK(top_level); - DLOG(INFO) << "Dropping window, " << LOG_WINDOW_INFO(top_level, window); - } else { - ++iter; - } - } - - if (was_focused) { - // The window that was removed from our hierarchy was the focused window, so - // de-focus it. - UpdateWindowFocus(); - } -} - -// An explicit request to focus a window. -// We lock focus to the top-most high-level window, and so will ignore this -// focus request if it isn't for the topmost window. If it is for a lower -// window, then we'll track it to focus it later when it rises to the top. -void CastFocusClientAura::FocusWindow(aura::Window* window) { - if (window) { - if (!window->CanFocus()) { - return; - } - aura::Window* top_level = GetZOrderWindow(window); - DCHECK(top_level); - DLOG(INFO) << "Requesting focus for " << LOG_WINDOW_INFO(top_level, window); - if (!base::Contains(focusable_windows_, window)) { - // We're not yet tracking this focusable window, so start tracking it as a - // potential focus target. - window->AddObserver(this); - focusable_windows_.push_back(window); - } - } - - // Check whether this new window is the most appropriate to focus. - UpdateWindowFocus(); -} - -// Finds the top-most window, and if it doesn't have focus, then gives it focus. -void CastFocusClientAura::UpdateWindowFocus() { - aura::Window* window = GetWindowToFocus(); - if (window == focused_window_) { - return; - } - - if (window) { - aura::Window* top_level = GetZOrderWindow(window); - DCHECK(top_level); - DLOG(INFO) << "Switching focus to " << LOG_WINDOW_INFO(top_level, window); - } - - aura::Window* unfocus_window = focused_window_; - focused_window_ = window; - - for (aura::client::FocusChangeObserver& observer : focus_observers_) { - observer.OnWindowFocused(focused_window_, unfocus_window); - if (focused_window_ != window) { - // The observer changed focused_window_. - return; - } - } - - if (unfocus_window) { - aura::client::FocusChangeObserver* focus_observer = - aura::client::GetFocusChangeObserver(unfocus_window); - if (focus_observer) { - focus_observer->OnWindowFocused(focused_window_, unfocus_window); - if (focused_window_ != window) { - // The observer changed focused_window_. - return; - } - } - } - if (focused_window_) { - aura::client::FocusChangeObserver* focus_observer = - aura::client::GetFocusChangeObserver(focused_window_); - if (focus_observer) { - focus_observer->OnWindowFocused(focused_window_, unfocus_window); - if (focused_window_ != window) { - // The observer changed focused_window_. - return; - } - } - } -} - -// Returns the most appropriate window to have focus. -// A focusable window could be anywhere within its window hierarchy, and we -// choose based on the z-order of the top-level window in its hierarchy. -aura::Window* CastFocusClientAura::GetWindowToFocus() { - aura::Window* next = nullptr; - aura::Window* next_top_level = nullptr; - for (aura::Window* window : focusable_windows_) { - if (!window->CanFocus() || !window->IsVisible()) { - continue; - } - - // Compare z-order of top-level windows using the window IDs. - aura::Window* top_level = GetZOrderWindow(window); - DCHECK(top_level); - if (!next || top_level->GetId() >= next_top_level->GetId()) { - next = window; - next_top_level = top_level; - } - } - return next; -} - -const aura::Window* CastFocusClientAura::GetZOrderWindow( - const aura::Window* window) const { - while (window->parent() && !window->parent()->IsRootWindow()) { - window = window->parent(); - } - return window; -} - -void CastFocusClientAura::ResetFocusWithinActiveWindow(aura::Window* window) { - // Sets focus to |window| if it's within the active window (a child of the - // focused window). - if (focused_window_ && focused_window_->Contains(window)) { - FocusWindow(window); - } -} - -void CastFocusClientAura::AddObserver(wm::ActivationChangeObserver* observer) {} - -void CastFocusClientAura::RemoveObserver( - wm::ActivationChangeObserver* observer) {} - -void CastFocusClientAura::ActivateWindow(aura::Window* window) {} - -void CastFocusClientAura::DeactivateWindow(aura::Window* window) {} - -const aura::Window* CastFocusClientAura::GetActiveWindow() const { - return nullptr; -} - -aura::Window* CastFocusClientAura::GetActivatableWindow( - aura::Window* window) const { - return window; -} - -const aura::Window* CastFocusClientAura::GetToplevelWindow( - const aura::Window* window) const { - return GetZOrderWindow(window); -} - -bool CastFocusClientAura::CanActivateWindow(const aura::Window* window) const { - return true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_focus_client_aura.h chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura.h --- chromium-132.0.6834.110/chromecast/graphics/cast_focus_client_aura.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_CAST_FOCUS_CLIENT_AURA_H_ -#define CHROMECAST_GRAPHICS_CAST_FOCUS_CLIENT_AURA_H_ - -#include - -#include "base/observer_list.h" -#include "ui/aura/client/focus_change_observer.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/window_observer.h" -#include "ui/wm/public/activation_client.h" - -namespace aura { -class Window; -} - -namespace chromecast { - -class CastFocusClientAura : public aura::WindowObserver, - public aura::client::FocusClient, - public wm::ActivationClient { - public: - CastFocusClientAura(); - - CastFocusClientAura(const CastFocusClientAura&) = delete; - CastFocusClientAura& operator=(const CastFocusClientAura&) = delete; - - ~CastFocusClientAura() override; - - // aura::client::FocusClient implementation: - void AddObserver(aura::client::FocusChangeObserver* observer) override; - void RemoveObserver(aura::client::FocusChangeObserver* observer) override; - void FocusWindow(aura::Window* window) override; - void ResetFocusWithinActiveWindow(aura::Window* window) override; - aura::Window* GetFocusedWindow() override; - - // Overridden from wm::ActivationClient: - void AddObserver(wm::ActivationChangeObserver* observer) override; - void RemoveObserver(wm::ActivationChangeObserver* observer) override; - void ActivateWindow(aura::Window* window) override; - void DeactivateWindow(aura::Window* window) override; - const aura::Window* GetActiveWindow() const override; - aura::Window* GetActivatableWindow(aura::Window* window) const override; - const aura::Window* GetToplevelWindow( - const aura::Window* window) const override; - bool CanActivateWindow(const aura::Window* window) const override; - - private: - // aura::WindowObserver implementation: - void OnWindowVisibilityChanged(aura::Window* window, bool visible) override; - void OnWindowDestroying(aura::Window* window) override; - void OnWindowHierarchyChanging(const HierarchyChangeParams& params) override; - - // Change the focused window and notify focus observers. - void UpdateWindowFocus(); - // Get the window that should be focused. - aura::Window* GetWindowToFocus(); - // Get the top-most window in a window's hierarchy to determine z order. - // This is the window directly under the root window (a child window of the - // root window). - aura::Window* GetZOrderWindow(aura::Window* window) const { - return const_cast( - GetZOrderWindow(const_cast(window))); - } - const aura::Window* GetZOrderWindow(const aura::Window* window) const; - - base::ObserverList focus_observers_; - - // Track the currently focused window, which isn't necessarily a top-level - // window. - aura::Window* focused_window_; - // Track the windows that we've focused in the past, so that we can restore - // focus to them. We assume that this is a small list so that we can perform - // linear ops on it. - std::vector focusable_windows_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_FOCUS_CLIENT_AURA_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_focus_client_aura_test.cc chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura_test.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_focus_client_aura_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_focus_client_aura_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,198 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_focus_client_aura.h" - -#include - -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/window.h" -#include "ui/platform_window/platform_window_init_properties.h" - -namespace chromecast { -namespace test { -namespace { - -class TestWindow { - public: - TestWindow() : window_(&delegate_) { - window_.Init(ui::LAYER_NOT_DRAWN); - window_.Show(); - } - - TestWindow(const TestWindow&) = delete; - TestWindow& operator=(const TestWindow&) = delete; - - aura::test::TestWindowDelegate* delegate() { return &delegate_; } - aura::Window* window() { return &window_; } - - private: - aura::test::TestWindowDelegate delegate_; - aura::Window window_; -}; - -} // namespace - -using CastFocusClientAuraTest = aura::test::AuraTestBase; - -TEST_F(CastFocusClientAuraTest, FocusableWindows) { - std::unique_ptr window_tree_host = - aura::WindowTreeHost::Create( - ui::PlatformWindowInitProperties{gfx::Rect(0, 0, 1280, 720)}); - window_tree_host->InitHost(); - window_tree_host->Show(); - - CastFocusClientAura focus_client; - - std::unique_ptr test_window(new TestWindow); - window_tree_host->window()->AddChild(test_window->window()); - - // Confirm that we can't add an un-focusable window. - test_window->delegate()->set_can_focus(false); - focus_client.FocusWindow(test_window->window()); - EXPECT_FALSE(focus_client.GetFocusedWindow()); - - // Confirm that we can add a focusable window. - test_window->delegate()->set_can_focus(true); - focus_client.FocusWindow(test_window->window()); - EXPECT_EQ(test_window->window(), focus_client.GetFocusedWindow()); - - // Confirm that the focused window loses focus when losing visibility. - test_window->window()->Hide(); - EXPECT_FALSE(focus_client.GetFocusedWindow()); - - // Confirm that we find a focusable window when it becomes visible. - test_window->window()->Show(); - EXPECT_EQ(test_window->window(), focus_client.GetFocusedWindow()); - - // Confirm that the focused window loses focus when it is destroyed. - test_window.reset(); - EXPECT_FALSE(focus_client.GetFocusedWindow()); -} - -TEST_F(CastFocusClientAuraTest, ChildFocus) { - std::unique_ptr window_tree_host = - aura::WindowTreeHost::Create( - ui::PlatformWindowInitProperties{gfx::Rect(0, 0, 1280, 720)}); - window_tree_host->InitHost(); - window_tree_host->Show(); - - CastFocusClientAura focus_client; - - std::unique_ptr parent(new TestWindow); - parent->delegate()->set_can_focus(true); - window_tree_host->window()->AddChild(parent->window()); - - std::unique_ptr child(new TestWindow); - child->delegate()->set_can_focus(true); - parent->window()->AddChild(child->window()); - - // Confirm that the child window has the focus, not its top-level parent - // window. - focus_client.FocusWindow(child->window()); - EXPECT_EQ(child->window(), focus_client.GetFocusedWindow()); - - // Confirm that removing the child window doesn't focus the parent window - // (since we've never requested focus for the parent window). - parent->window()->RemoveChild(child->window()); - EXPECT_FALSE(focus_client.GetFocusedWindow()); - - // Confirm that we still have no focused window after re-adding the child - // window, because we haven't requested focus. - parent->window()->AddChild(child->window()); - EXPECT_FALSE(focus_client.GetFocusedWindow()); - - // Request focus and confirm that the child is focused. - focus_client.FocusWindow(child->window()); - EXPECT_EQ(child->window(), focus_client.GetFocusedWindow()); -} - -TEST_F(CastFocusClientAuraTest, ZOrder) { - std::unique_ptr window_tree_host = - aura::WindowTreeHost::Create( - ui::PlatformWindowInitProperties{gfx::Rect(0, 0, 1280, 720)}); - window_tree_host->InitHost(); - window_tree_host->Show(); - - CastFocusClientAura focus_client; - - // Add the window with the lowest z-order. - std::unique_ptr low(new TestWindow); - low->delegate()->set_can_focus(true); - low->window()->SetId(1); - window_tree_host->window()->AddChild(low->window()); - focus_client.FocusWindow(low->window()); - EXPECT_EQ(low->window(), focus_client.GetFocusedWindow()); - - // Add the window with the highest z-order, and confirm that it gets focus. - std::unique_ptr high(new TestWindow); - high->delegate()->set_can_focus(true); - high->window()->SetId(3); - window_tree_host->window()->AddChild(high->window()); - focus_client.FocusWindow(high->window()); - EXPECT_EQ(high->window(), focus_client.GetFocusedWindow()); - - // Add the window with the middle z-order, and confirm that focus remains with - // the highest z-order window. - std::unique_ptr middle(new TestWindow); - middle->delegate()->set_can_focus(true); - middle->window()->SetId(2); - window_tree_host->window()->AddChild(middle->window()); - focus_client.FocusWindow(middle->window()); - EXPECT_EQ(high->window(), focus_client.GetFocusedWindow()); - - // Confirm that requesting focus on the lower z-order windows leaves focus on - // the highest z-order window. - focus_client.FocusWindow(low->window()); - EXPECT_EQ(high->window(), focus_client.GetFocusedWindow()); - focus_client.FocusWindow(middle->window()); - EXPECT_EQ(high->window(), focus_client.GetFocusedWindow()); - - // Confirm that focus moves to next highest window. - high.reset(); - EXPECT_EQ(middle->window(), focus_client.GetFocusedWindow()); - - // Confirm that focus moves to next highest window. - middle.reset(); - EXPECT_EQ(low->window(), focus_client.GetFocusedWindow()); - - // Confirm that there is no focused window. - low.reset(); - EXPECT_FALSE(focus_client.GetFocusedWindow()); -} - -TEST_F(CastFocusClientAuraTest, ZOrderWithChildWindows) { - std::unique_ptr window_tree_host = - aura::WindowTreeHost::Create( - ui::PlatformWindowInitProperties{gfx::Rect(0, 0, 1280, 720)}); - window_tree_host->InitHost(); - window_tree_host->Show(); - - CastFocusClientAura focus_client; - - // Add the window with the highest z-order. - std::unique_ptr high_parent(new TestWindow); - high_parent->window()->SetId(3); - std::unique_ptr high_child(new TestWindow); - high_child->delegate()->set_can_focus(true); - high_parent->window()->AddChild(high_child->window()); - window_tree_host->window()->AddChild(high_parent->window()); - focus_client.FocusWindow(high_child->window()); - EXPECT_EQ(high_child->window(), focus_client.GetFocusedWindow()); - - // Add the window with the lowest z-order. - std::unique_ptr low_parent(new TestWindow); - low_parent->window()->SetId(1); - std::unique_ptr low_child(new TestWindow); - low_child->delegate()->set_can_focus(true); - low_parent->window()->AddChild(low_child->window()); - window_tree_host->window()->AddChild(low_parent->window()); - focus_client.FocusWindow(low_child->window()); - // Focus should remain with the child of the highest window. - EXPECT_EQ(high_child->window(), focus_client.GetFocusedWindow()); -} - -} // namespace test -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_screen.cc chromium-132.0.6834.159/chromecast/graphics/cast_screen.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_screen.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_screen.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -// 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 "chromecast/graphics/cast_screen.h" - -#include - -#include "base/logging.h" -#include "ui/aura/env.h" -#include "ui/display/display.h" - -namespace chromecast { - -CastScreen::~CastScreen() { -} - -gfx::Point CastScreen::GetCursorScreenPoint() { - return aura::Env::GetInstance()->last_mouse_location(); -} - -bool CastScreen::IsWindowUnderCursor(gfx::NativeWindow window) { - NOTIMPLEMENTED(); - return false; -} - -gfx::NativeWindow CastScreen::GetWindowAtScreenPoint(const gfx::Point& point) { - return gfx::NativeWindow(); -} - -display::Display CastScreen::GetDisplayNearestWindow( - gfx::NativeWindow window) const { - return GetPrimaryDisplay(); -} - -CastScreen::CastScreen() { -} - -void CastScreen::OnDisplayChanged(int64_t display_id, - float device_scale_factor, - display::Display::Rotation rotation, - const gfx::Rect& bounds) { - display::Display display(display_id); - display.SetScaleAndBounds(device_scale_factor, bounds); - display.set_rotation(rotation); - DVLOG(1) << __func__ << " " << display.ToString(); - ProcessDisplayChanged(display, true /* is_primary */); -} - -void CastScreen::OverridePrimaryDisplaySettings( - const gfx::Rect& bounds, - float scale_factor, - display::Display::Rotation rotation) { - const auto primary_display = GetPrimaryDisplay(); - - stashed_display_settings_ = primary_display; - - LOG(INFO) << "Stashing primary display (" << primary_display.id() - << ") settings; device_scale_factor: " - << stashed_display_settings_->device_scale_factor() - << " rotation: " << stashed_display_settings_->RotationAsDegree() - << " size (pixels): " - << stashed_display_settings_->GetSizeInPixel().ToString(); - - OnDisplayChanged(primary_display.id(), scale_factor, rotation, bounds); -} - -bool CastScreen::RestorePrimaryDisplaySettings() { - if (!stashed_display_settings_) { - return false; - } - - LOG(INFO) - << "Restoring original primary display settings; device_scale_factor: " - << stashed_display_settings_->device_scale_factor() - << " rotation: " << stashed_display_settings_->RotationAsDegree() - << " size (pixels): " - << stashed_display_settings_->GetSizeInPixel().ToString(); - OnDisplayChanged(stashed_display_settings_->id(), - stashed_display_settings_->device_scale_factor(), - stashed_display_settings_->rotation(), - gfx::Rect(stashed_display_settings_->GetSizeInPixel())); - stashed_display_settings_.reset(); - - return true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_screen.h chromium-132.0.6834.159/chromecast/graphics/cast_screen.h --- chromium-132.0.6834.110/chromecast/graphics/cast_screen.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_screen.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// 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. - -#ifndef CHROMECAST_GRAPHICS_CAST_SCREEN_H_ -#define CHROMECAST_GRAPHICS_CAST_SCREEN_H_ - -#include - -#include "chromecast/public/graphics_types.h" -#include "ui/display/display.h" -#include "ui/display/screen_base.h" - -namespace chromecast { -namespace shell { -class CastBrowserMainParts; -} // namespace shell - -// CastScreen is Chromecast's own minimal implementation of display::Screen. -// Right now, it almost exactly duplicates the behavior of aura's TestScreen -// class for necessary methods. The instantiation of CastScreen occurs in -// CastBrowserMainParts, where its ownership is assigned to CastBrowserProcess. -// To then subsequently access CastScreen, see CastBrowerProcess. -class CastScreen : public display::ScreenBase { - public: - CastScreen(); - - CastScreen(const CastScreen&) = delete; - CastScreen& operator=(const CastScreen&) = delete; - - ~CastScreen() override; - - // display::Screen overrides: - gfx::Point GetCursorScreenPoint() override; - bool IsWindowUnderCursor(gfx::NativeWindow window) override; - gfx::NativeWindow GetWindowAtScreenPoint(const gfx::Point& point) override; - display::Display GetDisplayNearestWindow( - gfx::NativeWindow window) const override; - - void OnDisplayChanged(int64_t display_id, - float scale_factor, - display::Display::Rotation rotation, - const gfx::Rect& bounds); - - // Temporarily override the primary display settings with new bounds, scale - // factor, and rotation. - // The original display settings are stashed for later retrieval. - void OverridePrimaryDisplaySettings(const gfx::Rect& bounds, - float scale_factor, - display::Display::Rotation rotation); - - // Restore stashed display settings stored by OverridePrimaryDisplaySettings. - // Returns true if stashed settings were applied. False if none were - // available. - bool RestorePrimaryDisplaySettings(); - - private: - std::optional stashed_display_settings_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_SCREEN_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_screen_unittest.cc chromium-132.0.6834.159/chromecast/graphics/cast_screen_unittest.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_screen_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_screen_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_screen.h" - -#include "testing/gmock/include/gmock/gmock.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/display/display_observer.h" - -using testing::_; -using testing::AllOf; -using testing::Property; - -namespace chromecast { -namespace test { - -namespace { -constexpr int64_t kMockDisplayId = 0xcafebabe; -} - -using CastScreenTest = aura::test::AuraTestBase; - -class MockDisplayObserver : public display::DisplayObserver { - public: - MOCK_METHOD2(OnDisplayMetricsChanged, - void(const display::Display& display, uint32_t changed_metrics)); -}; - -TEST_F(CastScreenTest, OverrideAndRestore) { - MockDisplayObserver mock_display_observer; - CastScreen screen; - // Set up initial screen. - screen.OnDisplayChanged(kMockDisplayId, 1.0, - display::Display::Rotation::ROTATE_0, - gfx::Rect(0, 0, 1920, 1080)); - - EXPECT_CALL(mock_display_observer, - OnDisplayMetricsChanged( - AllOf(Property(&display::Display::id, kMockDisplayId), - Property(&display::Display::device_scale_factor, 2.2), - Property(&display::Display::rotation, - display::Display::Rotation::ROTATE_270)), - _)); - EXPECT_CALL(mock_display_observer, - OnDisplayMetricsChanged( - AllOf(Property(&display::Display::id, kMockDisplayId), - Property(&display::Display::device_scale_factor, 1.0), - Property(&display::Display::rotation, - display::Display::Rotation::ROTATE_0)), - _)); - screen.AddObserver(&mock_display_observer); - screen.OverridePrimaryDisplaySettings(gfx::Rect(0, 0, 1000, 1000), 2.2, - display::Display::Rotation::ROTATE_270); - screen.RestorePrimaryDisplaySettings(); -} - -} // namespace test -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_touch_activity_observer.h chromium-132.0.6834.159/chromecast/graphics/cast_touch_activity_observer.h --- chromium-132.0.6834.110/chromecast/graphics/cast_touch_activity_observer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_touch_activity_observer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_CAST_TOUCH_ACTIVITY_OBSERVER_H_ -#define CHROMECAST_GRAPHICS_CAST_TOUCH_ACTIVITY_OBSERVER_H_ - -namespace chromecast { - -class CastTouchActivityObserver { - public: - virtual ~CastTouchActivityObserver() = default; - - // Invoked when the window manager has touch input disabled. - virtual void OnTouchEventsDisabled(bool disabled) = 0; - - // Invoked when input is disabled and an input event is received. - // Can be used by the observer to turn touch input back on. - virtual void OnTouchActivity() = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_TOUCH_ACTIVITY_OBSERVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_touch_event_gate.cc chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_touch_event_gate.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_touch_event_gate.h" - -#include "chromecast/graphics/cast_touch_activity_observer.h" -#include "chromecast/graphics/cast_window_manager.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" - -namespace chromecast { - -CastTouchEventGate::CastTouchEventGate(aura::Window* root_window) - : root_window_(root_window) { - DCHECK(root_window); - root_window_->GetHost()->GetEventSource()->AddEventRewriter(this); -} - -CastTouchEventGate::~CastTouchEventGate() { - root_window_->GetHost()->GetEventSource()->RemoveEventRewriter(this); - if (enabled_) { - for (auto* observer : observers_) { - observer->OnTouchEventsDisabled(false); - } - } -} - -void CastTouchEventGate::AddObserver(CastTouchActivityObserver* observer) { - observers_.insert(observer); -} - -void CastTouchEventGate::RemoveObserver(CastTouchActivityObserver* observer) { - observers_.erase(observer); -} - -void CastTouchEventGate::SetEnabled(bool enabled) { - enabled_ = enabled; - for (auto* observer : observers_) { - observer->OnTouchEventsDisabled(enabled_); - } -} - -ui::EventDispatchDetails CastTouchEventGate::RewriteEvent( - const ui::Event& event, - const Continuation continuation) { - if (!enabled_ || !event.IsTouchEvent()) - return SendEvent(continuation, &event); - - for (auto* observer : observers_) { - observer->OnTouchActivity(); - } - return DiscardEvent(continuation); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_touch_event_gate.h chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate.h --- chromium-132.0.6834.110/chromecast/graphics/cast_touch_event_gate.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_CAST_TOUCH_EVENT_GATE_H_ -#define CHROMECAST_GRAPHICS_CAST_TOUCH_EVENT_GATE_H_ - -#include "base/containers/flat_set.h" -#include "ui/events/event_rewriter.h" - -namespace aura { -class Window; -} // namespace aura - -namespace chromecast { - -class CastTouchActivityObserver; - -// An event rewriter whose purpose is to discard events (when enabled). This -// class is meant to be installed as the first rewriter in the chain, to handle -// scenarios where all input needs to be disabled, such as when the device -// screen is turned off. Instances of CastTouchActivityObserver can be -// registered to receive notifications of gated events. -class CastTouchEventGate : public ui::EventRewriter { - public: - explicit CastTouchEventGate(aura::Window* root_window); - ~CastTouchEventGate() override; - - void SetEnabled(bool enabled); - - void AddObserver(CastTouchActivityObserver* observer); - void RemoveObserver(CastTouchActivityObserver* observer); - - // ui::EventRewriter implementation. - ui::EventDispatchDetails RewriteEvent( - const ui::Event& event, - const Continuation continuation) override; - - private: - bool enabled_ = false; - aura::Window* root_window_; - base::flat_set observers_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_TOUCH_EVENT_GATE_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_touch_event_gate_test.cc chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate_test.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_touch_event_gate_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_touch_event_gate_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_touch_event_gate.h" - -#include - -#include "base/run_loop.h" -#include "chromecast/graphics/cast_touch_activity_observer.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/window.h" -#include "ui/events/event_utils.h" -#include "ui/events/test/event_generator.h" -#include "ui/events/test/events_test_utils.h" - -using testing::_; -using testing::AtLeast; -using testing::Eq; - -namespace chromecast { - -class MockEventHandler : public ui::EventHandler { - public: - ~MockEventHandler() override = default; - MOCK_METHOD1(OnTouchEvent, void(ui::TouchEvent* event)); -}; - -class MockEventGateObserver : public CastTouchActivityObserver { - public: - ~MockEventGateObserver() override = default; - - MOCK_METHOD1(OnTouchEventsDisabled, void(bool disabled)); - MOCK_METHOD0(OnTouchActivity, void()); -}; - -class CastTouchEventGateTest : public aura::test::AuraTestBase { - public: - ~CastTouchEventGateTest() override = default; - - void SetUp() override { - aura::test::AuraTestBase::SetUp(); - - event_gate_ = std::make_unique(root_window()); - event_handler_ = std::make_unique(); - root_window()->AddPreTargetHandler(event_handler_.get()); - generator_ = std::make_unique(root_window()); - gate_observer_ = std::make_unique(); - event_gate_->AddObserver(gate_observer_.get()); - } - - void TearDown() override { - root_window()->RemovePreTargetHandler(event_handler_.get()); - event_gate_.reset(); - aura::test::AuraTestBase::TearDown(); - } - - CastTouchEventGate& event_gate() { return *event_gate_; } - MockEventGateObserver& gate_observer() { return *gate_observer_; } - MockEventHandler& mock_event_handler() { return *event_handler_; } - ui::test::EventGenerator& event_generator() { return *generator_; } - - private: - std::unique_ptr event_gate_; - std::unique_ptr gate_observer_; - std::unique_ptr event_handler_; - std::unique_ptr generator_; -}; - -TEST_F(CastTouchEventGateTest, DisabledByDefaultTest) { - // Tap leads to 2 touch events. - EXPECT_CALL(mock_event_handler(), OnTouchEvent(_)).Times(2); - - // Expect no notifications to the observer. - EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(_)).Times(0); - EXPECT_CALL(gate_observer(), OnTouchActivity()).Times(0); - event_generator().GestureTapAt(gfx::Point(50, 50)); - - base::RunLoop().RunUntilIdle(); -} - -TEST_F(CastTouchEventGateTest, EnabledBlocksEvent) { - // No event should get through. - EXPECT_CALL(mock_event_handler(), OnTouchEvent(_)).Times(0); - - // We should receive a notification at the observer that the gate was enabled. - EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(Eq(true))).Times(1); - - // Also that it was disabled at destruction. - EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(Eq(false))).Times(1); - - // And that the tap event was observed (multiple events) - EXPECT_CALL(gate_observer(), OnTouchActivity()).Times(AtLeast(2)); - - event_gate().SetEnabled(true); - event_generator().GestureTapAt(gfx::Point(50, 50)); - - base::RunLoop().RunUntilIdle(); -} - -TEST_F(CastTouchEventGateTest, EnableThenDisable) { - EXPECT_CALL(mock_event_handler(), OnTouchEvent(_)).Times(2); - EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(Eq(true))).Times(1); - EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(Eq(false))).Times(1); - EXPECT_CALL(gate_observer(), OnTouchActivity()).Times(AtLeast(2)); - - event_gate().SetEnabled(true); - event_generator().GestureTapAt(gfx::Point(50, 50)); - event_gate().SetEnabled(false); - event_generator().GestureTapAt(gfx::Point(50, 50)); - - base::RunLoop().RunUntilIdle(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_views_test.cc chromium-132.0.6834.159/chromecast/graphics/cast_views_test.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_views_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_views_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_window_manager_aura.h" -#include "ui/aura/window.h" -#include "ui/views/controls/progress_bar.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -namespace chromecast { -namespace test { - -using CastViewsTest = views::ViewsTestBase; - -TEST_F(CastViewsTest, ProgressBar) { - std::unique_ptr window_manager = - std::make_unique(true /* enable input */); - gfx::Rect bounds = window_manager->GetRootWindow()->bounds(); - - views::ProgressBar* progress_bar = new views::ProgressBar(); - progress_bar->SetPreferredHeight(bounds.height()); - progress_bar->SetValue(0.5); - - // Create the window. We close the window by deleting it, so we take - // ownership of the widget + native widget. - views::Widget::InitParams params( - views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET); - params.context = window_manager->GetRootWindow(); - params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; - params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; - params.shadow_type = views::Widget::InitParams::ShadowType::kNone; - params.bounds = bounds; - std::unique_ptr widget(new views::Widget); - widget->Init(std::move(params)); - widget->SetOpacity(0.6); - widget->SetContentsView(progress_bar); - window_manager->SetZOrder(widget->GetNativeView(), mojom::ZOrder::VOLUME); - widget->Show(); - - EXPECT_TRUE(progress_bar->GetWidget()); - EXPECT_TRUE(progress_bar->GetWidget()->IsVisible()); - EXPECT_TRUE(progress_bar->GetVisible()); - EXPECT_TRUE(progress_bar->GetEnabled()); - - widget.reset(); - window_manager.reset(); -} - -} // namespace test -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_window_manager.h chromium-132.0.6834.159/chromecast/graphics/cast_window_manager.h --- chromium-132.0.6834.110/chromecast/graphics/cast_window_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_window_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_H_ -#define CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_H_ - -#include -#include - -#include "chromecast/ui/mojom/ui_service.mojom.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { -class Event; -} // namespace ui - -namespace chromecast { - -class CastTouchActivityObserver; -class CastGestureHandler; - -// Chromecast's window-manager interface. -// This declares the interface to add top-level windows to the Chromecast -// platform window. It is owned by the UI thread, and generally one instance -// should exist per platform root window (e.g., in Ozone, one per Ozone window). -class CastWindowManager { - public: - // Note: these window IDs are ordered by z-order. - enum WindowId { - BOTTOM = -1, - // Base layer for WebUiManager and apps and activities managed by it. - APP = BOTTOM, - // Apps running in this layer won't be managed by WebUiManager. - UNMANAGED_APP = 0, - DEBUG_OVERLAY = 1, - INFO_OVERLAY = 2, - SOFT_KEYBOARD = 3, - VOLUME = 4, - MEDIA_INFO = 5, - SETTINGS = 6, - BOOT_ANIMATION_OVERLAY = 7, - TOP = BOOT_ANIMATION_OVERLAY, - }; - - class Observer { - public: - // Advertises a change in the current window ordering. Use - // CastWindowManager::GetWindowOrder() to retrieve the window ordering. - virtual void WindowOrderChanged() = 0; - - protected: - virtual ~Observer() = default; - }; - - virtual ~CastWindowManager() {} - - // Remove all windows and release all graphics resources. - // Can be called multiple times. - virtual void TearDown() = 0; - - // Adds a window to the window manager. - // This doesn't necessarily make the window visible. - // If the window manager hasn't been initialized, this has the side effect of - // causing it to initialize. - virtual void AddWindow(gfx::NativeView window) = 0; - - // Sets the Z order for the window. This allows windows with the same parent - // to stack in a well-defined order. - virtual void SetZOrder(gfx::NativeView window, mojom::ZOrder z_order) = 0; - - // Return the root window that holds all top-level windows. - virtual gfx::NativeView GetRootWindow() = 0; - - // Returns the current window ordering. The IDs are ordered by z-order, from - // lowest (bottom) to highest (top). Only visible windows are included in the - // list. - virtual std::vector GetWindowOrder() = 0; - - // Inject a UI event into the Cast window. - virtual void InjectEvent(ui::Event* event) = 0; - - // Observer methods: - virtual void AddObserver(Observer* observer) = 0; - virtual void RemoveObserver(Observer* observer) = 0; - - // Register a new handler for system gesture events. - virtual void AddGestureHandler(CastGestureHandler* handler) = 0; - - // Remove the registration of a system gesture events handler. - virtual void RemoveGestureHandler(CastGestureHandler* handler) = 0; - - // Enable/disable the handling of all touch events. - virtual void SetTouchInputDisabled(bool disabled) = 0; - - // Add an observer for when input events occur while touch input is disabled. - virtual void AddTouchActivityObserver( - CastTouchActivityObserver* observer) = 0; - - // Remove an observer for when input events occur while touch input is - // disabled. - virtual void RemoveTouchActivityObserver( - CastTouchActivityObserver* observer) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_aura.cc chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_aura.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,346 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_window_manager_aura.h" - -#include "base/memory/ptr_util.h" -#include "build/build_config.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/graphics/cast_focus_client_aura.h" -#include "chromecast/graphics/cast_touch_activity_observer.h" -#include "chromecast/graphics/cast_touch_event_gate.h" -#include "chromecast/graphics/cast_window_manager.h" -#include "chromecast/graphics/cast_window_tree_host_aura.h" -#include "chromecast/graphics/gestures/cast_system_gesture_event_handler.h" -#include "chromecast/graphics/gestures/side_swipe_detector.h" -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/client/focus_change_observer.h" -#include "ui/aura/env.h" -#include "ui/aura/layout_manager.h" -#include "ui/aura/window.h" -#include "ui/base/ime/init/input_method_factory.h" -#include "ui/base/ime/input_method.h" -#include "ui/compositor/compositor.h" -#include "ui/display/display.h" -#include "ui/display/display_transform.h" -#include "ui/display/screen.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/platform_window/platform_window_init_properties.h" -#include "ui/touch_selection/touch_selection_menu_runner.h" -#include "ui/wm/core/default_screen_position_client.h" - -#if BUILDFLAG(IS_FUCHSIA) -#include "ui/platform_window/fuchsia/initialize_presenter_api_view.h" -#endif - -namespace chromecast { -namespace { - -gfx::Transform GetPrimaryDisplayRotationTransform() { - display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); - return display::CreateRotationTransform(display.rotation(), - gfx::SizeF(display.size())); -} - -gfx::Rect GetPrimaryDisplayHostBounds() { - display::Display display(display::Screen::GetScreen()->GetPrimaryDisplay()); - gfx::Point display_origin_in_pixel = display.bounds().origin(); - gfx::Size display_size_in_pixel = display.GetSizeInPixel(); - switch (display.rotation()) { - case display::Display::ROTATE_90: - case display::Display::ROTATE_270: - return gfx::Rect(display_origin_in_pixel, - gfx::Size(display_size_in_pixel.height(), - display_size_in_pixel.width())); - case display::Display::ROTATE_0: - case display::Display::ROTATE_180: - // default: - return gfx::Rect(display_origin_in_pixel, display_size_in_pixel); - } -} - -// A layout manager owned by the root window. -class CastLayoutManager : public aura::LayoutManager { - public: - CastLayoutManager(CastWindowManagerAura* window_manager, - aura::Window* parent); - - CastLayoutManager(const CastLayoutManager&) = delete; - CastLayoutManager& operator=(const CastLayoutManager&) = delete; - - ~CastLayoutManager() override; - - private: - // aura::LayoutManager implementation: - void OnWindowResized() override; - void OnWindowAddedToLayout(aura::Window* child) override; - void OnWillRemoveWindowFromLayout(aura::Window* child) override; - void OnWindowRemovedFromLayout(aura::Window* child) override; - void OnChildWindowVisibilityChanged(aura::Window* child, - bool visible) override; - void SetChildBounds(aura::Window* child, - const gfx::Rect& requested_bounds) override; - - // Reorder child windows of the root window tree to reflect changes in layout. - void ReorderChildWindows(aura::Window* changed_window); - - CastWindowManagerAura* const window_manager_; - aura::Window* const parent_; -}; - -CastLayoutManager::CastLayoutManager(CastWindowManagerAura* window_manager, - aura::Window* parent) - : window_manager_(window_manager), parent_(parent) { - DCHECK(window_manager_); - DCHECK(parent_); -} - -CastLayoutManager::~CastLayoutManager() {} - -void CastLayoutManager::OnWindowResized() { - // Invoked when the root window of the window tree host has been resized. -} - -void CastLayoutManager::OnWindowAddedToLayout(aura::Window* child) { - ReorderChildWindows(child); -} - -void CastLayoutManager::OnWillRemoveWindowFromLayout(aura::Window* child) {} - -void CastLayoutManager::OnWindowRemovedFromLayout(aura::Window* child) { - ReorderChildWindows(child); -} - -void CastLayoutManager::OnChildWindowVisibilityChanged(aura::Window* child, - bool visible) { - ReorderChildWindows(child); -} - -void CastLayoutManager::ReorderChildWindows(aura::Window* changed_window) { - // Only update the window order if the child's parent matches the parent - // window for this layout. If the child has no parent, then that means it - // was removed from the layout and we should update the window ordering. - if (changed_window->parent() && changed_window->parent() != parent_) { - return; - } - - // We set z-order here, because the window's ID could be set after the window - // is added to the layout, particularly when using views::Widget to create the - // window. The window ID must be set prior to showing the window. Since we - // only process z-order on visibility changes for top-level windows, this - // logic will execute infrequently. - - // Determine z-order relative to existing windows. - aura::Window::Windows windows = parent_->children(); - std::stable_sort(windows.begin(), windows.end(), - [changed_window](aura::Window* lhs, aura::Window* rhs) { - // Promote |changed_window| to the top of the stack of - // windows with the same ID. - if (lhs->GetId() == rhs->GetId() && rhs == changed_window) - return true; - - return lhs->GetId() < rhs->GetId(); - }); - - std::vector visible_window_order; - for (size_t i = 0; i < windows.size(); ++i) { - if (windows[i]->IsVisible()) { - // static_cast is safe since the window ID value is originally derived - // from CastWindowManager::WindowId. - visible_window_order.push_back( - static_cast(windows[i]->GetId())); - } - if (i == 0) { - parent_->StackChildAtBottom(windows[i]); - } else { - parent_->StackChildAbove(windows[i], windows[i - 1]); - } - } - - window_manager_->OnWindowOrderChanged(visible_window_order); -} - -void CastLayoutManager::SetChildBounds(aura::Window* child, - const gfx::Rect& requested_bounds) { - SetChildBoundsDirect(child, requested_bounds); -} - -} // namespace - -CastWindowManagerAura::CastWindowManagerAura(bool enable_input) - : enable_input_(enable_input) {} - -CastWindowManagerAura::~CastWindowManagerAura() { - TearDown(); -} - -void CastWindowManagerAura::Setup() { - if (window_tree_host_) { - return; - } - DCHECK(display::Screen::GetScreen()); - - ui::InitializeInputMethodForTesting(); - - gfx::Rect host_bounds = GetPrimaryDisplayHostBounds(); - ui::PlatformWindowInitProperties properties(host_bounds); - - LOG(INFO) << "Starting window manager, bounds: " << host_bounds.ToString(); - CHECK(aura::Env::GetInstance()); - window_tree_host_ = std::make_unique( - enable_input_, std::move(properties)); - window_tree_host_->InitHost(); - aura::Window* root_window = window_tree_host_->window(); - root_window->SetLayoutManager( - std::make_unique(this, root_window)); - window_tree_host_->SetRootTransform(GetPrimaryDisplayRotationTransform()); - - // Allow seeing through to the hardware video plane: - window_tree_host_->compositor()->SetBackgroundColor(SK_ColorTRANSPARENT); - - focus_client_ = std::make_unique(); - aura::client::SetFocusClient(root_window, focus_client_.get()); - wm::SetActivationClient(root_window, focus_client_.get()); - aura::client::SetWindowParentingClient(root_window, this); - capture_client_.reset(new aura::client::DefaultCaptureClient(root_window)); - - screen_position_client_ = - std::make_unique(root_window); - - window_tree_host_->Show(); - - // Install the CastTouchEventGate before other event rewriters. It has to be - // the first in the chain. - event_gate_ = std::make_unique(root_window); - - system_gesture_dispatcher_ = std::make_unique(); - system_gesture_event_handler_ = - std::make_unique( - system_gesture_dispatcher_.get(), root_window); - // TODO(rdaum): Remove side swipe detection when all services requiring it - // have been rewritten. - side_swipe_detector_ = std::make_unique( - system_gesture_dispatcher_.get(), root_window); - -#if BUILDFLAG(IS_CAST_AUDIO_ONLY) - window_tree_host_->compositor()->SetDisplayVSyncParameters( - base::TimeTicks(), base::Milliseconds(250)); -#endif - - // Chromecast devices do not support cut/copy/paste. - DCHECK(!ui::TouchSelectionMenuRunner::GetInstance()); -} - -void CastWindowManagerAura::OnWindowOrderChanged( - std::vector window_order) { - window_order_.swap(window_order); - for (auto& observer : observer_list_) { - observer.WindowOrderChanged(); - } -} - -CastWindowTreeHostAura* CastWindowManagerAura::window_tree_host() const { - DCHECK(window_tree_host_); - return window_tree_host_.get(); -} - -void CastWindowManagerAura::TearDown() { - if (!window_tree_host_) { - return; - } - event_gate_.reset(); - side_swipe_detector_.reset(); - capture_client_.reset(); - aura::client::SetWindowParentingClient(window_tree_host_->window(), nullptr); - wm::SetActivationClient(window_tree_host_->window(), nullptr); - screen_position_client_.reset(); - aura::client::SetFocusClient(window_tree_host_->window(), nullptr); - focus_client_.reset(); - system_gesture_event_handler_.reset(); - window_tree_host_.reset(); -} - -void CastWindowManagerAura::SetZOrder(gfx::NativeView window, - mojom::ZOrder z_order) { - // Use aura::Window ID to maintain z-order. When the window's visibility - // changes, we stack sibling windows based on this ID. Windows with higher - // IDs are stacked on top. - window->SetId(static_cast(z_order)); -} - -void CastWindowManagerAura::InjectEvent(ui::Event* event) { - if (!window_tree_host_) { - return; - } - window_tree_host_->DispatchEvent(event); -} - -void CastWindowManagerAura::AddObserver(Observer* observer) { - observer_list_.AddObserver(observer); -} - -void CastWindowManagerAura::RemoveObserver(Observer* observer) { - observer_list_.RemoveObserver(observer); -} - -gfx::NativeView CastWindowManagerAura::GetRootWindow() { - Setup(); - return window_tree_host_->window(); -} - -std::vector -CastWindowManagerAura::GetWindowOrder() { - return window_order_; -} - -aura::Window* CastWindowManagerAura::GetDefaultParent( - aura::Window* window, - const gfx::Rect& bounds, - const int64_t display_id) { - DCHECK(window_tree_host_); - return window_tree_host_->window(); -} - -void CastWindowManagerAura::AddWindow(gfx::NativeView child) { - LOG(INFO) << "Adding window: " << child->GetId() << ": " << child->GetName(); - Setup(); - - DCHECK(child); - aura::Window* parent = window_tree_host_->window(); - if (!parent->Contains(child)) { - parent->AddChild(child); - } -} - -void CastWindowManagerAura::AddGestureHandler(CastGestureHandler* handler) { - DCHECK(system_gesture_event_handler_); - system_gesture_dispatcher_->AddGestureHandler(handler); -} - -void CastWindowManagerAura::CastWindowManagerAura::RemoveGestureHandler( - CastGestureHandler* handler) { - DCHECK(system_gesture_event_handler_); - system_gesture_dispatcher_->RemoveGestureHandler(handler); -} - -CastGestureHandler* CastWindowManagerAura::GetGestureHandler() const { - return system_gesture_dispatcher_.get(); -} - -void CastWindowManagerAura::SetTouchInputDisabled(bool disabled) { - event_gate_->SetEnabled(disabled); -} - -void CastWindowManagerAura::AddTouchActivityObserver( - CastTouchActivityObserver* observer) { - event_gate_->AddObserver(observer); -} - -void CastWindowManagerAura::RemoveTouchActivityObserver( - CastTouchActivityObserver* observer) { - event_gate_->RemoveObserver(observer); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_aura.h chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura.h --- chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_aura.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_AURA_H_ -#define CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_AURA_H_ - -#include - -#include "base/observer_list.h" -#include "chromecast/graphics/cast_window_manager.h" -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/client/window_parenting_client.h" -#include "ui/aura/window_tree_host_platform.h" - -namespace aura { -namespace client { -class ScreenPositionClient; -} // namespace client -} // namespace aura - -namespace chromecast { - -class CastTouchEventGate; -class CastFocusClientAura; -class CastGestureHandler; -class CastSystemGestureEventHandler; -class CastSystemGestureDispatcher; -class SideSwipeDetector; -class CastWindowTreeHostAura; - -class CastWindowManagerAura : public CastWindowManager, - public aura::client::WindowParentingClient { - public: - explicit CastWindowManagerAura(bool enable_input); - - CastWindowManagerAura(const CastWindowManagerAura&) = delete; - CastWindowManagerAura& operator=(const CastWindowManagerAura&) = delete; - - ~CastWindowManagerAura() override; - - void Setup(); - void OnWindowOrderChanged(std::vector window_order); - - // CastWindowManager implementation: - void TearDown() override; - void AddWindow(gfx::NativeView window) override; - gfx::NativeView GetRootWindow() override; - std::vector GetWindowOrder() override; - void SetZOrder(gfx::NativeView window, mojom::ZOrder z_order) override; - void InjectEvent(ui::Event* event) override; - void AddObserver(Observer* observer) override; - void RemoveObserver(Observer* observer) override; - void AddGestureHandler(CastGestureHandler* handler) override; - void RemoveGestureHandler(CastGestureHandler* handler) override; - void SetTouchInputDisabled(bool disabled) override; - void AddTouchActivityObserver(CastTouchActivityObserver* observer) override; - void RemoveTouchActivityObserver( - CastTouchActivityObserver* observer) override; - - // aura::client::WindowParentingClient implementation: - aura::Window* GetDefaultParent(aura::Window* window, - const gfx::Rect& bounds, - const int64_t display_id) override; - - CastWindowTreeHostAura* window_tree_host() const; - CastGestureHandler* GetGestureHandler() const; - aura::client::CaptureClient* capture_client() const { - return capture_client_.get(); - } - - private: - const bool enable_input_; - - std::unique_ptr window_tree_host_; - std::unique_ptr capture_client_; - std::unique_ptr focus_client_; - std::unique_ptr screen_position_client_; - std::unique_ptr event_gate_; - std::unique_ptr system_gesture_dispatcher_; - std::unique_ptr system_gesture_event_handler_; - std::unique_ptr side_swipe_detector_; - - std::vector window_order_; - base::ObserverList::Unchecked observer_list_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_AURA_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_aura_test.cc chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura_test.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_aura_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_aura_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,186 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_window_manager_aura.h" - -#include - -#include "ui/aura/client/focus_client.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/window.h" -#include "ui/events/test/event_generator.h" -#include "ui/views/test/views_test_base.h" - -namespace chromecast { -namespace test { -namespace { - -class CastTestWindowDelegate : public aura::test::TestWindowDelegate { - public: - CastTestWindowDelegate() : key_code_(ui::VKEY_UNKNOWN) {} - - CastTestWindowDelegate(const CastTestWindowDelegate&) = delete; - CastTestWindowDelegate& operator=(const CastTestWindowDelegate&) = delete; - - ~CastTestWindowDelegate() override {} - - // Overridden from TestWindowDelegate: - void OnKeyEvent(ui::KeyEvent* event) override { - key_code_ = event->key_code(); - } - - ui::KeyboardCode key_code() { return key_code_; } - - private: - ui::KeyboardCode key_code_; -}; - -class TestWindow { - public: - explicit TestWindow(int id) : window_(&delegate_) { - window_.Init(ui::LAYER_NOT_DRAWN); - window_.SetId(id); - window_.SetBounds(gfx::Rect(0, 0, 1280, 720)); - } - - TestWindow(const TestWindow&) = delete; - TestWindow& operator=(const TestWindow&) = delete; - - aura::Window* window() { return &window_; } - - private: - CastTestWindowDelegate delegate_; - aura::Window window_; -}; - -} // namespace - -// ViewsTestBase needed so that views/widget initialization is setup correctly -// for test runs. -using CastWindowManagerAuraTest = views::ViewsTestBase; - -TEST_F(CastWindowManagerAuraTest, InitialWindowId) { - CastTestWindowDelegate window_delegate; - aura::Window window(&window_delegate); - window.Init(ui::LAYER_NOT_DRAWN); - - // We have chosen WindowId::BOTTOM to match the initial window ID of an Aura - // window so that z-ordering works correctly. - EXPECT_EQ(window.GetId(), CastWindowManager::WindowId::BOTTOM); -} - -TEST_F(CastWindowManagerAuraTest, WindowInput) { - std::unique_ptr window_manager = - std::make_unique(true /* enable input */); - - CastTestWindowDelegate window_delegate; - aura::Window window(&window_delegate); - window.Init(ui::LAYER_NOT_DRAWN); - window.SetName("event window"); - window_manager->AddWindow(&window); - window.SetBounds(gfx::Rect(0, 0, 1280, 720)); - window.Show(); - EXPECT_FALSE(window.IsRootWindow()); - EXPECT_TRUE(window.GetHost()); - - // Confirm that the Aura focus client tracks window focus correctly. - aura::client::FocusClient* focus_client = - aura::client::GetFocusClient(&window); - EXPECT_TRUE(focus_client); - EXPECT_FALSE(focus_client->GetFocusedWindow()); - window.Focus(); - EXPECT_EQ(&window, focus_client->GetFocusedWindow()); - - // Confirm that a keyboard event is delivered to the window. - ui::test::EventGenerator event_generator(window.GetRootWindow()); - event_generator.PressKey(ui::VKEY_0, ui::EF_NONE); - EXPECT_EQ(ui::VKEY_0, window_delegate.key_code()); -} - -TEST_F(CastWindowManagerAuraTest, WindowInputDisabled) { - std::unique_ptr window_manager = - std::make_unique(false /* enable input */); - - CastTestWindowDelegate window_delegate; - aura::Window window(&window_delegate); - window.Init(ui::LAYER_NOT_DRAWN); - window.SetName("event window"); - window_manager->AddWindow(&window); - window.SetBounds(gfx::Rect(0, 0, 1280, 720)); - window.Show(); - EXPECT_FALSE(window.IsRootWindow()); - EXPECT_TRUE(window.GetHost()); - - // Confirm that the Aura focus client tracks window focus correctly. - aura::client::FocusClient* focus_client = - aura::client::GetFocusClient(&window); - EXPECT_TRUE(focus_client); - EXPECT_FALSE(focus_client->GetFocusedWindow()); - window.Focus(); - EXPECT_EQ(&window, focus_client->GetFocusedWindow()); - - // Confirm that a key event is *not* delivered to the window when input is - // disabled. - ui::test::EventGenerator event_generator(window.GetRootWindow()); - event_generator.PressKey(ui::VKEY_0, ui::EF_NONE); - EXPECT_EQ(ui::VKEY_UNKNOWN, window_delegate.key_code()); -} - -void VerifyWindowOrder(aura::Window* root_window) { - for (size_t i = 0; i < root_window->children().size() - 1; ++i) - EXPECT_LE(root_window->children()[i]->GetId(), - root_window->children()[i + 1]->GetId()); -} - -TEST_F(CastWindowManagerAuraTest, CheckProperWindowOrdering) { - std::unique_ptr window_manager = - std::make_unique(false /* enable input */); - - TestWindow window1(1); - TestWindow window3(3); - window_manager->AddWindow(window1.window()); - window_manager->AddWindow(window3.window()); - window1.window()->Show(); - window3.window()->Show(); - // Verify update for top window. - VerifyWindowOrder(window_manager->GetRootWindow()); - - TestWindow window0(0); - window_manager->AddWindow(window0.window()); - window0.window()->Show(); - // Verify update for bottom window. - VerifyWindowOrder(window_manager->GetRootWindow()); - - TestWindow window2(2); - window_manager->AddWindow(window2.window()); - window2.window()->Show(); - // Verify update for middle window. - VerifyWindowOrder(window_manager->GetRootWindow()); - - TestWindow window4(4); - TestWindow window5(5); - TestWindow window6(6); - window_manager->AddWindow(window6.window()); - window_manager->AddWindow(window4.window()); - window_manager->AddWindow(window5.window()); - window5.window()->Show(); - // Verify update with hidden windows. - VerifyWindowOrder(window_manager->GetRootWindow()); - - TestWindow window7(2); - window_manager->AddWindow(window7.window()); - window7.window()->Show(); - // Verify update with same window ID. - VerifyWindowOrder(window_manager->GetRootWindow()); - EXPECT_EQ(window7.window(), window_manager->GetRootWindow()->children()[3]); - - window2.window()->Hide(); - window2.window()->Show(); - // Verify update ordering with same window ID. - EXPECT_EQ(window2.window(), window_manager->GetRootWindow()->children()[3]); -} - -} // namespace test -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_default.cc chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_default.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_window_manager_default.h" - -#include "base/memory/ptr_util.h" - -namespace chromecast { - -CastWindowManagerDefault::CastWindowManagerDefault() {} - -CastWindowManagerDefault::~CastWindowManagerDefault() {} - -void CastWindowManagerDefault::TearDown() {} -void CastWindowManagerDefault::AddWindow(gfx::NativeView window) {} - -gfx::NativeView CastWindowManagerDefault::GetRootWindow() { - return nullptr; -} -std::vector -CastWindowManagerDefault::GetWindowOrder() { - return std::vector(); -} - -void CastWindowManagerDefault::InjectEvent(ui::Event* event) {} -void CastWindowManagerDefault::SetZOrder(gfx::NativeView window, - mojom::ZOrder z_order) {} -void CastWindowManagerDefault::AddObserver(Observer* observer) {} -void CastWindowManagerDefault::RemoveObserver(Observer* observer) {} - -// Register a new handler for system gesture events. -void CastWindowManagerDefault::AddGestureHandler(CastGestureHandler* handler) {} -// Remove the registration of a system gesture events handler. -void CastWindowManagerDefault::RemoveGestureHandler( - CastGestureHandler* handler) {} - -void CastWindowManagerDefault::SetTouchInputDisabled(bool disabled) {} - -void CastWindowManagerDefault::AddTouchActivityObserver( - CastTouchActivityObserver* observer) {} -void CastWindowManagerDefault::RemoveTouchActivityObserver( - CastTouchActivityObserver* observer) {} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_default.h chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_default.h --- chromium-132.0.6834.110/chromecast/graphics/cast_window_manager_default.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_window_manager_default.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_DEFAULT_H_ -#define CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_DEFAULT_H_ - -#include - -#include "chromecast/graphics/cast_window_manager.h" - -namespace chromecast { - -class CastWindowManagerDefault : public CastWindowManager { - public: - CastWindowManagerDefault(); - - CastWindowManagerDefault(const CastWindowManagerDefault&) = delete; - CastWindowManagerDefault& operator=(const CastWindowManagerDefault&) = delete; - - ~CastWindowManagerDefault() override; - - // CastWindowManager implementation: - void TearDown() override; - void AddWindow(gfx::NativeView window) override; - void SetZOrder(gfx::NativeView window, mojom::ZOrder z_order) override; - gfx::NativeView GetRootWindow() override; - std::vector GetWindowOrder() override; - void InjectEvent(ui::Event* event) override; - void AddObserver(Observer* observer) override; - void RemoveObserver(Observer* observer) override; - - void AddGestureHandler(CastGestureHandler* handler) override; - - void RemoveGestureHandler(CastGestureHandler* handler) override; - - void SetTouchInputDisabled(bool disabled) override; - void AddTouchActivityObserver(CastTouchActivityObserver* observer) override; - void RemoveTouchActivityObserver( - CastTouchActivityObserver* observer) override; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_WINDOW_MANAGER_DEFAULT_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_window_tree_host_aura.cc chromium-132.0.6834.159/chromecast/graphics/cast_window_tree_host_aura.cc --- chromium-132.0.6834.110/chromecast/graphics/cast_window_tree_host_aura.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_window_tree_host_aura.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/cast_window_tree_host_aura.h" - -#include "ui/aura/null_window_targeter.h" -#include "ui/gfx/geometry/size_conversions.h" -#include "ui/gfx/geometry/transform.h" -#include "ui/platform_window/platform_window_init_properties.h" - -namespace chromecast { - -CastWindowTreeHostAura::CastWindowTreeHostAura( - bool enable_input, - ui::PlatformWindowInitProperties properties) - : WindowTreeHostPlatform(std::move(properties)), - enable_input_(enable_input) { - if (!enable_input) { - window()->SetEventTargeter(std::make_unique()); - } - - ui_event_source_ = UiEventSource::Create(this); -} - -CastWindowTreeHostAura::~CastWindowTreeHostAura() {} - -void CastWindowTreeHostAura::DispatchEvent(ui::Event* event) { - if (!enable_input_) { - return; - } - - if (ui_event_source_ && event != nullptr && - !ui_event_source_->ShouldDispatchEvent(*event)) { - // Filter out unnecessary events. - return; - } - - WindowTreeHostPlatform::DispatchEvent(event); -} - -gfx::Rect CastWindowTreeHostAura::GetTransformedRootWindowBoundsFromPixelSize( - const gfx::Size& size_in_pixels) const { - gfx::RectF new_bounds = - GetInverseRootTransform().MapRect(gfx::RectF(gfx::Rect(size_in_pixels))); - - // Root window origin will be (0,0) except during bounds changes. - // Set to exactly zero to avoid rounding issues. - return gfx::Rect(gfx::ToCeiledSize(new_bounds.size())); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/cast_window_tree_host_aura.h chromium-132.0.6834.159/chromecast/graphics/cast_window_tree_host_aura.h --- chromium-132.0.6834.110/chromecast/graphics/cast_window_tree_host_aura.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/cast_window_tree_host_aura.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_CAST_WINDOW_TREE_HOST_AURA_H_ -#define CHROMECAST_GRAPHICS_CAST_WINDOW_TREE_HOST_AURA_H_ - -#include - -#include "chromecast/starboard/chromecast/events/ui_event_source.h" -#include "ui/aura/window_tree_host_platform.h" - -namespace chromecast { - -// An aura::WindowTreeHost that correctly converts input events. -class CastWindowTreeHostAura : public aura::WindowTreeHostPlatform { - public: - CastWindowTreeHostAura(bool enable_input, - ui::PlatformWindowInitProperties properties); - - CastWindowTreeHostAura(const CastWindowTreeHostAura&) = delete; - CastWindowTreeHostAura& operator=(const CastWindowTreeHostAura&) = delete; - - ~CastWindowTreeHostAura() override; - - // aura::WindowTreeHostPlatform implementation: - void DispatchEvent(ui::Event* event) override; - - // aura::WindowTreeHost implementation - gfx::Rect GetTransformedRootWindowBoundsFromPixelSize( - const gfx::Size& size_in_pixels) const override; - - private: - const bool enable_input_; - std::unique_ptr ui_event_source_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_CAST_WINDOW_TREE_HOST_AURA_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/cast_gesture_handler.cc chromium-132.0.6834.159/chromecast/graphics/gestures/cast_gesture_handler.cc --- chromium-132.0.6834.110/chromecast/graphics/gestures/cast_gesture_handler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/cast_gesture_handler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/gestures/cast_gesture_handler.h" - -namespace chromecast { - -bool CastGestureHandler::CanHandleSwipe(CastSideSwipeOrigin swipe_origin) { - return false; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/cast_gesture_handler.h chromium-132.0.6834.159/chromecast/graphics/gestures/cast_gesture_handler.h --- chromium-132.0.6834.110/chromecast/graphics/gestures/cast_gesture_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/cast_gesture_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_GESTURES_CAST_GESTURE_HANDLER_H_ -#define CHROMECAST_GRAPHICS_GESTURES_CAST_GESTURE_HANDLER_H_ - -namespace gfx { -class Point; -} // namespace gfx - -namespace chromecast { - -enum class CastSideSwipeOrigin { TOP, BOTTOM, LEFT, RIGHT, NONE }; - -enum class CastSideSwipeEvent { - // Indicates the beginning of a side-swipe event (finger down). - BEGIN, - // Indicates the continuance of a side-swipe event (finger drag). - CONTINUE, - // Indicates the end of a side-swipe event (finger up). - END -}; - -// Interface for handlers triggered on reception of gestures on the -// root window, including side-swipe and tap. -class CastGestureHandler { - public: - // Gesture handler priority. If multiple handlers can process a gesture event, - // then the highest-priority handler is the one which receives the event. - enum class Priority { - // Handler with NONE priority will never receive a gesture event. - NONE = 0, - ROOT_UI, - MAIN_ACTIVITY, - SETTINGS_UI, - MAX = SETTINGS_UI, - }; - - CastGestureHandler() = default; - - CastGestureHandler(const CastGestureHandler&) = delete; - CastGestureHandler& operator=(const CastGestureHandler&) = delete; - - virtual ~CastGestureHandler() = default; - - // Returns the gesture handler's current priority. - virtual Priority GetPriority() = 0; - - // Return true if this handler can handle swipes from the given origin. - virtual bool CanHandleSwipe(CastSideSwipeOrigin swipe_origin) = 0; - - // Triggered when a user swipes from an edge on the screen. - virtual void HandleSideSwipe(CastSideSwipeEvent event, - CastSideSwipeOrigin swipe_origin, - const gfx::Point& touch_location) = 0; - - // Triggered on the completion of a tap down event, fired when the - // finger is pressed. - virtual void HandleTapDownGesture(const gfx::Point& touch_location) = 0; - - // Triggered on the completion of a tap event, fire after a press - // followed by a release, within the tap timeout window - virtual void HandleTapGesture(const gfx::Point& touch_location) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_GESTURES_CAST_GESTURE_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_dispatcher.cc chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher.cc --- chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_dispatcher.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,120 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/gestures/cast_system_gesture_dispatcher.h" - -#include "base/logging.h" -#include "base/time/default_tick_clock.h" - -namespace chromecast { - -namespace { -const base::TimeDelta kExpirationTime = base::Seconds(3); -const size_t kMaxSwipes = 3; -} // namespace - -CastSystemGestureDispatcher::CastSystemGestureDispatcher( - const base::TickClock* tick_clock) - : send_gestures_to_root_(false), tick_clock_(tick_clock) {} - -CastSystemGestureDispatcher::CastSystemGestureDispatcher() - : CastSystemGestureDispatcher(base::DefaultTickClock::GetInstance()) {} - -CastSystemGestureDispatcher::~CastSystemGestureDispatcher() { - DCHECK(gesture_handlers_.empty()); -} - -void CastSystemGestureDispatcher::AddGestureHandler( - CastGestureHandler* handler) { - gesture_handlers_.insert(handler); -} - -void CastSystemGestureDispatcher::RemoveGestureHandler( - CastGestureHandler* handler) { - gesture_handlers_.erase(handler); -} - -CastGestureHandler::Priority CastSystemGestureDispatcher::GetPriority() { - return Priority::MAX; -} - -bool CastSystemGestureDispatcher::CanHandleSwipe( - CastSideSwipeOrigin swipe_origin) { - for (auto* gesture_handler : gesture_handlers_) { - if (gesture_handler->CanHandleSwipe(swipe_origin)) { - return true; - } - } - return false; -} - -void CastSystemGestureDispatcher::HandleSideSwipe( - CastSideSwipeEvent event, - CastSideSwipeOrigin swipe_origin, - const gfx::Point& touch_location) { - // Process previous events and check to see if the user attempted a swipe - // multiple times. This probably indicates that the swipe is not having the - // intended effect in the UI, most likely the highest priority handler is - // consuming the gesture but not taking any action. To prevent the system - // from getting stuck, route new gesture events to the main UI when this - // happens. - base::TimeTicks now = tick_clock_->NowTicks(); - if (event == CastSideSwipeEvent::BEGIN && - swipe_origin == CastSideSwipeOrigin::LEFT) { - recent_events_.push({now, swipe_origin}); - // Flush events which are older than the prescribed time. - while (!recent_events_.empty() && - recent_events_.front().event_time < now - kExpirationTime) { - recent_events_.pop(); - } - // If there are too many recent swipes, then this gesture should go to the - // root UI. - send_gestures_to_root_ = recent_events_.size() >= kMaxSwipes; - if (send_gestures_to_root_) { - LOG(INFO) << "User swiped " << kMaxSwipes << " times within " - << kExpirationTime - << ", sending next swipe gesture to root UI."; - } - } - CastGestureHandler* best_handler = nullptr; - Priority highest_priority = Priority::NONE; - // Iterate through all handlers. Pick the handler with the highest priority - // that is capable of handling the swipe event and is not Priority::NONE. - for (auto* gesture_handler : gesture_handlers_) { - if (send_gestures_to_root_ && - gesture_handler->GetPriority() == Priority::ROOT_UI) { - best_handler = gesture_handler; - break; - } - if (gesture_handler->CanHandleSwipe(swipe_origin) && - gesture_handler->GetPriority() > highest_priority) { - best_handler = gesture_handler; - highest_priority = gesture_handler->GetPriority(); - } - } - if (best_handler) - best_handler->HandleSideSwipe(event, swipe_origin, touch_location); - if (send_gestures_to_root_ && event == CastSideSwipeEvent::END) { - // Reset the recent events. - std::queue empty; - std::swap(recent_events_, empty); - send_gestures_to_root_ = false; - } -} - -void CastSystemGestureDispatcher::HandleTapDownGesture( - const gfx::Point& touch_location) { - for (auto* gesture_handler : gesture_handlers_) { - gesture_handler->HandleTapDownGesture(touch_location); - } -} - -void CastSystemGestureDispatcher::HandleTapGesture( - const gfx::Point& touch_location) { - for (auto* gesture_handler : gesture_handlers_) { - gesture_handler->HandleTapGesture(touch_location); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_dispatcher.h chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher.h --- chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_dispatcher.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_GESTURES_CAST_SYSTEM_GESTURE_DISPATCHER_H_ -#define CHROMECAST_GRAPHICS_GESTURES_CAST_SYSTEM_GESTURE_DISPATCHER_H_ - -#include - -#include "base/containers/flat_set.h" -#include "base/time/tick_clock.h" -#include "base/time/time.h" -#include "chromecast/graphics/gestures/cast_gesture_handler.h" - -namespace chromecast { - -// A CastGestureHandler that fans system gesture events out to multiple -// consumers. -class CastSystemGestureDispatcher : public CastGestureHandler { - public: - CastSystemGestureDispatcher(); - explicit CastSystemGestureDispatcher(const base::TickClock* tick_clock); - - ~CastSystemGestureDispatcher() override; - - // Register a new handler for gesture events, including side swipe and tap. - void AddGestureHandler(CastGestureHandler* handler); - - // Remove the registration of a gesture handler. - void RemoveGestureHandler(CastGestureHandler* handler); - - // Implementation of CastGestureHandler methods which fan out to our gesture - // handlers. - Priority GetPriority() override; - bool CanHandleSwipe(CastSideSwipeOrigin swipe_origin) override; - void HandleSideSwipe(CastSideSwipeEvent event, - CastSideSwipeOrigin swipe_origin, - const gfx::Point& touch_location) override; - void HandleTapDownGesture(const gfx::Point& touch_location) override; - void HandleTapGesture(const gfx::Point& touch_location) override; - - private: - // Logs a completed gesture event. - struct GestureEvent { - base::TimeTicks event_time; - CastSideSwipeOrigin origin; - }; - - std::queue recent_events_; - bool send_gestures_to_root_; - const base::TickClock* const tick_clock_; - base::flat_set gesture_handlers_; -}; -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_GESTURES_CAST_SYSTEM_GESTURE_DISPATCHER_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_dispatcher_test.cc chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher_test.cc --- chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_dispatcher_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_dispatcher_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,217 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/gestures/cast_system_gesture_dispatcher.h" - -#include - -#include "base/test/simple_test_tick_clock.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/geometry/point.h" - -using testing::_; -using testing::Return; - -namespace chromecast { - -namespace { - -constexpr base::TimeDelta kTimeoutWindow = base::Seconds(3); -const size_t kMaxSwipesWithinTimeout = 3; - -} // namespace - -class MockCastGestureHandler : public CastGestureHandler { - public: - ~MockCastGestureHandler() override = default; - - MOCK_METHOD0(GetPriority, Priority()); - MOCK_METHOD1(CanHandleSwipe, bool(CastSideSwipeOrigin origin)); - MOCK_METHOD3(HandleSideSwipe, - void(CastSideSwipeEvent event, - CastSideSwipeOrigin swipe_origin, - const gfx::Point& touch_location)); - MOCK_METHOD1(HandleTapDownGesture, void(const gfx::Point& touch_location)); - MOCK_METHOD1(HandleTapGesture, void(const gfx::Point& touch_location)); -}; - -class CastSystemGestureDispatcherTest : public testing::Test { - public: - ~CastSystemGestureDispatcherTest() override = default; - - void SetUp() override { - test_clock_ = std::make_unique(); - gesture_dispatcher_ = - std::make_unique(test_clock_.get()); - } - - void TearDown() override { gesture_dispatcher_.reset(); } - - protected: - std::unique_ptr gesture_dispatcher_; - std::unique_ptr test_clock_; -}; - -TEST_F(CastSystemGestureDispatcherTest, SingleHandler) { - MockCastGestureHandler handler; - gesture_dispatcher_->AddGestureHandler(&handler); - ON_CALL(handler, GetPriority()) - .WillByDefault(Return(CastGestureHandler::Priority::MAIN_ACTIVITY)); - - // Test when a handler is able to handle a swipe event. - ON_CALL(handler, CanHandleSwipe(_)).WillByDefault(Return(true)); - CastSideSwipeEvent event = CastSideSwipeEvent::BEGIN; - CastSideSwipeOrigin origin = CastSideSwipeOrigin::TOP; - gfx::Point point(0, 0); - EXPECT_CALL(handler, HandleSideSwipe(event, origin, point)); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - - // Test when a handler cannot handle a swipe event. - ON_CALL(handler, CanHandleSwipe(CastSideSwipeOrigin::BOTTOM)) - .WillByDefault(Return(false)); - EXPECT_CALL(handler, HandleSideSwipe(_, _, _)).Times(0); - gesture_dispatcher_->HandleSideSwipe(event, CastSideSwipeOrigin::BOTTOM, - point); - - gesture_dispatcher_->RemoveGestureHandler(&handler); -} - -TEST_F(CastSystemGestureDispatcherTest, SingleHandlerPriorityNone) { - MockCastGestureHandler handler; - gesture_dispatcher_->AddGestureHandler(&handler); - ON_CALL(handler, GetPriority()) - .WillByDefault(Return(CastGestureHandler::Priority::NONE)); - - // Test when a handler is able to handle a swipe event. - ON_CALL(handler, CanHandleSwipe(_)).WillByDefault(Return(true)); - CastSideSwipeEvent event = CastSideSwipeEvent::BEGIN; - CastSideSwipeOrigin origin = CastSideSwipeOrigin::TOP; - gfx::Point point(0, 0); - // The gesture event will not be sent since the handler's priority is NONE. - EXPECT_CALL(handler, HandleSideSwipe(_, _, _)).Times(0); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - - gesture_dispatcher_->RemoveGestureHandler(&handler); -} - -TEST_F(CastSystemGestureDispatcherTest, MultipleHandlersByPriority) { - MockCastGestureHandler handler_1; - MockCastGestureHandler handler_2; - ON_CALL(handler_1, GetPriority()) - .WillByDefault(Return(CastGestureHandler::Priority::ROOT_UI)); - ON_CALL(handler_2, GetPriority()) - .WillByDefault(Return(CastGestureHandler::Priority::MAIN_ACTIVITY)); - - gesture_dispatcher_->AddGestureHandler(&handler_1); - gesture_dispatcher_->AddGestureHandler(&handler_2); - - // Higher priority handler should get the event. - ON_CALL(handler_1, CanHandleSwipe(_)).WillByDefault(Return(true)); - ON_CALL(handler_2, CanHandleSwipe(_)).WillByDefault(Return(true)); - CastSideSwipeEvent event = CastSideSwipeEvent::BEGIN; - CastSideSwipeOrigin origin = CastSideSwipeOrigin::TOP; - gfx::Point point(0, 0); - EXPECT_CALL(handler_1, HandleSideSwipe(_, _, _)).Times(0); - EXPECT_CALL(handler_2, HandleSideSwipe(event, origin, point)); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - - test_clock_->Advance(kTimeoutWindow); - // Test when the higher priority handler can't handle the event. Lower - // priority handler should get it instead. - origin = CastSideSwipeOrigin::BOTTOM; - ON_CALL(handler_2, CanHandleSwipe(origin)).WillByDefault(Return(false)); - EXPECT_CALL(handler_1, HandleSideSwipe(event, origin, point)); - EXPECT_CALL(handler_2, HandleSideSwipe(_, _, _)).Times(0); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - test_clock_->Advance(kTimeoutWindow); - - // Test when no handlers can handle the event. - ON_CALL(handler_1, CanHandleSwipe(origin)).WillByDefault(Return(false)); - EXPECT_CALL(handler_1, HandleSideSwipe(_, _, _)).Times(0); - EXPECT_CALL(handler_2, HandleSideSwipe(_, _, _)).Times(0); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - test_clock_->Advance(kTimeoutWindow); - - gesture_dispatcher_->RemoveGestureHandler(&handler_2); - gesture_dispatcher_->RemoveGestureHandler(&handler_1); -} - -TEST_F(CastSystemGestureDispatcherTest, MultipleBackSwipesToRootUi) { - MockCastGestureHandler handler_1; - MockCastGestureHandler handler_2; - ON_CALL(handler_1, GetPriority()) - .WillByDefault(Return(CastGestureHandler::Priority::ROOT_UI)); - ON_CALL(handler_2, GetPriority()) - .WillByDefault(Return(CastGestureHandler::Priority::MAIN_ACTIVITY)); - - gesture_dispatcher_->AddGestureHandler(&handler_1); - gesture_dispatcher_->AddGestureHandler(&handler_2); - - // Higher priority handler should get the event. - ON_CALL(handler_1, CanHandleSwipe(_)).WillByDefault(Return(true)); - ON_CALL(handler_2, CanHandleSwipe(_)).WillByDefault(Return(true)); - CastSideSwipeEvent event = CastSideSwipeEvent::BEGIN; - CastSideSwipeOrigin origin = CastSideSwipeOrigin::TOP; - gfx::Point point(0, 0); - - // Swipe gestures from any other edge but LEFT will always hit the main target - // handler. - for (size_t i = 0; i < 2 * kMaxSwipesWithinTimeout; ++i) { - EXPECT_CALL(handler_1, HandleSideSwipe(_, _, _)).Times(0); - EXPECT_CALL(handler_2, HandleSideSwipe(event, origin, point)); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - } - - // Now test LEFT events. - origin = CastSideSwipeOrigin::LEFT; - // Trigger N - 1 events within the recent events timeout window. - for (size_t i = 0; i < kMaxSwipesWithinTimeout - 1; ++i) { - EXPECT_CALL(handler_1, HandleSideSwipe(_, _, _)).Times(0); - EXPECT_CALL(handler_2, HandleSideSwipe(event, origin, point)); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - base::TimeDelta time_between_events = - (kTimeoutWindow - base::Seconds(1)) / (kMaxSwipesWithinTimeout - 1); - test_clock_->Advance(time_between_events); - } - - // The Nth event will go to the root UI, since there were N BEGIN events that - // happened in rapid succession. This means the main activity is probably not - // handling the events properly, and we should defer to the root UI which is - // assumed to behave properly. - event = CastSideSwipeEvent::BEGIN; - EXPECT_CALL(handler_1, HandleSideSwipe(event, origin, point)); - EXPECT_CALL(handler_2, HandleSideSwipe(_, _, _)).Times(0); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - - // CONTINUE events still go to the root UI. - event = CastSideSwipeEvent::CONTINUE; - EXPECT_CALL(handler_1, HandleSideSwipe(event, origin, point)); - EXPECT_CALL(handler_2, HandleSideSwipe(_, _, _)).Times(0); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - - // All events will go to the root UI until the next BEGIN event after the - // 3-event timeout. - event = CastSideSwipeEvent::CONTINUE; - EXPECT_CALL(handler_1, HandleSideSwipe(event, origin, point)); - EXPECT_CALL(handler_2, HandleSideSwipe(_, _, _)).Times(0); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - - event = CastSideSwipeEvent::END; - EXPECT_CALL(handler_1, HandleSideSwipe(event, origin, point)); - EXPECT_CALL(handler_2, HandleSideSwipe(_, _, _)).Times(0); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - - // The next event will behave as normal; the timeout period restarts after - // the END swipe event. - event = CastSideSwipeEvent::BEGIN; - EXPECT_CALL(handler_1, HandleSideSwipe(_, _, _)).Times(0); - EXPECT_CALL(handler_2, HandleSideSwipe(event, origin, point)); - gesture_dispatcher_->HandleSideSwipe(event, origin, point); - - gesture_dispatcher_->RemoveGestureHandler(&handler_2); - gesture_dispatcher_->RemoveGestureHandler(&handler_1); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_event_handler.cc chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_event_handler.cc --- chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_event_handler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_event_handler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/gestures/cast_system_gesture_event_handler.h" - -#include - -#include "base/auto_reset.h" -#include "chromecast/base/chromecast_switches.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" -#include "ui/display/display.h" -#include "ui/display/screen.h" -#include "ui/events/event.h" -#include "ui/events/event_rewriter.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/wm/core/coordinate_conversion.h" - -namespace chromecast { - -CastSystemGestureEventHandler::CastSystemGestureEventHandler( - CastSystemGestureDispatcher* dispatcher, - aura::Window* root_window) - : EventHandler(), dispatcher_(dispatcher), root_window_(root_window) { - DCHECK(dispatcher); - DCHECK(root_window); - root_window->AddPreTargetHandler(this); -} - -CastSystemGestureEventHandler::~CastSystemGestureEventHandler() { - root_window_->RemovePreTargetHandler(this); -} - -void CastSystemGestureEventHandler::OnTouchEvent(ui::TouchEvent* event) { - if (event->type() == ui::EventType::kTouchPressed) { - dispatcher_->HandleTapDownGesture(event->location()); - } -} - -void CastSystemGestureEventHandler::OnGestureEvent(ui::GestureEvent* event) { - if (event->type() == ui::EventType::kGestureTap) { - dispatcher_->HandleTapGesture(event->location()); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_event_handler.h chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_event_handler.h --- chromium-132.0.6834.110/chromecast/graphics/gestures/cast_system_gesture_event_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/cast_system_gesture_event_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_GESTURES_CAST_SYSTEM_GESTURE_EVENT_HANDLER_H_ -#define CHROMECAST_GRAPHICS_GESTURES_CAST_SYSTEM_GESTURE_EVENT_HANDLER_H_ - -#include "chromecast/graphics/gestures/cast_system_gesture_dispatcher.h" -#include "ui/events/event_handler.h" - -namespace aura { -class Window; -} // namespace aura - -namespace chromecast { - -// Observes gesture events on the root window and dispatches them to the cast -// system gesture dispatcher. -class CastSystemGestureEventHandler : public ui::EventHandler { - public: - explicit CastSystemGestureEventHandler( - CastSystemGestureDispatcher* dispatcher, - aura::Window* root_window); - - CastSystemGestureEventHandler(const CastSystemGestureEventHandler&) = delete; - CastSystemGestureEventHandler& operator=( - const CastSystemGestureEventHandler&) = delete; - - ~CastSystemGestureEventHandler() override; - - // ui::EventHandler implementation. - void OnTouchEvent(ui::TouchEvent* event) override; - void OnGestureEvent(ui::GestureEvent* event) override; - - private: - CastSystemGestureDispatcher* dispatcher_; - aura::Window* root_window_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_GESTURES_CAST_SYSTEM_GESTURE_EVENT_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/multiple_tap_detector.cc chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector.cc --- chromium-132.0.6834.110/chromecast/graphics/gestures/multiple_tap_detector.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,156 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/gestures/multiple_tap_detector.h" - -#include - -#include "base/auto_reset.h" -#include "base/check.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" -#include "ui/events/event.h" -#include "ui/events/event_processor.h" -#include "ui/events/event_utils.h" - -namespace chromecast { - -MultipleTapDetector::MultipleTapDetector(aura::Window* root_window, - MultipleTapDetectorDelegate* delegate) - : root_window_(root_window), - delegate_(delegate), - enabled_(false), - tap_state_(MultiTapState::NONE), - tap_count_(0) { - root_window->GetHost()->GetEventSource()->AddEventRewriter(this); -} - -MultipleTapDetector::~MultipleTapDetector() { - root_window_->GetHost()->GetEventSource()->RemoveEventRewriter(this); -} - -ui::EventDispatchDetails MultipleTapDetector::RewriteEvent( - const ui::Event& event, - const Continuation continuation) { - if (!enabled_ || !delegate_ || !event.IsTouchEvent()) { - return SendEvent(continuation, &event); - } - - const ui::TouchEvent& touch_event = static_cast(event); - if (event.type() == ui::EventType::kTouchPressed) { - // If a press happened again before the minimum inter-tap interval, cancel - // the detection. - if (tap_state_ == MultiTapState::INTERVAL_WAIT && - (event.time_stamp() - stashed_events_.back().event.time_stamp()) < - gesture_detector_config_.double_tap_min_time) { - stashed_events_.clear(); - TapDetectorStateReset(); - return SendEvent(continuation, &event); - } - - // If the user moved too far from the last tap position, it's not a multi - // tap. - if (tap_count_) { - float distance = (touch_event.location() - last_tap_location_).Length(); - if (distance > gesture_detector_config_.double_tap_slop) { - TapDetectorStateReset(); - stashed_events_.clear(); - return SendEvent(continuation, &event); - } - } - - // Otherwise transition into a touched state. - tap_state_ = MultiTapState::TOUCH; - last_tap_location_ = touch_event.location(); - - // If this is pressed too long, it should be treated as a long-press, and - // not part of a triple-tap, so set a timer to detect that. - triple_tap_timer_.Start( - FROM_HERE, gesture_detector_config_.longpress_timeout, this, - &MultipleTapDetector::OnLongPressIntervalTimerFired); - - // If we've already gotten one tap, discard this event, only the original - // tap needs to get through. - if (tap_count_) { - return DiscardEvent(continuation); - } - - // Copy the event so we can issue a cancel for it later if this turns out to - // be a multi-tap. - stashed_events_.emplace_back(touch_event, continuation); - - return SendEvent(continuation, &event); - } - - // Finger was released while we were waiting for one, count it as a tap. - if (touch_event.type() == ui::EventType::kTouchReleased && - tap_state_ == MultiTapState::TOUCH) { - tap_state_ = MultiTapState::INTERVAL_WAIT; - triple_tap_timer_.Start(FROM_HERE, - gesture_detector_config_.double_tap_timeout, this, - &MultipleTapDetector::OnTapIntervalTimerFired); - - tap_count_++; - if (tap_count_ == 3) { - TapDetectorStateReset(); - delegate_->OnTripleTap(touch_event.location()); - - // Issue cancel events for old presses. - ui::EventDispatchDetails details; - for (const auto& it : stashed_events_) { - ui::TouchEvent cancel_event( - ui::EventType::kTouchCancelled, it.event.location_f(), - it.event.root_location_f(), it.event.time_stamp(), - it.event.pointer_details(), it.event.flags()); - details = SendEvent(it.continuation, &cancel_event); - if (details.dispatcher_destroyed) - break; - } - stashed_events_.clear(); - return details; - } else if (tap_count_ > 1) { - return DiscardEvent(continuation); - } - } - - return SendEvent(continuation, &event); -} - -void MultipleTapDetector::OnTapIntervalTimerFired() { - // We didn't quite reach a third tap, but a second was reached. - // So call out the double-tap. - if (tap_count_ == 2) { - delegate_->OnDoubleTap(last_tap_location_); - if (!stashed_events_.empty()) { - Stash& stash = stashed_events_.front(); - ui::TouchEvent cancel_event( - ui::EventType::kTouchCancelled, stash.event.location_f(), - stash.event.root_location_f(), base::TimeTicks::Now(), - stash.event.pointer_details(), stash.event.flags()); - DCHECK( - !SendEvent(stash.continuation, &cancel_event).dispatcher_destroyed); - } - } - TapDetectorStateReset(); - stashed_events_.clear(); -} - -void MultipleTapDetector::OnLongPressIntervalTimerFired() { - TapDetectorStateReset(); - stashed_events_.clear(); -} - -void MultipleTapDetector::TapDetectorStateReset() { - tap_state_ = MultiTapState::NONE; - tap_count_ = 0; - triple_tap_timer_.Stop(); -} - -MultipleTapDetector::Stash::Stash(const ui::TouchEvent& e, const Continuation c) - : event(e), continuation(c) {} - -MultipleTapDetector::Stash::~Stash() {} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/multiple_tap_detector.h chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector.h --- chromium-132.0.6834.110/chromecast/graphics/gestures/multiple_tap_detector.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,98 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_GESTURES_MULTIPLE_TAP_DETECTOR_H_ -#define CHROMECAST_GRAPHICS_GESTURES_MULTIPLE_TAP_DETECTOR_H_ - -#include - -#include "base/memory/weak_ptr.h" -#include "base/timer/timer.h" -#include "ui/events/event.h" -#include "ui/events/event_rewriter.h" -#include "ui/events/gesture_detection/gesture_detector.h" -#include "ui/events/gestures/gesture_provider_aura.h" -#include "ui/gfx/geometry/point.h" - -namespace aura { -class Window; -} - -namespace ui { -class Event; -class TouchEvent; -} // namespace ui - -namespace chromecast { - -class MultipleTapDetectorDelegate { - public: - virtual ~MultipleTapDetectorDelegate() = default; - virtual void OnTripleTap(const gfx::Point& touch_location) = 0; - virtual void OnDoubleTap(const gfx::Point& touch_location) {} -}; - -enum class MultiTapState { - NONE, - TOUCH, - INTERVAL_WAIT, -}; - -// An event rewriter responsible for detecting triple-tap or double-tap events -// on the root window. -class MultipleTapDetector : public ui::EventRewriter { - public: - MultipleTapDetector(aura::Window* root_window, - MultipleTapDetectorDelegate* delegate); - - MultipleTapDetector(const MultipleTapDetector&) = delete; - MultipleTapDetector& operator=(const MultipleTapDetector&) = delete; - - ~MultipleTapDetector() override; - - void set_enabled(bool enabled) { enabled_ = enabled; } - bool enabled() const { return enabled_; } - - // Overridden from ui::EventRewriter - ui::EventDispatchDetails RewriteEvent( - const ui::Event& event, - const Continuation continuation) override; - - private: - friend class MultipleTapDetectorTest; - - // Expiration event for maximum time between taps in a tap. - void OnTapIntervalTimerFired(); - // Expiration event for a finger that is pressed too long during a multi tap. - void OnLongPressIntervalTimerFired(); - void TapDetectorStateReset(); - - void DispatchEvent(ui::TouchEvent* event); - - // A default gesture detector config, so we can share the same - // timeout and pixel slop constants. - ui::GestureDetector::Config gesture_detector_config_; - - aura::Window* root_window_; - MultipleTapDetectorDelegate* delegate_; - - bool enabled_; - - MultiTapState tap_state_; - int tap_count_; - gfx::Point last_tap_location_; - base::OneShotTimer triple_tap_timer_; - class Stash { - public: - Stash(const ui::TouchEvent& e, const Continuation c); - ~Stash(); - const ui::TouchEvent event; - const Continuation continuation; - }; - std::deque stashed_events_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_GESTURES_MULTIPLE_TAP_DETECTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/multiple_tap_detector_test.cc chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector_test.cc --- chromium-132.0.6834.110/chromecast/graphics/gestures/multiple_tap_detector_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/multiple_tap_detector_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,185 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/gestures/multiple_tap_detector.h" - -#include "base/run_loop.h" -#include "base/test/simple_test_tick_clock.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/window.h" -#include "ui/events/event_utils.h" -#include "ui/events/gesture_detection/gesture_configuration.h" -#include "ui/events/test/event_generator.h" -#include "ui/events/test/events_test_utils.h" - -using testing::_; -using testing::Eq; - -namespace chromecast { - -namespace { -constexpr gfx::Point kTestTapLocation(50, 50); -constexpr int kTapLengthMs = 50; -} // namespace - -class MockMultipleTapDetectorDelegate : public MultipleTapDetectorDelegate { - public: - ~MockMultipleTapDetectorDelegate() override = default; - MOCK_METHOD1(OnTripleTap, void(const gfx::Point&)); - MOCK_METHOD1(OnDoubleTap, void(const gfx::Point&)); -}; - -class MultipleTapDetectorTest : public aura::test::AuraTestBase { - public: - ~MultipleTapDetectorTest() override = default; - - void SetUp() override { - aura::test::AuraTestBase::SetUp(); - - triple_tap_delegate_ = std::make_unique(); - triple_tap_detector_ = std::make_unique( - root_window(), triple_tap_delegate_.get()); - - generator_.reset(new ui::test::EventGenerator(root_window())); - - // Tests fail if time is ever 0. - simulated_clock_.Advance(base::Milliseconds(10)); - // ui takes ownership of the tick clock. - ui::SetEventTickClockForTesting(&simulated_clock_); - } - - void TearDown() override { - ui::SetEventTickClockForTesting(nullptr); - triple_tap_detector_.reset(); - aura::test::AuraTestBase::TearDown(); - } - - // Pause the minimum amount of tap to trigger a double tap. - void DoubleTapPause() { - simulated_clock_.Advance(gesture_detector_config_.double_tap_min_time); - } - - // Pause just past the maximum amount of time to trigger a double tap. - void TooLongPause() { - simulated_clock_.Advance(gesture_detector_config_.double_tap_timeout); - simulated_clock_.Advance(base::Milliseconds(1)); - triple_tap_detector_->triple_tap_timer_.Stop(); - triple_tap_detector_->OnTapIntervalTimerFired(); - } - - // Simulate a tap event. - void Tap(const gfx::Point& tap_point) { - ui::TouchEvent press(ui::EventType::kTouchPressed, tap_point, - simulated_clock_.NowTicks(), - ui::PointerDetails(ui::EventPointerType::kTouch, - ui::kPointerIdUnknown)); - generator_->Dispatch(&press); - simulated_clock_.Advance(base::Milliseconds(kTapLengthMs)); - ui::TouchEvent release(ui::EventType::kTouchReleased, tap_point, - simulated_clock_.NowTicks(), - ui::PointerDetails(ui::EventPointerType::kTouch, - ui::kPointerIdUnknown)); - generator_->Dispatch(&release); - } - - void Tap() { Tap(kTestTapLocation); } - - MultipleTapDetector& detector() { return *triple_tap_detector_; } - MockMultipleTapDetectorDelegate& delegate() { return *triple_tap_delegate_; } - - private: - ui::GestureDetector::Config gesture_detector_config_; - - std::unique_ptr triple_tap_detector_; - std::unique_ptr triple_tap_delegate_; - base::SimpleTestTickClock simulated_clock_; - std::unique_ptr generator_; -}; - -// Verify that a simple correct triple tap triggers the delegate. -TEST_F(MultipleTapDetectorTest, TripleTap) { - EXPECT_CALL(delegate(), OnTripleTap(Eq(kTestTapLocation))).Times(1); - EXPECT_CALL(delegate(), OnDoubleTap(Eq(kTestTapLocation))).Times(0); - - detector().set_enabled(true); - - Tap(); - DoubleTapPause(); - Tap(); - DoubleTapPause(); - Tap(); - - base::RunLoop run_loop; - run_loop.RunUntilIdle(); -} - -// Verify double tap when there's two taps then a pause past our double tap -// interval. -TEST_F(MultipleTapDetectorTest, DoubleTap) { - EXPECT_CALL(delegate(), OnTripleTap(Eq(kTestTapLocation))).Times(0); - EXPECT_CALL(delegate(), OnDoubleTap(Eq(kTestTapLocation))).Times(1); - - detector().set_enabled(true); - - Tap(); - DoubleTapPause(); - Tap(); - TooLongPause(); - - base::RunLoop run_loop; - run_loop.RunUntilIdle(); -} - -// Verify that no multi taps are detected when the detector is not enabled. -TEST_F(MultipleTapDetectorTest, Inactive) { - EXPECT_CALL(delegate(), OnTripleTap(Eq(kTestTapLocation))).Times(0); - EXPECT_CALL(delegate(), OnDoubleTap(Eq(kTestTapLocation))).Times(0); - Tap(); - DoubleTapPause(); - Tap(); - DoubleTapPause(); - Tap(); - - base::RunLoop run_loop; - run_loop.RunUntilIdle(); -} - -// Verify it's not a multi tap of any kind if the pause from the first tap to -// the second tap is too long. -TEST_F(MultipleTapDetectorTest, FirstTapTooLong) { - EXPECT_CALL(delegate(), OnTripleTap(Eq(kTestTapLocation))).Times(0); - EXPECT_CALL(delegate(), OnDoubleTap(Eq(kTestTapLocation))).Times(0); - - detector().set_enabled(true); - - Tap(); - TooLongPause(); - Tap(); - DoubleTapPause(); - Tap(); - - base::RunLoop run_loop; - run_loop.RunUntilIdle(); -} - -// Verify it's not a triple tap but instead a doubletap if the pause from the -// second tap to the last tap is too long. -TEST_F(MultipleTapDetectorTest, LastTapTooLongIsDoubleTap) { - EXPECT_CALL(delegate(), OnTripleTap(Eq(kTestTapLocation))).Times(0); - EXPECT_CALL(delegate(), OnDoubleTap(Eq(kTestTapLocation))).Times(1); - - detector().set_enabled(true); - - Tap(); - DoubleTapPause(); - Tap(); - TooLongPause(); - Tap(); - - base::RunLoop run_loop; - run_loop.RunUntilIdle(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/side_swipe_detector.cc chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector.cc --- chromium-132.0.6834.110/chromecast/graphics/gestures/side_swipe_detector.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,214 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/gestures/side_swipe_detector.h" - -#include - -#include "base/auto_reset.h" -#include "chromecast/base/chromecast_switches.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" -#include "ui/display/display.h" -#include "ui/display/screen.h" -#include "ui/events/event.h" -#include "ui/events/event_rewriter.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/wm/core/coordinate_conversion.h" - -namespace chromecast { -namespace { -// The number of pixels from the very left or right of the screen to consider as -// a valid origin for the left or right swipe gesture. -constexpr int kDefaultSideGestureStartWidth = 35; - -// The number of pixels from the very top or bottom of the screen to consider as -// a valid origin for the top or bottom swipe gesture. -constexpr int kDefaultSideGestureStartHeight = 35; - -// The amount of time after gesture start to allow events which occur in the -// margin to be stashed and replayed within. For example a tap event which -// occurs inside the gesture margin will be valid as long as it occurs within -// the time specified by this threshold. -constexpr base::TimeDelta kGestureMarginEventsTimeLimit = - base::Milliseconds(500); - -// Get the correct bottom gesture start height by checking both margin flags in -// order, and then the default value if neither is set. -int BottomGestureStartHeight() { - return GetSwitchValueInt( - switches::kBottomSystemGestureStartHeight, - GetSwitchValueInt(switches::kSystemGestureStartHeight, - kDefaultSideGestureStartHeight)); -} - -} // namespace - -SideSwipeDetector::SideSwipeDetector(CastGestureHandler* gesture_handler, - aura::Window* root_window) - : gesture_start_width_(GetSwitchValueInt(switches::kSystemGestureStartWidth, - kDefaultSideGestureStartWidth)), - gesture_start_height_( - GetSwitchValueInt(switches::kSystemGestureStartHeight, - kDefaultSideGestureStartHeight)), - bottom_gesture_start_height_(BottomGestureStartHeight()), - gesture_handler_(gesture_handler), - root_window_(root_window), - current_swipe_(CastSideSwipeOrigin::NONE), - current_pointer_id_(ui::kPointerIdUnknown) { - DCHECK(gesture_handler); - DCHECK(root_window); - root_window_->GetHost()->GetEventSource()->AddEventRewriter(this); -} - -SideSwipeDetector::~SideSwipeDetector() { - root_window_->GetHost()->GetEventSource()->RemoveEventRewriter(this); -} - -CastSideSwipeOrigin SideSwipeDetector::GetDragPosition( - const gfx::Point& point, - const gfx::Rect& screen_bounds) const { - if (point.y() < (screen_bounds.y() + gesture_start_height_)) { - return CastSideSwipeOrigin::TOP; - } - if (point.x() < (screen_bounds.x() + gesture_start_width_)) { - return CastSideSwipeOrigin::LEFT; - } - if (point.x() > - (screen_bounds.x() + screen_bounds.width() - gesture_start_width_)) { - return CastSideSwipeOrigin::RIGHT; - } - if (point.y() > (screen_bounds.y() + screen_bounds.height() - - bottom_gesture_start_height_)) { - return CastSideSwipeOrigin::BOTTOM; - } - return CastSideSwipeOrigin::NONE; -} - -void SideSwipeDetector::StashEvent(const ui::TouchEvent& event) { - // If the time since the gesture start is longer than our threshold, do not - // stash the event (and clear the stashed events). - if (current_swipe_time_.Elapsed() > kGestureMarginEventsTimeLimit) { - stashed_events_.clear(); - return; - } - - stashed_events_.push_back(event); -} - -ui::EventDispatchDetails SideSwipeDetector::RewriteEvent( - const ui::Event& event, - const Continuation continuation) { - if (!event.IsTouchEvent()) { - return SendEvent(continuation, &event); - } - - const ui::TouchEvent* touch_event = event.AsTouchEvent(); - - // Touch events come through in screen pixels, but untransformed. This is the - // raw coordinate not yet mapped to the root window's coordinate system or the - // screen. Convert it into the root window's coordinate system, in DIP which - // is what the rest of this class expects. - gfx::Point touch_location = touch_event->root_location(); - root_window_->GetHost()->ConvertPixelsToDIP(&touch_location); - gfx::Rect screen_bounds = display::Screen::GetScreen() - ->GetDisplayNearestPoint(touch_location) - .bounds(); - CastSideSwipeOrigin side_swipe_origin = - GetDragPosition(touch_location, screen_bounds); - - // A located event has occurred inside the margin. It might be the start of - // our gesture, or a touch that we need to squash. - if (current_swipe_ == CastSideSwipeOrigin::NONE && - side_swipe_origin != CastSideSwipeOrigin::NONE) { - // Check to see if we have any potential consumers of events on this side. - // If not, we can continue on without consuming it. - if (!gesture_handler_->CanHandleSwipe(side_swipe_origin)) { - return SendEvent(continuation, &event); - } - - // Detect the beginning of a system gesture swipe. - if (touch_event->type() != ui::EventType::kTouchPressed) { - return SendEvent(continuation, &event); - } - - current_swipe_ = side_swipe_origin; - current_pointer_id_ = touch_event->pointer_details().id; - - // Let the subscribers know about the gesture begin. - gesture_handler_->HandleSideSwipe(CastSideSwipeEvent::BEGIN, - side_swipe_origin, touch_location); - - DVLOG(1) << "side swipe gesture begin @ " << touch_location.ToString(); - current_swipe_time_ = base::ElapsedTimer(); - - // Stash a copy of the event should we decide to reconstitute it later if we - // decide that this isn't in fact a side swipe. - StashEvent(*touch_event); - - // Avoid corrupt gesture state caused by a missing kGestureScrollEnd event - // as we potentially transition between web views. - root_window_->CleanupGestureState(); - - // And then stop the original event from propagating. - return DiscardEvent(continuation); - } - - // If no swipe in progress, just move on. - if (current_swipe_ == CastSideSwipeOrigin::NONE) { - return SendEvent(continuation, &event); - } - - // If the finger involved is not the one we're looking for, discard it. - if (touch_event->pointer_details().id != current_pointer_id_) { - return DiscardEvent(continuation); - } - - // A swipe is in progress, or has completed, so stop propagation of underlying - // gesture/touch events, after stashing a copy of the original event. - StashEvent(*touch_event); - - // The finger has lifted, which means the end of the gesture, or if the finger - // hasn't travelled far enough, replay the original events. - if (touch_event->type() == ui::EventType::kTouchReleased) { - DVLOG(1) << "gesture release; time since press: " - << current_swipe_time_.Elapsed().InMilliseconds() << "ms @ " - << touch_location.ToString(); - gesture_handler_->HandleSideSwipe(CastSideSwipeEvent::END, current_swipe_, - touch_location); - current_swipe_ = CastSideSwipeOrigin::NONE; - current_pointer_id_ = ui::kPointerIdUnknown; - - // If the finger is still inside the touch margin at release, this is not - // really a side swipe. Stream out events we stashed for later retrieval. - if (side_swipe_origin != CastSideSwipeOrigin::NONE && - !stashed_events_.empty()) { - ui::EventDispatchDetails details; - for (const auto& it : stashed_events_) { - details = SendEvent(continuation, &it); - if (details.dispatcher_destroyed) - break; - } - stashed_events_.clear(); - return details; - } - - // Otherwise, clear them. - stashed_events_.clear(); - return DiscardEvent(continuation); - } - - // The system gesture is ongoing... - gesture_handler_->HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - current_swipe_, touch_location); - DVLOG(1) << "gesture continue; time since press: " - << current_swipe_time_.Elapsed().InMilliseconds() << "ms @ " - << touch_location.ToString(); - - return DiscardEvent(continuation); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/side_swipe_detector.h chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector.h --- chromium-132.0.6834.110/chromecast/graphics/gestures/side_swipe_detector.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_GRAPHICS_GESTURES_SIDE_SWIPE_DETECTOR_H_ -#define CHROMECAST_GRAPHICS_GESTURES_SIDE_SWIPE_DETECTOR_H_ - -#include - -#include "base/timer/elapsed_timer.h" -#include "chromecast/graphics/gestures/cast_gesture_handler.h" -#include "ui/events/event_rewriter.h" - -namespace aura { -class Window; -} // namespace aura - -namespace chromecast { - -// An event rewriter for detecting system-wide gestures performed on the margins -// of the root window. -// Recognizes swipe gestures that originate from the top, left, bottom, and -// right of the root window. Stashes copies of touch events that occur during -// the side swipe, and replays them if the finger releases before leaving the -// margin area. -class SideSwipeDetector : public ui::EventRewriter { - public: - SideSwipeDetector(CastGestureHandler* gesture_handler, - aura::Window* root_window); - - SideSwipeDetector(const SideSwipeDetector&) = delete; - SideSwipeDetector& operator=(const SideSwipeDetector&) = delete; - - ~SideSwipeDetector() override; - - CastSideSwipeOrigin GetDragPosition(const gfx::Point& point, - const gfx::Rect& screen_bounds) const; - - // Overridden from ui::EventRewriter - ui::EventDispatchDetails RewriteEvent( - const ui::Event& event, - const Continuation continuation) override; - - private: - void StashEvent(const ui::TouchEvent& event); - - const int gesture_start_width_; - const int gesture_start_height_; - const int bottom_gesture_start_height_; - - CastGestureHandler* gesture_handler_; - aura::Window* root_window_; - CastSideSwipeOrigin current_swipe_; - ui::PointerId current_pointer_id_; - base::ElapsedTimer current_swipe_time_; - - std::deque stashed_events_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_GRAPHICS_GESTURES_SIDE_SWIPE_DETECTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/graphics/gestures/side_swipe_detector_test.cc chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector_test.cc --- chromium-132.0.6834.110/chromecast/graphics/gestures/side_swipe_detector_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/gestures/side_swipe_detector_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,359 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/graphics/gestures/side_swipe_detector.h" - -#include - -#include "base/run_loop.h" -#include "base/test/simple_test_tick_clock.h" -#include "base/test/test_mock_time_task_runner.h" -#include "base/timer/timer.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/window.h" -#include "ui/events/test/event_generator.h" - -// Gmock matchers and actions that we use below. -using testing::_; -using testing::AnyOf; -using testing::Eq; -using testing::Return; - -namespace chromecast { -namespace test { - -namespace { - -constexpr base::TimeDelta kTimeDelay = base::Milliseconds(100); -constexpr int kSwipeDistance = 50; -constexpr int kNumSteps = 5; -// constexpr gfx::Point kZeroPoint{0, 0}; - -} // namespace - -class MockCastGestureHandler : public CastGestureHandler { - public: - ~MockCastGestureHandler() override = default; - - MOCK_METHOD0(GetPriority, Priority()); - MOCK_METHOD1(CanHandleSwipe, bool(CastSideSwipeOrigin origin)); - MOCK_METHOD3(HandleSideSwipe, - void(CastSideSwipeEvent event, - CastSideSwipeOrigin swipe_origin, - const gfx::Point& touch_location)); - MOCK_METHOD1(HandleTapDownGesture, void(const gfx::Point& touch_location)); - MOCK_METHOD1(HandleTapGesture, void(const gfx::Point& touch_location)); -}; - -// Event sink to check for events that get through (or don't get through) after -// the system gesture handler handles them. -class TestEventHandler : public ui::EventHandler { - public: - TestEventHandler() : EventHandler(), num_touch_events_received_(0) {} - - void OnTouchEvent(ui::TouchEvent* event) override { - num_touch_events_received_++; - } - - int NumTouchEventsReceived() const { return num_touch_events_received_; } - - private: - int num_touch_events_received_; -}; - -class SideSwipeDetectorTest : public aura::test::AuraTestBase { - public: - ~SideSwipeDetectorTest() override = default; - - void SetUp() override { - aura::test::AuraTestBase::SetUp(); - - gesture_handler_ = std::make_unique(); - side_swipe_detector_ = std::make_unique( - gesture_handler_.get(), root_window()); - test_event_handler_ = std::make_unique(); - root_window()->AddPostTargetHandler(test_event_handler_.get()); - - mock_task_runner_ = base::MakeRefCounted( - base::Time::Now(), base::TimeTicks::Now()); - auto mock_timer = std::make_unique( - mock_task_runner_->GetMockTickClock()); - mock_timer->SetTaskRunner(mock_task_runner_); - } - - void TearDown() override { - side_swipe_detector_.reset(); - gesture_handler_.reset(); - - aura::test::AuraTestBase::TearDown(); - } - - void Drag(const gfx::Point& start_point, - const base::TimeDelta& start_hold_time, - const base::TimeDelta& drag_time, - const gfx::Point& end_point, - ui::PointerId pointer_id, - bool end_release = true) { - ui::TouchEvent press( - ui::EventType::kTouchPressed, start_point, mock_clock()->NowTicks(), - ui::PointerDetails(ui::EventPointerType::kTouch, pointer_id)); - GetEventGenerator().Dispatch(&press); - mock_task_runner()->AdvanceMockTickClock(start_hold_time); - mock_task_runner()->FastForwardBy(start_hold_time); - - ui::TouchEvent move( - ui::EventType::kTouchMoved, end_point, mock_clock()->NowTicks(), - ui::PointerDetails(ui::EventPointerType::kTouch, pointer_id)); - GetEventGenerator().Dispatch(&move); - mock_task_runner()->AdvanceMockTickClock(drag_time); - mock_task_runner()->FastForwardBy(drag_time); - - if (end_release) { - ui::TouchEvent release( - ui::EventType::kTouchReleased, end_point, mock_clock()->NowTicks(), - ui::PointerDetails(ui::EventPointerType::kTouch, pointer_id)); - GetEventGenerator().Dispatch(&release); - } - } - - ui::test::EventGenerator& GetEventGenerator() { - if (!event_generator_) { - event_generator_ = - std::make_unique(root_window()); - } - return *event_generator_.get(); - } - - MockCastGestureHandler& mock_gesture_handler() { return *gesture_handler_; } - - base::TestMockTimeTaskRunner* mock_task_runner() const { - return mock_task_runner_.get(); - } - - const base::TickClock* mock_clock() const { - return mock_task_runner_->GetMockTickClock(); - } - - TestEventHandler& test_event_handler() { return *test_event_handler_; } - - private: - std::unique_ptr event_generator_; - scoped_refptr mock_task_runner_; - - std::unique_ptr side_swipe_detector_; - std::unique_ptr test_event_handler_; - std::unique_ptr gesture_handler_; -}; - -// Test that initialization works and initial state is clean. -TEST_F(SideSwipeDetectorTest, Initialization) { - EXPECT_CALL(mock_gesture_handler(), CanHandleSwipe(_)) - .WillRepeatedly(Return(false)); - EXPECT_CALL(mock_gesture_handler(), HandleSideSwipe(_, _, _)).Times(0); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(0, test_event_handler().NumTouchEventsReceived()); -} - -// A swipe in the middle of the screen should produce no system gesture. -TEST_F(SideSwipeDetectorTest, SwipeWithNoSystemGesture) { - gfx::Point drag_point(root_window()->bounds().width() / 2, - root_window()->bounds().height() / 2); - ui::test::EventGenerator& generator = GetEventGenerator(); - generator.GestureScrollSequence(drag_point, - drag_point - gfx::Vector2d(0, kSwipeDistance), - kTimeDelay, kNumSteps); - - EXPECT_CALL(mock_gesture_handler(), CanHandleSwipe(_)) - .WillRepeatedly(Return(false)); - EXPECT_CALL(mock_gesture_handler(), HandleSideSwipe(_, _, _)).Times(0); - base::RunLoop().RunUntilIdle(); - EXPECT_NE(0, test_event_handler().NumTouchEventsReceived()); -} - -TEST_F(SideSwipeDetectorTest, SwipeFromLeft) { - gfx::Point drag_point(0, root_window()->bounds().height() / 2); - auto end_point = drag_point + gfx::Vector2d(kSwipeDistance, 0); - - EXPECT_CALL(mock_gesture_handler(), - CanHandleSwipe(Eq(CastSideSwipeOrigin::LEFT))) - .WillRepeatedly(Return(true)); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::BEGIN, - Eq(CastSideSwipeOrigin::LEFT), drag_point)) - .Times(1); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - Eq(CastSideSwipeOrigin::LEFT), _)) - .Times(kNumSteps); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::END, - Eq(CastSideSwipeOrigin::LEFT), end_point)) - .Times(1); - - ui::test::EventGenerator& generator = GetEventGenerator(); - generator.GestureScrollSequence(drag_point, end_point, kTimeDelay, kNumSteps); - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(0, test_event_handler().NumTouchEventsReceived()); -} - -TEST_F(SideSwipeDetectorTest, SwipeFromRight) { - gfx::Point drag_point(root_window()->bounds().width(), - root_window()->bounds().height() / 2); - auto end_point = drag_point - gfx::Vector2d(kSwipeDistance, 0); - - EXPECT_CALL(mock_gesture_handler(), - CanHandleSwipe(Eq(CastSideSwipeOrigin::RIGHT))) - .WillRepeatedly(Return(true)); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::BEGIN, - Eq(CastSideSwipeOrigin::RIGHT), drag_point)) - .Times(1); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - Eq(CastSideSwipeOrigin::RIGHT), _)) - .Times(kNumSteps); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::END, - Eq(CastSideSwipeOrigin::RIGHT), end_point)) - .Times(1); - - ui::test::EventGenerator& generator = GetEventGenerator(); - generator.GestureScrollSequence(drag_point, end_point, kTimeDelay, kNumSteps); - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(0, test_event_handler().NumTouchEventsReceived()); -} - -TEST_F(SideSwipeDetectorTest, SwipeFromTop) { - gfx::Point drag_point(root_window()->bounds().width() / 2, 0); - auto end_point = drag_point + gfx::Vector2d(0, kSwipeDistance); - - EXPECT_CALL(mock_gesture_handler(), - CanHandleSwipe(Eq(CastSideSwipeOrigin::TOP))) - .WillRepeatedly(Return(true)); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::BEGIN, - Eq(CastSideSwipeOrigin::TOP), drag_point)) - .Times(1); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - Eq(CastSideSwipeOrigin::TOP), _)) - .Times(kNumSteps); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::END, - Eq(CastSideSwipeOrigin::TOP), end_point)) - .Times(1); - - ui::test::EventGenerator& generator = GetEventGenerator(); - generator.GestureScrollSequence(drag_point, end_point, kTimeDelay, kNumSteps); - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(0, test_event_handler().NumTouchEventsReceived()); -} - -TEST_F(SideSwipeDetectorTest, SwipeFromBottom) { - gfx::Point drag_point(root_window()->bounds().width() / 2, - root_window()->bounds().height()); - auto end_point = drag_point - gfx::Vector2d(0, kSwipeDistance); - - EXPECT_CALL(mock_gesture_handler(), - CanHandleSwipe(Eq(CastSideSwipeOrigin::BOTTOM))) - .WillRepeatedly(Return(true)); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::BEGIN, - Eq(CastSideSwipeOrigin::BOTTOM), drag_point)) - .Times(1); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - Eq(CastSideSwipeOrigin::BOTTOM), _)) - .Times(kNumSteps); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::END, - Eq(CastSideSwipeOrigin::BOTTOM), end_point)) - .Times(1); - - ui::test::EventGenerator& generator = GetEventGenerator(); - generator.GestureScrollSequence(drag_point, end_point, kTimeDelay, kNumSteps); - - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(0, test_event_handler().NumTouchEventsReceived()); -} - -TEST_F(SideSwipeDetectorTest, SwipeUnhandledIgnored) { - gfx::Point drag_point(root_window()->bounds().width() / 2, - root_window()->bounds().height()); - auto end_point = drag_point - gfx::Vector2d(0, kSwipeDistance); - - EXPECT_CALL(mock_gesture_handler(), - CanHandleSwipe(Eq(CastSideSwipeOrigin::BOTTOM))) - .WillRepeatedly(Return(false)); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::BEGIN, - Eq(CastSideSwipeOrigin::BOTTOM), drag_point)) - .Times(0); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - Eq(CastSideSwipeOrigin::BOTTOM), _)) - .Times(0); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::END, - Eq(CastSideSwipeOrigin::BOTTOM), end_point)) - .Times(0); - - ui::test::EventGenerator& generator = GetEventGenerator(); - generator.GestureScrollSequence(drag_point, end_point, kTimeDelay, kNumSteps); - - base::RunLoop().RunUntilIdle(); - EXPECT_NE(0, test_event_handler().NumTouchEventsReceived()); -} - -// Test that a second gesture while the first is still in process will be -// ignored. -TEST_F(SideSwipeDetectorTest, IgnoreSecondFinger) { - gfx::Point drag_point(root_window()->bounds().width() / 2, - root_window()->bounds().height()); - auto end_point = drag_point - gfx::Vector2d(0, kSwipeDistance); - - EXPECT_CALL(mock_gesture_handler(), - CanHandleSwipe(Eq(CastSideSwipeOrigin::BOTTOM))) - .WillRepeatedly(Return(true)); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::BEGIN, - Eq(CastSideSwipeOrigin::BOTTOM), drag_point)) - .Times(1); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::CONTINUE, - Eq(CastSideSwipeOrigin::BOTTOM), _)) - .Times(1); - EXPECT_CALL(mock_gesture_handler(), - HandleSideSwipe(CastSideSwipeEvent::END, - Eq(CastSideSwipeOrigin::BOTTOM), end_point)) - .Times(0); - - // Start a drag but don't complete. - Drag(drag_point, base::Milliseconds(10) /*start_hold_time */, - base::Milliseconds(1000) /* drag_time */, end_point, 1 /* pointer_id */, - false /* end_release */); - - // A second drag is started with another finger, but will be ignored as a - // swipe and all its events eaten. - Drag(drag_point, base::Milliseconds(10) /*start_hold_time */, - base::Milliseconds(1000) /* drag_time */, end_point, 2 /* pointer_id */, - true /* end_release */); - - base::RunLoop().RunUntilIdle(); - - // There should be no events generated, even by the second finger. - EXPECT_EQ(0, test_event_handler().NumTouchEventsReceived()); -} - -} // namespace test -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/graphics_properties_default.cc chromium-132.0.6834.159/chromecast/graphics/graphics_properties_default.cc --- chromium-132.0.6834.110/chromecast/graphics/graphics_properties_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/graphics_properties_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// 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 "base/command_line.h" -#include "base/notreached.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/init_command_line_shlib.h" -#include "chromecast/public/graphics_properties_shlib.h" - -namespace chromecast { - -bool GraphicsPropertiesShlib::IsSupported( - Resolution resolution, - const std::vector& argv) { - InitCommandLineShlib(argv); - switch (resolution) { - case Resolution::k1080p: - return base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDesktopWindow1080p); - case Resolution::kUHDTV: - return false; - default: - NOTREACHED(); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/osd_plane_default.cc chromium-132.0.6834.159/chromecast/graphics/osd_plane_default.cc --- chromium-132.0.6834.110/chromecast/graphics/osd_plane_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/osd_plane_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -// 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 - -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/osd_plane.h" -#include "chromecast/public/osd_plane_shlib.h" -#include "chromecast/public/osd_surface.h" - -namespace chromecast { -namespace { - -// Default no-op OsdSurface implementation -class OsdSurfaceDefault : public OsdSurface { - public: - OsdSurfaceDefault(const Size& size) : size_(size) {} - - OsdSurfaceDefault(const OsdSurfaceDefault&) = delete; - OsdSurfaceDefault& operator=(const OsdSurfaceDefault&) = delete; - - // OsdSurface implementation: - void Blit(OsdSurface* src_surface, - const Rect& src_rect, - const Point& dst_point) override {} - void Composite(OsdSurface* src_surface, - const Rect& src_rect, - const Point& dst_point) override {} - void CopyBitmap(char* src_bitmap, - const Rect& src_rect, - const Rect& damage_rect, - const Point& dst_point) override {} - void Fill(const Rect& rect, int argb) override {} - - const Size& size() const override { return size_; } - - private: - const Size size_; -}; - -// Default no-op OsdPlane implementation -class OsdPlaneDefault : public OsdPlane { - public: - OsdPlaneDefault() : size_(0, 0) {} - - OsdPlaneDefault(const OsdPlaneDefault&) = delete; - OsdPlaneDefault& operator=(const OsdPlaneDefault&) = delete; - - // OsdPlane implementation: - OsdSurface* CreateSurface(const Size& size) override { - return new OsdSurfaceDefault(size); - } - void SetClipRectangle(const Rect& rect, - const Size& screen_res, - float output_scale) override { - size_ = Size(rect.width, rect.height); - } - OsdSurface* GetBackBuffer() override { - if (!back_buffer_) - back_buffer_.reset(new OsdSurfaceDefault(size_)); - return back_buffer_.get(); - } - - void Flip() override {} - - private: - std::unique_ptr back_buffer_; - Size size_; -}; - -} // namespace - -OsdPlane* OsdPlaneShlib::Create(const std::vector& argv) { - return new OsdPlaneDefault; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/graphics/run_all_unittests.cc chromium-132.0.6834.159/chromecast/graphics/run_all_unittests.cc --- chromium-132.0.6834.110/chromecast/graphics/run_all_unittests.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/graphics/run_all_unittests.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/functional/bind.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "mojo/core/embedder/embedder.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/accessibility/platform/provide_ax_platform_for_tests.h" -#include "ui/aura/env.h" -#include "ui/gl/test/gl_surface_test_support.h" - -class ChromecastGraphicsTestSuite : public base::TestSuite { - public: - ChromecastGraphicsTestSuite(int argc, char** argv) - : base::TestSuite(argc, argv) {} - - ChromecastGraphicsTestSuite(const ChromecastGraphicsTestSuite&) = delete; - ChromecastGraphicsTestSuite& operator=(const ChromecastGraphicsTestSuite&) = - delete; - - protected: - void Initialize() override { - base::TestSuite::Initialize(); - gl::GLSurfaceTestSupport::InitializeOneOff(); - - env_ = aura::Env::CreateInstance(); - testing::UnitTest::GetInstance()->listeners().Append( - new ui::ProvideAXPlatformForTests()); - } - - void Shutdown() override { - env_.reset(); - base::TestSuite::Shutdown(); - } - - private: - std::unique_ptr env_; -}; - -int main(int argc, char** argv) { - ChromecastGraphicsTestSuite test_suite(argc, argv); - - mojo::core::Init(); - - return base::LaunchUnitTests(argc, argv, - base::BindOnce(&ChromecastGraphicsTestSuite::Run, - base::Unretained(&test_suite))); -} diff -Nru chromium-132.0.6834.110/chromecast/media/DEPS chromium-132.0.6834.159/chromecast/media/DEPS --- chromium-132.0.6834.110/chromecast/media/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -include_rules = [ - "+chromecast/common/mojom", - "+chromecast/external_mojo", - "+chromecast/net/socket_util.h", - "+content/public/renderer", - "+media", - "+media/audio", - "+media/base", - "+media/cdm", - "+media/filters", - "+media/mojo/mojom", - "+mojo/core/embedder/embedder.h", - "+mojo/public/cpp/bindings", - "+mojo/public/cpp/platform/platform_handle.h", - "+net/base/io_buffer.h", - "+net/base/net_errors.h", - "+net/socket/stream_socket.h", - "+ui/gfx/geometry", - "+ui/gfx/hdr_metadata.h", - "+ui/gfx/overlay_transform.h", - "+services/service_manager/public", - "+third_party/blink/public/common/tokens/tokens.h", - "+third_party/blink/public/platform/audio/web_audio_device_source_type.h", - "+third_party/blink/public/platform/browser_interface_broker_proxy.h", - "+third_party/blink/public/web/modules/media/audio/audio_device_factory.h", - "+third_party/blink/public/web/modules/media/audio/audio_output_ipc_factory.h", - "+third_party/blink/public/web/web_local_frame.h", - "+third_party/widevine/cdm/buildflags.h", - "+third_party/widevine/cdm/widevine_cdm_common.h", -] diff -Nru chromium-132.0.6834.110/chromecast/media/OWNERS chromium-132.0.6834.159/chromecast/media/OWNERS --- chromium-132.0.6834.110/chromecast/media/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -kmackay@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/media/api/audio_clock_simulator.h chromium-132.0.6834.159/chromecast/media/api/audio_clock_simulator.h --- chromium-132.0.6834.110/chromecast/media/api/audio_clock_simulator.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/audio_clock_simulator.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_AUDIO_CLOCK_SIMULATOR_H_ -#define CHROMECAST_MEDIA_API_AUDIO_CLOCK_SIMULATOR_H_ - -#include -#include -#include - -#include "chromecast/media/api/audio_provider.h" - -namespace chromecast { -namespace media { - -// Simulates a modifiable audio output clock rate by resampling. Note that this -// will always provide audio (FillFrames() always fills the entire buffer), -// even if the upstream provider does not provide any data. -class AudioClockSimulator : public AudioProvider { - public: - static std::unique_ptr Create(AudioProvider* provider); - - // Sets the simulated audio clock rate. Returns the effective rate. - virtual double SetRate(double rate) = 0; - - // Returns the number of frames of additional delay due to audio stored - // internally. - virtual double DelayFrames() const = 0; - - // Sets a new playback sample rate. Needed to calculate timestamps correctly. - virtual void SetSampleRate(int sample_rate) = 0; - - // Sets the playback rate (rate at which samples are played out relative to - // the sample rate). Needed to calculate timestamps correctly. - virtual void SetPlaybackRate(double playback_rate) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_AUDIO_CLOCK_SIMULATOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/audio_provider.h chromium-132.0.6834.159/chromecast/media/api/audio_provider.h --- chromium-132.0.6834.110/chromecast/media/api/audio_provider.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/audio_provider.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_AUDIO_PROVIDER_H_ -#define CHROMECAST_MEDIA_API_AUDIO_PROVIDER_H_ - -#include - -namespace chromecast { -namespace media { - -// Abstract interface for classes that provide audio data. -class AudioProvider { - public: - // Fills in |channel_data| with up to |num_frames| frames of audio. - // The |playout_timestamp| indicates when the first sample of the filled audio - // is expected to play out. Returns the number of frames actually filled; - // implementations should try to fill as much audio as possible. - virtual int FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) = 0; - - // Returns the number of audio channels and the sample rate of the provider. - // Used for DCHECKing only; all callers of a provider must use the same - // channel count and sample rate as the provider. - virtual size_t num_channels() const = 0; - virtual int sample_rate() const = 0; - - protected: - virtual ~AudioProvider() = default; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_AUDIO_PROVIDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/cast_audio_decoder.h chromium-132.0.6834.159/chromecast/media/api/cast_audio_decoder.h --- chromium-132.0.6834.110/chromecast/media/api/cast_audio_decoder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/cast_audio_decoder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_API_CAST_AUDIO_DECODER_H_ -#define CHROMECAST_MEDIA_API_CAST_AUDIO_DECODER_H_ - -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/public/media/decoder_config.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -namespace media { - -// Audio decoder interface. -class CastAudioDecoder { - public: - enum Status { - kDecodeOk, - kDecodeError, - }; - - enum OutputFormat { - kOutputSigned16, // Output signed 16-bit interleaved samples. - kOutputPlanarFloat, // Output planar float samples. - }; - - // Callback called when a buffer has been decoded. |config| is the actual - // config of the buffer, which may differ from the config indicated by the - // wrapper format. - typedef base::OnceCallback decoded)> - DecodeCallback; - - // Creates a CastAudioDecoder instance for the given |config|. Decoding must - // occur on the same thread as |task_runner|. Returns an empty unique_ptr if - // the decoder could not be created. - static std::unique_ptr Create( - scoped_refptr task_runner, - const media::AudioConfig& config, - OutputFormat output_format); - - // Given a CastAudioDecoder::OutputFormat, return the size of each sample in - // that OutputFormat in bytes. - static int OutputFormatSizeInBytes(CastAudioDecoder::OutputFormat format); - - virtual ~CastAudioDecoder() = default; - - // Returns the expected config of the next decoded audio. Note that the config - // may change as more audio is decoded. - virtual const AudioConfig& GetOutputConfig() const = 0; - - // Converts encoded data to the |output_format|. Must be called on the same - // thread as |task_runner|. Decoded data will be passed to |decode_callback|. - // The |decode_callback| will not be called after the CastAudioDecoder - // instance is destroyed. It is OK to pass an end-of-stream DecoderBuffer as - // |data|. - virtual void Decode(scoped_refptr data, - DecodeCallback decode_callback) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_CAST_AUDIO_DECODER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/cast_audio_demuxer.h chromium-132.0.6834.159/chromecast/media/api/cast_audio_demuxer.h --- chromium-132.0.6834.110/chromecast/media/api/cast_audio_demuxer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/cast_audio_demuxer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_API_CAST_AUDIO_DEMUXER_H_ -#define CHROMECAST_MEDIA_API_CAST_AUDIO_DEMUXER_H_ - -#include - -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/public/media/decoder_config.h" - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -// Demuxes an audio container and provides audio config and buffers that can be -// used to play the audio via the CMA backend. Must be created and destroyed on -// the same thread, and all methods must be called on that thread. -class CastAudioDemuxer { - public: - class Delegate { - public: - // Called with the audio config for the audio resource. Always called before - // OnDemuxedAudioBuffer() and never called more than once. - virtual void OnDemuxedAudioConfig(const AudioConfig& config) {} - - // Called for each buffer read from the audio resource. This may be called - // multiple times, and the last call will pass an end-of-stream buffer - // unless an error occurs. - virtual void OnDemuxedAudioBuffer(scoped_refptr buffer) { - } - - // Called with the duration of the audio resource after the entire audio - // resource has been read. No more methods will be called after this. It is - // safe to destroy the CastAudioDemuxer in this callback. - virtual void OnDemuxComplete(base::TimeDelta duration) = 0; - - // Called when the audio resource could not be read due to an error. No more - // methods will be called after this. It is safe to destroy the - // CastAudioDemuxer in this callback. - virtual void OnDemuxError() = 0; - - protected: - virtual ~Delegate() = default; - }; - - virtual ~CastAudioDemuxer() = default; - - // Creates a CastAudioDemuxer instance for the given |audio_data|. - // |audio_data| must outlive the demuxer. - static std::unique_ptr Create(std::string_view audio_data, - Delegate* delegate); - - // Sets the base timestamp for the audio buffers passed to - // OnDemuxedAudioBuffer() on the delegate so that the first buffer has a - // timestamp equal to |timestamp| and the timestamps of all subsequent buffers - // are adjusted accordingly. Must not be called after Demux(). - virtual void SetBaseTimestamp(base::TimeDelta timestamp) = 0; - - // Demuxes the audio data. May be called only once. Unless an error occurs, - // this triggers a call to OnDemuxedAudioConfig() on the delegate followed by - // one or more calls to OnDemuxedAudioBuffer() and finally a call to - // OnDemuxComplete(), after which no more methods will be called. If an error - // occurs, OnDemuxError() will be called and no more methods will be called. - virtual void Demux() = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_CAST_AUDIO_DEMUXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/cast_audio_resampler.h chromium-132.0.6834.159/chromecast/media/api/cast_audio_resampler.h --- chromium-132.0.6834.110/chromecast/media/api/cast_audio_resampler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/cast_audio_resampler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_API_CAST_AUDIO_RESAMPLER_H_ -#define CHROMECAST_MEDIA_API_CAST_AUDIO_RESAMPLER_H_ - -#include -#include - -namespace chromecast { -namespace media { - -// Audio resampler interface. -class CastAudioResampler { - public: - // Creates a CastAudioResampler instance. - static std::unique_ptr Create(int channel_count, - int input_sample_rate, - int output_sample_rate); - - virtual ~CastAudioResampler() = default; - - // Resamples |input|, which is assumed to be in planar float format, appending - // the resampled audio in planar float format into |output_channels|, which is - // an array of |channel_count| vectors (one per channel). Note that some - // audio from |input| may be stored internally and will not be output until - // the next call to Resample() or Flush(). - virtual void Resample(const float* input, - int num_frames, - std::vector* output_channels) = 0; - - // Resamples any internally-buffered input audio, filling with silence as - // necessary. The resampled audio is appended in planar float format into - // |output_channels|, which is an array of |channel_count| vectors (one per - // channel). - virtual void Flush(std::vector* output_channels) = 0; - - // Returns the number of input frames that are buffered internally (ie, have - // not yet been resampled into output). - virtual int BufferedInputFrames() const = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_CAST_AUDIO_RESAMPLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/cast_channel_mixer.h chromium-132.0.6834.159/chromecast/media/api/cast_channel_mixer.h --- chromium-132.0.6834.110/chromecast/media/api/cast_channel_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/cast_channel_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_CAST_CHANNEL_MIXER_H_ -#define CHROMECAST_MEDIA_API_CAST_CHANNEL_MIXER_H_ - -#include - -#include "chromecast/public/media/decoder_config.h" - -namespace chromecast { -namespace media { - -// Channel mixer to convert audio between different channel layouts. -class CastChannelMixer { - public: - static std::unique_ptr Create(ChannelLayout input, - ChannelLayout output); - - virtual ~CastChannelMixer() = default; - - // Change the channel counts for |input|. |input| should be prepared in planar - // float format. The returned value points to an array that is owned by this - // class, also in planar float format. The returned data is only valid until - // the next call. - virtual const float* Transform(const float* input, int num_frames) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_CAST_CHANNEL_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/cast_sounds_manager.h chromium-132.0.6834.159/chromecast/media/api/cast_sounds_manager.h --- chromium-132.0.6834.110/chromecast/media/api/cast_sounds_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/cast_sounds_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_API_CAST_SOUNDS_MANAGER_H_ -#define CHROMECAST_MEDIA_API_CAST_SOUNDS_MANAGER_H_ - -#include - -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -// Plays a sound stored as a resource. All methods are thread-safe. -class CastSoundsManager { - public: - using DurationCallback = base::OnceCallback; - - virtual ~CastSoundsManager() = default; - - // Adds a sound where |resource_id| contains the audio data. If |multichannel| - // is true, the sound is played on all devices in a multichannel group, and if - // it is false, the sound is played only on this device. If |repeat| is true, - // the sound is played repeatedly until Stop() is called for the sound or - // another sound is played. Both |multichannel| and |repeat| cannot be true. - virtual void AddSound(int key, - int resource_id, - bool multichannel, - bool repeat) = 0; - - // Adds a sound by binding |key| to the provided |audio_data|. - // This is to support playing sounds outside of resource packs on the - // device(s). If |multichannel| is true, the sound is played on all devices in - // a multichannel group, and if it is false, the sound is played only on this - // device. If |repeat| is true, the sound is played repeatedly until Stop() is - // called for the sound or another sound is played. |multichannel| and - // |repeat| cannot both be true. - virtual void AddSoundWithAudioData(int key, - const std::string audio_data, - bool multichannel, - bool repeat) = 0; - - // Plays the sound added for |key|. - virtual void Play(int key, AudioContentType content_type) = 0; - - // Stops playing the sound added for |key| if it is currently playing. - virtual void Stop(int key) = 0; - - // Calls |callback| with the duration of the sound added for |key|, or a - // duration of ::media::kInfiniteDuration if no sound was added for |key|. - // There is no guarantee about whether |callback| is called synchronously or - // asynchronously or on which thread it is called. - virtual void GetDuration(int key, DurationCallback callback) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_CAST_SOUNDS_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/cma_backend.h chromium-132.0.6834.159/chromecast/media/api/cma_backend.h --- chromium-132.0.6834.110/chromecast/media/api/cma_backend.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/cma_backend.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,111 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_CMA_BACKEND_H_ -#define CHROMECAST_MEDIA_API_CMA_BACKEND_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -namespace media { - -// Interface for the media backend used by the CMA pipeline. The implementation -// is selected by CmaBackendFactory. MediaPipelineBackend is a lower-level -// interface used to abstract the platform, with a separate implementation for -// each platform, while CmaBackend implementations are used across multiple -// platforms. -class CmaBackend { - public: - using BufferStatus = MediaPipelineBackend::BufferStatus; - - class Decoder { - public: - using BufferStatus = MediaPipelineBackend::BufferStatus; - using Delegate = MediaPipelineBackend::Decoder::Delegate; - - // These methods have the same behavior as the corresponding methods on - // MediaPipelineBackend::Decoder. - // See chromecast/public/media/media_pipeline_backend.h for documentation. - virtual void SetDelegate(Delegate* delegate) = 0; - - // Pushes buffer to decoder. A new |buffer| should be used for each call - // and should not be mutated by the caller. - virtual BufferStatus PushBuffer( - scoped_refptr buffer) = 0; - - protected: - virtual ~Decoder() = default; - }; - - class AudioDecoder : public Decoder { - public: - using RenderingDelay = MediaPipelineBackend::AudioDecoder::RenderingDelay; - using Statistics = MediaPipelineBackend::AudioDecoder::Statistics; - using AudioTrackTimestamp = - MediaPipelineBackend::AudioDecoder::AudioTrackTimestamp; - - // These methods have the same behavior as the corresponding methods on - // MediaPipelineBackend::AudioDecoder. - // See chromecast/public/media/media_pipeline_backend.h for documentation. - virtual bool SetConfig(const AudioConfig& config) = 0; - virtual bool SetVolume(float multiplier) = 0; - virtual RenderingDelay GetRenderingDelay() = 0; - virtual void GetStatistics(Statistics* statistics) = 0; - virtual AudioTrackTimestamp GetAudioTrackTimestamp() = 0; - virtual int GetStartThresholdInFrames() = 0; - - // Returns true if the audio decoder requires that encrypted buffers be - // decrypted before being passed to PushBuffer(). The return value may - // change whenever SetConfig() is called or the backend is initialized. - virtual bool RequiresDecryption() = 0; - - protected: - ~AudioDecoder() override = default; - }; - - class VideoDecoder : public Decoder { - public: - using Statistics = MediaPipelineBackend::VideoDecoder::Statistics; - - // These methods have the same behavior as the corresponding methods on - // MediaPipelineBackend::VideoDecoder. - // See chromecast/public/media/media_pipeline_backend.h for documentation. - virtual bool SetConfig(const VideoConfig& config) = 0; - virtual void GetStatistics(Statistics* statistics) = 0; - - protected: - ~VideoDecoder() override = default; - }; - - virtual ~CmaBackend() = default; - - // These methods have the same behavior as the corresponding methods on - // MediaPipelineBackend. See chromecast/public/media/media_pipeline_backend.h - // for documentation. - virtual AudioDecoder* CreateAudioDecoder() = 0; - virtual VideoDecoder* CreateVideoDecoder() = 0; - virtual bool Initialize() = 0; - virtual bool Start(int64_t start_pts) = 0; - virtual void Stop() = 0; - virtual bool Pause() = 0; - virtual bool Resume() = 0; - virtual int64_t GetCurrentPts() = 0; - virtual bool SetPlaybackRate(float rate) = 0; - - // Logically pauses/resumes a backend instance, without actually pausing or - // resuming it. This is used by multiroom output to avoid playback stutter on - // resume. - virtual void LogicalPause() = 0; - virtual void LogicalResume() = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_CMA_BACKEND_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/cma_backend_factory.h chromium-132.0.6834.159/chromecast/media/api/cma_backend_factory.h --- chromium-132.0.6834.110/chromecast/media/api/cma_backend_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/cma_backend_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_CMA_BACKEND_FACTORY_H_ -#define CHROMECAST_MEDIA_API_CMA_BACKEND_FACTORY_H_ - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/external_mojo/external_service_support/external_connector.h" - -namespace chromecast { -namespace media { - -class CmaBackend; -class MediaPipelineBackendManager; -struct MediaPipelineDeviceParams; - -// Abstract base class to create CmaBackend. -class CmaBackendFactory { - public: - static std::unique_ptr Create( - MediaPipelineBackendManager* media_pipeline_backend_manager, - std::unique_ptr connector); - - virtual ~CmaBackendFactory() = default; - - // Creates a CMA backend. Must be called on the same thread as - // |media_task_runner_|. - virtual std::unique_ptr CreateBackend( - const MediaPipelineDeviceParams& params) = 0; - - // Returns |media_task_runner_|. - virtual scoped_refptr GetMediaTaskRunner() = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_CMA_BACKEND_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/decoder_buffer_base.h chromium-132.0.6834.159/chromecast/media/api/decoder_buffer_base.h --- chromium-132.0.6834.110/chromecast/media/api/decoder_buffer_base.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/decoder_buffer_base.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_DECODER_BUFFER_BASE_H_ -#define CHROMECAST_MEDIA_API_DECODER_BUFFER_BASE_H_ - -#include - -#include -#include - -#include "base/memory/ref_counted.h" -#include "base/time/time.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/public/media/decrypt_context.h" - -namespace chromecast { -namespace media { - -// DecoderBufferBase exposes only the properties of an audio/video buffer. -// The way a DecoderBufferBase is created and organized in memory -// is left as a detail of the implementation of derived classes. -class DecoderBufferBase : public CastDecoderBuffer, - public base::RefCountedThreadSafe { - public: - // Partial CastDecoderBuffer implementation: - DecryptContext* decrypt_context() const override; - - void set_decrypt_context(std::unique_ptr context) { - decrypt_context_ = std::move(context); - } - - // Sets the PTS of the frame. - virtual void set_timestamp(base::TimeDelta timestamp) = 0; - - // Gets a pointer to the frame data buffer. - virtual uint8_t* writable_data() const = 0; - - protected: - friend class base::RefCountedThreadSafe; - - DecoderBufferBase(); - ~DecoderBufferBase() override; - - private: - std::unique_ptr decrypt_context_; - - DecoderBufferBase(const DecoderBufferBase&) = delete; - DecoderBufferBase& operator=(const DecoderBufferBase&) = delete; -}; - -inline DecoderBufferBase::DecoderBufferBase() {} - -inline DecoderBufferBase::~DecoderBufferBase() {} - -inline DecryptContext* DecoderBufferBase::decrypt_context() const { - return decrypt_context_.get(); -} - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_DECODER_BUFFER_BASE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/monotonic_clock.h chromium-132.0.6834.159/chromecast/media/api/monotonic_clock.h --- chromium-132.0.6834.110/chromecast/media/api/monotonic_clock.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/monotonic_clock.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_MONOTONIC_CLOCK_H_ -#define CHROMECAST_MEDIA_API_MONOTONIC_CLOCK_H_ - -#include - -#include - -namespace chromecast { -namespace media { - -// Interface that provides the monotonic time. -class MonotonicClock { - public: - static std::unique_ptr Create(); - - virtual ~MonotonicClock() = default; - // Returns the monotonic time in microseconds. - virtual int64_t Now() const = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_MONOTONIC_CLOCK_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/sound_player.h chromium-132.0.6834.159/chromecast/media/api/sound_player.h --- chromium-132.0.6834.110/chromecast/media/api/sound_player.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/sound_player.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_API_SOUND_PLAYER_H_ -#define CHROMECAST_MEDIA_API_SOUND_PLAYER_H_ - -#include -#include -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -class SoundPlayer { - public: - using AudioData = base::RefCountedData; - - // Plays the sound resource with |resource_id|. Any sound that is currently - // playing is stopped. Once played, audio data is registered with a - // |sound_key| so the Stop() function can later identify which sound should be - // stopped. If |repeat| is true, the sound is repeated until Stop() is called - // with the same |sound_key| or another sound is played. - virtual void Play(int sound_key, - int resource_id, - bool repeat, - AudioContentType content_type) = 0; - - // Plays the sound using the provided |audio_data|. - // Once played, audio data is registered with a |sound_key| so the Stop() - // function can later identify which sound should be stopped. If |repeat| is - // true, the sound is repeated until Stop() is called with the same - // |sound_key| or another sound is played. - virtual void PlayAudioData(int sound_key, - scoped_refptr audio_data, - bool repeat, - AudioContentType content_type) = 0; - - // Plays the sound resource with |resource_id| starting at |timestamp|. - // Any sound that is currently playing is stopped immediately. - // If |audio_channel| is kLeft or kRight, only that channel is played. - virtual void PlayAtTime(int resource_id, - int64_t timestamp, - media::AudioChannel audio_channel, - AudioContentType content_type) = 0; - - // Plays the sound using the provided |audio_data| starting at |timestamp|. - // Any sound that is currently playing is stopped immediately. - // If |audio_channel| is kLeft or kRight, only that channel is played. - virtual void PlayAudioDataAtTime(scoped_refptr audio_data, - int64_t timestamp, - AudioChannel audio_channel, - AudioContentType content_type) = 0; - - // Stops playing the sound resource with |resource_id| if it is currently - // playing. - virtual void Stop(int resource_id) = 0; - - protected: - virtual ~SoundPlayer() = default; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_SOUND_PLAYER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/test/mock_cast_sounds_manager.cc chromium-132.0.6834.159/chromecast/media/api/test/mock_cast_sounds_manager.cc --- chromium-132.0.6834.110/chromecast/media/api/test/mock_cast_sounds_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/test/mock_cast_sounds_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// 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 "chromecast/media/api/test/mock_cast_sounds_manager.h" - -namespace chromecast { -namespace media { - -MockCastSoundsManager::MockCastSoundsManager() = default; - -MockCastSoundsManager::~MockCastSoundsManager() = default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/api/test/mock_cast_sounds_manager.h chromium-132.0.6834.159/chromecast/media/api/test/mock_cast_sounds_manager.h --- chromium-132.0.6834.110/chromecast/media/api/test/mock_cast_sounds_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/test/mock_cast_sounds_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_API_TEST_MOCK_CAST_SOUNDS_MANAGER_H_ -#define CHROMECAST_MEDIA_API_TEST_MOCK_CAST_SOUNDS_MANAGER_H_ - -#include - -#include "base/functional/callback.h" -#include "chromecast/media/api/cast_sounds_manager.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace media { - -class MockCastSoundsManager : public CastSoundsManager { - public: - MockCastSoundsManager(); - ~MockCastSoundsManager() override; - MOCK_METHOD4(AddSound, void(int, int, bool, bool)); - MOCK_METHOD4(AddSoundWithAudioData, void(int, const std::string, bool, bool)); - MOCK_METHOD2(Play, void(int, AudioContentType)); - MOCK_METHOD1(Stop, void(int)); - void GetDuration(int key, DurationCallback callback) override { - DoGetDuration(key, &callback); - } - MOCK_METHOD2(DoGetDuration, void(int, DurationCallback*)); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_TEST_MOCK_CAST_SOUNDS_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/test/mock_cma_backend.cc chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend.cc --- chromium-132.0.6834.110/chromecast/media/api/test/mock_cma_backend.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/api/test/mock_cma_backend.h" - -namespace chromecast { -namespace media { - -MockCmaBackend::DecoderDelegate::DecoderDelegate() = default; -MockCmaBackend::DecoderDelegate::~DecoderDelegate() = default; - -MockCmaBackend::AudioDecoder::AudioDecoder() = default; -MockCmaBackend::AudioDecoder::~AudioDecoder() = default; - -MockCmaBackend::VideoDecoder::VideoDecoder() = default; -MockCmaBackend::VideoDecoder::~VideoDecoder() = default; - -MockCmaBackend::MockCmaBackend() = default; -MockCmaBackend::~MockCmaBackend() = default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/api/test/mock_cma_backend.h chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend.h --- chromium-132.0.6834.110/chromecast/media/api/test/mock_cma_backend.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_TEST_MOCK_CMA_BACKEND_H_ -#define CHROMECAST_MEDIA_API_TEST_MOCK_CMA_BACKEND_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/public/graphics_types.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace media { - -class MockCmaBackend : public CmaBackend { - public: - class DecoderDelegate : public CmaBackend::Decoder::Delegate { - public: - DecoderDelegate(); - ~DecoderDelegate() override; - MOCK_METHOD1(OnPushBufferComplete, void(BufferStatus)); - MOCK_METHOD0(OnEndOfStream, void()); - MOCK_METHOD0(OnDecoderError, void()); - MOCK_METHOD3(OnKeyStatusChanged, - void(const std::string&, CastKeyStatus, uint32_t)); - MOCK_METHOD1(OnVideoResolutionChanged, void(const Size&)); - }; - - class AudioDecoder : public CmaBackend::AudioDecoder { - public: - AudioDecoder(); - ~AudioDecoder() override; - MOCK_METHOD1(SetDelegate, void(Delegate*)); - MOCK_METHOD1(PushBuffer, BufferStatus(scoped_refptr)); - MOCK_METHOD1(SetConfig, bool(const AudioConfig&)); - MOCK_METHOD1(SetVolume, bool(float)); - MOCK_METHOD0(GetRenderingDelay, RenderingDelay()); - MOCK_METHOD1(GetStatistics, void(Statistics*)); - MOCK_METHOD0(GetAudioTrackTimestamp, AudioTrackTimestamp()); - MOCK_METHOD0(GetStartThresholdInFrames, int()); - MOCK_METHOD0(RequiresDecryption, bool()); - }; - - class VideoDecoder : public CmaBackend::VideoDecoder { - public: - VideoDecoder(); - ~VideoDecoder() override; - MOCK_METHOD1(SetDelegate, void(Delegate*)); - MOCK_METHOD1(PushBuffer, BufferStatus(scoped_refptr)); - MOCK_METHOD1(SetConfig, bool(const VideoConfig&)); - MOCK_METHOD1(GetStatistics, void(Statistics*)); - }; - - MockCmaBackend(); - ~MockCmaBackend() override; - MOCK_METHOD0(CreateAudioDecoder, AudioDecoder*()); - MOCK_METHOD0(CreateVideoDecoder, VideoDecoder*()); - MOCK_METHOD0(Initialize, bool()); - MOCK_METHOD1(Start, bool(int64_t)); - MOCK_METHOD0(Stop, void()); - MOCK_METHOD0(Pause, bool()); - MOCK_METHOD0(Resume, bool()); - MOCK_METHOD0(GetCurrentPts, int64_t()); - MOCK_METHOD1(SetPlaybackRate, bool(float)); - MOCK_METHOD0(LogicalPause, void()); - MOCK_METHOD0(LogicalResume, void()); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_TEST_MOCK_CMA_BACKEND_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/test/mock_cma_backend_factory.cc chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend_factory.cc --- chromium-132.0.6834.110/chromecast/media/api/test/mock_cma_backend_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/api/test/mock_cma_backend_factory.h" - -namespace chromecast { -namespace media { - -MockCmaBackendFactory::MockCmaBackendFactory() = default; -MockCmaBackendFactory::~MockCmaBackendFactory() = default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/api/test/mock_cma_backend_factory.h chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend_factory.h --- chromium-132.0.6834.110/chromecast/media/api/test/mock_cma_backend_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/test/mock_cma_backend_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_API_TEST_MOCK_CMA_BACKEND_FACTORY_H_ -#define CHROMECAST_MEDIA_API_TEST_MOCK_CMA_BACKEND_FACTORY_H_ - -#include - -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace media { - -class MockCmaBackendFactory : public CmaBackendFactory { - public: - MockCmaBackendFactory(); - ~MockCmaBackendFactory() override; - - MOCK_METHOD(std::unique_ptr, CreateBackend, - (const MediaPipelineDeviceParams&), (override)); - MOCK_METHOD(scoped_refptr, GetMediaTaskRunner, - (), (override)); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_TEST_MOCK_CMA_BACKEND_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/api/test/mock_sound_player.cc chromium-132.0.6834.159/chromecast/media/api/test/mock_sound_player.cc --- chromium-132.0.6834.110/chromecast/media/api/test/mock_sound_player.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/test/mock_sound_player.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// 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 "chromecast/media/api/test/mock_sound_player.h" - -namespace chromecast { -namespace media { - -MockSoundPlayer::MockSoundPlayer() = default; -MockSoundPlayer::~MockSoundPlayer() = default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/api/test/mock_sound_player.h chromium-132.0.6834.159/chromecast/media/api/test/mock_sound_player.h --- chromium-132.0.6834.110/chromecast/media/api/test/mock_sound_player.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/api/test/mock_sound_player.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_API_TEST_MOCK_SOUND_PLAYER_H_ -#define CHROMECAST_MEDIA_API_TEST_MOCK_SOUND_PLAYER_H_ - -#include "chromecast/media/api/sound_player.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace media { - -class MockSoundPlayer : public SoundPlayer { - public: - MockSoundPlayer(); - ~MockSoundPlayer() override; - - MOCK_METHOD(void, Play, (int, int, bool, AudioContentType), (override)); - MOCK_METHOD(void, - PlayAudioData, - (int, scoped_refptr, bool, AudioContentType), - (override)); - MOCK_METHOD(void, - PlayAtTime, - (int, int64_t, media::AudioChannel, AudioContentType), - (override)); - MOCK_METHOD( - void, - PlayAudioDataAtTime, - (scoped_refptr, int64_t, AudioChannel, AudioContentType), - (override)); - MOCK_METHOD(void, Stop, (int), (override)); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_API_TEST_MOCK_SOUND_PLAYER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_clock_simulator_impl.cc chromium-132.0.6834.159/chromecast/media/audio/audio_clock_simulator_impl.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_clock_simulator_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_clock_simulator_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include -#include -#include -#include - -#include "base/check_op.h" -#include "base/functional/bind.h" -#include "chromecast/media/api/audio_clock_simulator.h" -#include "chromecast/media/api/audio_provider.h" -#include "media/base/audio_bus.h" -#include "media/base/multi_channel_resampler.h" - -namespace chromecast { -namespace media { - -namespace { -constexpr size_t kMaxChannels = 32; -constexpr size_t kDefaultResampleBufferFrames = 2048; - -class AudioClockSimulatorImpl : public AudioClockSimulator { - public: - explicit AudioClockSimulatorImpl(AudioProvider* provider) - : provider_(provider), - sample_rate_(provider_->sample_rate()), - num_channels_(provider_->num_channels()) { - DCHECK(provider_); - DCHECK_GT(sample_rate_, 0); - DCHECK_GT(num_channels_, 0u); - DCHECK_LE(num_channels_, kMaxChannels); - - resample_buffer_ = - ::media::AudioBus::Create(num_channels_, kDefaultResampleBufferFrames); - resampler_ = std::make_unique<::media::MultiChannelResampler>( - num_channels_, 1.0, ::media::SincResampler::kSmallRequestSize, - base::BindRepeating(&AudioClockSimulatorImpl::ResamplerReadCallback, - base::Unretained(this))); - resampler_->PrimeWithSilence(); - } - - ~AudioClockSimulatorImpl() override = default; - - AudioClockSimulatorImpl(const AudioClockSimulatorImpl&) = delete; - AudioClockSimulatorImpl& operator=(const AudioClockSimulatorImpl&) = delete; - - // AudioClockSimulator implementation: - double SetRate(double rate) override { - if (in_fill_) { - pending_rate_ = rate; - return rate; - } - if (rate != clock_rate_) { - clock_rate_ = rate; - resampler_->SetRatio(clock_rate_); - } - return rate; - } - - double DelayFrames() const override { - return resampler_->BufferedFrames() + resampler_->KernelSize() / 2; - } - - void SetSampleRate(int sample_rate) override { sample_rate_ = sample_rate; } - - void SetPlaybackRate(double playback_rate) override { - playback_rate_ = playback_rate; - } - - int FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) override { - if (num_frames > resample_buffer_->frames()) { - resample_buffer_ = - ::media::AudioBus::Create(num_channels_, num_frames * 2); - } - request_timestamp_ = playout_timestamp; - // resampler_->BufferedFrames() gives incorrect values in the read callback, - // so track the number of buffered frames ourselves. - resampler_buffered_frames_ = DelayFrames(); - in_fill_ = true; - resampler_->Resample(num_frames, resample_buffer_.get()); - in_fill_ = false; - if (pending_rate_.has_value()) { - SetRate(pending_rate_.value()); - pending_rate_.reset(); - } - for (size_t c = 0; c < num_channels_; ++c) { - std::copy_n(resample_buffer_->channel(c), num_frames, channel_data[c]); - } - return num_frames; - } - - size_t num_channels() const override { return num_channels_; } - - int sample_rate() const override { return sample_rate_; } - - private: - void ResamplerReadCallback(int frame_delay, ::media::AudioBus* output) { - float* channels[kMaxChannels]; - for (size_t c = 0; c < num_channels_; ++c) { - channels[c] = output->channel(c); - } - - int64_t timestamp = - request_timestamp_ + FramesToMicroseconds(resampler_buffered_frames_); - const int needed_frames = output->frames(); - int filled = provider_->FillFrames(output->frames(), timestamp, channels); - if (filled < needed_frames) { - output->ZeroFramesPartial(filled, needed_frames - filled); - } - resampler_buffered_frames_ += output->frames(); - } - - int64_t FramesToMicroseconds(double frames) { - return std::round(frames * 1000000 / (sample_rate_ * playback_rate_)); - } - - AudioProvider* const provider_; - int sample_rate_; - const size_t num_channels_; - double playback_rate_ = 1.0; - - double clock_rate_ = 1.0; - - std::unique_ptr<::media::AudioBus> resample_buffer_; - std::unique_ptr<::media::MultiChannelResampler> resampler_; - - int64_t request_timestamp_ = 0; - double resampler_buffered_frames_ = 0.0; - bool in_fill_ = false; - std::optional pending_rate_; -}; - -} // namespace - -// static -std::unique_ptr AudioClockSimulator::Create( - AudioProvider* provider) { - return std::make_unique(provider); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_clock_simulator_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/audio_clock_simulator_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_clock_simulator_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_clock_simulator_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,200 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include - -#include "base/check_op.h" -#include "base/functional/callback.h" -#include "base/logging.h" -#include "chromecast/media/api/audio_clock_simulator.h" -#include "media/base/sinc_resampler.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::_; -using ::testing::Invoke; -using ::testing::NiceMock; - -namespace chromecast { -namespace media { - -namespace { - -constexpr int kSampleRate = 48000; -constexpr size_t kDefaultChannels = 1; - -constexpr int kBufferSize = 4096; - -int64_t FramesToTime(int64_t frames, int sample_rate) { - return std::round(frames * 1000000.0 / sample_rate); -} - -class FakeAudioProvider : public AudioProvider { - public: - explicit FakeAudioProvider(size_t num_channels) - : num_channels_(num_channels) { - DCHECK_GT(num_channels_, 0u); - ON_CALL(*this, FillFrames) - .WillByDefault(Invoke(this, &FakeAudioProvider::FillFramesImpl)); - } - - void SetFillCallback(base::RepeatingCallback callback) { - fill_callback_ = std::move(callback); - } - - // AudioProvider implementation: - MOCK_METHOD(int, FillFrames, (int, int64_t, float* const*)); - size_t num_channels() const override { return num_channels_; } - int sample_rate() const override { return kSampleRate; } - - int FillFramesImpl(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) { - for (int f = 0; f < num_frames; ++f) { - for (size_t c = 0; c < num_channels_; ++c) { - channel_data[c][f] = static_cast(next_ + f); - } - } - next_ += num_frames; - - if (fill_callback_) { - fill_callback_.Run(); - } - return num_frames; - } - - int consumed() { return next_; } - - private: - const size_t num_channels_; - int next_ = 0; - - base::RepeatingCallback fill_callback_; -}; - -using TestParams = - std::tuple; - -} // namespace - -class AudioClockSimulatorTest : public testing::TestWithParam { - public: - AudioClockSimulatorTest() = default; - ~AudioClockSimulatorTest() override = default; -}; - -TEST_P(AudioClockSimulatorTest, Fill) { - const TestParams& params = GetParam(); - const int request_size = testing::get<0>(params); - const double clock_rate = testing::get<1>(params); - LOG(INFO) << "Request size = " << request_size - << ", clock rate = " << clock_rate; - NiceMock provider(kDefaultChannels); - auto clock = AudioClockSimulator::Create(&provider); - if (request_size > kBufferSize) { - return; - } - - EXPECT_EQ(clock->SetRate(clock_rate), clock_rate); - - float output[kBufferSize]; - std::fill_n(output, kBufferSize, 0); - float* test_data[1] = {output}; - int i; - for (i = 0; i + request_size <= kBufferSize; i += request_size) { - test_data[0] = output + i; - int64_t timestamp = FramesToTime(i, kSampleRate); - - EXPECT_CALL(provider, FillFrames(_, _, _)).Times(testing::AnyNumber()); - // Timestamp for requests to provider should not be before current fill - // timestamp. - EXPECT_CALL(provider, FillFrames(_, testing::Lt(timestamp), _)).Times(0); - int provided = clock->FillFrames(request_size, timestamp, test_data); - EXPECT_EQ(provided, request_size); - - double delay = clock->DelayFrames(); - EXPECT_GE(delay, 0); - testing::Mock::VerifyAndClearExpectations(&provider); - } -} - -TEST(AudioClockSimulatorTest, ChangeRateDuringFill) { - NiceMock provider(2); - auto clock = AudioClockSimulator::Create(&provider); - - double rates[] = {0.9999, 1.0001, 0.9998, 1.0002, 1.0}; - int rate_index = 0; - provider.SetFillCallback(base::BindRepeating( - [](AudioClockSimulator* clock, double* rates, int* rate_index) { - if (*rate_index >= 5) { - return; - } - clock->SetRate(rates[*rate_index]); - *rate_index += 1; - }, - clock.get(), rates, &rate_index)); - - float output1[kBufferSize]; - float output2[kBufferSize]; - std::fill_n(output1, kBufferSize, 0); - std::fill_n(output2, kBufferSize, 0); - float* test_data[2] = {output1, output2}; - int requested_frames = 0; - while (true) { - int64_t timestamp = FramesToTime(requested_frames, kSampleRate); - EXPECT_CALL(provider, FillFrames(_, _, _)).Times(testing::AnyNumber()); - int provided = clock->FillFrames(kBufferSize, timestamp, test_data); - EXPECT_EQ(provided, kBufferSize); - testing::Mock::VerifyAndClearExpectations(&provider); - if (rate_index >= 5) { - return; - } - } -} - -INSTANTIATE_TEST_SUITE_P( - RequestSizes, - AudioClockSimulatorTest, - testing::Combine(::testing::Values(1, 2, 31, 63, 64, 65, 1000), - ::testing::Values(1.0, 0.999, 1.001, 0.9995, 1.0005))); - -class AudioClockSimulatorLongRunningTest - : public testing::TestWithParam { - public: - AudioClockSimulatorLongRunningTest() = default; - ~AudioClockSimulatorLongRunningTest() override = default; -}; - -TEST_P(AudioClockSimulatorLongRunningTest, Run) { - double rate = GetParam(); - LOG(INFO) << "Rate = " << rate; - NiceMock provider(kDefaultChannels); - auto clock = AudioClockSimulator::Create(&provider); - clock->SetRate(rate); - - const int kRequestSize = 1000; - const int kIterations = 1000; - - float output[kRequestSize]; - float* test_data[1] = {output}; - for (int i = 0; i < kIterations; ++i) { - int provided = clock->FillFrames(kRequestSize, 0, test_data); - EXPECT_EQ(provided, kRequestSize); - } - - int input_frames = provider.consumed(); - int output_frames = kRequestSize * kIterations; - - EXPECT_GE(input_frames, std::floor(rate * output_frames)); - EXPECT_LE(input_frames, std::ceil(rate * output_frames) + - ::media::SincResampler::kSmallRequestSize); -} - -INSTANTIATE_TEST_SUITE_P(Rates, - AudioClockSimulatorLongRunningTest, - ::testing::Values(1.0, 0.999, 1.001, 0.9995, 1.0005)); - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_fader.cc chromium-132.0.6834.159/chromecast/media/audio/audio_fader.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_fader.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_fader.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,250 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_fader.h" - -#include - -#include "base/bits.h" -#include "base/check_op.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr size_t kMaxChannels = 32; - -} // namespace - -AudioFader::AudioFader(AudioProvider* provider, - base::TimeDelta fade_time, - double playback_rate) - : AudioFader(provider, - std::round(fade_time.InSecondsF() * provider->sample_rate() * - playback_rate), - playback_rate) {} - -AudioFader::AudioFader(AudioProvider* provider, - int fade_frames, - double playback_rate) - : provider_(provider), - // Ensure that fade_frames_ is a multiple of 4 to keep correct alignment. - fade_frames_(base::bits::AlignUpDeprecatedDoNotUse(fade_frames, 4)), - num_channels_(provider_->num_channels()), - sample_rate_(provider_->sample_rate()), - playback_rate_(playback_rate) { - DCHECK(provider_); - DCHECK_GT(fade_frames_, 0); - DCHECK_GT(num_channels_, 0u); - DCHECK_LE(num_channels_, kMaxChannels); - DCHECK_GT(sample_rate_, 0); - - fade_buffer_ = CastAudioBus::Create(num_channels_, fade_frames_); - fade_buffer_->Zero(); -} - -AudioFader::~AudioFader() = default; - -int AudioFader::FramesNeededFromSource(int num_fill_frames) const { - DCHECK_GE(num_fill_frames, 0); - DCHECK_GE(fade_frames_, buffered_frames_); - return num_fill_frames + fade_frames_ - buffered_frames_; -} - -int64_t AudioFader::FramesToMicroseconds(int64_t frames) { - return frames * base::Time::kMicrosecondsPerSecond / - (sample_rate_ * playback_rate_); -} - -size_t AudioFader::num_channels() const { - return num_channels_; -} - -int AudioFader::sample_rate() const { - return sample_rate_; -} - -int AudioFader::FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) { - DCHECK(channel_data); - - int filled_frames = std::min(buffered_frames_, num_frames); - if (filled_frames > 0) { - for (size_t c = 0; c < num_channels_; ++c) { - float* fade_channel = fade_buffer_->channel(c); - // First, copy data from fade_buffer_. - std::copy_n(fade_channel, filled_frames, channel_data[c]); - // Move data in fade_buffer_ to start. - std::copy(fade_channel + filled_frames, fade_channel + buffered_frames_, - fade_channel); - } - - buffered_frames_ -= filled_frames; - num_frames -= filled_frames; - } - - float* fill_channel_data[kMaxChannels]; - if (num_frames > 0) { - // Still need more frames; ask source to fill. - for (size_t c = 0; c < num_channels_; ++c) { - fill_channel_data[c] = channel_data[c] + filled_frames; - } - int64_t timestamp = playout_timestamp + - FramesToMicroseconds(filled_frames + buffered_frames_); - int filled = - provider_->FillFrames(num_frames, timestamp, fill_channel_data); - filled_frames += filled; - num_frames -= filled; - } - // Refill fade_buffer_ from source. - for (size_t c = 0; c < num_channels_; ++c) { - fill_channel_data[c] = fade_buffer_->channel(c) + buffered_frames_; - } - int64_t timestamp = playout_timestamp + - FramesToMicroseconds(filled_frames + buffered_frames_); - buffered_frames_ += provider_->FillFrames(fade_frames_ - buffered_frames_, - timestamp, fill_channel_data); - - const bool complete = (num_frames == 0 && buffered_frames_ == fade_frames_); - if (complete) { - CompleteFill(channel_data, filled_frames); - } else { - if (state_ == State::kPlaying) { - int extra_frames = - std::max(filled_frames + buffered_frames_ - fade_frames_, 0); - for (size_t c = 0; c < num_channels_; ++c) { - fill_channel_data[c] = channel_data[c] + extra_frames; - } - IncompleteFill(fill_channel_data, filled_frames - extra_frames); - } else { - IncompleteFill(channel_data, filled_frames); - } - } - - return filled_frames; -} - -void AudioFader::CompleteFill(float* const* channel_data, int filled_frames) { - switch (state_) { - case State::kSilent: - // Fade in. - state_ = State::kFadingIn; - fade_frames_remaining_ = fade_frames_; - break; - case State::kFadingIn: - // Continue fading in. - break; - case State::kPlaying: - // Nothing to do in this case. - return; - case State::kFadingOut: - // Fade back in. - state_ = State::kFadingIn; - fade_frames_remaining_ = - std::max(0, fade_frames_ - fade_frames_remaining_ - 1); - break; - } - FadeIn(channel_data, filled_frames); -} - -void AudioFader::IncompleteFill(float* const* channel_data, int filled_frames) { - switch (state_) { - case State::kSilent: - // Remain silent. - buffered_frames_ = 0; - for (size_t c = 0; c < num_channels_; ++c) { - std::fill_n(channel_data[c], filled_frames, 0); - } - return; - case State::kFadingIn: - // Fade back out. - state_ = State::kFadingOut; - fade_frames_remaining_ = - std::max(0, fade_frames_ - fade_frames_remaining_ - 1); - break; - case State::kPlaying: - // Fade out. - state_ = State::kFadingOut; - fade_frames_remaining_ = fade_frames_; - break; - case State::kFadingOut: - // Continue fading out. - break; - } - FadeOut(channel_data, filled_frames); -} - -void AudioFader::FadeIn(float* const* channel_data, int filled_frames) { - DCHECK(state_ == State::kFadingIn); - - FadeInHelper(channel_data, num_channels_, filled_frames, fade_frames_, - fade_frames_remaining_); - fade_frames_remaining_ = std::max(0, fade_frames_remaining_ - filled_frames); - - if (fade_frames_remaining_ == 0) { - state_ = State::kPlaying; - } -} - -// static -void AudioFader::FadeInHelper(float* const* channel_data, - size_t num_channels, - int filled_frames, - int fade_frames, - int fade_frames_remaining) { - const float inverse_fade_frames = 1.0f / static_cast(fade_frames); - const int fade_limit = std::min(filled_frames, fade_frames_remaining + 1); - - for (size_t c = 0; c < num_channels; ++c) { - float* channel = channel_data[c]; - for (int f = 0; f < fade_limit; ++f) { - const float fade_multiplier = - 1.0 - (fade_frames_remaining - f) * inverse_fade_frames; - channel[f] *= fade_multiplier; - } - } -} - -void AudioFader::FadeOut(float* const* channel_data, int filled_frames) { - DCHECK(state_ == State::kFadingOut); - - FadeOutHelper(channel_data, num_channels_, filled_frames, fade_frames_, - fade_frames_remaining_); - fade_frames_remaining_ = std::max(0, fade_frames_remaining_ - filled_frames); - - if (fade_frames_remaining_ == 0) { - state_ = State::kSilent; - buffered_frames_ = 0; - } -} - -// static -void AudioFader::FadeOutHelper(float* const* channel_data, - size_t num_channels, - int filled_frames, - int fade_frames, - int fade_frames_remaining) { - const float inverse_fade_frames = 1.0f / static_cast(fade_frames); - const int fade_limit = std::min(filled_frames, fade_frames_remaining + 1); - - for (size_t c = 0; c < num_channels; ++c) { - float* channel = channel_data[c]; - for (int f = 0; f < fade_limit; ++f) { - const float fade_multiplier = - (fade_frames_remaining - f) * inverse_fade_frames; - channel[f] *= fade_multiplier; - } - } - if (filled_frames > fade_frames_remaining) { - for (size_t c = 0; c < num_channels; ++c) { - std::fill_n(channel_data[c] + fade_frames_remaining, - filled_frames - fade_frames_remaining, 0); - } - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_fader.h chromium-132.0.6834.159/chromecast/media/audio/audio_fader.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_fader.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_fader.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_FADER_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_FADER_H_ - -#include -#include - -#include "base/time/time.h" -#include "chromecast/media/api/audio_provider.h" -#include "chromecast/media/audio/cast_audio_bus.h" - -namespace chromecast { -namespace media { - -// AudioFader handles smoothly fading audio in/out when a stream underruns -// (ie, when the data source does not have any data to provide when the output -// requests it). This prevents pops and clicks. Internally, it buffers enough -// data to ensure that a full fade can always take place if necessary; note that -// this increases output latency by |fade_frames| samples. All methods except -// constructor/destructor must be called on the same thread. -class AudioFader : public AudioProvider { - public: - AudioFader(AudioProvider* provider, - base::TimeDelta fade_time, - double playback_rate); - AudioFader(AudioProvider* provider, int fade_frames, double playback_rate); - - AudioFader(const AudioFader&) = delete; - AudioFader& operator=(const AudioFader&) = delete; - - ~AudioFader() override; - - int buffered_frames() const { return buffered_frames_; } - - // AudioProvider implementation: - int FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) override; - size_t num_channels() const override; - int sample_rate() const override; - - void set_playback_rate(double playback_rate) { - playback_rate_ = playback_rate; - } - - // Returns the total number of frames that will be requested from the source - // (potentially over multiple calls to source_->FillFaderFrames()) if - // FillFrames() is called to fill |num_fill_frames| frames. - int FramesNeededFromSource(int num_fill_frames) const; - - // Helper methods to fade in/out a buffer. |channel_data| contains the data to - // fade; |filled_frames| is the amount of data actually in |channel_data|. - // |fade_frames| is the number of frames over which a complete fade should - // happen (ie, how many frames it takes to go from a 1.0 to 0.0 multiplier). - // |fade_frames_remaining| is the number of frames left in the current fade - // (which will be less than |fade_frames| if part of the fade has already - // been completed on a previous buffer). - static void FadeInHelper(float* const* channel_data, - size_t num_channels, - int filled_frames, - int fade_frames, - int fade_frames_remaining); - static void FadeOutHelper(float* const* channel_data, - size_t num_channels, - int filled_frames, - int fade_frames, - int fade_frames_remaining); - - private: - enum class State { - kSilent, - kFadingIn, - kPlaying, - kFadingOut, - }; - - int64_t FramesToMicroseconds(int64_t frames); - - void CompleteFill(float* const* channel_data, int filled_frames); - void IncompleteFill(float* const* channel_data, int filled_frames); - void FadeIn(float* const* channel_data, int filled_frames); - void FadeOut(float* const* channel_data, int filled_frames); - - AudioProvider* const provider_; - const int fade_frames_; - const size_t num_channels_; - const int sample_rate_; - double playback_rate_; - - State state_ = State::kSilent; - std::unique_ptr fade_buffer_; - int buffered_frames_ = 0; - int fade_frames_remaining_ = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_FADER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_fader_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/audio_fader_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_fader_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_fader_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,357 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "chromecast/media/audio/audio_fader.h" -#include "media/base/audio_bus.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; - -namespace chromecast { -namespace media { - -namespace { - -const int kNumChannels = 2; -const int kFadeFrames = 128; -const int kSampleRate = 48000; - -std::unique_ptr<::media::AudioBus> CreateAudioBus(int num_frames) { - auto buffer = ::media::AudioBus::Create(kNumChannels, num_frames); - // Fill with invalid values. - for (int c = 0; c < buffer->channels(); ++c) { - float* channel_data = buffer->channel(c); - std::fill_n(channel_data, num_frames, -2.0f); - } - return buffer; -} - -class TestFaderSource : public AudioProvider { - public: - TestFaderSource() - : max_fill_frames_(std::numeric_limits::max()), - total_requested_frames_(0), - last_requested_frames_(0), - last_filled_frames_(0) {} - - TestFaderSource(const TestFaderSource&) = delete; - TestFaderSource& operator=(const TestFaderSource&) = delete; - - // AudioProvider implementation: - int FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) override { - last_requested_frames_ = num_frames; - total_requested_frames_ += num_frames; - - int count = std::min(num_frames, max_fill_frames_); - last_filled_frames_ = count; - - for (int c = 0; c < kNumChannels; ++c) { - std::fill_n(channel_data[c], count, 1.0f); - } - - return count; - } - size_t num_channels() const override { return kNumChannels; } - int sample_rate() const override { return kSampleRate; } - - void set_max_fill_frames(int frames) { max_fill_frames_ = frames; } - - int total_requested_frames() const { return total_requested_frames_; } - int last_requested_frames() const { return last_requested_frames_; } - int last_filled_frames() const { return last_filled_frames_; } - - private: - int max_fill_frames_; - int total_requested_frames_; - int last_requested_frames_; - int last_filled_frames_; -}; - -} // namespace - -TEST(AudioFaderTest, Startup) { - TestFaderSource source; - AudioFader fader(&source, kFadeFrames, 1.0); - - // Fader has no buffered frames initially. - EXPECT_EQ(fader.buffered_frames(), 0); - - const int kFillSize = kFadeFrames * 2; - int frames_needed = fader.FramesNeededFromSource(kFillSize); - // The fader should fill its internal buffer, plus the size of the request. - EXPECT_EQ(frames_needed, kFadeFrames + kFillSize); - - auto dest = CreateAudioBus(kFillSize); - float* channels[kNumChannels]; - for (int c = 0; c < kNumChannels; ++c) { - channels[c] = dest->channel(c); - } - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - - // Test that FramesNeededFromSource() works correctly. - EXPECT_EQ(source.total_requested_frames(), frames_needed); - - // Fader's internal buffer should be full. - EXPECT_EQ(fader.buffered_frames(), kFadeFrames); - - // Data should be faded in. - EXPECT_EQ(dest->channel(0)[0], 0.0f); - EXPECT_EQ(dest->channel(0)[kFadeFrames], 1.0f); -} - -TEST(AudioFaderTest, FadeInOver2Buffers) { - TestFaderSource source; - AudioFader fader(&source, kFadeFrames, 1.0); - - // Fader has no buffered frames initially. - EXPECT_EQ(fader.buffered_frames(), 0); - - const int kFillSize = kFadeFrames * 2 / 3; - int frames_needed = fader.FramesNeededFromSource(kFillSize); - auto dest = CreateAudioBus(kFillSize); - float* channels[kNumChannels]; - for (int c = 0; c < kNumChannels; ++c) { - channels[c] = dest->channel(c); - } - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - - // Fader's internal buffer should be full. - EXPECT_EQ(fader.buffered_frames(), kFadeFrames); - // Data should be partially faded in. - EXPECT_EQ(dest->channel(0)[0], 0.0f); - EXPECT_GT(dest->channel(0)[kFillSize - 1], 0.0f); - EXPECT_LT(dest->channel(0)[kFillSize - 1], 1.0f); - - // Fill more data. - frames_needed += fader.FramesNeededFromSource(kFillSize); - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - EXPECT_EQ(fader.buffered_frames(), kFadeFrames); - - // Test that FramesNeededFromSource() works correctly. - EXPECT_EQ(source.total_requested_frames(), frames_needed); - - // Fader's internal buffer should be full. - EXPECT_EQ(fader.buffered_frames(), kFadeFrames); - - // Data should be faded in. - EXPECT_EQ(dest->channel(0)[kFillSize - 1], 1.0f); -} - -TEST(AudioFaderTest, ContinuePlaying) { - TestFaderSource source; - AudioFader fader(&source, kFadeFrames, 1.0); - - // Fader has no buffered frames initially. - EXPECT_EQ(fader.buffered_frames(), 0); - - const int kFillSize = kFadeFrames * 2; - auto dest = CreateAudioBus(kFillSize); - - int frames_needed = fader.FramesNeededFromSource(kFillSize); - float* channels[kNumChannels]; - for (int c = 0; c < kNumChannels; ++c) { - channels[c] = dest->channel(c); - } - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - - // Data should be faded in. - EXPECT_EQ(dest->channel(0)[kFadeFrames], 1.0f); - - // Now request more data. Data should remain fully faded in. - frames_needed += fader.FramesNeededFromSource(kFillSize); - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - EXPECT_EQ(dest->channel(0)[0], 1.0f); - - // Test that FramesNeededFromSource() works correctly. - EXPECT_EQ(source.total_requested_frames(), frames_needed); - - // Fader's internal buffer should be full. - EXPECT_EQ(fader.buffered_frames(), kFadeFrames); -} - -TEST(AudioFaderTest, FadeOut) { - TestFaderSource source; - AudioFader fader(&source, kFadeFrames, 1.0); - - // Fader has no buffered frames initially. - EXPECT_EQ(fader.buffered_frames(), 0); - - const int kFillSize = kFadeFrames * 2; - auto dest = CreateAudioBus(kFillSize); - - int frames_needed = fader.FramesNeededFromSource(kFillSize); - float* channels[kNumChannels]; - for (int c = 0; c < kNumChannels; ++c) { - channels[c] = dest->channel(c); - } - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - - // Data should be faded in. - EXPECT_EQ(dest->channel(0)[kFadeFrames], 1.0f); - - // Now request more data. Data should remain fully faded in. - frames_needed += fader.FramesNeededFromSource(kFillSize); - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - EXPECT_EQ(dest->channel(0)[0], 1.0f); - - // Now make the source not provide enough data. - EXPECT_GT(fader.FramesNeededFromSource(kFillSize), 0); - source.set_max_fill_frames(0); - frames_needed += fader.FramesNeededFromSource(kFillSize); - int filled = fader.FillFrames(kFillSize, 0, channels); - EXPECT_EQ(filled, kFadeFrames); - - // Test that FramesNeededFromSource() works correctly. - EXPECT_EQ(source.total_requested_frames(), frames_needed); - - // Data should be faded out. - EXPECT_EQ(dest->channel(0)[0], 1.0f); - EXPECT_LT(dest->channel(0)[filled - 1], 0.1f); - EXPECT_GE(dest->channel(0)[filled - 1], 0.0f); - - // Fader's internal buffer should be empty since we are fully faded out. - EXPECT_EQ(fader.buffered_frames(), 0); -} - -TEST(AudioFaderTest, FadeOutPartially) { - TestFaderSource source; - AudioFader fader(&source, kFadeFrames, 1.0); - - // Fader has no buffered frames initially. - EXPECT_EQ(fader.buffered_frames(), 0); - - const int kFillSize = kFadeFrames * 2; - auto dest = CreateAudioBus(kFillSize); - - int frames_needed = fader.FramesNeededFromSource(kFillSize); - float* channels[kNumChannels]; - for (int c = 0; c < kNumChannels; ++c) { - channels[c] = dest->channel(c); - } - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - - // Data should be faded in. - EXPECT_EQ(dest->channel(0)[kFadeFrames], 1.0f); - - // Now request more data. Data should remain fully faded in. - frames_needed += fader.FramesNeededFromSource(kFillSize); - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - EXPECT_EQ(dest->channel(0)[0], 1.0f); - - // Now make the source not provide enough data. - EXPECT_GT(fader.FramesNeededFromSource(kFillSize), 0); - source.set_max_fill_frames(0); - frames_needed += fader.FramesNeededFromSource(kFadeFrames / 3); - int filled = fader.FillFrames(kFadeFrames / 3, 0, channels); - EXPECT_EQ(filled, kFadeFrames / 3); - - // Data should be partially faded out. - EXPECT_EQ(dest->channel(0)[0], 1.0f); - EXPECT_LT(dest->channel(0)[filled - 1], 1.0f); - EXPECT_GE(dest->channel(0)[filled - 1], 0.0f); - float fade_min = dest->channel(0)[filled - 1]; - - // Fader's internal buffer should be partially full. - EXPECT_LT(fader.buffered_frames(), kFadeFrames); - - // Now let the source provide data again. - source.set_max_fill_frames(std::numeric_limits::max()); - frames_needed += fader.FramesNeededFromSource(kFillSize); - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - // Data should fade back in from the point it faded out to. - EXPECT_GE(dest->channel(0)[0], fade_min); - EXPECT_EQ(dest->channel(0)[kFillSize - 1], 1.0f); - - // Test that FramesNeededFromSource() works correctly. - EXPECT_EQ(source.total_requested_frames(), frames_needed); - - // Fader's internal buffer should be full. - EXPECT_EQ(fader.buffered_frames(), kFadeFrames); -} - -TEST(AudioFaderTest, IncompleteFadeIn) { - TestFaderSource source; - AudioFader fader(&source, kFadeFrames, 1.0); - - // Fader has no buffered frames initially. - EXPECT_EQ(fader.buffered_frames(), 0); - - const int kFillSize = kFadeFrames * 2; - int frames_needed = fader.FramesNeededFromSource(kFillSize); - - // The source only partially fills the fader request. Since we're fading in - // from silence, the fader should output silence. - auto dest = CreateAudioBus(kFillSize); - source.set_max_fill_frames(10); - float* channels[kNumChannels]; - for (int c = 0; c < kNumChannels; ++c) { - channels[c] = dest->channel(c); - } - int filled = fader.FillFrames(kFillSize, 0, channels); - - // Test that FramesNeededFromSource() works correctly. - EXPECT_EQ(source.total_requested_frames(), frames_needed); - - // Fader's internal buffer should be empty. - EXPECT_EQ(fader.buffered_frames(), 0); - - // Data should be silent. - for (int i = 0; i < filled; ++i) { - EXPECT_EQ(dest->channel(0)[i], 0.0f); - } -} - -TEST(AudioFaderTest, FadeInPartially) { - TestFaderSource source; - AudioFader fader(&source, kFadeFrames, 1.0); - - // Fader has no buffered frames initially. - EXPECT_EQ(fader.buffered_frames(), 0); - - const int kFillSize = kFadeFrames * 2 / 3; - - int frames_needed = fader.FramesNeededFromSource(kFillSize); - auto dest = CreateAudioBus(kFillSize); - float* channels[kNumChannels]; - for (int c = 0; c < kNumChannels; ++c) { - channels[c] = dest->channel(c); - } - EXPECT_EQ(fader.FillFrames(kFillSize, 0, channels), kFillSize); - - // Fader's internal buffer should be full. - EXPECT_EQ(fader.buffered_frames(), kFadeFrames); - - // Data should be partially faded in. - EXPECT_EQ(dest->channel(0)[0], 0.0f); - EXPECT_GT(dest->channel(0)[kFillSize - 1], 0.0f); - EXPECT_LT(dest->channel(0)[kFillSize - 1], 1.0f); - float fade_max = dest->channel(0)[kFillSize - 1]; - - // Now tell the source not to provide any data. The fader output should fade - // back out to silence. - source.set_max_fill_frames(0); - frames_needed += fader.FramesNeededFromSource(kFillSize); - int filled = fader.FillFrames(kFillSize, 0, channels); - - // Data should be faded out. - EXPECT_LE(dest->channel(0)[0], fade_max); - EXPECT_GE(dest->channel(0)[0], 0.0f); - EXPECT_EQ(dest->channel(0)[filled - 1], 0.0f); - - // Test that FramesNeededFromSource() works correctly. - EXPECT_EQ(source.total_requested_frames(), frames_needed); - - // Fader's internal buffer should be empty. - EXPECT_EQ(fader.buffered_frames(), 0); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_io_thread.cc chromium-132.0.6834.159/chromecast/media/audio/audio_io_thread.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_io_thread.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_io_thread.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_io_thread.h" - -#include "base/check.h" -#include "base/message_loop/message_pump_type.h" -#include "base/no_destructor.h" - -namespace chromecast { - -// static -AudioIoThread* AudioIoThread::Get() { - static base::NoDestructor instance; - return instance.get(); -} - -AudioIoThread::AudioIoThread() : thread_("AudioIO") { - base::Thread::Options options; - options.message_pump_type = base::MessagePumpType::IO; - options.thread_type = base::ThreadType::kRealtimeAudio; - CHECK(thread_.StartWithOptions(std::move(options))); -} - -AudioIoThread::~AudioIoThread() = default; - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_io_thread.h chromium-132.0.6834.159/chromecast/media/audio/audio_io_thread.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_io_thread.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_io_thread.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_IO_THREAD_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_IO_THREAD_H_ - -#include "base/memory/ref_counted.h" -#include "base/threading/thread.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace chromecast { - -// Provides process-wide access to a single kRealtimeAudio type IO thread. -class AudioIoThread { - public: - static AudioIoThread* Get(); - - AudioIoThread(); - - AudioIoThread(const AudioIoThread&) = delete; - AudioIoThread& operator=(const AudioIoThread&) = delete; - - ~AudioIoThread(); - - scoped_refptr task_runner() const { - return thread_.task_runner(); - } - - private: - base::Thread thread_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_IO_THREAD_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_log.cc chromium-132.0.6834.159/chromecast/media/audio/audio_log.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_log.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_log.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,203 +0,0 @@ -// 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 "chromecast/media/audio/audio_log.h" - -#include - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/location.h" -#include "base/memory/scoped_refptr.h" -#include "base/no_destructor.h" -#include "base/synchronization/lock.h" -#include "base/task/sequenced_task_runner.h" -#include "base/thread_annotations.h" - -namespace logging { - -namespace { -constexpr int kBufferSize = 256; -constexpr int kMaxBuffers = 32; -} // namespace - -class AudioLogMessage::StreamBuf : public std::streambuf { - public: - StreamBuf() = default; - - StreamBuf(const StreamBuf&) = delete; - StreamBuf& operator=(const StreamBuf&) = delete; - - void Initialize(const char* file, int line, LogSeverity severity) { - file_ = file; - line_ = line; - severity_ = severity; - setp(buffer_, buffer_ + kBufferSize); - } - - void Log() { - if (!file_) { - // Cancelled. - return; - } - - ::logging::LogMessage message(file_, line_, severity_); - int size = pptr() - pbase(); - message.stream().write(buffer_, size); - } - - void Cancel() { file_ = nullptr; } - - private: - const char* file_ = nullptr; - int line_; - LogSeverity severity_; - char buffer_[kBufferSize]; -}; - -class AudioLogMessage::BufferManager { - public: - static BufferManager* Get(); - - void SetOwner(BufferManager* owner) { owner_ = owner; } - - void Setup() { - base::AutoLock lock(lock_); - if (ready_) { - return; - } - - task_runner_ = base::SequencedTaskRunner::GetCurrentDefault(); - dispose_callback_ = base::BindRepeating( - &BufferManager::HandleDisposedBuffers, base::Unretained(this)); - - for (int i = 0; i < kMaxBuffers; ++i) { - free_buffers_[i] = &buffers_[i]; - } - num_free_buffers_ = kMaxBuffers; - ready_ = true; - } - - AudioLogMessage::StreamBuf* GetBuffer(const char* file, - int line, - LogSeverity severity) { - if (owner_) { - return owner_->GetBuffer(file, line, severity); - } - - AudioLogMessage::StreamBuf* buffer; - { - base::AutoLock lock(lock_); - if (num_free_buffers_ == 0) { - ++num_missing_buffers_; - return nullptr; - } - - --num_free_buffers_; - buffer = free_buffers_[num_free_buffers_]; - } - buffer->Initialize(file, line, severity); - return buffer; - } - - void Dispose(AudioLogMessage::StreamBuf* buffer) { - if (!buffer) { - return; - } - - if (owner_) { - return owner_->Dispose(buffer); - } - - { - base::AutoLock lock(lock_); - DCHECK_LT(num_disposed_buffers_, kMaxBuffers); - disposed_buffers_[num_disposed_buffers_] = buffer; - ++num_disposed_buffers_; - } - DCHECK(task_runner_); - task_runner_->PostTask(FROM_HERE, dispose_callback_); - } - - private: - void HandleDisposedBuffers() { - AudioLogMessage::StreamBuf* buffers[kMaxBuffers]; - int num_buffers; - int num_missing; - { - base::AutoLock lock(lock_); - std::copy_n(disposed_buffers_, num_disposed_buffers_, buffers); - num_buffers = num_disposed_buffers_; - num_disposed_buffers_ = 0; - - num_missing = num_missing_buffers_; - num_missing_buffers_ = 0; - } - - for (int i = 0; i < num_buffers; ++i) { - buffers[i]->Log(); - { - base::AutoLock lock(lock_); - free_buffers_[num_free_buffers_] = buffers[i]; - ++num_free_buffers_; - } - } - - LOG_IF(ERROR, num_missing > 0) - << num_missing << " log messages lost due to lack of buffers"; - } - - AudioLogMessage::StreamBuf buffers_[kMaxBuffers]; - BufferManager* owner_ = nullptr; - - base::Lock lock_; - bool ready_ GUARDED_BY(lock_) = false; - AudioLogMessage::StreamBuf* free_buffers_[kMaxBuffers] GUARDED_BY(lock_); - int num_free_buffers_ GUARDED_BY(lock_) = 0; - - AudioLogMessage::StreamBuf* disposed_buffers_[kMaxBuffers] GUARDED_BY(lock_); - int num_disposed_buffers_ GUARDED_BY(lock_) = 0; - - int num_missing_buffers_ GUARDED_BY(lock_) = 0; - - scoped_refptr task_runner_; - base::RepeatingClosure dispose_callback_; -}; - -// static -AudioLogMessage::BufferManager* AudioLogMessage::BufferManager::Get() { - static base::NoDestructor g_buffer_manager; - return g_buffer_manager.get(); -} - -// static -AudioLogMessage::BufferManager* AudioLogMessage::GetBufferManager() { - return BufferManager::Get(); -} - -AudioLogMessage::AudioLogMessage(const char* file, - int line, - LogSeverity severity) - : buffer_(BufferManager::Get()->GetBuffer(file, line, severity)), - stream_(buffer_) {} - -AudioLogMessage::~AudioLogMessage() { - BufferManager::Get()->Dispose(buffer_); -} - -void AudioLogMessage::Cancel() { - if (buffer_) { - buffer_->Cancel(); - } -} - -void InitializeAudioLog() { - AudioLogMessage::BufferManager::Get()->Setup(); -} - -void InitializeShlibAudioLog(AudioLogMessage::BufferManager* manager) { - AudioLogMessage::BufferManager::Get()->SetOwner(manager); -} - -} // namespace logging diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_log.h chromium-132.0.6834.159/chromecast/media/audio/audio_log.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_log.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_log.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_LOG_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_LOG_H_ - -#include - -#include "base/logging.h" - -namespace logging { - -#define AUDIO_LOG_STREAM(severity) \ - COMPACT_GOOGLE_LOG_EX_##severity(AudioLogMessage).stream() - -#define AUDIO_LOG(severity) \ - LAZY_STREAM(AUDIO_LOG_STREAM(severity), LOG_IS_ON(severity)) - -#define AUDIO_LOG_IF(severity, condition) \ - LAZY_STREAM(AUDIO_LOG_STREAM(severity), LOG_IS_ON(severity) && (condition)) - -class AudioLogMessage { - public: - class BufferManager; - static BufferManager* GetBufferManager(); - - AudioLogMessage(const char* file, int line, LogSeverity severity); - ~AudioLogMessage(); - - AudioLogMessage(const AudioLogMessage&) = delete; - AudioLogMessage& operator=(const AudioLogMessage&) = delete; - - std::ostream& stream() { return stream_; } - - // Cancels any log output for this message. - void Cancel(); - - private: - class StreamBuf; - - StreamBuf* buffer_; - std::ostream stream_; -}; - -// Should be called on a lower-priority thread. Actual output of log messages -// will be done on this thread. Note that any use of AudioLogMessage prior to -// InitializeAudioLog() will not produce any output. -void InitializeAudioLog(); - -// Initializes audio log with an existing buffer manager. May be called from any -// thread (the thread that originally called InitializeAudioLog() to create the -// buffer manager will be used for log output). Useful for logging in shlibs. -void InitializeShlibAudioLog(AudioLogMessage::BufferManager* manager); - -} // namespace logging - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_LOG_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/audio_output_service.proto chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/audio_output_service.proto --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/audio_output_service.proto 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/audio_output_service.proto 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package chromecast.media.audio_output_service; - -import "chromecast/media/audio/net/common.proto"; - -message ApplicationMediaInfo { - optional string application_session_id = 1; -} - -message AudioDecoderConfig { - optional audio_service.AudioCodec audio_codec = 1; - optional audio_service.ChannelLayout channel_layout = 2; - optional audio_service.SampleFormat sample_format = 3; - optional int32 num_channels = 4; - optional int32 sample_rate = 5; - optional bytes extra_data = 6; -} - -message CmaBackendParams { - optional ApplicationMediaInfo application_media_info = 1; - optional AudioDecoderConfig audio_decoder_config = 2; -} - -// Indicates that we want to start playing the sample with PTS |start_pts| -// at audio clock timestamp |start_timestamp| in microseconds. May be sent -// multiple times to restart playback at a new timestamp (ie for hard -// corrections). -message SetStartTimestamp { - optional int64 start_timestamp = 1; - optional int64 start_pts = 2; -} - -// Informs the backend how fast the PTS increases per frame. For example if the -// playback rate is 2.0, then each frame increases the PTS by 2.0 / sample_rate -// seconds. -message SetPlaybackRate { - optional float playback_rate = 1; -} - -// Changes the volume multiplier for an audio output stream. -message StreamVolume { - optional float volume = 1; -} - -// Indicates that EOS for an audio output stream has been played out. -message EosPlayedOut {} - -// Current media pts, the corresponding reference timestamp, rendering delay and -// the timestamp when the delay was measured. -// TODO(b/173250111): Rename this message to RenderingDelay when all users of -// |media_timestamp_microseconds| and |reference_timestamp_microseconds| have -// migrated to using delay information. -message CurrentMediaTimestamp { - optional int64 media_timestamp_microseconds = 1; - optional int64 reference_timestamp_microseconds = 2; - optional int64 delay_microseconds = 3; - optional int64 delay_timestamp_microseconds = 4; -} - -// Informs the backend to stop the playback. -message StopPlayback {} - -// Indicates the status of the initialization of the audio pipeline backend. -message BackendInitializationStatus { - enum Status { - // Audio pipeline backend is successfully initialized. - SUCCESS = 0; - // There was an error during the initialization of audio pipeline backend. - ERROR = 1; - } - optional Status status = 1; -} - -// Used to keep the socket connection active. -message Heartbeat {} - -message Generic { - optional CmaBackendParams backend_params = 1; - optional SetStartTimestamp set_start_timestamp = 2; - optional SetPlaybackRate set_playback_rate = 3; - optional StreamVolume set_stream_volume = 4; - optional EosPlayedOut eos_played_out = 5; - optional CurrentMediaTimestamp current_media_timestamp = 6; - optional StopPlayback stop_playback = 7; - optional BackendInitializationStatus backend_initialization_status = 8; - optional Heartbeat heartbeat = 9; -} diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/constants.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/constants.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/constants.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/constants.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/constants.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { - -const char kDefaultAudioOutputServiceUnixDomainSocketPath[] = - "/tmp/audio-output-service"; -const int kDefaultAudioOutputServiceTcpPort = 13651; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/constants.h chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/constants.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/constants.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/constants.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_CONSTANTS_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_CONSTANTS_H_ - -namespace chromecast { -namespace media { -namespace audio_output_service { - -extern const char kDefaultAudioOutputServiceUnixDomainSocketPath[]; -extern const int kDefaultAudioOutputServiceTcpPort; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_CONSTANTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_connection.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/output_connection.h" - -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "chromecast/media/audio/audio_output_service/output_socket.h" -#include "chromecast/net/socket_util.h" -#include "net/base/net_errors.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { - -namespace { - -constexpr base::TimeDelta kReconnectDelay = base::Seconds(1); -constexpr int kMaxRetries = 3; - -} // namespace - -OutputConnection::OutputConnection( - mojo::PendingRemote pending_socket_broker) - : socket_broker_(std::move(pending_socket_broker)) { - DCHECK(socket_broker_.is_connected()); -} - -OutputConnection::~OutputConnection() = default; - -void OutputConnection::Connect() { - DCHECK(!connecting_socket_); - - socket_broker_->GetSocketDescriptor(base::BindOnce( - &OutputConnection::OnSocketDescriptor, weak_factory_.GetWeakPtr())); -} - -void OutputConnection::OnSocketDescriptor(mojo::PlatformHandle handle) { - if (!handle.is_valid_fd()) { - LOG(ERROR) << "Received invalid socket descriptor."; - HandleConnectResult(net::ERR_FAILED); - return; - } - - connecting_socket_ = AdoptUnnamedSocketHandle(handle.TakeFD()); - if (!connecting_socket_) { - LOG(ERROR) << "Cannot adopt socket descriptor."; - HandleConnectResult(net::ERR_FAILED); - return; - } - DCHECK(connecting_socket_->IsConnected()); - HandleConnectResult(net::OK); -} - -void OutputConnection::HandleConnectResult(int result) { - DCHECK_NE(result, net::ERR_IO_PENDING); - - if (result == net::OK) { - log_connection_failure_ = true; - retry_count_ = 0; - auto socket = std::make_unique(std::move(connecting_socket_)); - OnConnected(std::move(socket)); - return; - } - - base::TimeDelta delay = kReconnectDelay; - if (log_connection_failure_) { - LOG(ERROR) << "Failed to connect to audio output service: " << result; - log_connection_failure_ = false; - delay = base::TimeDelta(); // No reconnect delay on the first failure. - } - connecting_socket_.reset(); - - if (++retry_count_ > kMaxRetries) { - OnConnectionFailed(); - return; - } - - base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&OutputConnection::Connect, weak_factory_.GetWeakPtr()), - delay); -} - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_connection.h chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_CONNECTION_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_CONNECTION_H_ - -#include - -#include "base/memory/weak_ptr.h" -#include "chromecast/common/mojom/audio_socket.mojom.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "mojo/public/cpp/platform/platform_handle.h" - -namespace net { -class StreamSocket; -} // namespace net - -namespace chromecast { -namespace media { -namespace audio_output_service { -class OutputSocket; - -// Base class for connecting to the audio output service. -// Since this class lives in renderers, to avoid creating sockets directly, it -// uses AudioSocketBroker to get socket handles. -class OutputConnection { - public: - explicit OutputConnection( - mojo::PendingRemote pending_socket_broker); - OutputConnection(const OutputConnection&) = delete; - OutputConnection& operator=(const OutputConnection&) = delete; - virtual ~OutputConnection(); - - // Initiates connection to the audio output service. Will call OnConnected() - // when connection is successful. - void Connect(); - - protected: - // Called when a connection is established to the audio output service. - virtual void OnConnected(std::unique_ptr socket) = 0; - - // Called when the connection failed (after retries). - virtual void OnConnectionFailed() = 0; - - private: - void HandleConnectResult(int result); - void OnSocketDescriptor(mojo::PlatformHandle handle); - - const mojo::Remote socket_broker_; - std::unique_ptr connecting_socket_; - - bool log_connection_failure_ = true; - int retry_count_ = 0; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_connection_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_connection_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_connection_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,163 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/output_connection.h" - -#include -#include - -#include "base/files/scoped_file.h" -#include "base/memory/scoped_refptr.h" -#include "base/test/gmock_callback_support.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "chromecast/common/mojom/audio_socket.mojom.h" -#include "chromecast/media/audio/audio_output_service/audio_output_service.pb.h" -#include "chromecast/media/audio/audio_output_service/output_socket.h" -#include "chromecast/net/socket_util.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/platform/platform_handle.h" -#include "net/base/io_buffer.h" -#include "net/socket/stream_socket.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { - -namespace { - -using base::test::RunOnceCallback; -using testing::_; -using testing::Invoke; - -MATCHER_P(EqualsProto, other, "") { - return arg.SerializeAsString() == other.SerializeAsString(); -} - -enum MessageTypes : int { - kTest = 1, -}; - -class MockAudioSocketBroker : public mojom::AudioSocketBroker { - public: - explicit MockAudioSocketBroker( - mojo::PendingReceiver pending_receiver) - : receiver_(this, std::move(pending_receiver)) {} - MockAudioSocketBroker(const MockAudioSocketBroker&) = delete; - MockAudioSocketBroker& operator=(const MockAudioSocketBroker&) = delete; - ~MockAudioSocketBroker() override = default; - - MOCK_METHOD(void, - GetSocketDescriptor, - (GetSocketDescriptorCallback), - (override)); - - private: - mojo::Receiver receiver_; -}; - -class MockOutputConnection : public OutputConnection { - public: - MockOutputConnection( - mojo::PendingRemote pending_socket_broker) - : OutputConnection(std::move(pending_socket_broker)) {} - MockOutputConnection(const MockOutputConnection&) = delete; - MockOutputConnection& operator=(const MockOutputConnection&) = delete; - ~MockOutputConnection() override = default; - - MOCK_METHOD(void, OnConnected, (std::unique_ptr), (override)); - MOCK_METHOD(void, OnConnectionFailed, (), (override)); -}; - -class MockAudioSocketDelegate : public OutputSocket::Delegate { - public: - MockAudioSocketDelegate() = default; - MockAudioSocketDelegate(const MockAudioSocketDelegate&) = delete; - MockAudioSocketDelegate& operator=(const MockAudioSocketDelegate&) = delete; - ~MockAudioSocketDelegate() override = default; - - MOCK_METHOD(bool, HandleMetadata, (const Generic&), (override)); - MOCK_METHOD(bool, HandleAudioData, (char*, size_t, int64_t), (override)); - MOCK_METHOD(bool, - HandleAudioBuffer, - (scoped_refptr, char*, size_t, int64_t), - (override)); - MOCK_METHOD(void, OnConnectionError, (), (override)); -}; - -} // namespace - -class OutputConnectionTest : public testing::Test { - public: - OutputConnectionTest() { - mojo::PendingRemote pending_socket_broker; - audio_socket_broker_ = std::make_unique( - pending_socket_broker.InitWithNewPipeAndPassReceiver()); - output_connection_ = std::make_unique( - std::move(pending_socket_broker)); - } - ~OutputConnectionTest() override = default; - - protected: - base::test::TaskEnvironment task_environment_{ - base::test::TaskEnvironment::MainThreadType::IO, - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; - std::unique_ptr audio_socket_broker_; - std::unique_ptr output_connection_; -}; - -TEST_F(OutputConnectionTest, ConnectSucceed) { - base::ScopedFD fd1, fd2; - CreateUnnamedSocketPair(&fd1, &fd2); - auto receiving_socket = - std::make_unique(AdoptUnnamedSocketHandle(std::move(fd2))); - auto receiving_socket_delegate = std::make_unique(); - receiving_socket->SetDelegate(receiving_socket_delegate.get()); - - Generic message; - message.mutable_set_playback_rate()->set_playback_rate(1.0); - - // Return a connected socket handle. - EXPECT_CALL(*audio_socket_broker_, GetSocketDescriptor(_)) - .Times(1) - .WillOnce(RunOnceCallback<0>(mojo::PlatformHandle(std::move(fd1)))); - - // Verify the connection is successfully established, and the returned - // OutputSocket is usable. - EXPECT_CALL(*output_connection_, OnConnected(_)) - .Times(1) - .WillOnce(Invoke([&message](std::unique_ptr socket) { - EXPECT_TRUE(!!socket); - EXPECT_TRUE(socket->SendProto(kTest, message)); - })); - - // Verify the delegate method can be triggered on the receiving end. - EXPECT_CALL(*receiving_socket_delegate, HandleMetadata(EqualsProto(message))) - .Times(1); - - output_connection_->Connect(); - task_environment_.RunUntilIdle(); -} - -TEST_F(OutputConnectionTest, ConnectFail) { - EXPECT_CALL(*audio_socket_broker_, GetSocketDescriptor(_)) - .WillRepeatedly( - [](mojom::AudioSocketBroker::GetSocketDescriptorCallback callback) { - std::move(callback).Run(mojo::PlatformHandle()); - }); - EXPECT_CALL(*output_connection_, OnConnected(_)).Times(0); - EXPECT_CALL(*output_connection_, OnConnectionFailed()).Times(1); - - output_connection_->Connect(); - task_environment_.FastForwardBy(base::Seconds(30)); - task_environment_.RunUntilIdle(); -} - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_socket.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_socket.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_socket.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_socket.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/output_socket.h" - -#include - -#include "base/check.h" -#include "base/logging.h" -#include "chromecast/media/audio/audio_output_service/audio_output_service.pb.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { - -bool OutputSocket::Delegate::HandleMetadata(const Generic& message) { - return true; -} - -OutputSocket::Delegate::~Delegate() = default; - -OutputSocket::OutputSocket(std::unique_ptr socket) - : AudioSocket(std::move(socket)) {} - -OutputSocket::OutputSocket() = default; - -OutputSocket::~OutputSocket() = default; - -void OutputSocket::SetDelegate(Delegate* delegate) { - DCHECK(delegate); - - delegate_ = delegate; - AudioSocket::SetDelegate(delegate); -} - -bool OutputSocket::ParseMetadata(char* data, size_t size) { - Generic message; - if (!message.ParseFromArray(data, size)) { - LOG(INFO) << "Invalid metadata message from " << this; - delegate_->OnConnectionError(); - return false; - } - - return delegate_->HandleMetadata(message); -} - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_socket.h chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_socket.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_socket.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_socket.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_SOCKET_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_SOCKET_H_ - -#include -#include - -#include "chromecast/media/audio/net/audio_socket.h" - -namespace net { -class StreamSocket; -} // namespace net - -namespace chromecast { -namespace media { -namespace audio_output_service { -class Generic; - -// AudioSocket implementation for sending and receiving messages to/from the -// audio output service. -class OutputSocket : public AudioSocket { - public: - class Delegate : public AudioSocket::Delegate { - public: - // Called when metadata is received from the other side of the connection. - // Return |true| if the socket should continue to receive messages. - virtual bool HandleMetadata(const Generic& message); - - protected: - ~Delegate() override; - }; - - explicit OutputSocket(std::unique_ptr socket); - OutputSocket(); - OutputSocket(const OutputSocket&) = delete; - OutputSocket& operator=(const OutputSocket&) = delete; - ~OutputSocket() override; - - // Sets/changes the delegate. Must be called immediately after creation - // (ie, synchronously on the same sequence). - void SetDelegate(Delegate* delegate); - - private: - // AudioSocket implementation: - bool ParseMetadata(char* data, size_t size) override; - - Delegate* delegate_ = nullptr; -}; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_SOCKET_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_stream_connection.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_stream_connection.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_stream_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_stream_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,199 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/output_stream_connection.h" - -#include - -#include "base/check.h" -#include "base/logging.h" -#include "net/base/io_buffer.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { - -namespace { - -constexpr base::TimeDelta kHeartbeatTimeout = base::Seconds(2); - -enum MessageTypes : int { - kInitial = 1, - kStartTimestamp, - kPlaybackRate, - kStreamVolume, - kEndOfStream, - kUpdateAudioConfig, - kStop, - kHeartbeat, -}; - -} // namespace - -OutputStreamConnection::OutputStreamConnection( - Delegate* delegate, - CmaBackendParams params, - mojo::PendingRemote pending_socket_broker) - : OutputConnection(std::move(pending_socket_broker)), - delegate_(delegate), - params_(std::move(params)) { - DCHECK(delegate_); -} - -OutputStreamConnection::~OutputStreamConnection() = default; - -void OutputStreamConnection::SendAudioBuffer( - scoped_refptr audio_buffer, - int buffer_size_bytes, - int64_t pts) { - if (!socket_) { - LOG(INFO) << "Tried to send buffer without a connection."; - return; - } - if (sent_eos_) { - // Should not send any more data after the EOS buffer. - return; - } - - if (buffer_size_bytes == 0) { - sent_eos_ = true; - Generic message; - message.mutable_eos_played_out(); - socket_->SendProto(kEndOfStream, message); - return; - } - if (socket_->SendAudioBuffer(std::move(audio_buffer), buffer_size_bytes, - pts)) { - LOG_IF(INFO, dropping_audio_) << "Stopped dropping audio."; - dropping_audio_ = false; - } else { - LOG_IF(WARNING, !dropping_audio_) << "Dropping audio."; - dropping_audio_ = true; - } - heartbeat_timer_.Reset(); -} - -void OutputStreamConnection::StartPlayingFrom(int64_t start_pts) { - if (!socket_) { - return; - } - Generic message; - message.mutable_set_start_timestamp()->set_start_pts(start_pts); - socket_->SendProto(kStartTimestamp, message); - heartbeat_timer_.Reset(); -} - -void OutputStreamConnection::StopPlayback() { - if (!socket_) { - return; - } - Generic message; - message.mutable_stop_playback(); - socket_->SendProto(kStop, message); - heartbeat_timer_.Reset(); -} - -void OutputStreamConnection::SetPlaybackRate(float playback_rate) { - playback_rate_ = playback_rate; - if (!socket_) { - return; - } - Generic message; - message.mutable_set_playback_rate()->set_playback_rate(playback_rate_); - socket_->SendProto(kPlaybackRate, message); - heartbeat_timer_.Reset(); -} - -void OutputStreamConnection::SetVolume(float volume) { - volume_ = volume; - if (!socket_) { - return; - } - Generic message; - message.mutable_set_stream_volume()->set_volume(volume_); - socket_->SendProto(kStreamVolume, message); - heartbeat_timer_.Reset(); -} - -void OutputStreamConnection::UpdateAudioConfig(const CmaBackendParams& params) { - params_.MergeFrom(params); - if (!socket_) { - return; - } - Generic message; - *(message.mutable_backend_params()) = params_; - socket_->SendProto(kUpdateAudioConfig, message); - heartbeat_timer_.Reset(); -} - -void OutputStreamConnection::Connect() { - if (socket_) { - // Don't reconnect if the connection is already established. - return; - } - OutputConnection::Connect(); -} - -void OutputStreamConnection::OnConnected(std::unique_ptr socket) { - DCHECK(socket); - - socket_ = std::move(socket); - socket_->SetDelegate(this); - - Generic message; - *(message.mutable_backend_params()) = params_; - if (playback_rate_ != 1.0f) { - message.mutable_set_playback_rate()->set_playback_rate(playback_rate_); - } - if (volume_ != 1.0f) { - message.mutable_set_stream_volume()->set_volume(volume_); - } - socket_->SendProto(kInitial, message); - heartbeat_timer_.Start(FROM_HERE, kHeartbeatTimeout, this, - &OutputStreamConnection::SendHeartbeat); -} - -void OutputStreamConnection::OnConnectionFailed() { - BackendInitializationStatus status; - status.set_status(BackendInitializationStatus::ERROR); - delegate_->OnBackendInitialized(status); -} - -void OutputStreamConnection::OnConnectionError() { - heartbeat_timer_.Stop(); - socket_.reset(); - OutputConnection::Connect(); -} - -void OutputStreamConnection::SendHeartbeat() { - if (!socket_) { - LOG(ERROR) << "No active connection. Skip heartbeat."; - return; - } - - Generic message; - message.mutable_heartbeat(); - socket_->SendProto(kHeartbeat, message); - heartbeat_timer_.Start(FROM_HERE, kHeartbeatTimeout, this, - &OutputStreamConnection::SendHeartbeat); -} - -bool OutputStreamConnection::HandleMetadata(const Generic& message) { - if (message.has_backend_initialization_status()) { - delegate_->OnBackendInitialized(message.backend_initialization_status()); - } - - if (message.has_current_media_timestamp()) { - delegate_->OnNextBuffer( - message.current_media_timestamp().media_timestamp_microseconds(), - message.current_media_timestamp().reference_timestamp_microseconds(), - message.current_media_timestamp().delay_microseconds(), - message.current_media_timestamp().delay_timestamp_microseconds()); - } - return true; -} - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_stream_connection.h chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_stream_connection.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/output_stream_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/output_stream_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_STREAM_CONNECTION_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_STREAM_CONNECTION_H_ - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "chromecast/common/mojom/audio_socket.mojom.h" -#include "chromecast/media/audio/audio_output_service/audio_output_service.pb.h" -#include "chromecast/media/audio/audio_output_service/output_connection.h" -#include "chromecast/media/audio/audio_output_service/output_socket.h" -#include "mojo/public/cpp/bindings/pending_remote.h" - -namespace net { -class IOBuffer; -} // namespace net - -namespace chromecast { -namespace media { -namespace audio_output_service { - -// OutputStreamConnection sends proto messages and audio buffers through the -// underlying socket to the audio output service to control the audio decoder -// and render audio. It also receives status updates from the audio output -// service. Threading model: this class should be created and used on an IO -// thread. -class OutputStreamConnection : public OutputConnection, - public OutputSocket::Delegate { - public: - // Delegate methods will be called on the sequence OutputStreamConnection is - // created. - class Delegate { - public: - // Called when the audio pipeline backend is initialized. - virtual void OnBackendInitialized( - const BackendInitializationStatus& status) = 0; - - // Called when the audio pipeline backend is ready to receive the next - // buffer. - // TODO(b/173250111): Remove `media_timestamp_microseconds` and - // `reference_timestamp_microseconds` once all the implementations switched - // to using delay information. - virtual void OnNextBuffer(int64_t media_timestamp_microseconds, - int64_t reference_timestamp_microseconds, - int64_t delay_microseconds, - int64_t delay_timestamp_microseconds) = 0; - - protected: - virtual ~Delegate() = default; - }; - - OutputStreamConnection( - Delegate* delegate, - CmaBackendParams params, - mojo::PendingRemote pending_socket_broker); - OutputStreamConnection(const OutputStreamConnection&) = delete; - OutputStreamConnection& operator=(const OutputStreamConnection&) = delete; - ~OutputStreamConnection() override; - - // Connects to the audio output service. After this is called, delegate - // methods may start to be called. If the output connection is lost, this will - // automatically reconnect. - void Connect(); - - // Sends |audio_buffer| to the audio output service. - void SendAudioBuffer(scoped_refptr audio_buffer, - int buffer_size_bytes, - int64_t pts); - - // Starts the playback from |start_pts|. - void StartPlayingFrom(int64_t start_pts); - - // Stops the playback. - void StopPlayback(); - - // Sets the playback rate. - void SetPlaybackRate(float playback_rate); - - // Sets the playback volume. - void SetVolume(float volume); - - // Updates the config for the audio decoder. - void UpdateAudioConfig(const CmaBackendParams& params); - - private: - // OutputConnection implementation: - void OnConnected(std::unique_ptr socket) override; - void OnConnectionFailed() override; - void OnConnectionError() override; - - // OutputSocket::Delegate implementation: - bool HandleMetadata(const Generic& message) override; - - void SendHeartbeat(); - - Delegate* const delegate_; - CmaBackendParams params_; - std::unique_ptr socket_; - base::OneShotTimer heartbeat_timer_; - float volume_ = 1.0f; - float playback_rate_ = 1.0f; - bool sent_eos_ = false; - bool dropping_audio_ = false; -}; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_OUTPUT_STREAM_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,250 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.h" - -#include - -#include "base/check.h" -#include "base/logging.h" -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/audio/audio_output_service/constants.h" -#include "chromecast/media/audio/audio_output_service/output_socket.h" -#include "chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { - -namespace { - -constexpr base::TimeDelta kInactivityTimeout = base::Seconds(5); - -enum MessageTypes : int { - kUpdateMediaTime = 1, - kBackendInitialized = 2, -}; - -} // namespace - -class AudioOutputServiceReceiver::Stream - : public audio_output_service::OutputSocket::Delegate, - public audio_output_service::CmaBackendShim::Delegate { - public: - Stream(AudioOutputServiceReceiver* receiver, - std::unique_ptr socket) - : receiver_(receiver), socket_(std::move(socket)) { - DCHECK(receiver_); - DCHECK(socket_); - - socket_->SetDelegate(this); - - inactivity_timer_.Start(FROM_HERE, kInactivityTimeout, this, - &Stream::OnInactivityTimeout); - } - Stream(const Stream&) = delete; - Stream& operator=(const Stream&) = delete; - ~Stream() override = default; - - // OutputSocket::Delegate implementation: - bool HandleMetadata(const Generic& message) override { - last_receive_time_ = base::TimeTicks::Now(); - inactivity_timer_.Reset(); - - if (message.has_heartbeat()) { - return true; - } - - if (message.has_backend_params()) { - if (cma_audio_) { - LOG(INFO) << "Received stream metadata after initialization, there must" - << " be an update to the audio config."; - cma_audio_->UpdateAudioConfig(message.backend_params()); - return true; - } - - pushed_eos_ = false; - cma_audio_.reset(new audio_output_service::CmaBackendShim( - weak_factory_.GetWeakPtr(), - base::SequencedTaskRunner::GetCurrentDefault(), - receiver_->media_task_runner(), message.backend_params(), - receiver_->cma_backend_factory())); - } - - if (message.has_set_start_timestamp()) { - if (!cma_audio_) { - LOG(INFO) << "Can't start before stream is set up."; - ResetConnection(); - return false; - } - cma_audio_->StartPlayingFrom(message.set_start_timestamp().start_pts()); - } - - if (message.has_stop_playback()) { - if (!cma_audio_) { - LOG(INFO) << "Can't stop before stream is set up."; - ResetConnection(); - return false; - } - cma_audio_->Stop(); - } - - if (message.has_set_stream_volume()) { - if (!cma_audio_) { - LOG(INFO) << "Can't set volume before stream is set up."; - ResetConnection(); - return false; - } - cma_audio_->SetVolumeMultiplier(message.set_stream_volume().volume()); - } - - if (message.has_set_playback_rate()) { - if (!cma_audio_) { - LOG(INFO) << "Can't set playback rate before stream is set up."; - ResetConnection(); - return false; - } - cma_audio_->SetPlaybackRate(message.set_playback_rate().playback_rate()); - } - - if (message.has_eos_played_out()) { - // Explicit EOS. - return HandleAudioData(nullptr, 0, INT64_MIN); - } - - return true; - } - - bool HandleAudioData(char* data, size_t size, int64_t timestamp) override { - last_receive_time_ = base::TimeTicks::Now(); - inactivity_timer_.Reset(); - - if (!cma_audio_) { - LOG(INFO) << "Received audio before stream metadata; ignoring"; - ResetConnection(); - return false; - } - - if (size == 0) { - pushed_eos_ = true; - } - cma_audio_->AddData(data, size, timestamp); - stopped_receiving_ = true; - return false; // Don't receive any more messages until the buffer is - // pushed. - } - - void OnConnectionError() override { - LOG(INFO) << "Connection lost for " << this; - receiver_->RemoveStream(this); - } - - private: - void OnInactivityTimeout() { - LOG(INFO) << "Timed out " << this - << " due to inactivity; now = " << base::TimeTicks::Now() - << ", last send = " << last_send_time_ - << ", last receive = " << last_receive_time_; - receiver_->RemoveStream(this); - } - - // CmaBackendShim::Delegate implementation: - void OnBackendInitialized(bool success) override { - audio_output_service::Generic generic; - generic.mutable_backend_initialization_status()->set_status( - success ? audio_output_service::BackendInitializationStatus::SUCCESS - : audio_output_service::BackendInitializationStatus::ERROR); - socket_->SendProto(kBackendInitialized, generic); - last_send_time_ = base::TimeTicks::Now(); - } - - void OnBufferPushed() override { - if (!stopped_receiving_) { - return; - } - stopped_receiving_ = false; - socket_->ReceiveMoreMessages(); - } - - void UpdateMediaTimeAndRenderingDelay( - int64_t media_timestamp_microseconds, - int64_t reference_timestamp_microseconds, - int64_t delay_microseconds, - int64_t delay_timestamp_microseconds) override { - audio_output_service::CurrentMediaTimestamp message; - message.set_media_timestamp_microseconds(media_timestamp_microseconds); - message.set_reference_timestamp_microseconds( - reference_timestamp_microseconds); - message.set_delay_microseconds(delay_microseconds); - message.set_delay_timestamp_microseconds(delay_timestamp_microseconds); - audio_output_service::Generic generic; - *(generic.mutable_current_media_timestamp()) = message; - socket_->SendProto(kUpdateMediaTime, generic); - last_send_time_ = base::TimeTicks::Now(); - } - - void OnAudioPlaybackError() override { - LOG(INFO) << "Audio playback error for " << this; - receiver_->RemoveStream(this); - } - - void ResetConnection() { - // Reset will cause the deletion of |this|, so it is better to post a task. - base::SequencedTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&Stream::OnAudioPlaybackError, - weak_factory_.GetWeakPtr())); - } - - AudioOutputServiceReceiver* const receiver_; - const std::unique_ptr socket_; - - base::OneShotTimer inactivity_timer_; - - std::unique_ptr - cma_audio_; - bool pushed_eos_ = false; - bool stopped_receiving_ = false; - - base::TimeTicks last_send_time_; - base::TimeTicks last_receive_time_; - - base::WeakPtrFactory weak_factory_{this}; -}; - -AudioOutputServiceReceiver::AudioOutputServiceReceiver( - CmaBackendFactory* cma_backend_factory, - scoped_refptr media_task_runner) - : Receiver( - audio_output_service::kDefaultAudioOutputServiceUnixDomainSocketPath, - audio_output_service::kDefaultAudioOutputServiceTcpPort), - cma_backend_factory_(cma_backend_factory), - media_task_runner_(std::move(media_task_runner)) { - DCHECK(cma_backend_factory_); - DCHECK(media_task_runner_); -} - -AudioOutputServiceReceiver::~AudioOutputServiceReceiver() = default; - -void AudioOutputServiceReceiver::CreateOutputStream( - std::unique_ptr socket, - const Generic& message) { - auto stream = std::make_unique(this, std::move(socket)); - Stream* ptr = stream.get(); - streams_[ptr] = std::move(stream); - ptr->HandleMetadata(message); -} - -void AudioOutputServiceReceiver::RemoveStream(Stream* stream) { - streams_.erase(stream); -} - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.h chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_AUDIO_OUTPUT_SERVICE_RECEIVER_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_AUDIO_OUTPUT_SERVICE_RECEIVER_H_ - -#include - -#include "base/containers/flat_map.h" -#include "base/memory/scoped_refptr.h" -#include "chromecast/media/audio/audio_output_service/audio_output_service.pb.h" -#include "chromecast/media/audio/audio_output_service/receiver/receiver.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -namespace media { -class CmaBackendFactory; - -namespace audio_output_service { -class OutputSocket; - -class AudioOutputServiceReceiver : public Receiver { - public: - explicit AudioOutputServiceReceiver( - CmaBackendFactory* cma_backend_factory, - scoped_refptr media_task_runner); - AudioOutputServiceReceiver(const AudioOutputServiceReceiver&) = delete; - AudioOutputServiceReceiver& operator=(const AudioOutputServiceReceiver&) = - delete; - ~AudioOutputServiceReceiver() override; - - CmaBackendFactory* cma_backend_factory() const { - return cma_backend_factory_; - } - - scoped_refptr media_task_runner() const { - return media_task_runner_; - } - - private: - class Stream; - - // Receiver implementation: - void CreateOutputStream(std::unique_ptr socket, - const Generic& message) override; - - void RemoveStream(Stream* stream); - - CmaBackendFactory* const cma_backend_factory_; - const scoped_refptr media_task_runner_; - - base::flat_map> streams_; -}; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_AUDIO_OUTPUT_SERVICE_RECEIVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.h" - -#include - -#include "base/task/single_thread_task_runner.h" -#include "base/threading/sequence_bound.h" -#include "chromecast/media/audio/audio_io_thread.h" -#include "chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { - -namespace { - -class AudioOutputServiceReceiverInstance : public ReceiverInstance { - public: - AudioOutputServiceReceiverInstance( - CmaBackendFactory* cma_backend_factory, - scoped_refptr media_task_runner) - : receiver_(AudioIoThread::Get()->task_runner(), - cma_backend_factory, - std::move(media_task_runner)) {} - - ~AudioOutputServiceReceiverInstance() override = default; - - private: - base::SequenceBound receiver_; -}; - -} // namespace - -// static -std::unique_ptr ReceiverInstance::Create( - CmaBackendFactory* cma_backend_factory, - scoped_refptr media_task_runner) { - return std::make_unique( - cma_backend_factory, std::move(media_task_runner)); -} - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.h chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/audio_output_service_receiver_instance.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_AUDIO_OUTPUT_SERVICE_RECEIVER_INSTANCE_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_AUDIO_OUTPUT_SERVICE_RECEIVER_INSTANCE_H_ - -#include - -#include "base/memory/scoped_refptr.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { - -namespace media { -class CmaBackendFactory; - -namespace audio_output_service { - -class ReceiverInstance { - public: - virtual ~ReceiverInstance() = default; - - static std::unique_ptr Create( - CmaBackendFactory* cma_backend_factory, - scoped_refptr media_task_runner); -}; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_AUDIO_OUTPUT_SERVICE_RECEIVER_INSTANCE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,337 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/media/base/audio_device_ids.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/media/stream_id.h" -#include "chromecast/public/volume_control.h" - -#define POST_DELEGATE_TASK(callback, ...) \ - delegate_task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(callback, delegate_, ##__VA_ARGS__)); - -#define POST_MEDIA_TASK(callback, ...) \ - media_task_runner_->PostTask( \ - FROM_HERE, \ - base::BindOnce(callback, base::Unretained(this), ##__VA_ARGS__)) - -namespace chromecast { -namespace media { - -namespace audio_output_service { - -CmaBackendShim::CmaBackendShim( - base::WeakPtr delegate, - scoped_refptr delegate_task_runner, - scoped_refptr media_task_runner, - const audio_output_service::CmaBackendParams& params, - CmaBackendFactory* cma_backend_factory) - : delegate_(std::move(delegate)), - delegate_task_runner_(std::move(delegate_task_runner)), - cma_backend_factory_(cma_backend_factory), - media_task_runner_(std::move(media_task_runner)), - backend_task_runner_(media_task_runner_), - backend_params_(params), - audio_decoder_(nullptr) { - DCHECK(delegate_task_runner_); - DCHECK(cma_backend_factory_); - DCHECK(media_task_runner_); - - POST_MEDIA_TASK(&CmaBackendShim::InitializeOnMediaThread); -} - -CmaBackendShim::~CmaBackendShim() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - if (backend_state_ != BackendState::kStopped) { - cma_backend_->Stop(); - } -} - -void CmaBackendShim::Remove() { - POST_MEDIA_TASK(&CmaBackendShim::DestroyOnMediaThread); -} - -void CmaBackendShim::InitializeOnMediaThread() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - MediaPipelineDeviceParams device_params( - MediaPipelineDeviceParams::kModeSyncPts, &backend_task_runner_, - AudioContentType::kMedia, kDefaultDeviceId); - device_params.session_id = - backend_params_.application_media_info().application_session_id(); - cma_backend_ = cma_backend_factory_->CreateBackend(device_params); - - audio_decoder_ = cma_backend_->CreateAudioDecoder(); - if (!audio_decoder_) { - LOG(ERROR) << "Failed to create CMA audio decoder"; - POST_DELEGATE_TASK(&Delegate::OnBackendInitialized, /*success=*/false); - return; - } - audio_decoder_->SetDelegate(this); - - bool success = SetAudioConfig(); - if (!success) { - LOG(ERROR) << "Failed to set audio decoder config."; - POST_DELEGATE_TASK(&Delegate::OnBackendInitialized, success); - return; - } - audio_decoder_->SetVolume(1.0f); - - success = cma_backend_->Initialize(); - if (!success) { - LOG(ERROR) << "Failed to initialize CMA backend"; - } - POST_DELEGATE_TASK(&Delegate::OnBackendInitialized, success); -} - -void CmaBackendShim::DestroyOnMediaThread() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - delete this; -} - -void CmaBackendShim::AddData(char* data, int size, int64_t timestamp) { - if (size == 0) { - POST_MEDIA_TASK(&CmaBackendShim::AddEosDataOnMediaThread); - return; - } - auto buffer = base::MakeRefCounted(size); - memcpy(buffer->writable_data(), reinterpret_cast(data), size); - buffer->set_timestamp(base::Microseconds(timestamp)); - POST_MEDIA_TASK(&CmaBackendShim::AddDataOnMediaThread, std::move(buffer)); -} - -void CmaBackendShim::AddEosDataOnMediaThread() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - scoped_refptr buffer = - CastDecoderBufferImpl::CreateEOSBuffer(); - AddDataOnMediaThread(std::move(buffer)); -} - -void CmaBackendShim::AddDataOnMediaThread( - scoped_refptr buffer) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK_NE(backend_state_, BackendState::kStopped); - - if (!audio_decoder_) { - return; - } - pushed_buffer_ = std::move(buffer); - BufferStatus status = audio_decoder_->PushBuffer(pushed_buffer_); - if (status != MediaPipelineBackend::kBufferPending) { - OnPushBufferComplete(status); - } -} - -void CmaBackendShim::SetVolumeMultiplier(float multiplier) { - multiplier = std::max(0.0f, std::min(multiplier, 1.0f)); - POST_MEDIA_TASK(&CmaBackendShim::SetVolumeMultiplierOnMediaThread, - multiplier); -} - -void CmaBackendShim::SetPlaybackRate(float playback_rate) { - POST_MEDIA_TASK(&CmaBackendShim::SetPlaybackRateOnMediaThread, playback_rate); -} - -void CmaBackendShim::StartPlayingFrom(int64_t start_pts) { - POST_MEDIA_TASK(&CmaBackendShim::StartPlayingFromOnMediaThread, start_pts); -} - -void CmaBackendShim::Stop() { - POST_MEDIA_TASK(&CmaBackendShim::StopOnMediaThread); -} - -void CmaBackendShim::UpdateAudioConfig( - const audio_output_service::CmaBackendParams& params) { - POST_MEDIA_TASK(&CmaBackendShim::UpdateAudioConfigOnMediaThread, params); -} - -void CmaBackendShim::SetVolumeMultiplierOnMediaThread(float multiplier) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - if (!audio_decoder_) { - return; - } - audio_decoder_->SetVolume(multiplier); -} - -void CmaBackendShim::SetPlaybackRateOnMediaThread(float playback_rate) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - if (!cma_backend_ || playback_rate_ == playback_rate) { - return; - } - float old_playback_rate = playback_rate_; - playback_rate_ = playback_rate; - if (backend_state_ == BackendState::kPlaying && playback_rate_ == 0.0f) { - if (!cma_backend_->Pause()) { - LOG(ERROR) << "Failed to pause CMA backend."; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - } - backend_state_ = BackendState::kPaused; - } - - if (backend_state_ == BackendState::kPaused && old_playback_rate == 0.0f) { - if (!cma_backend_->Resume()) { - LOG(ERROR) << "Failed to resume CMA backend."; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } - backend_state_ = BackendState::kPlaying; - } - - if (backend_state_ != BackendState::kStopped) { - UpdateMediaTimeAndRenderingDelay(); - } - - if (playback_rate_ == 0.0f) { - return; - } - - if (!cma_backend_->SetPlaybackRate(playback_rate_)) { - LOG(ERROR) << "Failed to set playback rate for CMA backend."; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } -} - -void CmaBackendShim::StartPlayingFromOnMediaThread(int64_t start_pts) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - if (!cma_backend_) { - return; - } - if (!cma_backend_->Start(start_pts)) { - LOG(ERROR) << "Failed to start CMA backend"; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } - if (playback_rate_ == 0.0f) { - if (!cma_backend_->Pause()) { - LOG(ERROR) << "Failed to pause CMA backend"; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } - backend_state_ = BackendState::kPaused; - } else { - backend_state_ = BackendState::kPlaying; - } -} - -void CmaBackendShim::StopOnMediaThread() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - if (!cma_backend_ || backend_state_ == BackendState::kStopped) { - return; - } - cma_backend_->Stop(); - backend_state_ = BackendState::kStopped; -} - -void CmaBackendShim::UpdateAudioConfigOnMediaThread( - const audio_output_service::CmaBackendParams& params) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - backend_params_.MergeFrom(params); - if (!audio_decoder_) { - return; - } - if (!SetAudioConfig()) { - LOG(ERROR) << "Failed to set CMA audio config"; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - } -} - -bool CmaBackendShim::SetAudioConfig() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK(audio_decoder_); - - const auto& audio_decoder_config = backend_params_.audio_decoder_config(); - - AudioConfig audio_config; - audio_config.id = kPrimary; - audio_config.codec = - audio_service::ConvertAudioCodec(audio_decoder_config.audio_codec()); - audio_config.channel_layout = - ConvertChannelLayout(audio_decoder_config.channel_layout()); - if (audio_config.channel_layout == media::ChannelLayout::UNSUPPORTED) { - audio_config.channel_layout = - ChannelLayoutFromChannelNumber(audio_decoder_config.num_channels()); - } - audio_config.sample_format = - audio_service::ConvertSampleFormat(audio_decoder_config.sample_format()); - audio_config.bytes_per_channel = - audio_service::GetSampleSizeBytes(audio_decoder_config.sample_format()); - audio_config.channel_number = audio_decoder_config.num_channels(); - audio_config.samples_per_second = audio_decoder_config.sample_rate(); - audio_config.extra_data = - std::vector(audio_decoder_config.extra_data().begin(), - audio_decoder_config.extra_data().end()); - return audio_decoder_->SetConfig(audio_config); -} - -void CmaBackendShim::UpdateMediaTimeAndRenderingDelay() { - if (!cma_backend_ || !audio_decoder_) { - return; - } - auto rendering_delay = audio_decoder_->GetRenderingDelay(); - POST_DELEGATE_TASK(&Delegate::UpdateMediaTimeAndRenderingDelay, - cma_backend_->GetCurrentPts(), - base::TimeTicks::Now().since_origin().InMicroseconds(), - rendering_delay.delay_microseconds, - rendering_delay.timestamp_microseconds); -} - -void CmaBackendShim::OnPushBufferComplete(BufferStatus status) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - pushed_buffer_.reset(); - if (status != MediaPipelineBackend::kBufferSuccess) { - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } - POST_DELEGATE_TASK(&Delegate::OnBufferPushed); - UpdateMediaTimeAndRenderingDelay(); -} - -void CmaBackendShim::OnEndOfStream() { - NOTIMPLEMENTED_LOG_ONCE(); -} - -void CmaBackendShim::OnDecoderError() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); -} - -void CmaBackendShim::OnKeyStatusChanged(const std::string& /* key_id */, - CastKeyStatus /* key_status */, - uint32_t /* system_code */) { - NOTIMPLEMENTED_LOG_ONCE(); -} - -void CmaBackendShim::OnVideoResolutionChanged(const Size& /* size */) { - NOTIMPLEMENTED_LOG_ONCE(); -} - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.h chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/cma_backend_shim.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,147 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_CMA_BACKEND_SHIM_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_CMA_BACKEND_SHIM_H_ - -#include -#include -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/audio/audio_output_service/audio_output_service.pb.h" - -namespace base { -class SequencedTaskRunner; -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { - -namespace media { -class CmaBackendFactory; - -namespace audio_output_service { - -// A shim to allow the audio output service to use the CMA backend API. -// May be created and used on any thread; internally runs all tasks on the media -// thread. Deletion must be done using Remove() (or using a unique_ptr with -// custom Deleter); Remove() will eventually delete this on the appropriate -// sequence. -class CmaBackendShim : public CmaBackend::AudioDecoder::Delegate { - public: - class Delegate { - public: - // Called when the CMA backend is initialized (success or failure). - virtual void OnBackendInitialized(bool success) = 0; - - // Called once data passed to AddData() has been accepted into the queue. - virtual void OnBufferPushed() = 0; - - // Called when the audio pts changed. - virtual void UpdateMediaTimeAndRenderingDelay( - int64_t media_timestamp_microseconds, - int64_t reference_timestamp_microseconds, - int64_t delay_microseconds, - int64_t delay_timestamp_microseconds) = 0; - - // Called if an error occurs in audio playback. No more delegate calls will - // be made. - virtual void OnAudioPlaybackError() = 0; - - protected: - virtual ~Delegate() = default; - }; - - // Can be used as a custom deleter for unique_ptr. - struct Deleter { - void operator()(CmaBackendShim* obj) { obj->Remove(); } - }; - - CmaBackendShim(base::WeakPtr delegate, - scoped_refptr delegate_task_runner, - scoped_refptr media_task_runner, - const CmaBackendParams& params, - CmaBackendFactory* cma_backend_factory); - - // Removes this audio output. Public methods must not be called after Remove() - // is called. - void Remove(); - - // Adds more data to be played out. More data should not be passed to - // AddData() until OnBufferPushed() has been called for the previous AddData() - // call. |size| is the size of |data| in bytes; a size of 0 indicates - // end-of-stream. - void AddData(char* data, int size, int64_t timestamp); - - // Sets the volume multiplier for this stream. - void SetVolumeMultiplier(float multiplier); - - // Sets the playback rate. - void SetPlaybackRate(float playback_rate); - - // Starts playback from |start_pts|. - void StartPlayingFrom(int64_t start_pts); - - // Stops CMA backend. - void Stop(); - - // Updates the config for audio decoder. - void UpdateAudioConfig(const CmaBackendParams& params); - - private: - enum class BackendState { - kStopped, - kPlaying, - kPaused, - }; - - ~CmaBackendShim() override; - - // CmaBackend::AudioDecoder::Delegate implementation: - void OnPushBufferComplete(BufferStatus status) override; - void OnEndOfStream() override; - void OnDecoderError() override; - void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override; - void OnVideoResolutionChanged(const Size& size) override; - - void InitializeOnMediaThread(); - void DestroyOnMediaThread(); - void AddEosDataOnMediaThread(); - void AddDataOnMediaThread(scoped_refptr buffer); - void StartPlayingFromOnMediaThread(int64_t start_pts); - void SetVolumeMultiplierOnMediaThread(float multiplier); - void SetPlaybackRateOnMediaThread(float playback_rate); - void StopOnMediaThread(); - void UpdateAudioConfigOnMediaThread(const CmaBackendParams& params); - bool SetAudioConfig(); - void UpdateMediaTimeAndRenderingDelay(); - - const base::WeakPtr delegate_; - const scoped_refptr delegate_task_runner_; - CmaBackendFactory* const cma_backend_factory_; - const scoped_refptr media_task_runner_; - TaskRunnerImpl backend_task_runner_; - CmaBackendParams backend_params_; - scoped_refptr pushed_buffer_; - - float playback_rate_ = 0.0f; - - std::unique_ptr cma_backend_; - BackendState backend_state_ = BackendState::kStopped; - CmaBackend::AudioDecoder* audio_decoder_; -}; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_CMA_BACKEND_SHIM_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/receiver.cc chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/receiver.cc --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/receiver.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/receiver.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/audio_output_service/receiver/receiver.h" - -#include - -#include "chromecast/media/audio/audio_output_service/audio_output_service.pb.h" -#include "chromecast/media/audio/audio_output_service/output_socket.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { - -namespace { - -constexpr int kMaxAcceptLoop = 5; - -} // namespace - -class Receiver::InitialSocket : public OutputSocket::Delegate { - public: - InitialSocket(Receiver* receiver, std::unique_ptr socket) - : receiver_(receiver), socket_(std::move(socket)) { - DCHECK(receiver_); - socket_->SetDelegate(this); - } - - InitialSocket(const InitialSocket&) = delete; - InitialSocket& operator=(const InitialSocket&) = delete; - ~InitialSocket() override = default; - - private: - // OutputSocket::Delegate implementation: - bool HandleMetadata(const Generic& message) override { - if (message.has_backend_params()) { - receiver_->CreateOutputStream(std::move(socket_), message); - receiver_->RemoveInitialSocket(this); - } - - return true; - } - - void OnConnectionError() override { receiver_->RemoveInitialSocket(this); } - - Receiver* const receiver_; - std::unique_ptr socket_; -}; - -Receiver::Receiver(const std::string& uds_path, int tcp_port) - : socket_service_(uds_path, - tcp_port, - kMaxAcceptLoop, - this, - /*use_socket_descriptor=*/true) { - socket_service_.Accept(); -} - -Receiver::~Receiver() = default; - -void Receiver::HandleAcceptedSocket(std::unique_ptr socket) { - AddInitialSocket(std::make_unique( - this, std::make_unique(std::move(socket)))); -} - -void Receiver::AddInitialSocket(std::unique_ptr initial_socket) { - InitialSocket* ptr = initial_socket.get(); - initial_sockets_[ptr] = std::move(initial_socket); -} - -void Receiver::RemoveInitialSocket(InitialSocket* initial_socket) { - initial_sockets_.erase(initial_socket); -} - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/receiver.h chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/receiver.h --- chromium-132.0.6834.110/chromecast/media/audio/audio_output_service/receiver/receiver.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/audio_output_service/receiver/receiver.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_RECEIVER_H_ -#define CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_RECEIVER_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/media/audio/net/audio_socket_service.h" - -namespace chromecast { -namespace media { -namespace audio_output_service { -class Generic; -class OutputSocket; - -class Receiver : public AudioSocketService::Delegate { - public: - Receiver(const std::string& uds_path, int tcp_port); - Receiver(const Receiver&) = delete; - Receiver& operator=(const Receiver&) = delete; - ~Receiver() override; - - virtual void CreateOutputStream(std::unique_ptr socket, - const Generic& message) = 0; - - private: - class InitialSocket; - - // mixer_service::AudioSocketService::Delegate implementation: - void HandleAcceptedSocket(std::unique_ptr socket) override; - - void AddInitialSocket(std::unique_ptr initial_socket); - void RemoveInitialSocket(InitialSocket* initial_socket); - - AudioSocketService socket_service_; - base::flat_map> - initial_sockets_; -}; - -} // namespace audio_output_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_AUDIO_OUTPUT_SERVICE_RECEIVER_RECEIVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/DEPS chromium-132.0.6834.159/chromecast/media/audio/capture_service/DEPS --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+chromecast/net", - "+net", -] diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/capture_service_receiver.cc chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver.cc --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/capture_service_receiver.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,284 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/capture_service/capture_service_receiver.h" - -#include -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/message_loop/message_pump_type.h" -#include "base/synchronization/waitable_event.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/audio/capture_service/message_parsing_utils.h" -#include "chromecast/media/audio/net/audio_socket_service.h" -#include "chromecast/net/small_message_socket.h" -#include "net/base/io_buffer.h" -#include "net/socket/stream_socket.h" - -// Helper macro to post tasks to the io thread. It is safe to use unretained -// |this|, since |this| owns the thread. -#define ENSURE_ON_IO_THREAD(method, ...) \ - if (!task_runner_->RunsTasksInCurrentSequence()) { \ - task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&CaptureServiceReceiver::method, \ - base::Unretained(this), ##__VA_ARGS__)); \ - return; \ - } - -namespace chromecast { -namespace media { - -class CaptureServiceReceiver::Socket : public SmallMessageSocket::Delegate { - public: - Socket(std::unique_ptr socket, - capture_service::StreamInfo request_stream_info, - CaptureServiceReceiver::Delegate* delegate); - Socket(const Socket&) = delete; - Socket& operator=(const Socket&) = delete; - ~Socket() override; - - private: - enum class State { - kInit, - kWaitForAck, - kStreaming, - kShutdown, - }; - - // SmallMessageSocket::Delegate implementation: - void OnSendUnblocked() override; - void OnError(int error) override; - void OnEndOfStream() override; - bool OnMessage(char* data, size_t size) override; - - bool SendRequest(); - void OnInactivityTimeout(); - void OnInitialStreamInfo(const capture_service::StreamInfo& stream_info); - bool HandleAck(char* data, size_t size); - bool HandleAudio(char* data, size_t size); - void ReportErrorAndStop(); - - SmallMessageSocket socket_; - - const capture_service::StreamInfo request_stream_info_; - CaptureServiceReceiver::Delegate* const delegate_; - - State state_ = State::kInit; -}; - -CaptureServiceReceiver::Socket::Socket( - std::unique_ptr socket, - capture_service::StreamInfo request_stream_info, - CaptureServiceReceiver::Delegate* delegate) - : socket_(this, std::move(socket)), - request_stream_info_(std::move(request_stream_info)), - delegate_(delegate) { - DCHECK(delegate_); - if (!SendRequest()) { - ReportErrorAndStop(); - return; - } - socket_.ReceiveMessages(); -} - -CaptureServiceReceiver::Socket::~Socket() = default; - -bool CaptureServiceReceiver::Socket::SendRequest() { - DCHECK_EQ(state_, State::kInit); - auto request_buffer = - capture_service::MakeHandshakeMessage(request_stream_info_); - if (!request_buffer) { - return false; - } - if (!socket_.SendBuffer(request_buffer.get(), request_buffer->size())) { - LOG(WARNING) << "Socket should not block sending since the request is the " - "first buffer sent."; - return false; - } - state_ = State::kWaitForAck; - return true; -} - -void CaptureServiceReceiver::Socket::OnSendUnblocked() { - // The request is the first buffer sent, so it should be always accepted by - // the socket. - NOTREACHED(); -} - -void CaptureServiceReceiver::Socket::ReportErrorAndStop() { - DCHECK_NE(state_, State::kShutdown); - delegate_->OnCaptureError(); - state_ = State::kShutdown; -} - -void CaptureServiceReceiver::Socket::OnError(int error) { - LOG(INFO) << "Socket error from " << this << ": " << error; - ReportErrorAndStop(); -} - -void CaptureServiceReceiver::Socket::OnEndOfStream() { - LOG(ERROR) << "Got EOS " << this; - ReportErrorAndStop(); -} - -bool CaptureServiceReceiver::Socket::OnMessage(char* data, size_t size) { - uint8_t type = 0; - if (size < sizeof(type)) { - LOG(ERROR) << "Invalid message size: " << size << "."; - return false; - } - memcpy(&type, data, sizeof(type)); - capture_service::MessageType message_type = - static_cast(type); - - if (state_ == State::kWaitForAck && - message_type == capture_service::MessageType::kHandshake) { - return HandleAck(data, size); - } - - if (state_ == State::kStreaming && - (message_type == capture_service::MessageType::kPcmAudio || - message_type == capture_service::MessageType::kOpusAudio)) { - return HandleAudio(data, size); - } - - if (message_type == capture_service::MessageType::kMetadata) { - delegate_->OnCaptureMetadata(data, size); - return true; - } - - LOG(WARNING) << "Receive message with type " << type << " at state " - << static_cast(state_) << ", ignored."; - return true; -} - -bool CaptureServiceReceiver::Socket::HandleAck(char* data, size_t size) { - DCHECK_EQ(state_, State::kWaitForAck); - capture_service::StreamInfo info; - if (!capture_service::ReadHandshakeMessage(data, size, &info) || - !delegate_->OnInitialStreamInfo(info)) { - ReportErrorAndStop(); - return false; - } - state_ = State::kStreaming; - return true; -} - -bool CaptureServiceReceiver::Socket::HandleAudio(char* data, size_t size) { - DCHECK_EQ(state_, State::kStreaming); - if (!delegate_->OnCaptureData(data, size)) { - ReportErrorAndStop(); - return false; - } - return true; -} - -// static -constexpr base::TimeDelta CaptureServiceReceiver::kConnectTimeout; - -CaptureServiceReceiver::CaptureServiceReceiver( - capture_service::StreamInfo request_stream_info, - Delegate* delegate) - : request_stream_info_(std::move(request_stream_info)), - delegate_(delegate), - io_thread_(__func__) { - DCHECK(delegate_); - base::Thread::Options options; - options.message_pump_type = base::MessagePumpType::IO; - options.thread_type = base::ThreadType::kDisplayCritical; - CHECK(io_thread_.StartWithOptions(std::move(options))); - task_runner_ = io_thread_.task_runner(); - DCHECK(task_runner_); -} - -CaptureServiceReceiver::~CaptureServiceReceiver() { - Stop(); - io_thread_.Stop(); -} - -void CaptureServiceReceiver::Start() { - ENSURE_ON_IO_THREAD(Start); - - std::string path = capture_service::kDefaultUnixDomainSocketPath; - int port = capture_service::kDefaultTcpPort; - - StartWithSocket(AudioSocketService::Connect(path, port)); -} - -void CaptureServiceReceiver::StartWithSocket( - std::unique_ptr connecting_socket) { - ENSURE_ON_IO_THREAD(StartWithSocket, std::move(connecting_socket)); - DCHECK(!connecting_socket_); - DCHECK(!socket_); - - connecting_socket_ = std::move(connecting_socket); - DCHECK(connecting_socket_); - int result = connecting_socket_->Connect(base::BindOnce( - &CaptureServiceReceiver::OnConnected, base::Unretained(this))); - if (result != net::ERR_IO_PENDING) { - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&CaptureServiceReceiver::OnConnected, - base::Unretained(this), result)); - return; - } - - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce(&CaptureServiceReceiver::OnConnectTimeout, - base::Unretained(this)), - kConnectTimeout); -} - -void CaptureServiceReceiver::OnConnected(int result) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - DCHECK_NE(result, net::ERR_IO_PENDING); - if (!connecting_socket_) { - return; - } - - if (result == net::OK) { - socket_ = std::make_unique(std::move(connecting_socket_), - request_stream_info_, delegate_); - } else { - LOG(INFO) << "Connecting failed: " << net::ErrorToString(result); - delegate_->OnCaptureError(); - connecting_socket_.reset(); - } -} - -void CaptureServiceReceiver::OnConnectTimeout() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - if (!connecting_socket_) { - return; - } - LOG(ERROR) << __func__; - delegate_->OnCaptureError(); - connecting_socket_.reset(); -} - -void CaptureServiceReceiver::Stop() { - base::WaitableEvent finished; - StopOnTaskRunner(&finished); - finished.Wait(); -} - -void CaptureServiceReceiver::StopOnTaskRunner(base::WaitableEvent* finished) { - ENSURE_ON_IO_THREAD(StopOnTaskRunner, finished); - connecting_socket_.reset(); - socket_.reset(); - finished->Signal(); -} - -void CaptureServiceReceiver::SetTaskRunnerForTest( - scoped_refptr task_runner) { - task_runner_ = std::move(task_runner); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/capture_service_receiver.h chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver.h --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/capture_service_receiver.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,98 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_CAPTURE_SERVICE_RECEIVER_H_ -#define CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_CAPTURE_SERVICE_RECEIVER_H_ - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/threading/thread.h" -#include "base/time/time.h" -#include "chromecast/media/audio/capture_service/constants.h" - -namespace base { -class SequencedTaskRunner; -class WaitableEvent; -} // namespace base - -namespace net { -class StreamSocket; -} // namespace net - -namespace chromecast { -namespace media { - -class CaptureServiceReceiver { - public: - // Delegate cannot be destroyed before CaptureServiceReceiver. Note methods of - // Delegate will always be called from CaptureServiceReceiver's own thread. - class Delegate { - public: - virtual ~Delegate() = default; - - virtual bool OnInitialStreamInfo( - const capture_service::StreamInfo& stream_info) = 0; - - // Called when more data are received from socket. Return |true| to continue - // reading messages after OnCaptureData() returns. - virtual bool OnCaptureData(const char* data, size_t size) = 0; - - // Called when internal error occurs. - virtual void OnCaptureError() = 0; - - // Called when there is metadata. - virtual void OnCaptureMetadata(const char* data, size_t size) = 0; - }; - - // The timeout for a connecting socket to stop waiting and report error. - static constexpr base::TimeDelta kConnectTimeout = base::Seconds(1); - - CaptureServiceReceiver(capture_service::StreamInfo request_stream_info, - Delegate* delegate); - CaptureServiceReceiver(const CaptureServiceReceiver&) = delete; - CaptureServiceReceiver& operator=(const CaptureServiceReceiver&) = delete; - ~CaptureServiceReceiver(); - - // Starts capture receiving process. It cannot be called if - // CaptureServiceReceiver has been started and not stopped. - void Start(); - // Stops capture receiving process synchronously. It will be no-op if Start() - // has not been started or already been stopped. - void Stop(); - - // Unit test can call this method rather than the public one to inject mocked - // stream socket. - void StartWithSocket(std::unique_ptr connecting_socket); - - // Unit test can set test task runner so as to run test in sync. Must be - // called after construction and before any other methods. - void SetTaskRunnerForTest( - scoped_refptr task_runner); - - private: - class Socket; - - void OnConnected(int result); - void OnConnectTimeout(); - void StopOnTaskRunner(base::WaitableEvent* finished); - - const capture_service::StreamInfo request_stream_info_; - Delegate* const delegate_; - - // Socket requires IO thread, and low latency input stream requires high - // thread priority. Therefore, a private thread instead of the IO thread from - // browser thread pool is necessary so as to make sure input stream won't be - // blocked nor block other tasks on the same thread. - base::Thread io_thread_; - scoped_refptr task_runner_; - - std::unique_ptr connecting_socket_; - std::unique_ptr socket_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_CAPTURE_SERVICE_RECEIVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/capture_service_receiver_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/capture_service_receiver_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/capture_service_receiver_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,251 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/capture_service/capture_service_receiver.h" - -#include -#include -#include - -#include "base/numerics/byte_conversions.h" -#include "base/numerics/safe_conversions.h" -#include "base/run_loop.h" -#include "base/task/thread_pool.h" -#include "base/test/task_environment.h" -#include "chromecast/media/audio/capture_service/message_parsing_utils.h" -#include "chromecast/media/audio/capture_service/packet_header.h" -#include "chromecast/net/mock_stream_socket.h" -#include "net/base/io_buffer.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -namespace chromecast { -namespace media { -namespace capture_service { -namespace { - -constexpr StreamInfo kStreamInfo = - StreamInfo{.stream_type = StreamType::kSoftwareEchoCancelled, - .audio_codec = AudioCodec::kPcm, - .num_channels = 1, - .sample_format = SampleFormat::PLANAR_FLOAT, - .sample_rate = 16000, - .frames_per_buffer = 160}; -constexpr HandshakePacket kHandshakePacket = HandshakePacket{ - .size = 0, // dummy - .message_type = static_cast(MessageType::kHandshake), - .stream_type = static_cast(kStreamInfo.stream_type), - .audio_codec = static_cast(kStreamInfo.audio_codec), - .sample_format = static_cast(kStreamInfo.sample_format), - .num_channels = kStreamInfo.num_channels, - .num_frames = kStreamInfo.frames_per_buffer, - .sample_rate = kStreamInfo.sample_rate}; -constexpr PcmPacketHeader kPcmAudioPacketHeader = PcmPacketHeader{ - .size = 0, // dummy - .message_type = static_cast(MessageType::kPcmAudio), - .stream_type = static_cast(kStreamInfo.stream_type), - .timestamp_us = 0}; - -class MockStreamSocket : public chromecast::MockStreamSocket { - public: - MockStreamSocket() = default; - ~MockStreamSocket() override = default; -}; - -class MockCaptureServiceReceiverDelegate - : public chromecast::media::CaptureServiceReceiver::Delegate { - public: - MockCaptureServiceReceiverDelegate() = default; - ~MockCaptureServiceReceiverDelegate() override = default; - - MOCK_METHOD(bool, OnInitialStreamInfo, (const StreamInfo&), (override)); - MOCK_METHOD(bool, OnCaptureData, (const char*, size_t), (override)); - MOCK_METHOD(void, OnCaptureError, (), (override)); - MOCK_METHOD(void, OnCaptureMetadata, (const char*, size_t), (override)); -}; - -class CaptureServiceReceiverTest : public ::testing::Test { - public: - CaptureServiceReceiverTest() : receiver_(kStreamInfo, &delegate_) { - receiver_.SetTaskRunnerForTest(base::ThreadPool::CreateSequencedTaskRunner( - {base::TaskPriority::USER_BLOCKING})); - } - ~CaptureServiceReceiverTest() override = default; - - protected: - base::test::TaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; - MockCaptureServiceReceiverDelegate delegate_; - CaptureServiceReceiver receiver_; -}; - -TEST_F(CaptureServiceReceiverTest, StartStop) { - auto socket1 = std::make_unique(); - auto socket2 = std::make_unique(); - EXPECT_CALL(*socket1, Connect).WillOnce(Return(net::OK)); - EXPECT_CALL(*socket1, Write).WillOnce(Return(sizeof(HandshakePacket))); - EXPECT_CALL(*socket1, Read).WillOnce(Return(net::ERR_IO_PENDING)); - EXPECT_CALL(*socket2, Connect).WillOnce(Return(net::OK)); - - // Sync. - receiver_.StartWithSocket(std::move(socket1)); - task_environment_.RunUntilIdle(); - receiver_.Stop(); - - // Async. - receiver_.StartWithSocket(std::move(socket2)); - receiver_.Stop(); - task_environment_.RunUntilIdle(); -} - -TEST_F(CaptureServiceReceiverTest, ConnectFailed) { - auto socket = std::make_unique(); - EXPECT_CALL(*socket, Connect).WillOnce(Return(net::ERR_FAILED)); - EXPECT_CALL(delegate_, OnCaptureError); - - receiver_.StartWithSocket(std::move(socket)); - task_environment_.RunUntilIdle(); -} - -TEST_F(CaptureServiceReceiverTest, ConnectTimeout) { - auto socket = std::make_unique(); - EXPECT_CALL(*socket, Connect).WillOnce(Return(net::ERR_IO_PENDING)); - EXPECT_CALL(delegate_, OnCaptureError); - - receiver_.StartWithSocket(std::move(socket)); - task_environment_.FastForwardBy(CaptureServiceReceiver::kConnectTimeout); -} - -TEST_F(CaptureServiceReceiverTest, SendRequest) { - auto socket = std::make_unique(); - EXPECT_CALL(*socket, Connect).WillOnce(Return(net::OK)); - EXPECT_CALL(*socket, Write) - .WillOnce(Invoke([](net::IOBuffer* buf, int buf_len, - net::CompletionOnceCallback, - const net::NetworkTrafficAnnotationTag&) { - EXPECT_EQ(buf_len, static_cast(sizeof(HandshakePacket))); - auto data = base::as_bytes(buf->span()); - uint16_t size = base::numerics::U16FromBigEndian(data.first<2u>()); - EXPECT_EQ(size, sizeof(HandshakePacket) - sizeof(size)); - HandshakePacket packet; - base::byte_span_from_ref(packet).copy_from( - data.first()); - EXPECT_EQ(packet.message_type, kHandshakePacket.message_type); - EXPECT_EQ(packet.stream_type, kHandshakePacket.stream_type); - EXPECT_EQ(packet.audio_codec, kHandshakePacket.audio_codec); - EXPECT_EQ(packet.num_channels, kHandshakePacket.num_channels); - EXPECT_EQ(packet.num_frames, kHandshakePacket.num_frames); - EXPECT_EQ(packet.sample_rate, kHandshakePacket.sample_rate); - return buf_len; - })); - EXPECT_CALL(*socket, Read).WillOnce(Return(net::ERR_IO_PENDING)); - - receiver_.StartWithSocket(std::move(socket)); - task_environment_.RunUntilIdle(); - // Stop receiver to disconnect socket, since receiver doesn't own the IO - // task runner in unittests. - receiver_.Stop(); - task_environment_.RunUntilIdle(); -} - -TEST_F(CaptureServiceReceiverTest, ReceivePcmAudioMessage) { - auto socket = std::make_unique(); - EXPECT_CALL(*socket, Connect).WillOnce(Return(net::OK)); - EXPECT_CALL(*socket, Write).WillOnce(Return(sizeof(HandshakePacket))); - EXPECT_CALL(*socket, Read) - // Ack message. - .WillOnce(Invoke( - [](net::IOBuffer* buf, int buf_len, net::CompletionOnceCallback) { - auto write = base::as_writable_bytes(buf->span()) - .first(sizeof(kHandshakePacket)); - auto packet_as_bytes = base::byte_span_from_ref(kHandshakePacket) - .subspan(sizeof(uint16_t)); - auto rem = FillBuffer(write, packet_as_bytes); - EXPECT_TRUE(rem.empty()); - return write.size(); - })) - // Audio message. - .WillOnce(Invoke([](net::IOBuffer* buf, int buf_len, - net::CompletionOnceCallback) { - auto write = base::as_writable_bytes(buf->span()) - .first(sizeof(kPcmAudioPacketHeader) + - DataSizeInBytes(kStreamInfo)); - auto header_as_bytes = base::byte_span_from_ref(kPcmAudioPacketHeader) - .subspan(sizeof(uint16_t)); - auto audio = FillBuffer(write, header_as_bytes); - // No need to write valid audio frames, but we can't leave - // uninitialized memory (as it causes UB if it's read). - std::ranges::fill(audio, uint8_t{0}); - return write.size(); - })) - .WillOnce(Return(net::ERR_IO_PENDING)); - EXPECT_CALL(delegate_, OnInitialStreamInfo).WillOnce(Return(true)); - EXPECT_CALL(delegate_, OnCaptureData).WillOnce(Return(true)); - - receiver_.StartWithSocket(std::move(socket)); - task_environment_.RunUntilIdle(); - // Stop receiver to disconnect socket, since receiver doesn't own the IO - // task runner in unittests. - receiver_.Stop(); - task_environment_.RunUntilIdle(); -} - -TEST_F(CaptureServiceReceiverTest, ReceiveMetadataMessage) { - auto socket = std::make_unique(); - EXPECT_CALL(*socket, Connect).WillOnce(Return(net::OK)); - EXPECT_CALL(*socket, Write).WillOnce(Return(sizeof(HandshakePacket))); - EXPECT_CALL(*socket, Read) - .WillOnce(Invoke([](net::IOBuffer* buf, int buf_len, - net::CompletionOnceCallback) { - // The message contains `MessageType` (as uint8_t) and 1 byte. - constexpr uint16_t message_size = sizeof(uint8_t) + 1u; - constexpr size_t total_size = sizeof(uint16_t) + message_size; - auto [write_size, write_message] = base::as_writable_bytes(buf->span()) - .first() - .split_at(); - write_size.copy_from(base::numerics::U16ToBigEndian(message_size)); - write_message[0u] = static_cast(MessageType::kMetadata); - // No need to fill valid metadata. - std::ranges::fill(write_message.subspan(1u), uint8_t{0}); - return total_size; - })) - .WillOnce(Return(net::ERR_IO_PENDING)); - // Neither OnCaptureError nor OnCaptureData will be called. - EXPECT_CALL(delegate_, OnCaptureError).Times(0); - EXPECT_CALL(delegate_, OnCaptureData).Times(0); - EXPECT_CALL(delegate_, OnCaptureMetadata).Times(1); - - receiver_.StartWithSocket(std::move(socket)); - task_environment_.RunUntilIdle(); -} - -TEST_F(CaptureServiceReceiverTest, ReceiveError) { - auto socket = std::make_unique(); - EXPECT_CALL(*socket, Connect).WillOnce(Return(net::OK)); - EXPECT_CALL(*socket, Write).WillOnce(Return(sizeof(HandshakePacket))); - EXPECT_CALL(*socket, Read).WillOnce(Return(net::ERR_CONNECTION_RESET)); - EXPECT_CALL(delegate_, OnCaptureError); - - receiver_.StartWithSocket(std::move(socket)); - task_environment_.RunUntilIdle(); -} - -TEST_F(CaptureServiceReceiverTest, ReceiveEosMessage) { - auto socket = std::make_unique(); - EXPECT_CALL(*socket, Connect).WillOnce(Return(net::OK)); - EXPECT_CALL(*socket, Write).WillOnce(Return(sizeof(HandshakePacket))); - EXPECT_CALL(*socket, Read).WillOnce(Return(0)); - EXPECT_CALL(delegate_, OnCaptureError); - - receiver_.StartWithSocket(std::move(socket)); - task_environment_.RunUntilIdle(); -} - -} // namespace -} // namespace capture_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/constants.h chromium-132.0.6834.159/chromecast/media/audio/capture_service/constants.h --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/constants.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/constants.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,111 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_CONSTANTS_H_ -#define CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_CONSTANTS_H_ - -#include -#include - -namespace chromecast { -namespace media { -namespace capture_service { - -constexpr char kDefaultUnixDomainSocketPath[] = "/tmp/capture-service"; -constexpr int kDefaultTcpPort = 12855; - -enum class SampleFormat : uint8_t { - INTERLEAVED_INT16 = 0, - INTERLEAVED_INT32 = 1, - INTERLEAVED_FLOAT = 2, - PLANAR_INT16 = 3, - PLANAR_INT32 = 4, - PLANAR_FLOAT = 5, - LAST_FORMAT = PLANAR_FLOAT, -}; - -inline std::ostream& operator<<(std::ostream& os, SampleFormat sample_format) { - switch (sample_format) { - case SampleFormat::INTERLEAVED_INT16: - return os << "INTERLEAVED_INT16"; - case SampleFormat::INTERLEAVED_INT32: - return os << "INTERLEAVED_INT32"; - case SampleFormat::INTERLEAVED_FLOAT: - return os << "INTERLEAVED_FLOAT"; - case SampleFormat::PLANAR_INT16: - return os << "PLANAR_INT16"; - case SampleFormat::PLANAR_INT32: - return os << "PLANAR_INT32"; - case SampleFormat::PLANAR_FLOAT: - return os << "PLANAR_FLOAT"; - // Don't use default, so compiler can capture missed enums. - } -} - -enum class StreamType : uint8_t { - // Raw microphone capture from ALSA or other platform interface. - kMicRaw = 0, - // Echo cancelled capture using software AEC. - kSoftwareEchoCancelled, - // Echo linearly removed capture using software eraser that has lower cost but - // will have some non-linear echo residual left. - kSoftwareEchoCancelledLinear, - // Hardware echo cancelled capture, e.g., from DSP. - kHardwareEchoCancelled, - // Software echo rescaled capture that balances the volume of both far-end and - // near-end captures. The far-end sound is the echo voice that travels out - // from the loudspeaker and then is picked up by the system microphone, - // whereas the near-end sound is the remaining capture sound without the echo - // voice. - kSoftwareEchoRescaled, - // Hardware echo rescaled capture, e.g., from DSP. - kHardwareEchoRescaled, - // TDM loopback, e.g., from DSP output processing output. - kTdmLoopback, - // USB audio input. - kUsbAudio, - // Mark the last type. - kLastType = kUsbAudio, -}; - -enum class AudioCodec : uint8_t { - kPcm = 0, - kOpus, - // Mark the last codec. - kLastCodec = kOpus, -}; - -enum class MessageType : uint8_t { - // Handshake message that has stream header but empty body. It is used by - // receiver notifying the stream it is observing, and sender can confirm the - // types/codec are supported and send back more detailed parameters. - kHandshake = 0, - // PCM audio message that has stream header and audio data in the message - // body. The audio data will match the parameters in the header. - kPcmAudio, - // Opus encoded audio message that doesn't have stream header but a serialized - // proto data besides the type bits. - kOpusAudio, - // Metadata message that doesn't have stream header but a serialized proto - // data besides the type bits. - kMetadata, -}; - -struct StreamInfo { - StreamType stream_type = StreamType::kMicRaw; - AudioCodec audio_codec = AudioCodec::kPcm; - int num_channels = 0; - SampleFormat sample_format = SampleFormat::INTERLEAVED_INT16; - int sample_rate = 0; - int frames_per_buffer = 0; -}; - -// Size of a PCM audio message header. -constexpr size_t kPcmAudioHeaderBytes = 10; - -} // namespace capture_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_CONSTANTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/message_parsing_fuzzer.cc chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_fuzzer.cc --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/message_parsing_fuzzer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_fuzzer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include - -#include "base/logging.h" -#include "chromecast/media/audio/capture_service/message_parsing_utils.h" - -struct Environment { - Environment() { logging::SetMinLogLevel(logging::LOGGING_FATAL); } -}; - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - static Environment env; - StreamInfo info; - chromecast::media::capture_service::ReadHandshakeMessage( - reinterpret_cast(data), size, &info); - return 0; -} diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/message_parsing_utils.cc chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils.cc --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/message_parsing_utils.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,356 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/capture_service/message_parsing_utils.h" - -#include -#include -#include -#include - -#include "base/check.h" -#include "base/check_op.h" -#include "base/containers/span_writer.h" -#include "base/logging.h" -#include "base/notreached.h" -#include "base/numerics/byte_conversions.h" -#include "chromecast/media/audio/capture_service/constants.h" -#include "chromecast/media/audio/capture_service/packet_header.h" -#include "media/base/limits.h" - -namespace chromecast { -namespace media { -namespace capture_service { -namespace { - -// Size in bytes of the header part of a handshake message. -constexpr size_t kHandshakeHeaderBytes = - sizeof(HandshakePacket) - sizeof(uint16_t); - -static_assert(sizeof(PcmPacketHeader) % 4 == 0, - "Size of PCM audio packet header must be a multiple of 4 bytes."); -static_assert(sizeof(HandshakePacket) % 4 == 0, - "Size of handshake packet must be a multiple of 4 bytes."); -static_assert(kPcmAudioHeaderBytes == - sizeof(PcmPacketHeader) - sizeof(uint16_t), - "Invalid message header size."); -static_assert(offsetof(struct PcmPacketHeader, message_type) == - sizeof(uint16_t), - "Invalid message header offset."); -static_assert(offsetof(struct HandshakePacket, message_type) == - sizeof(uint16_t), - "Invalid message header offset."); - -// Check if audio data is properly aligned and has valid frame size. Return the -// number of frames if they are all good, otherwise return 0 to indicate -// failure. -template -int CheckAudioData(int channels, const char* data, size_t data_size) { - if (reinterpret_cast(data) % sizeof(T) != 0u) { - LOG(ERROR) << "Misaligned audio data"; - return 0; - } - - const int frame_size = channels * sizeof(T); - if (frame_size == 0) { - LOG(ERROR) << "Frame size is 0."; - return 0; - } - const int frames = data_size / frame_size; - if (data_size % frame_size != 0) { - LOG(ERROR) << "Audio data size (" << data_size - << ") is not an integer number of frames (" << frame_size - << ")."; - return 0; - } - return frames; -} - -template -bool ConvertInterleavedData(int channels, - const char* data, - size_t data_size, - ::media::AudioBus* audio) { - const int frames = - CheckAudioData(channels, data, data_size); - if (frames <= 0) { - return false; - } - - DCHECK_EQ(frames, audio->frames()); - audio->FromInterleaved( - reinterpret_cast(data), frames); - return true; -} - -template -bool ConvertPlanarData(int channels, - const char* data, - size_t data_size, - ::media::AudioBus* audio) { - const int frames = - CheckAudioData(channels, data, data_size); - if (frames <= 0) { - return false; - } - - DCHECK_EQ(frames, audio->frames()); - const typename Traits::ValueType* base_data = - reinterpret_cast(data); - for (int c = 0; c < channels; ++c) { - const typename Traits::ValueType* source = base_data + c * frames; - float* dest = audio->channel(c); - for (int f = 0; f < frames; ++f) { - dest[f] = Traits::ToFloat(source[f]); - } - } - return true; -} - -bool ConvertPlanarFloat(int channels, - const char* data, - size_t data_size, - ::media::AudioBus* audio) { - const int frames = CheckAudioData(channels, data, data_size); - if (frames <= 0) { - return false; - } - - DCHECK_EQ(frames, audio->frames()); - const float* base_data = reinterpret_cast(data); - for (int c = 0; c < channels; ++c) { - const float* source = base_data + c * frames; - std::copy(source, source + frames, audio->channel(c)); - } - return true; -} - -bool ConvertData(int channels, - SampleFormat format, - const char* data, - size_t data_size, - ::media::AudioBus* audio) { - switch (format) { - case capture_service::SampleFormat::INTERLEAVED_INT16: - return ConvertInterleavedData<::media::SignedInt16SampleTypeTraits>( - channels, data, data_size, audio); - case capture_service::SampleFormat::INTERLEAVED_INT32: - return ConvertInterleavedData<::media::SignedInt32SampleTypeTraits>( - channels, data, data_size, audio); - case capture_service::SampleFormat::INTERLEAVED_FLOAT: - return ConvertInterleavedData<::media::Float32SampleTypeTraits>( - channels, data, data_size, audio); - case capture_service::SampleFormat::PLANAR_INT16: - return ConvertPlanarData<::media::SignedInt16SampleTypeTraits>( - channels, data, data_size, audio); - case capture_service::SampleFormat::PLANAR_INT32: - return ConvertPlanarData<::media::SignedInt32SampleTypeTraits>( - channels, data, data_size, audio); - case capture_service::SampleFormat::PLANAR_FLOAT: - return ConvertPlanarFloat(channels, data, data_size, audio); - } - LOG(ERROR) << "Unknown sample format " << static_cast(format); - return false; -} - -} // namespace - -base::span FillBuffer(base::span buf, - base::span data) { - auto [write_size, rem] = buf.split_at(sizeof(uint16_t)); - write_size.copy_from(base::numerics::U16ToBigEndian( - base::checked_cast(buf.size()) - uint16_t{sizeof(uint16_t)})); - auto [write_data, uninit] = rem.split_at(data.size()); - write_data.copy_from(data); - return uninit; -} - -char* PopulatePcmAudioHeader(char* data_ptr, - size_t size, - StreamType stream_type, - int64_t timestamp_us) { - PcmPacketHeader header; - header.message_type = static_cast(MessageType::kPcmAudio); - header.stream_type = static_cast(stream_type); - header.timestamp_us = timestamp_us; - - auto data = base::as_writable_bytes( - // TODO(crbug.com/328018028): PopulatePcmAudioHeader() should - // get a span, not a pointer and length. - UNSAFE_TODO(base::span(data_ptr, size))); - auto header_as_bytes = - base::byte_span_from_ref(header).subspan(sizeof(header.size)); - auto after = FillBuffer(data, header_as_bytes); - // TODO(crbug.com/328018028): Return the span instead of just a pointer. - return base::as_writable_chars(after).data(); -} - -void PopulateHandshakeMessage(char* data_ptr, - size_t size, - const StreamInfo& stream_info) { - HandshakePacket packet; - packet.message_type = static_cast(MessageType::kHandshake); - packet.stream_type = static_cast(stream_info.stream_type); - packet.audio_codec = static_cast(stream_info.audio_codec); - packet.sample_format = static_cast(stream_info.sample_format); - packet.num_channels = stream_info.num_channels; - packet.num_frames = stream_info.frames_per_buffer; - packet.sample_rate = stream_info.sample_rate; - - auto data = base::as_writable_bytes( - // TODO(crbug.com/328018028): PopulateHandshakeMessage() should - // get a span, not a pointer and length. - UNSAFE_TODO(base::span(data_ptr, size))); - auto packet_as_bytes = - base::byte_span_from_ref(packet).subspan(sizeof(packet.size)); - FillBuffer(data, packet_as_bytes); -} - -bool ReadPcmAudioHeader(const char* data, - size_t size, - const StreamInfo& stream_info, - int64_t* timestamp_us) { - DCHECK(timestamp_us); - if (size < kPcmAudioHeaderBytes) { - LOG(ERROR) << "Message doesn't have a complete header: " << size << " v.s. " - << kPcmAudioHeaderBytes << "."; - return false; - } - PcmPacketHeader header; - memcpy(&header.message_type, data, kPcmAudioHeaderBytes); - if (static_cast(header.message_type) != MessageType::kPcmAudio) { - LOG(ERROR) << "Message type mismatch."; - return false; - } - if (static_cast(header.stream_type) != stream_info.stream_type) { - LOG(ERROR) << "Stream type mistach."; - return false; - } - *timestamp_us = header.timestamp_us; - return true; -} - -scoped_refptr MakePcmAudioMessage(StreamType stream_type, - int64_t timestamp_us, - const char* data, - size_t data_size) { - const size_t total_size = sizeof(PcmPacketHeader) + data_size; - DCHECK_LE(total_size, std::numeric_limits::max()); - auto io_buffer = base::MakeRefCounted(total_size); - char* ptr = PopulatePcmAudioHeader(io_buffer->data(), io_buffer->size(), - stream_type, timestamp_us); - if (!ptr) { - return nullptr; - } - if (data_size > 0) { - DCHECK(data); - std::copy(data, data + data_size, ptr); - } - return io_buffer; -} - -scoped_refptr MakeHandshakeMessage( - const StreamInfo& stream_info) { - auto io_buffer = - base::MakeRefCounted(sizeof(HandshakePacket)); - PopulateHandshakeMessage(io_buffer->data(), io_buffer->size(), stream_info); - return io_buffer; -} - -scoped_refptr MakeSerializedMessage( - MessageType message_type, - base::span data) { - if (data.empty()) { - LOG(ERROR) << "Invalid data size: " << data.size() << "."; - return nullptr; - } - - const auto message_type_uint8 = static_cast(message_type); - const auto message_size = - static_cast(sizeof(message_type_uint8) + data.size()); - DCHECK_LE(message_size, std::numeric_limits::max()); - auto io_buffer = base::MakeRefCounted( - sizeof(message_size) + message_size); - - base::SpanWriter writer(base::as_writable_bytes(io_buffer->span())); - writer.WriteU16BigEndian(message_size); - writer.WriteU8BigEndian(message_type_uint8); - writer.Write(data); - return io_buffer; -} - -bool ReadDataToAudioBus(const StreamInfo& stream_info, - const char* data, - size_t size, - ::media::AudioBus* audio_bus) { - DCHECK(audio_bus); - DCHECK_EQ(stream_info.num_channels, audio_bus->channels()); - return ConvertData(stream_info.num_channels, stream_info.sample_format, - data + kPcmAudioHeaderBytes, size - kPcmAudioHeaderBytes, - audio_bus); -} - -bool ReadPcmAudioMessage(const char* data, - size_t size, - const StreamInfo& stream_info, - int64_t* timestamp_us, - ::media::AudioBus* audio_bus) { - if (!ReadPcmAudioHeader(data, size, stream_info, timestamp_us)) { - return false; - } - return ReadDataToAudioBus(stream_info, data, size, audio_bus); -} - -bool ReadHandshakeMessage(const char* data, - size_t size, - StreamInfo* stream_info) { - DCHECK(stream_info); - if (size != kHandshakeHeaderBytes) { - LOG(ERROR) << "Message doesn't have a complete handshake packet: " << size - << " v.s. " << kHandshakeHeaderBytes << "."; - return false; - } - HandshakePacket packet; - memcpy(&packet.message_type, data, kHandshakeHeaderBytes); - MessageType message_type = static_cast(packet.message_type); - if (message_type != MessageType::kHandshake || - packet.stream_type > static_cast(StreamType::kLastType) || - packet.audio_codec > static_cast(AudioCodec::kLastCodec) || - packet.sample_format > static_cast(SampleFormat::LAST_FORMAT)) { - LOG(ERROR) << "Invalid message header."; - return false; - } - if (packet.num_channels > ::media::limits::kMaxChannels) { - LOG(ERROR) << "Invalid number of channels: " << packet.num_channels; - return false; - } - stream_info->stream_type = static_cast(packet.stream_type); - stream_info->audio_codec = static_cast(packet.audio_codec); - stream_info->sample_format = static_cast(packet.sample_format); - stream_info->num_channels = packet.num_channels; - stream_info->frames_per_buffer = packet.num_frames; - stream_info->sample_rate = packet.sample_rate; - return true; -} - -size_t DataSizeInBytes(const StreamInfo& stream_info) { - switch (stream_info.sample_format) { - case SampleFormat::INTERLEAVED_INT16: - case SampleFormat::PLANAR_INT16: - return sizeof(int16_t) * stream_info.num_channels * - stream_info.frames_per_buffer; - case SampleFormat::INTERLEAVED_INT32: - case SampleFormat::PLANAR_INT32: - return sizeof(int32_t) * stream_info.num_channels * - stream_info.frames_per_buffer; - case SampleFormat::INTERLEAVED_FLOAT: - case SampleFormat::PLANAR_FLOAT: - return sizeof(float) * stream_info.num_channels * - stream_info.frames_per_buffer; - } -} - -} // namespace capture_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/message_parsing_utils.h chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils.h --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/message_parsing_utils.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,113 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_MESSAGE_PARSING_UTILS_H_ -#define CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_MESSAGE_PARSING_UTILS_H_ - -#include - -#include "base/containers/span.h" -#include "base/memory/scoped_refptr.h" -#include "chromecast/media/audio/capture_service/constants.h" -#include "media/base/audio_bus.h" -#include "net/base/io_buffer.h" - -namespace chromecast { -namespace media { -namespace capture_service { - -// Read message header, check if it matches |stream_info|, retrieve timestamp, -// and return whether success. -// Note |data| here has been parsed firstly by SmallMessageSocket, and thus -// doesn't have bits. -bool ReadPcmAudioHeader(const char* data, - size_t size, - const StreamInfo& stream_info, - int64_t* timestamp_us); - -// Make a IO buffer for stream message. It will populate the header and copy -// |data| into the message if packet has audio and |data| is not null. The -// returned buffer will have a length of |data_size| + header size. Return -// nullptr if fails. Caller must guarantee the memory of |data| has at least -// |data_size| when has audio. -// Note buffer will be sent with SmallMessageSocket, and thus contains a uint16 -// size field in the very first. -scoped_refptr MakePcmAudioMessage(StreamType stream_type, - int64_t timestamp_us, - const char* data, - size_t data_size); - -// Make a IO buffer for handshake message. It will populate the header with -// |stream_info|. Return nullptr if fails. -// Note buffer will be sent with SmallMessageSocket, and thus contains a uint16 -// size field in the very first. -scoped_refptr MakeHandshakeMessage( - const StreamInfo& stream_info); - -// Make a IO buffer for serialized message. It will populate message size and -// type fields, and copy |data| into the message. The returned buffer will have -// a length of |data_size| + sizeof(uint8_t message_type) + sizeof(uint16_t -// size). -// Note serialized data cannot be empty, and the method will fail and return -// null if |data| is null or |data_size| is zero. -// -// **This looks like dead code but is used by internal code.** -scoped_refptr MakeSerializedMessage( - MessageType message_type, - base::span data); - -// Read the audio data in the message and copy to |audio_bus| based on -// |stream_info|. Return false if fails. -bool ReadDataToAudioBus(const StreamInfo& stream_info, - const char* data, - size_t size, - ::media::AudioBus* audio_bus); - -// Read the PCM audio message and copy the audio data to audio bus, as well as -// the timestamp. Return whether success. This will run ReadPcmAudioHeader() and -// ReadDataToAudioBus() in the underlying implementation. -bool ReadPcmAudioMessage(const char* data, - size_t size, - const StreamInfo& stream_info, - int64_t* timestamp_us, - ::media::AudioBus* audio_bus); - -// Read the handshake message to |stream_info|, and return true on success. -bool ReadHandshakeMessage(const char* data, - size_t size, - StreamInfo* stream_info); - -// Return the expected size of the data of a stream message with |stream_info|. -size_t DataSizeInBytes(const StreamInfo& stream_info); - -// Following methods are exposed for unittests: - -// Writes into buf: -// - The size of `buf` as 16 bits in big-endian order. -// - The contents of `data`, which must fit into the remaining bytes of `buf`. -// -// Any other bytes in `buf` are left **uninitialized**. The unwritten tail of -// `buf` is returned, which will be empty if all of `buf` was filled. -base::span FillBuffer(base::span buf, - base::span data); - -// Populate header of the PCM audio message, including the SmallMessageSocket -// size bits. -// Note this is used by unittest, user should use MakePcmAudioMessage directly. -char* PopulatePcmAudioHeader(char* data, - size_t size, - StreamType stream_type, - int64_t timestamp_us); - -// Populate the handshake message, including the SmallMessageSocket size bits. -// Note this is used by unittest, user should use MakeHandshakeMessage directly. -void PopulateHandshakeMessage(char* data, - size_t size, - const StreamInfo& stream_info); - -} // namespace capture_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_MESSAGE_PARSING_UTILS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/message_parsing_utils_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/message_parsing_utils_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/message_parsing_utils_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,255 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/capture_service/message_parsing_utils.h" - -#include - -#include "base/big_endian.h" -#include "chromecast/media/audio/capture_service/constants.h" -#include "chromecast/media/audio/capture_service/packet_header.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace capture_service { -namespace { - -constexpr size_t kFrames = 10; -constexpr size_t kChannels = 2; -constexpr StreamInfo kStreamInfo = - StreamInfo{StreamType::kSoftwareEchoCancelled, - AudioCodec::kPcm, - kChannels, - SampleFormat::PLANAR_FLOAT, - 16000, - kFrames}; - -class PacketHeaderTest - : public testing::TestWithParam< - std::tuple> { - protected: - StreamInfo GetStreamInfo() { - StreamInfo info; - info.stream_type = std::get<0>(GetParam()); - info.audio_codec = std::get<1>(GetParam()); - info.num_channels = std::get<2>(GetParam()); - info.sample_format = std::get<3>(GetParam()); - info.sample_rate = std::get<4>(GetParam()); - info.frames_per_buffer = std::get<5>(GetParam()); - return info; - } -}; - -TEST_P(PacketHeaderTest, HandshakeMessage) { - std::vector data(sizeof(HandshakePacket), 0); - StreamInfo stream_info = GetStreamInfo(); - PopulateHandshakeMessage(data.data(), data.size(), stream_info); - - StreamInfo info_out; - bool success = - ReadHandshakeMessage(data.data() + sizeof(uint16_t), - data.size() - sizeof(uint16_t), &info_out); - EXPECT_TRUE(success); - EXPECT_EQ(info_out.stream_type, stream_info.stream_type); - EXPECT_EQ(info_out.audio_codec, stream_info.audio_codec); - EXPECT_EQ(info_out.sample_format, stream_info.sample_format); - EXPECT_EQ(info_out.num_channels, stream_info.num_channels); - EXPECT_EQ(info_out.sample_rate, stream_info.sample_rate); - EXPECT_EQ(info_out.frames_per_buffer, stream_info.frames_per_buffer); -} - -TEST(MessageParsingUtilsTest, PcmAudioMessage) { - size_t data_size = sizeof(PcmPacketHeader) / sizeof(float); - std::vector data(data_size, 1.0f); - int64_t timestamp_us = 100; - PopulatePcmAudioHeader(reinterpret_cast(data.data()), - data.size() * sizeof(float), kStreamInfo.stream_type, - timestamp_us); - - int64_t timestamp_out = 0; - bool success = ReadPcmAudioHeader( - reinterpret_cast(data.data()) + sizeof(uint16_t), - data_size * sizeof(float) - sizeof(uint16_t), kStreamInfo, - ×tamp_out); - EXPECT_TRUE(success); - EXPECT_EQ(timestamp_out, timestamp_us); -} - -TEST(MessageParsingUtilsTest, ValidPlanarFloat) { - size_t data_size = - sizeof(PcmPacketHeader) / sizeof(float) + kFrames * kChannels; - std::vector data(data_size, .0f); - PopulatePcmAudioHeader(reinterpret_cast(data.data()), - data.size() * sizeof(float), kStreamInfo.stream_type, - 0); - // Fill the last k frames, i.e., the second channel, with 0.5f. - for (size_t i = data_size - kFrames; i < data_size; i++) { - data[i] = .5f; - } - - auto audio_bus = ::media::AudioBus::Create(kChannels, kFrames); - bool success = ReadDataToAudioBus( - kStreamInfo, reinterpret_cast(data.data()) + sizeof(uint16_t), - data_size * sizeof(float) - sizeof(uint16_t), audio_bus.get()); - EXPECT_TRUE(success); - for (size_t f = 0; f < kFrames; f++) { - EXPECT_FLOAT_EQ(audio_bus->channel(0)[f], .0f); - EXPECT_FLOAT_EQ(audio_bus->channel(1)[f], .5f); - } -} - -TEST(MessageParsingUtilsTest, ValidInterleavedInt16) { - size_t data_size = - sizeof(PcmPacketHeader) / sizeof(int16_t) + kFrames * kChannels; - std::vector data(data_size, std::numeric_limits::max()); - PopulatePcmAudioHeader(reinterpret_cast(data.data()), - data.size() * sizeof(int16_t), kStreamInfo.stream_type, - 0); - // Fill the second channel with min(). - for (size_t i = sizeof(PcmPacketHeader) / sizeof(int16_t) + 1; i < data_size; - i += 2) { - data[i] = std::numeric_limits::min(); - } - - auto audio_bus = ::media::AudioBus::Create(kChannels, kFrames); - StreamInfo stream_info = kStreamInfo; - stream_info.sample_format = SampleFormat::INTERLEAVED_INT16; - bool success = ReadDataToAudioBus( - stream_info, reinterpret_cast(data.data()) + sizeof(uint16_t), - data_size * sizeof(int16_t) - sizeof(uint16_t), audio_bus.get()); - EXPECT_TRUE(success); - for (size_t f = 0; f < kFrames; f++) { - EXPECT_FLOAT_EQ(audio_bus->channel(0)[f], 1.0f); - EXPECT_FLOAT_EQ(audio_bus->channel(1)[f], -1.0f); - } -} - -TEST(MessageParsingUtilsTest, ValidInterleavedInt32) { - size_t data_size = - sizeof(PcmPacketHeader) / sizeof(int32_t) + kFrames * kChannels; - std::vector data(data_size, std::numeric_limits::min()); - PopulatePcmAudioHeader(reinterpret_cast(data.data()), - data.size() * sizeof(int32_t), kStreamInfo.stream_type, - 0); - // Fill the second channel with max(). - for (size_t i = sizeof(PcmPacketHeader) / sizeof(int32_t) + 1; i < data_size; - i += 2) { - data[i] = std::numeric_limits::max(); - } - - auto audio_bus = ::media::AudioBus::Create(kChannels, kFrames); - StreamInfo stream_info = kStreamInfo; - stream_info.sample_format = SampleFormat::INTERLEAVED_INT32; - bool success = ReadDataToAudioBus( - stream_info, reinterpret_cast(data.data()) + sizeof(uint16_t), - data_size * sizeof(int32_t) - sizeof(uint16_t), audio_bus.get()); - EXPECT_TRUE(success); - for (size_t f = 0; f < kFrames; f++) { - EXPECT_FLOAT_EQ(audio_bus->channel(0)[f], -1.0f); - EXPECT_FLOAT_EQ(audio_bus->channel(1)[f], 1.0f); - } -} - -TEST(MessageParsingUtilsTest, InvalidTypeHandshake) { - std::vector data(sizeof(HandshakePacket), 0); - StreamInfo stream_info = kStreamInfo; - PopulateHandshakeMessage(data.data(), data.size(), stream_info); - *(reinterpret_cast(data.data()) + - offsetof(struct HandshakePacket, stream_type)) = - static_cast(StreamType::kLastType) + 1; - bool success = - ReadHandshakeMessage(data.data() + sizeof(uint16_t), - data.size() - sizeof(uint16_t), &stream_info); - EXPECT_FALSE(success); -} - -TEST(MessageParsingUtilsTest, InvalidTypePcmAudio) { - size_t data_size = sizeof(PcmPacketHeader) / sizeof(float); - std::vector data(data_size, 1.0f); - PopulatePcmAudioHeader(reinterpret_cast(data.data()), - data.size() * sizeof(float), kStreamInfo.stream_type, - 0); - *(reinterpret_cast(data.data()) + - offsetof(struct PcmPacketHeader, stream_type)) = - static_cast(StreamType::kLastType) + 1; - int64_t timestamp_us; - bool success = ReadPcmAudioHeader( - reinterpret_cast(data.data()) + sizeof(uint16_t), - data_size * sizeof(float) - sizeof(uint16_t), kStreamInfo, ×tamp_us); - EXPECT_FALSE(success); -} - -TEST(MessageParsingUtilsTest, InvalidCodec) { - std::vector data(sizeof(HandshakePacket), 0); - StreamInfo stream_info = kStreamInfo; - PopulateHandshakeMessage(data.data(), data.size(), stream_info); - *(reinterpret_cast(data.data()) + - offsetof(struct HandshakePacket, audio_codec)) = - static_cast(AudioCodec::kLastCodec) + 1; - bool success = - ReadHandshakeMessage(data.data() + sizeof(uint16_t), - data.size() - sizeof(uint16_t), &stream_info); - EXPECT_FALSE(success); -} - -TEST(MessageParsingUtilsTest, InvalidFormat) { - std::vector data(sizeof(HandshakePacket), 0); - StreamInfo stream_info = kStreamInfo; - PopulateHandshakeMessage(data.data(), data.size(), stream_info); - *(reinterpret_cast(data.data()) + - offsetof(struct HandshakePacket, sample_format)) = - static_cast(SampleFormat::LAST_FORMAT) + 1; - bool success = - ReadHandshakeMessage(data.data() + sizeof(uint16_t), - data.size() - sizeof(uint16_t), &stream_info); - EXPECT_FALSE(success); -} - -TEST(MessageParsingUtilsTest, InvalidDataLength) { - size_t data_size = - sizeof(PcmPacketHeader) / sizeof(float) + kFrames * kChannels + 1; - std::vector data(data_size, 1.0f); - PopulatePcmAudioHeader(reinterpret_cast(data.data()), - data.size() * sizeof(float), kStreamInfo.stream_type, - 0); - - auto audio_bus = ::media::AudioBus::Create(kChannels, kFrames); - bool success = ReadDataToAudioBus( - kStreamInfo, reinterpret_cast(data.data()) + sizeof(uint16_t), - data_size * sizeof(float) - sizeof(uint16_t), audio_bus.get()); - EXPECT_FALSE(success); -} - -TEST(MessageParsingUtilsTest, NotAlignedData) { - size_t data_size = - sizeof(PcmPacketHeader) / sizeof(float) + kFrames * kChannels + 1; - std::vector data(data_size, 1.0f); - PopulatePcmAudioHeader(reinterpret_cast(data.data()) + 1, - data.size() * sizeof(float) - 1, - kStreamInfo.stream_type, 0); - - auto audio_bus = ::media::AudioBus::Create(kChannels, kFrames); - bool success = ReadDataToAudioBus( - kStreamInfo, reinterpret_cast(data.data()) + 1 + sizeof(uint16_t), - data_size * sizeof(float) - 1 - sizeof(uint16_t), audio_bus.get()); - EXPECT_FALSE(success); -} - -INSTANTIATE_TEST_SUITE_P( - MessageParsingUtilsTest, - PacketHeaderTest, - testing::Combine(testing::Values(StreamType::kMicRaw, - StreamType::kHardwareEchoRescaled), - testing::Values(AudioCodec::kPcm, AudioCodec::kOpus), - testing::Values(1, 8), - testing::Values(SampleFormat::INTERLEAVED_INT16, - SampleFormat::PLANAR_FLOAT), - testing::Values(16000, 96000), - testing::Values(0, 32761))); - -} // namespace -} // namespace capture_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/capture_service/packet_header.h chromium-132.0.6834.159/chromecast/media/audio/capture_service/packet_header.h --- chromium-132.0.6834.110/chromecast/media/audio/capture_service/packet_header.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/capture_service/packet_header.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_PACKET_HEADER_H_ -#define CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_PACKET_HEADER_H_ - -#include - -namespace chromecast { -namespace media { -namespace capture_service { - -// Memory block of a PCM audio packet header. Changes to it need to ensure the -// size is a multiple of 4 bytes. It reflects real packet header structure, -// however, the |size| bits are in big-endian order, and thus is only for -// padding purpose in this struct, when all bytes after it represent a message -// header. -struct __attribute__((__packed__)) PcmPacketHeader { - uint16_t size; - uint8_t message_type; - uint8_t stream_type; - int64_t timestamp_us; -}; - -// Memory block of a handshake packet. Audio packet may be sent after handshake -// packet, and thus handshake packet must also have a multiple of 4 bytes, since -// audio data must be aligned. -struct __attribute__((__packed__)) HandshakePacket { - uint16_t size; - uint8_t message_type; - uint8_t stream_type; - uint8_t audio_codec; - uint8_t sample_format; - uint8_t num_channels; - uint8_t padding_uint8; - uint16_t num_frames; - uint16_t padding_uint16; - uint32_t sample_rate; -}; - -} // namespace capture_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAPTURE_SERVICE_PACKET_HEADER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_bus.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_bus.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_bus.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_bus.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// 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 "chromecast/media/audio/cast_audio_bus.h" - -#include - -#include "base/memory/ptr_util.h" - -namespace chromecast { -namespace media { - -CastAudioBus::CastAudioBus(int channels, int frames) : frames_(frames) { - data_.reset(new float[channels * frames]); - channel_data_.reserve(channels); - for (int i = 0; i < channels; ++i) - channel_data_.push_back(data_.get() + i * frames); -} - -CastAudioBus::~CastAudioBus() = default; - -// static -std::unique_ptr CastAudioBus::Create(int channels, int frames) { - return base::WrapUnique(new CastAudioBus(channels, frames)); -} - -void CastAudioBus::Zero() { - std::fill_n(data_.get(), frames() * channels(), 0); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_bus.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_bus.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_bus.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_bus.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_BUS_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_BUS_H_ - -#include -#include - -namespace chromecast { -namespace media { - -// This class is a simplified version of ::media::AudioBus without any -// dependency on //media. -class CastAudioBus { - public: - // Creates a new CastAudioBus and allocates |channels| of length |frames|. - static std::unique_ptr Create(int channels, int frames); - - // Returns a raw pointer to the requested channel. - float* channel(int channel) { return channel_data_[channel]; } - const float* channel(int channel) const { return channel_data_[channel]; } - - // Returns the number of channels. - int channels() const { return static_cast(channel_data_.size()); } - // Returns the number of frames. - int frames() const { return frames_; } - - // Helper method for zeroing out all channels of audio data. - void Zero(); - - ~CastAudioBus(); - - private: - CastAudioBus(int channels, int frames); - - // Contiguous block of channel memory. - std::unique_ptr data_; - - // One float pointer per channel pointing to a contiguous block of memory for - // that channel. - std::vector channel_data_; - int frames_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_BUS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_device_factory.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_device_factory.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_device_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_device_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,267 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_device_factory.h" - -#include - -#include "base/android/bundle_utils.h" -#include "base/check.h" -#include "base/feature_list.h" -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/media/audio/cast_audio_output_device.h" -#include "content/public/renderer/render_frame.h" -#include "media/audio/audio_output_device.h" -#include "media/base/audio_capturer_source.h" -#include "media/base/audio_parameters.h" -#include "media/base/audio_renderer_sink.h" -#include "media/base/output_device_info.h" -#include "third_party/blink/public/platform/browser_interface_broker_proxy.h" -#include "third_party/blink/public/web/modules/media/audio/audio_output_ipc_factory.h" -#include "third_party/blink/public/web/web_local_frame.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr base::TimeDelta kAuthorizationTimeout = base::Seconds(100); - -content::RenderFrame* GetRenderFrameForToken( - const blink::LocalFrameToken& frame_token) { - auto* web_frame = blink::WebLocalFrame::FromFrameToken(frame_token); - DCHECK(web_frame); - - return content::RenderFrame::FromWebFrame(web_frame); -} - -scoped_refptr<::media::AudioOutputDevice> NewOutputDevice( - const blink::LocalFrameToken& frame_token, - const ::media::AudioSinkParameters& params, - base::TimeDelta auth_timeout) { - auto device = base::MakeRefCounted<::media::AudioOutputDevice>( - blink::AudioOutputIPCFactory::GetInstance().CreateAudioOutputIPC( - frame_token), - blink::AudioOutputIPCFactory::GetInstance().io_task_runner(), params, - auth_timeout); - device->RequestDeviceAuthorization(); - return device; -} - -} // namespace - -class NonSwitchableAudioRendererSink - : public ::media::SwitchableAudioRendererSink { - public: - explicit NonSwitchableAudioRendererSink( - const blink::LocalFrameToken& frame_token, - const ::media::AudioSinkParameters& params) - : frame_token_(frame_token), sink_params_(params) { - auto* render_frame = GetRenderFrameForToken(frame_token); - DCHECK(render_frame); - render_frame->GetBrowserInterfaceBroker().GetInterface( - pending_audio_socket_broker_.InitWithNewPipeAndPassReceiver()); - render_frame->GetBrowserInterfaceBroker().GetInterface( - pending_app_media_info_manager_.InitWithNewPipeAndPassReceiver()); - } - - void Initialize(const ::media::AudioParameters& params, - RenderCallback* callback) override { - // NonSwitchableAudioRendererSink derives from RestartableRenderSink which - // does allow calling Initialize and Play again after stopping. - if (is_initialized_) - return; - is_initialized_ = true; - - if (!(base::android::BundleUtils::IsBundle() || - base::FeatureList::IsEnabled(kEnableCastAudioOutputDevice)) || - params.IsBitstreamFormat()) { - output_device_ = - NewOutputDevice(frame_token_, sink_params_, kAuthorizationTimeout); - output_device_->Initialize(params, callback); - return; - } - - app_media_info_manager_.Bind(std::move(pending_app_media_info_manager_)); - app_media_info_manager_->GetCastApplicationMediaInfo(base::BindOnce( - &NonSwitchableAudioRendererSink::OnApplicationMediaInfoReceived, this, - params, callback)); - } - - void Start() override { - if (output_device_) { - output_device_->Start(); - } else { - pending_start_ = true; - } - } - - void Stop() override { - pending_start_ = false; - if (output_device_) { - output_device_->Stop(); - } - } - - void Pause() override { - if (output_device_) { - output_device_->Pause(); - } else { - pending_pause_ = true; - } - } - - void Play() override { - pending_pause_ = false; - if (output_device_) { - output_device_->Play(); - } - } - - bool SetVolume(double volume) override { - if (output_device_) { - return output_device_->SetVolume(volume); - } - - pending_volume_ = volume; - return true; - } - - ::media::OutputDeviceInfo GetOutputDeviceInfo() override { - if (output_device_) { - return output_device_->GetOutputDeviceInfo(); - } - // GetOutputDeviceInfo() may be called when the underlying `output_device_` - // hasn't been constructed. Return the default set of parameters in this - // case. - return ::media::OutputDeviceInfo( - std::string(), ::media::OUTPUT_DEVICE_STATUS_OK, - ::media::AudioParameters( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), 48000, 480)); - } - - void GetOutputDeviceInfoAsync(OutputDeviceInfoCB info_cb) override { - if (output_device_) { - output_device_->GetOutputDeviceInfoAsync(std::move(info_cb)); - return; - } - // Always post to avoid the caller being reentrant. - base::BindPostTaskToCurrentDefault( - base::BindOnce(std::move(info_cb), GetOutputDeviceInfo())) - .Run(); - } - - bool IsOptimizedForHardwareParameters() override { - if (output_device_) { - return output_device_->IsOptimizedForHardwareParameters(); - } - return false; - } - - bool CurrentThreadIsRenderingThread() override { - return output_device_ && output_device_->CurrentThreadIsRenderingThread(); - } - - void SwitchOutputDevice(const std::string& device_id, - ::media::OutputDeviceStatusCB callback) override { - LOG(ERROR) << __func__ << " is not suported."; - std::move(callback).Run(::media::OUTPUT_DEVICE_STATUS_ERROR_INTERNAL); - } - - void Flush() override { - if (output_device_) { - output_device_->Flush(); - } - } - - protected: - ~NonSwitchableAudioRendererSink() override { - if (output_device_) - output_device_->Stop(); - } - - private: - void OnApplicationMediaInfoReceived( - const ::media::AudioParameters& params, - RenderCallback* callback, - ::media::mojom::CastApplicationMediaInfoPtr application_media_info) { - // Use CastAudioOutputDevice if either: - // 1. the playback only has audio stream. - // 2. the app is an audio only app. - // Otherwise create Chromium's audio output for better av sync quality. - if (params.effects() & ::media::AudioParameters::AUDIO_PREFETCH || - application_media_info->is_audio_only_session) { - LOG(INFO) << "Use cast audio output device."; - output_device_ = base::MakeRefCounted( - std::move(pending_audio_socket_broker_), - application_media_info->application_session_id); - } else { - output_device_ = - NewOutputDevice(frame_token_, sink_params_, kAuthorizationTimeout); - } - - // The media info manager is only needed to query whether this is an - // audio-only session and session id; after this, the binding can be reset. - // - // If this is not done on the thread on which the binding was created (in - // Initialize()), then the destructor can run on a different thread and - // violate a mojo sequence checker assertion. - app_media_info_manager_.reset(); - - output_device_->Initialize(params, callback); - - if (pending_start_) { - output_device_->Start(); - pending_start_ = false; - } - - if (pending_pause_) { - output_device_->Pause(); - pending_pause_ = false; - } - - if (pending_volume_) { - output_device_->SetVolume(pending_volume_.value()); - pending_volume_ = std::nullopt; - } - } - - const blink::LocalFrameToken frame_token_; - const ::media::AudioSinkParameters sink_params_; - - mojo::PendingRemote pending_audio_socket_broker_; - mojo::PendingRemote<::media::mojom::CastApplicationMediaInfoManager> - pending_app_media_info_manager_; - mojo::Remote<::media::mojom::CastApplicationMediaInfoManager> - app_media_info_manager_; - scoped_refptr<::media::AudioRendererSink> output_device_; - bool is_initialized_ = false; - bool pending_start_ = false; - bool pending_pause_ = false; - std::optional pending_volume_; -}; - -CastAudioDeviceFactory::CastAudioDeviceFactory() { - DVLOG(1) << "Register CastAudioDeviceFactory"; -} - -CastAudioDeviceFactory::~CastAudioDeviceFactory() { - DVLOG(1) << "Unregister CastAudioDeviceFactory"; -} - -scoped_refptr<::media::SwitchableAudioRendererSink> -CastAudioDeviceFactory::NewMixableSink( - blink::WebAudioDeviceSourceType source_type, - const blink::LocalFrameToken& frame_token, - const blink::FrameToken& main_frame_token, - const ::media::AudioSinkParameters& params) { - return base::MakeRefCounted(frame_token, - params); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_device_factory.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_device_factory.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_device_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_device_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_DEVICE_FACTORY_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_DEVICE_FACTORY_H_ - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "media/audio/audio_sink_parameters.h" -#include "third_party/blink/public/common/tokens/tokens.h" -#include "third_party/blink/public/platform/audio/web_audio_device_source_type.h" -#include "third_party/blink/public/web/modules/media/audio/audio_device_factory.h" - -namespace media { -class SwitchableAudioRendererSink; -} // namespace media - -namespace chromecast { -namespace media { - -class CastAudioDeviceFactory final : public blink::AudioDeviceFactory { - public: - CastAudioDeviceFactory(); - ~CastAudioDeviceFactory() override; - - scoped_refptr<::media::SwitchableAudioRendererSink> NewMixableSink( - blink::WebAudioDeviceSourceType source_type, - const blink::LocalFrameToken& frame_token, - const blink::FrameToken& main_frame_token, - const ::media::AudioSinkParameters& params) override; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_DEVICE_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_input_stream.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_input_stream.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_input_stream.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_input_stream.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,167 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_input_stream.h" - -#include "base/logging.h" -#include "chromecast/media/audio/capture_service/constants.h" -#include "chromecast/media/audio/capture_service/message_parsing_utils.h" -#include "media/audio/audio_manager_base.h" - -namespace chromecast { -namespace media { - -CastAudioInputStream::CastAudioInputStream( - ::media::AudioManagerBase* audio_manager, - const ::media::AudioParameters& audio_params, - const std::string& device_id) - : audio_manager_(audio_manager), audio_params_(audio_params) { - DETACH_FROM_THREAD(audio_thread_checker_); - LOG(INFO) << __func__ << " " << this - << " created from device_id = " << device_id - << " with audio_params = {" << audio_params_.AsHumanReadableString() - << "}."; -} - -CastAudioInputStream::~CastAudioInputStream() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); -} - -::media::AudioInputStream::OpenOutcome CastAudioInputStream::Open() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DCHECK(!capture_service_receiver_); - LOG(INFO) << __func__ << " " << this << "."; - - // Sanity check the audio parameters. - ::media::AudioParameters::Format format = audio_params_.format(); - DCHECK((format == ::media::AudioParameters::AUDIO_PCM_LINEAR) || - (format == ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY)); - ::media::ChannelLayout channel_layout = audio_params_.channel_layout(); - if ((channel_layout != ::media::CHANNEL_LAYOUT_MONO) && - (channel_layout != ::media::CHANNEL_LAYOUT_STEREO)) { - LOG(WARNING) << "Unsupported channel layout: " << channel_layout; - return ::media::AudioInputStream::OpenOutcome::kFailed; - } - DCHECK_GE(audio_params_.channels(), 1); - DCHECK_LE(audio_params_.channels(), 2); - - audio_bus_ = ::media::AudioBus::Create(audio_params_.channels(), - audio_params_.frames_per_buffer()); - stream_info_ = capture_service::StreamInfo{ - capture_service::StreamType::kSoftwareEchoCancelled, - capture_service::AudioCodec::kPcm, audio_params_.channels(), - // Format doesn't matter in the request. - capture_service::SampleFormat::LAST_FORMAT, audio_params_.sample_rate(), - audio_params_.frames_per_buffer()}; - capture_service_receiver_ = - std::make_unique(stream_info_, this); - return ::media::AudioInputStream::OpenOutcome::kSuccess; -} - -void CastAudioInputStream::Start(AudioInputCallback* input_callback) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DCHECK(capture_service_receiver_); - DCHECK(!input_callback_); - DCHECK(input_callback); - LOG(INFO) << __func__ << " " << this << "."; - input_callback_ = input_callback; - capture_service_receiver_->Start(); -} - -void CastAudioInputStream::Stop() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DCHECK(capture_service_receiver_); - LOG(INFO) << __func__ << " " << this << "."; - capture_service_receiver_->Stop(); - input_callback_ = nullptr; -} - -void CastAudioInputStream::Close() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - LOG(INFO) << __func__ << " " << this << "."; - capture_service_receiver_.reset(); - audio_bus_.reset(); - if (audio_manager_) { - audio_manager_->ReleaseInputStream(this); - } -} - -double CastAudioInputStream::GetMaxVolume() { - return 1.0; -} - -void CastAudioInputStream::SetVolume(double volume) {} - -double CastAudioInputStream::GetVolume() { - return 1.0; -} - -bool CastAudioInputStream::SetAutomaticGainControl(bool enabled) { - return false; -} - -bool CastAudioInputStream::GetAutomaticGainControl() { - return false; -} - -bool CastAudioInputStream::IsMuted() { - return false; -} - -void CastAudioInputStream::SetOutputDeviceForAec( - const std::string& output_device_id) { - // Not supported. Do nothing. -} - -bool CastAudioInputStream::OnInitialStreamInfo( - const capture_service::StreamInfo& stream_info) { - const bool is_params_match = - stream_info.stream_type == stream_info_.stream_type && - stream_info.audio_codec == stream_info_.audio_codec && - stream_info.num_channels == stream_info_.num_channels && - stream_info.sample_rate == stream_info_.sample_rate && - stream_info.frames_per_buffer == stream_info_.frames_per_buffer; - LOG_IF(ERROR, !is_params_match) - << "Got different parameters from sender, stream_type: " - << static_cast(stream_info_.stream_type) << " -> " - << static_cast(stream_info.stream_type) - << ", audio_codec: " << static_cast(stream_info_.audio_codec) - << " -> " << static_cast(stream_info.audio_codec) - << ", sample_rate: " << stream_info_.sample_rate << " Hz -> " - << stream_info.sample_rate - << " Hz, num_channels: " << stream_info_.num_channels << " -> " - << stream_info.num_channels - << ", frames_per_buffer: " << stream_info_.frames_per_buffer << " -> " - << stream_info.frames_per_buffer << "."; - stream_info_.sample_format = stream_info.sample_format; - LOG(INFO) << "Set sample_format: " - << static_cast(stream_info.sample_format); - return is_params_match; -} - -bool CastAudioInputStream::OnCaptureData(const char* data, size_t size) { - int64_t timestamp_us; - if (!capture_service::ReadPcmAudioMessage(data, size, stream_info_, - ×tamp_us, audio_bus_.get())) { - return false; - } - - DCHECK(input_callback_); - input_callback_->OnData(audio_bus_.get(), - base::TimeTicks() + base::Microseconds(timestamp_us), - /* volume */ 1.0, {}); - return true; -} - -void CastAudioInputStream::OnCaptureError() { - DCHECK(input_callback_); - input_callback_->OnError(); -} - -void CastAudioInputStream::OnCaptureMetadata(const char* data, size_t size) { - // Not implemented! -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_input_stream.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_input_stream.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_input_stream.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_input_stream.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_INPUT_STREAM_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_INPUT_STREAM_H_ - -#include -#include - -#include "base/threading/thread_checker.h" -#include "chromecast/media/audio/capture_service/capture_service_receiver.h" -#include "chromecast/media/audio/capture_service/constants.h" -#include "media/audio/audio_io.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_parameters.h" - -namespace media { -class AudioManagerBase; -} // namespace media - -namespace chromecast { -namespace media { - -class CaptureServiceReceiver; -class CastAudioManager; - -class CastAudioInputStream : public ::media::AudioInputStream, - public CaptureServiceReceiver::Delegate { - public: - CastAudioInputStream(::media::AudioManagerBase* audio_manager, - const ::media::AudioParameters& audio_params, - const std::string& device_id); - CastAudioInputStream(const CastAudioInputStream&) = delete; - CastAudioInputStream& operator=(const CastAudioInputStream&) = delete; - ~CastAudioInputStream() override; - - // ::media::AudioInputStream implementation: - ::media::AudioInputStream::OpenOutcome Open() override; - void Start(AudioInputCallback* source_callback) override; - void Stop() override; - void Close() override; - double GetMaxVolume() override; - void SetVolume(double volume) override; - double GetVolume() override; - bool SetAutomaticGainControl(bool enabled) override; - bool GetAutomaticGainControl() override; - bool IsMuted() override; - void SetOutputDeviceForAec(const std::string& output_device_id) override; - - // CaptureServiceReceiver::Delegate implementation: - bool OnInitialStreamInfo( - const capture_service::StreamInfo& stream_info) override; - bool OnCaptureData(const char* data, size_t size) override; - void OnCaptureError() override; - void OnCaptureMetadata(const char* data, size_t size) override; - - private: - // Hold a raw pointer to audio manager to inform releasing |this|. The pointer - // may be null, if |this| is not created by audio manager, e.g., in unit test. - ::media::AudioManagerBase* const audio_manager_; - const ::media::AudioParameters audio_params_; - capture_service::StreamInfo stream_info_; - std::unique_ptr capture_service_receiver_; - AudioInputCallback* input_callback_ = nullptr; - std::unique_ptr<::media::AudioBus> audio_bus_; - - THREAD_CHECKER(audio_thread_checker_); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_INPUT_STREAM_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,221 +0,0 @@ -// 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 "chromecast/media/audio/cast_audio_manager.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "build/build_config.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/audio/audio_buildflags.h" -#include "chromecast/media/audio/cast_audio_mixer.h" -#include "chromecast/media/audio/cast_audio_output_stream.h" -#include "chromecast/media/audio/mixer_service/constants.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "media/audio/audio_device_description.h" - -namespace { -// TODO(alokp): Query the preferred value from media backend. -const int kDefaultSampleRate = 48000; - -// TODO(jyw): Query the preferred value from media backend. -static const int kDefaultInputBufferSize = 1024; -} // namespace - -namespace chromecast { -namespace media { - -CastAudioManager::CastAudioManager( - std::unique_ptr<::media::AudioThread> audio_thread, - ::media::AudioLogFactory* audio_log_factory, - CastAudioManagerHelper::Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr browser_task_runner, - scoped_refptr media_task_runner, - bool use_mixer) - : CastAudioManager(std::move(audio_thread), - audio_log_factory, - delegate, - std::move(backend_factory_getter), - std::move(browser_task_runner), - std::move(media_task_runner), - use_mixer, - false) {} - -CastAudioManager::CastAudioManager( - std::unique_ptr<::media::AudioThread> audio_thread, - ::media::AudioLogFactory* audio_log_factory, - CastAudioManagerHelper::Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr browser_task_runner, - scoped_refptr media_task_runner, - bool use_mixer, - bool force_use_cma_backend_for_output) - : AudioManagerBase(std::move(audio_thread), audio_log_factory), - helper_(this, - delegate, - std::move(backend_factory_getter), - std::move(media_task_runner)), - browser_task_runner_(std::move(browser_task_runner)), - force_use_cma_backend_for_output_(force_use_cma_backend_for_output), - weak_factory_(this) { - DCHECK(browser_task_runner_->BelongsToCurrentThread()); - weak_this_ = weak_factory_.GetWeakPtr(); - if (use_mixer) - mixer_ = std::make_unique(this); -} - -CastAudioManager::~CastAudioManager() { - DCHECK(browser_task_runner_->BelongsToCurrentThread()); -} - -bool CastAudioManager::HasAudioOutputDevices() { - return true; -} - -void CastAudioManager::GetAudioOutputDeviceNames( - ::media::AudioDeviceNames* device_names) { - DCHECK(device_names->empty()); - if (HasAudioOutputDevices()) { - device_names->push_front(::media::AudioDeviceName::CreateCommunications()); - device_names->push_front(::media::AudioDeviceName::CreateDefault()); - } -} - -bool CastAudioManager::HasAudioInputDevices() { - return false; -} - -void CastAudioManager::GetAudioInputDeviceNames( - ::media::AudioDeviceNames* device_names) { - DCHECK(device_names->empty()); - LOG(WARNING) << "No support for input audio devices"; -} - -::media::AudioParameters CastAudioManager::GetInputStreamParameters( - const std::string& device_id) { - LOG(WARNING) << "No support for input audio devices"; - // Need to send a valid AudioParameters object even when it will be unused. - return ::media::AudioParameters( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), kDefaultSampleRate, - kDefaultInputBufferSize); -} - -const char* CastAudioManager::GetName() { - return "Cast"; -} - -void CastAudioManager::ReleaseOutputStream(::media::AudioOutputStream* stream) { - // If |stream| is |mixer_output_stream_|, we should not use - // AudioManagerBase::ReleaseOutputStream as we do not want the release - // function to decrement |AudioManagerBase::num_output_streams_|. This is - // because the stream generated from MakeMixerOutputStream was not created - // using AudioManagerBase::MakeAudioOutputStream, which appropriately - // increments this variable. - if (mixer_output_stream_.get() == stream) { - DCHECK(mixer_); // Should only occur if |mixer_| exists - mixer_output_stream_.reset(); - } else { - AudioManagerBase::ReleaseOutputStream(stream); - } -} - -::media::AudioOutputStream* CastAudioManager::MakeLinearOutputStream( - const ::media::AudioParameters& params, - const ::media::AudioManager::LogCallback& log_callback) { - DCHECK_EQ(::media::AudioParameters::AUDIO_PCM_LINEAR, params.format()); - - // If |mixer_| exists, return a mixing stream. - if (mixer_) { - return mixer_->MakeStream(params); - } else { - return new CastAudioOutputStream( - &helper_, params, ::media::AudioDeviceDescription::kDefaultDeviceId, - UseMixerOutputStream(params)); - } -} - -::media::AudioOutputStream* CastAudioManager::MakeLowLatencyOutputStream( - const ::media::AudioParameters& params, - const std::string& device_id_or_group_id, - const ::media::AudioManager::LogCallback& log_callback) { - DCHECK_EQ(::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); - - // For non-default device IDs, we always want to use CastAudioOutputStream - // to allow features like redirection. For default device ID, if |mixer_| - // exists, return a mixing stream. If used, the mixing stream will always use - // the default device_id. - if (::media::AudioDeviceDescription::IsDefaultDevice(device_id_or_group_id) && - mixer_) { - return mixer_->MakeStream(params); - } else { - return new CastAudioOutputStream( - &helper_, params, - device_id_or_group_id.empty() - ? ::media::AudioDeviceDescription::kDefaultDeviceId - : device_id_or_group_id, - UseMixerOutputStream(params)); - } -} - -::media::AudioInputStream* CastAudioManager::MakeLinearInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) { - LOG(WARNING) << "No support for input audio devices"; - return nullptr; -} - -::media::AudioInputStream* CastAudioManager::MakeLowLatencyInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) { - LOG(WARNING) << "No support for input audio devices"; - return nullptr; -} - -::media::AudioParameters CastAudioManager::GetPreferredOutputStreamParameters( - const std::string& output_device_id, - const ::media::AudioParameters& input_params) { - int sample_rate = kDefaultSampleRate; - // Set buffer size to 10ms of the sample rate. - int buffer_size = sample_rate / 100; - ::media::AudioParameters output_params( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), sample_rate, buffer_size); - return output_params; -} - -::media::AudioOutputStream* CastAudioManager::MakeMixerOutputStream( - const ::media::AudioParameters& params) { - DCHECK(mixer_); - DCHECK(!mixer_output_stream_); // Only allow 1 |mixer_output_stream_|. - - // Keep a reference to this stream for proper behavior on - // CastAudioManager::ReleaseOutputStream. - mixer_output_stream_.reset(new CastAudioOutputStream( - &helper_, params, ::media::AudioDeviceDescription::kDefaultDeviceId, - UseMixerOutputStream(params))); - return mixer_output_stream_.get(); -} - -bool CastAudioManager::UseMixerOutputStream( - const ::media::AudioParameters& params) { - bool use_cma_backend = - (params.effects() & ::media::AudioParameters::MULTIZONE) || - !mixer_service::HaveFullMixer() || force_use_cma_backend_for_output_; - - return !use_cma_backend; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,142 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_H_ - -#include -#include - -#include "base/gtest_prod_util.h" -#include "base/memory/weak_ptr.h" -#include "base/task/single_thread_task_runner.h" -#include "build/build_config.h" -#include "chromecast/media/audio/cast_audio_manager_helper.h" -#include "media/audio/audio_manager_base.h" - -// NOTE: CastAudioManager receives a |device_id| from the audio service, and -// passes it to CastAudioOutputStream as a |device_id_or_group_id|. -// -// The output stream interprets the |device_id_or_group_id| as a device_id if it -// the value matches a valid device_id, either kCommunicationsDeviceId or -// kDefaultDeviceId (or an empty string as kDefaultDeviceId). If -// |device_id_or_group_id| does not match a valid device_id, then it is -// interpreted as a group_id. group_id is used to determine the |session_id| -// from CastSessionIdMap. Multizone audio is only enabled for kDefaultDeviceId -// so the correct device_id can be inferred without conflict. |group_id| are -// uuid. -// -// At the top end of the audio stack, StreamFactory replaces the |device_id| -// with the |group_id| if the |group_id| is not empty. This implementation in -// StreamFactory is required for multizone audio for Cast devices using CAOS for -// their primary audio playback. - -namespace chromecast { - -namespace media { - -class CastAudioMixer; -class CastAudioManagerTest; -class CastAudioOutputStreamTest; -class CmaBackendFactory; - -class CastAudioManager : public ::media::AudioManagerBase { - public: - CastAudioManager( - std::unique_ptr<::media::AudioThread> audio_thread, - ::media::AudioLogFactory* audio_log_factory, - CastAudioManagerHelper::Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr browser_task_runner, - scoped_refptr media_task_runner, - bool use_mixer); - - CastAudioManager(const CastAudioManager&) = delete; - CastAudioManager& operator=(const CastAudioManager&) = delete; - - ~CastAudioManager() override; - - // AudioManagerBase implementation. - bool HasAudioOutputDevices() override; - void GetAudioOutputDeviceNames( - ::media::AudioDeviceNames* device_names) override; - bool HasAudioInputDevices() override; - void GetAudioInputDeviceNames( - ::media::AudioDeviceNames* device_names) override; - ::media::AudioParameters GetInputStreamParameters( - const std::string& device_id) override; - const char* GetName() override; - void ReleaseOutputStream(::media::AudioOutputStream* stream) override; - - // Make this public for testing. - using ::media::AudioManagerBase::GetOutputStreamParameters; - - protected: - // AudioManagerBase implementation. - ::media::AudioOutputStream* MakeLinearOutputStream( - const ::media::AudioParameters& params, - const ::media::AudioManager::LogCallback& log_callback) override; - ::media::AudioOutputStream* MakeLowLatencyOutputStream( - const ::media::AudioParameters& params, - const std::string& device_id_or_group_id, - const ::media::AudioManager::LogCallback& log_callback) override; - ::media::AudioInputStream* MakeLinearInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) override; - ::media::AudioInputStream* MakeLowLatencyInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) override; - ::media::AudioParameters GetPreferredOutputStreamParameters( - const std::string& output_device_id, - const ::media::AudioParameters& input_params) override; - - // Generates a CastAudioOutputStream for |mixer_|. - virtual ::media::AudioOutputStream* MakeMixerOutputStream( - const ::media::AudioParameters& params); - - private: - FRIEND_TEST_ALL_PREFIXES(CastAudioManagerTest, CanMakeStreamProxy); - friend class CastAudioMixer; - friend class CastAudioManagerTest; - friend class CastAudioOutputStreamTest; - - CastAudioManager( - std::unique_ptr<::media::AudioThread> audio_thread, - ::media::AudioLogFactory* audio_log_factory, - CastAudioManagerHelper::Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr browser_task_runner, - scoped_refptr media_task_runner, - bool use_mixer, - bool force_use_cma_backend_for_output); - - // Returns false if it is not appropriate to use the mixer service for output - // stream audio playback. - bool UseMixerOutputStream(const ::media::AudioParameters& params); - - CastAudioManagerHelper helper_; - - scoped_refptr browser_task_runner_; - std::unique_ptr<::media::AudioOutputStream> mixer_output_stream_; - std::unique_ptr mixer_; - - // Let unit test force the CastOutputStream to uses - // CmaBackend implementation. - // TODO(b/117980762): After refactoring CastOutputStream, so - // that the CastOutputStream has a unified output API, regardless - // of the platform condition, then the unit test would be able to test - // CastOutputStream properly. - bool force_use_cma_backend_for_output_; - - // Weak pointers must be dereferenced on the |browser_task_runner|. - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_alsa.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_alsa.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,244 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_manager_alsa.h" - -#include -#include - -#include "base/logging.h" -#include "base/memory/free_deleter.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/audio/audio_buildflags.h" -#include "chromecast/media/audio/cast_audio_input_stream.h" -#include "media/audio/alsa/alsa_input.h" -#include "media/audio/alsa/alsa_wrapper.h" - -namespace chromecast { -namespace media { - -namespace { - -// TODO(alokp): Query the preferred value from media backend. -const int kDefaultSampleRate = BUILDFLAG(AUDIO_INPUT_SAMPLE_RATE); - -// TODO(jyw): Query the preferred value from media backend. -const int kDefaultInputBufferSize = 1024; - -#if BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) -const int kCommunicationsSampleRate = 16000; -const int kCommunicationsInputBufferSize = 160; // 10 ms. -#endif - -// Since "default" and "dmix" devices are virtual devices mapped to real -// devices, we remove them from the list to avoiding duplicate counting. -constexpr std::string_view kInvalidAudioInputDevices[] = { - "default", - "dmix", - "null", - "communications", -}; - -// Constants specified by the ALSA API for device hints. -constexpr char kPcmInterfaceName[] = "pcm"; -constexpr char kIoHintName[] = "IOID"; -constexpr char kNameHintName[] = "NAME"; -constexpr char kDescriptionHintName[] = "DESC"; - -bool IsAlsaDeviceAvailable(CastAudioManagerAlsa::StreamType type, - const char* device_name) { - if (!device_name) - return false; - - // We do prefix matches on the device name to see whether to include - // it or not. - if (type == CastAudioManagerAlsa::kStreamCapture) { - // Check if the device is in the list of invalid devices. - for (size_t i = 0; i < std::size(kInvalidAudioInputDevices); ++i) { - if (kInvalidAudioInputDevices[i] == device_name) - return false; - } - return true; - } else { - DCHECK_EQ(CastAudioManagerAlsa::kStreamPlayback, type); - // We prefer the device type that maps straight to hardware but - // goes through software conversion if needed (e.g. incompatible - // sample rate). - // TODO(joi): Should we prefer "hw" instead? - const std::string kDeviceTypeDesired = "plughw"; - return kDeviceTypeDesired == device_name; - } -} - -std::string UnwantedDeviceTypeWhenEnumerating( - CastAudioManagerAlsa::StreamType wanted_type) { - return wanted_type == CastAudioManagerAlsa::kStreamPlayback ? "Input" - : "Output"; -} - -} // namespace - -CastAudioManagerAlsa::CastAudioManagerAlsa( - std::unique_ptr<::media::AudioThread> audio_thread, - ::media::AudioLogFactory* audio_log_factory, - CastAudioManagerHelper::Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr browser_task_runner, - scoped_refptr media_task_runner, - bool use_mixer) - : CastAudioManager(std::move(audio_thread), - audio_log_factory, - delegate, - std::move(backend_factory_getter), - browser_task_runner, - media_task_runner, - use_mixer), - wrapper_(new ::media::AlsaWrapper()) {} - -CastAudioManagerAlsa::~CastAudioManagerAlsa() {} - -bool CastAudioManagerAlsa::HasAudioInputDevices() { - return true; -} - -void CastAudioManagerAlsa::GetAudioInputDeviceNames( - ::media::AudioDeviceNames* device_names) { - DCHECK(device_names->empty()); - - // Prepend the default device since we always want it to be on the top of the - // list for all platforms. Note, pulse has exclusively opened the default - // device, so we must open the device via the "default" moniker. - device_names->push_front(::media::AudioDeviceName::CreateDefault()); -#if BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - device_names->push_back(::media::AudioDeviceName::CreateCommunications()); -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - - GetAlsaAudioDevices(kStreamCapture, device_names); -} - -::media::AudioParameters CastAudioManagerAlsa::GetInputStreamParameters( - const std::string& device_id) { - if (device_id == ::media::AudioDeviceDescription::kCommunicationsDeviceId) { -#if !BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - NOTIMPLEMENTED() - << "Capture Service is not enabled, return a fake AudioParameters."; - return ::media::AudioParameters(); -#else - return ::media::AudioParameters(::media::AudioParameters::AUDIO_PCM_LINEAR, - ::media::CHANNEL_LAYOUT_MONO, - kCommunicationsSampleRate, - kCommunicationsInputBufferSize); -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - } - // TODO(jyw): Be smarter about sample rate instead of hardcoding it. - // Need to send a valid AudioParameters object even when it will be unused. - return ::media::AudioParameters( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), kDefaultSampleRate, - kDefaultInputBufferSize); -} - -::media::AudioInputStream* CastAudioManagerAlsa::MakeLinearInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) { - DCHECK_EQ(::media::AudioParameters::AUDIO_PCM_LINEAR, params.format()); - return MakeInputStream(params, device_id); -} - -::media::AudioInputStream* CastAudioManagerAlsa::MakeLowLatencyInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) { - DCHECK_EQ(::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); - return MakeInputStream(params, device_id); -} - -::media::AudioInputStream* CastAudioManagerAlsa::MakeInputStream( - const ::media::AudioParameters& params, - const std::string& device_id) { - std::string device_name = - (device_id == ::media::AudioDeviceDescription::kDefaultDeviceId) - ? ::media::AlsaPcmInputStream::kAutoSelectDevice - : device_id; - if (device_name == ::media::AudioDeviceDescription::kCommunicationsDeviceId) { -#if !BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - NOTIMPLEMENTED() << "Capture Service is not enabled, return nullptr."; - return nullptr; -#else - return new CastAudioInputStream(this, params, device_name); -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - } - return new ::media::AlsaPcmInputStream(this, device_name, params, - wrapper_.get()); -} - -void CastAudioManagerAlsa::GetAlsaAudioDevices( - StreamType type, - ::media::AudioDeviceNames* device_names) { - int card = -1; - - // Loop through the sound cards to get ALSA device hints. - while (!wrapper_->CardNext(&card) && card >= 0) { - void** hints = NULL; - int error = wrapper_->DeviceNameHint(card, kPcmInterfaceName, &hints); - if (!error) { - GetAlsaDevicesInfo(type, hints, device_names); - - // Destroy the hints now that we're done with it. - wrapper_->DeviceNameFreeHint(hints); - } else { - DLOG(WARNING) << "GetAlsaAudioDevices: unable to get device hints: " - << wrapper_->StrError(error); - } - } -} - -void CastAudioManagerAlsa::GetAlsaDevicesInfo( - StreamType type, - void** hints, - ::media::AudioDeviceNames* device_names) { - const std::string unwanted_device_type = - UnwantedDeviceTypeWhenEnumerating(type); - - for (void** hint_iter = hints; *hint_iter != NULL; hint_iter++) { - // Only examine devices of the right type. Valid values are - // "Input", "Output", and NULL which means both input and output. - std::unique_ptr io( - wrapper_->DeviceNameGetHint(*hint_iter, kIoHintName)); - if (io && unwanted_device_type == io.get()) - continue; - - // Get the unique device name for the device. - std::unique_ptr unique_device_name( - wrapper_->DeviceNameGetHint(*hint_iter, kNameHintName)); - - // Find out if the device is available. - if (IsAlsaDeviceAvailable(type, unique_device_name.get())) { - // Get the description for the device. - std::unique_ptr desc( - wrapper_->DeviceNameGetHint(*hint_iter, kDescriptionHintName)); - - ::media::AudioDeviceName name; - name.unique_id = unique_device_name.get(); - if (desc) { - name.device_name = desc.get(); - // Use the more user friendly description as name. - // Replace '\n' with '-'. - name.device_name.replace(name.device_name.find('\n'), 1, 1, '-'); - } else { - // Virtual devices don't necessarily have descriptions. - // Use their names instead. - name.device_name = unique_device_name.get(); - } - - // Store the device information. - device_names->push_back(name); - } - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_alsa.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_alsa.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_ALSA_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_ALSA_H_ - -#include -#include - -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/audio/cast_audio_manager.h" -#include "chromecast/media/audio/cast_audio_manager_helper.h" - -namespace media { -class AlsaWrapper; -} - -namespace chromecast { - -namespace media { - -class CastAudioManagerAlsa : public CastAudioManager { - public: - enum StreamType { - kStreamPlayback = 0, - kStreamCapture, - }; - - CastAudioManagerAlsa( - std::unique_ptr<::media::AudioThread> audio_thread, - ::media::AudioLogFactory* audio_log_factory, - CastAudioManagerHelper::Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr browser_task_runner, - scoped_refptr media_task_runner, - bool use_mixer); - - CastAudioManagerAlsa(const CastAudioManagerAlsa&) = delete; - CastAudioManagerAlsa& operator=(const CastAudioManagerAlsa&) = delete; - - ~CastAudioManagerAlsa() override; - - // CastAudioManager implementation. - bool HasAudioInputDevices() override; - void GetAudioInputDeviceNames( - ::media::AudioDeviceNames* device_names) override; - ::media::AudioParameters GetInputStreamParameters( - const std::string& device_id) override; - - private: - // CastAudioManager implementation. - ::media::AudioInputStream* MakeLinearInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) override; - ::media::AudioInputStream* MakeLowLatencyInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) override; - - ::media::AudioInputStream* MakeInputStream( - const ::media::AudioParameters& params, - const std::string& device_id); - - // Gets a list of available ALSA devices. - void GetAlsaAudioDevices(StreamType type, - ::media::AudioDeviceNames* device_names); - - // Gets the ALSA devices' names and ids that support streams of the - // given type. - void GetAlsaDevicesInfo(StreamType type, - void** hint, - ::media::AudioDeviceNames* device_names); - - std::unique_ptr<::media::AlsaWrapper> wrapper_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_ALSA_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_alsa_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_alsa_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_alsa_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_manager_alsa.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/test_message_loop.h" -#include "chromecast/media/api/test/mock_cma_backend_factory.h" -#include "chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h" -#include "media/audio/fake_audio_log_factory.h" -#include "media/audio/test_audio_thread.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -const char kDefaultAlsaDevice[] = "plug:default"; - -const ::media::AudioParameters kDefaultAudioParams( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), - ::media::AudioParameters::kAudioCDSampleRate, - 256); - -void OnLogMessage(const std::string& message) {} - -class CastAudioManagerAlsaTest : public testing::Test { - public: - CastAudioManagerAlsaTest() : media_thread_("CastMediaThread") { - CHECK(media_thread_.Start()); - - backend_factory_ = std::make_unique(); - audio_manager_ = std::make_unique( - std::make_unique<::media::TestAudioThread>(), &audio_log_factory_, - &delegate_, - base::BindRepeating(&CastAudioManagerAlsaTest::GetCmaBackendFactory, - base::Unretained(this)), - base::SingleThreadTaskRunner::GetCurrentDefault(), - media_thread_.task_runner(), false); - } - - ~CastAudioManagerAlsaTest() override { audio_manager_->Shutdown(); } - CmaBackendFactory* GetCmaBackendFactory() { return backend_factory_.get(); } - - protected: - base::TestMessageLoop message_loop_; - std::unique_ptr backend_factory_; - base::Thread media_thread_; - ::media::FakeAudioLogFactory audio_log_factory_; - MockCastAudioManagerHelperDelegate delegate_; - std::unique_ptr audio_manager_; -}; - -TEST_F(CastAudioManagerAlsaTest, MakeAudioInputStream) { - ::media::AudioInputStream* stream = audio_manager_->MakeAudioInputStream( - kDefaultAudioParams, kDefaultAlsaDevice, - base::BindRepeating(&OnLogMessage)); - ASSERT_TRUE(stream); - EXPECT_EQ(::media::AudioInputStream::OpenOutcome::kSuccess, stream->Open()); - stream->Close(); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_android.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_android.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,195 +0,0 @@ -// 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 "chromecast/media/audio/cast_audio_manager_android.h" - -#include - -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/audio/audio_buildflags.h" -#include "chromecast/media/audio/cast_audio_input_stream.h" -#include "chromecast/media/audio/cast_audio_output_stream.h" -#include "chromecast/media/audio/cast_audio_output_utils.h" -#include "media/audio/android/audio_track_output_stream.h" -#include "media/audio/audio_device_name.h" -#include "media/base/audio_parameters.h" -#include "media/base/channel_layout.h" - -namespace chromecast { -namespace media { -namespace { - -const int kDefaultSampleRate = 48000; -const int kDefaultInputBufferSize = 1024; - -#if BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) -const int kCommunicationsSampleRate = 16000; -const int kCommunicationsInputBufferSize = 160; // 10 ms. -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - -bool ShouldUseCastAudioOutputStream(bool is_audio_app, - bool is_group, - const ::media::AudioParameters& params) { - return is_audio_app || is_group || - (params.effects() & ::media::AudioParameters::AUDIO_PREFETCH); -} - -} // namespace - -CastAudioManagerAndroid::CastAudioManagerAndroid( - std::unique_ptr<::media::AudioThread> audio_thread, - ::media::AudioLogFactory* audio_log_factory, - CastAudioManagerHelper::Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr media_task_runner) - : ::media::AudioManagerAndroid(std::move(audio_thread), audio_log_factory), - helper_(this, - delegate, - std::move(backend_factory_getter), - std::move(media_task_runner)) {} - -CastAudioManagerAndroid::~CastAudioManagerAndroid() = default; - -bool CastAudioManagerAndroid::HasAudioInputDevices() { -#if BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - return true; -#else - return false; -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) -} - -void CastAudioManagerAndroid::GetAudioInputDeviceNames( - ::media::AudioDeviceNames* device_names) { - DCHECK(device_names->empty()); -#if BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - device_names->push_back(::media::AudioDeviceName::CreateCommunications()); -#else - LOG(WARNING) << "No support for input audio devices"; -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) -} - -::media::AudioParameters CastAudioManagerAndroid::GetInputStreamParameters( - const std::string& device_id) { -#if BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - if (device_id == ::media::AudioDeviceDescription::kCommunicationsDeviceId) { - return ::media::AudioParameters(::media::AudioParameters::AUDIO_PCM_LINEAR, - ::media::CHANNEL_LAYOUT_MONO, - kCommunicationsSampleRate, - kCommunicationsInputBufferSize); - } -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - LOG(WARNING) << "No support for input audio devices"; - // Need to send a valid AudioParameters object even when it will be unused. - return ::media::AudioParameters( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), kDefaultSampleRate, - kDefaultInputBufferSize); -} - -::media::AudioInputStream* CastAudioManagerAndroid::MakeLinearInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) { -#if BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - if (device_id == ::media::AudioDeviceDescription::kCommunicationsDeviceId) { - return new CastAudioInputStream(this, params, device_id); - } -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - LOG(WARNING) << "No support for input audio devices"; - return nullptr; -} - -::media::AudioInputStream* CastAudioManagerAndroid::MakeLowLatencyInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) { -#if BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - if (device_id == ::media::AudioDeviceDescription::kCommunicationsDeviceId) { - return new CastAudioInputStream(this, params, device_id); - } -#endif // BUILDFLAG(ENABLE_AUDIO_CAPTURE_SERVICE) - LOG(WARNING) << "No support for input audio devices"; - return nullptr; -} - -void CastAudioManagerAndroid::GetAudioOutputDeviceNames( - ::media::AudioDeviceNames* device_names) { - DCHECK(device_names->empty()); - DCHECK(HasAudioOutputDevices()); - - // Default device name is added inside AudioManagerAndroid. - ::media::AudioManagerAndroid::GetAudioOutputDeviceNames(device_names); - - device_names->push_back(::media::AudioDeviceName::CreateCommunications()); -} - -::media::AudioOutputStream* CastAudioManagerAndroid::MakeLinearOutputStream( - const ::media::AudioParameters& params, - const ::media::AudioManager::LogCallback& log_callback) { - DCHECK_EQ(::media::AudioParameters::AUDIO_PCM_LINEAR, params.format()); - // MakeLinearOutputStream is only used on Windows. In this case, we cannot get - // a valid session id based on kDefaultDeviceId. Therefore we cannot know - // whether it is an audio only session. - if (ShouldUseCastAudioOutputStream(false /* is_audio_app */, - false /* is_group */, params)) { - LOG(WARNING) << __func__ << ": Cannot get valid session_id."; - return new CastAudioOutputStream( - &helper_, params, ::media::AudioDeviceDescription::kDefaultDeviceId, - false /* use_mixer_service */); - } - - return ::media::AudioManagerAndroid::MakeLinearOutputStream(params, - log_callback); -} - -::media::AudioOutputStream* CastAudioManagerAndroid::MakeLowLatencyOutputStream( - const ::media::AudioParameters& params, - const std::string& device_id_or_group_id, - const ::media::AudioManager::LogCallback& log_callback) { - DCHECK_EQ(::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); - std::string session_id = - helper_.GetSessionId(GetGroupId(device_id_or_group_id)); - bool is_audio_app = helper_.IsAudioOnlySession(session_id); - bool is_group = helper_.IsGroup(session_id); - if (ShouldUseCastAudioOutputStream(is_audio_app, is_group, params)) { - return new CastAudioOutputStream( - &helper_, params, - device_id_or_group_id.empty() - ? ::media::AudioDeviceDescription::kDefaultDeviceId - : device_id_or_group_id, - false /* use_mixer_service */); - } - - return ::media::AudioManagerAndroid::MakeLowLatencyOutputStream( - params, device_id_or_group_id, log_callback); -} - -::media::AudioOutputStream* CastAudioManagerAndroid::MakeBitstreamOutputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) { - DCHECK(params.IsBitstreamFormat()); - return new ::media::AudioTrackOutputStream(this, params); -} - -::media::AudioOutputStream* CastAudioManagerAndroid::MakeAudioOutputStreamProxy( - const ::media::AudioParameters& params, - const std::string& device_id) { - std::string session_id = helper_.GetSessionId(GetGroupId(device_id)); - bool is_audio_app = helper_.IsAudioOnlySession(session_id); - bool is_group = helper_.IsGroup(session_id); - if (ShouldUseCastAudioOutputStream(is_audio_app, is_group, params)) { - // Override to use MakeAudioOutputStream to prevent the audio output stream - // from closing during pause/stop. - return MakeAudioOutputStream(params, device_id, - /*log_callback, not used*/ base::DoNothing()); - } - - return ::media::AudioManagerAndroid::MakeAudioOutputStreamProxy(params, - device_id); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_android.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_android.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_ANDROID_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_ANDROID_H_ - -#include -#include - -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/audio/cast_audio_manager_helper.h" -#include "media/audio/android/audio_manager_android.h" - -namespace chromecast::media { - -class CastAudioManagerAndroid : public ::media::AudioManagerAndroid { - public: - CastAudioManagerAndroid( - std::unique_ptr<::media::AudioThread> audio_thread, - ::media::AudioLogFactory* audio_log_factory, - CastAudioManagerHelper::Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr media_task_runner); - ~CastAudioManagerAndroid() override; - - CastAudioManagerAndroid(const CastAudioManagerAndroid&) = delete; - CastAudioManagerAndroid& operator=(const CastAudioManagerAndroid&) = delete; - - // AudioManager implementation. - void GetAudioOutputDeviceNames( - ::media::AudioDeviceNames* device_names) override; - ::media::AudioOutputStream* MakeAudioOutputStreamProxy( - const ::media::AudioParameters& params, - const std::string& device_id) override; - ::media::AudioOutputStream* MakeLinearOutputStream( - const ::media::AudioParameters& params, - const ::media::AudioManager::LogCallback& log_callback) override; - ::media::AudioOutputStream* MakeLowLatencyOutputStream( - const ::media::AudioParameters& params, - const std::string& device_id_or_group_id, - const ::media::AudioManager::LogCallback& log_callback) override; - ::media::AudioOutputStream* MakeBitstreamOutputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) override; - - bool HasAudioInputDevices() override; - void GetAudioInputDeviceNames( - ::media::AudioDeviceNames* device_names) override; - ::media::AudioParameters GetInputStreamParameters( - const std::string& device_id) override; - - // Make this public for testing. - using ::media::AudioManagerBase::GetOutputStreamParameters; - - private: - friend class CastAudioManagerTest; - - // CastAudioManager implementation. - ::media::AudioInputStream* MakeLinearInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) override; - ::media::AudioInputStream* MakeLowLatencyInputStream( - const ::media::AudioParameters& params, - const std::string& device_id, - const ::media::AudioManager::LogCallback& log_callback) override; - - CastAudioManagerHelper helper_; -}; - -} // namespace chromecast::media - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_helper.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_helper.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_helper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_helper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// 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 "chromecast/media/audio/cast_audio_manager_helper.h" - -#include - -#include "base/check.h" -#include "base/task/single_thread_task_runner.h" - -namespace chromecast { -namespace media { - -CastAudioManagerHelper::CastAudioManagerHelper( - ::media::AudioManagerBase* audio_manager, - Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr media_task_runner) - : audio_manager_(audio_manager), - delegate_(delegate), - backend_factory_getter_(std::move(backend_factory_getter)), - media_task_runner_(std::move(media_task_runner)) { - DCHECK(audio_manager_); - DCHECK(delegate_); - DCHECK(backend_factory_getter_); -} - -CastAudioManagerHelper::~CastAudioManagerHelper() = default; - -CmaBackendFactory* CastAudioManagerHelper::GetCmaBackendFactory() { - if (!cma_backend_factory_) - cma_backend_factory_ = backend_factory_getter_.Run(); - return cma_backend_factory_; -} - -std::string CastAudioManagerHelper::GetSessionId( - const std::string& audio_group_id) { - return delegate_->GetSessionId(audio_group_id); -} - -bool CastAudioManagerHelper::IsAudioOnlySession(const std::string& session_id) { - return delegate_->IsAudioOnlySession(session_id); -} - -bool CastAudioManagerHelper::IsGroup(const std::string& session_id) { - return delegate_->IsGroup(session_id); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_helper.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_helper.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_helper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_helper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_HELPER_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_HELPER_H_ - -#include - -#include "base/functional/callback.h" -#include "base/memory/scoped_refptr.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace media { -class AudioManagerBase; -} // namespace media - -namespace chromecast { -namespace media { - -class CmaBackendFactory; - -// Helper class to share common logic between different AudioManager. -class CastAudioManagerHelper { - public: - class Delegate { - public: - // Get session ID for the provided group ID. - virtual std::string GetSessionId(const std::string& group_id) = 0; - // Get whether the session is audio-only for the provided session ID. - virtual bool IsAudioOnlySession(const std::string& session_id) = 0; - // Get whether the session is launched in a group for the provided session - // ID. - virtual bool IsGroup(const std::string& session_id) = 0; - - protected: - virtual ~Delegate() = default; - }; - - CastAudioManagerHelper( - ::media::AudioManagerBase* audio_manager, - Delegate* delegate, - base::RepeatingCallback backend_factory_getter, - scoped_refptr media_task_runner); - ~CastAudioManagerHelper(); - - ::media::AudioManagerBase* audio_manager() { return audio_manager_; } - - base::SingleThreadTaskRunner* media_task_runner() { - return media_task_runner_.get(); - } - - CmaBackendFactory* GetCmaBackendFactory(); - std::string GetSessionId(const std::string& audio_group_id); - bool IsAudioOnlySession(const std::string& session_id); - bool IsGroup(const std::string& session_id); - - private: - ::media::AudioManagerBase* const audio_manager_; - Delegate* const delegate_; - base::RepeatingCallback backend_factory_getter_; - CmaBackendFactory* cma_backend_factory_ = nullptr; - scoped_refptr media_task_runner_; - - CastAudioManagerHelper(const CastAudioManagerHelper&) = delete; - CastAudioManagerHelper& operator=(const CastAudioManagerHelper&) = delete; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MANAGER_HELPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_manager_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_manager_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,322 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/memory/ptr_util.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "build/build_config.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/test/mock_cma_backend.h" -#include "chromecast/media/api/test/mock_cma_backend_factory.h" -#include "chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h" -#include "media/audio/audio_device_info_accessor_for_tests.h" -#include "media/audio/fake_audio_log_factory.h" -#include "media/audio/mock_audio_source_callback.h" -#include "media/audio/test_audio_thread.h" -#include "media/media_buildflags.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if BUILDFLAG(IS_ANDROID) -#include "chromecast/media/audio/cast_audio_manager_android.h" -#include "media/audio/android/audio_track_output_stream.h" -#else // BUILDFLAG(IS_ANDROID) -#include "chromecast/media/audio/cast_audio_manager.h" -#endif // BUILDFLAG(IS_ANDROID) - -using testing::_; -using testing::AnyNumber; -using testing::Invoke; -using testing::NiceMock; -using testing::Return; -using testing::StrictMock; - -namespace { - -const ::media::AudioParameters kDefaultAudioParams( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), - ::media::AudioParameters::kAudioCDSampleRate, - 256); - -const ::media::AudioParameters kAudioParamsInvalidLayout( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::FromLayout<::media::CHANNEL_LAYOUT_NONE>(), - ::media::AudioParameters::kAudioCDSampleRate, - 256); - -int OnMoreData(base::TimeDelta delay, - base::TimeTicks delay_timestamp, - const ::media::AudioGlitchInfo& glitch_info, - ::media::AudioBus* dest) { - dest->Zero(); - return kDefaultAudioParams.frames_per_buffer(); -} - -} // namespace - -namespace chromecast::media { - -class CastAudioManagerTest : public testing::Test { - public: - CastAudioManagerTest() : audio_thread_("CastAudioThread") {} - - void SetUp() override { CreateAudioManagerForTesting(); } - - void TearDown() override { - RunThreadsUntilIdle(); - audio_manager_->Shutdown(); - RunThreadsUntilIdle(); - audio_thread_.Stop(); - } - - protected: - void FakeLogCallback(const std::string& string) {} - CmaBackendFactory* GetCmaBackendFactory() { - return mock_backend_factory_.get(); - } - - void CreateAudioManagerForTesting(bool use_mixer = false) { - // Only one AudioManager may exist at a time, so destroy the one we're - // currently holding before creating a new one. - // Flush the message loop to run any shutdown tasks posted by AudioManager. - if (audio_manager_) { - audio_manager_->Shutdown(); - audio_manager_.reset(); - } - if (audio_thread_.IsRunning()) { - audio_thread_.Stop(); - } - CHECK(audio_thread_.StartAndWaitForTesting()); - - mock_backend_factory_ = std::make_unique(); -#if BUILDFLAG(IS_ANDROID) - audio_manager_ = std::make_unique( - std::make_unique<::media::TestAudioThread>(), &fake_audio_log_factory_, - &mock_delegate_, - base::BindRepeating(&CastAudioManagerTest::GetCmaBackendFactory, - base::Unretained(this)), - task_environment_.GetMainThreadTaskRunner()); -#else // BUILDFLAG(IS_ANDROID) - audio_manager_ = base::WrapUnique(new CastAudioManager( - std::make_unique<::media::TestAudioThread>(), &fake_audio_log_factory_, - &mock_delegate_, - base::BindRepeating(&CastAudioManagerTest::GetCmaBackendFactory, - base::Unretained(this)), - task_environment_.GetMainThreadTaskRunner(), - audio_thread_.task_runner(), use_mixer, - true /* force_use_cma_backend_for_output*/ - )); -#endif // BUILDFLAG(IS_ANDROID) - // A few AudioManager implementations post initialization tasks to - // audio thread. Flush the thread to ensure that |audio_manager_| is - // initialized and ready to use before returning from this function. - // TODO(alokp): We should perhaps do this in AudioManager::Create(). - RunThreadsUntilIdle(); - device_info_accessor_ = - std::make_unique<::media::AudioDeviceInfoAccessorForTests>( - audio_manager_.get()); - } - - void SetUpBackendAndDecoder() { -#if !BUILDFLAG(IS_ANDROID) - // Android impl of CastAudioManager does not use CMA. - mock_audio_decoder_ = - std::make_unique>(); - EXPECT_CALL(*mock_audio_decoder_, SetDelegate(_)).Times(1); - EXPECT_CALL(*mock_audio_decoder_, SetConfig(_)).WillOnce(Return(true)); - - mock_cma_backend_ = std::make_unique>(); - EXPECT_CALL(*mock_cma_backend_, CreateAudioDecoder()) - .WillOnce(Return(mock_audio_decoder_.get())); - EXPECT_CALL(*mock_cma_backend_, Initialize()).WillOnce(Return(true)); - - EXPECT_CALL(*mock_backend_factory_, CreateBackend(_)) - .WillOnce(Invoke([this](const MediaPipelineDeviceParams&) { - return std::move(mock_cma_backend_); - })); -#endif // !BUILDFLAG(IS_ANDROID) - EXPECT_EQ(mock_backend_factory_.get(), - audio_manager_->helper_.GetCmaBackendFactory()); - } - - void RunThreadsUntilIdle() { - task_environment_.RunUntilIdle(); - audio_thread_.FlushForTesting(); - } - - base::Thread audio_thread_; - base::test::TaskEnvironment task_environment_; - ::media::FakeAudioLogFactory fake_audio_log_factory_; - MockCastAudioManagerHelperDelegate mock_delegate_; - std::unique_ptr mock_backend_factory_; - ::media::MockAudioSourceCallback mock_source_callback_; - std::unique_ptr mock_cma_backend_; - std::unique_ptr mock_audio_decoder_; - -#if BUILDFLAG(IS_ANDROID) - std::unique_ptr audio_manager_; -#else // BUILDFLAG(IS_ANDROID) - std::unique_ptr audio_manager_; -#endif // BUILDFLAG(IS_ANDROID) - - std::unique_ptr<::media::AudioDeviceInfoAccessorForTests> - device_info_accessor_; -}; - -TEST_F(CastAudioManagerTest, HasValidOutputStreamParameters) { - std::string default_device_id = - ::media::AudioDeviceDescription::kDefaultDeviceId; - ::media::AudioParameters params = - audio_manager_->GetOutputStreamParameters(default_device_id); - EXPECT_TRUE(params.IsValid()); -} - -TEST_F(CastAudioManagerTest, CanMakeStream) { - SetUpBackendAndDecoder(); - ::media::AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream( - kDefaultAudioParams, "", ::media::AudioManager::LogCallback()); - EXPECT_TRUE(stream->Open()); - - if (mock_cma_backend_) { - EXPECT_CALL(*mock_cma_backend_, Start(_)).WillOnce(Return(true)); - } - EXPECT_CALL(mock_source_callback_, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - EXPECT_CALL(mock_source_callback_, OnError(_)).Times(0); - stream->Start(&mock_source_callback_); - RunThreadsUntilIdle(); - - stream->Stop(); - RunThreadsUntilIdle(); - - stream->Close(); - RunThreadsUntilIdle(); -} - -#if BUILDFLAG(IS_ANDROID) -TEST_F(CastAudioManagerTest, CanMakeAC3Stream) { - const ::media::AudioParameters kAC3AudioParams( - ::media::AudioParameters::AUDIO_BITSTREAM_AC3, - ::media::ChannelLayoutConfig::FromLayout<::media::CHANNEL_LAYOUT_5_1>(), - ::media::AudioParameters::kAudioCDSampleRate, 256); - ::media::AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream( - kAC3AudioParams, "", ::media::AudioManager::LogCallback()); - ASSERT_TRUE(stream); - // Only run the rest of the test if the device supports AC3. - if (stream->Open()) { - EXPECT_CALL(mock_source_callback_, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - EXPECT_CALL(mock_source_callback_, OnError(_)).Times(0); - stream->Start(&mock_source_callback_); - RunThreadsUntilIdle(); - - stream->Stop(); - RunThreadsUntilIdle(); - } - stream->Close(); -} - -#if BUILDFLAG(ENABLE_PLATFORM_DTS_AUDIO) -TEST_F(CastAudioManagerTest, CanMakeDTSStream) { - const ::media::AudioParameters kDTSAudioParams( - ::media::AudioParameters::AUDIO_BITSTREAM_DTS, - ::media::ChannelLayoutConfig::FromLayout<::media::CHANNEL_LAYOUT_5_1>, - ::media::AudioParameters::kAudioCDSampleRate, 256); - ::media::AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream( - kDTSAudioParams, "", ::media::AudioManager::LogCallback()); - ASSERT_TRUE(stream); - // Only run the rest of the test if the device supports DTS. - if (stream->Open()) { - EXPECT_CALL(mock_source_callback_, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - EXPECT_CALL(mock_source_callback_, OnError(_)).Times(0); - stream->Start(&mock_source_callback_); - RunThreadsUntilIdle(); - - stream->Stop(); - RunThreadsUntilIdle(); - } - stream->Close(); -} -#endif // BUILDFLAG(ENABLE_PLATFORM_DTS_AUDIO)) -#endif // BUILDFLAG(IS_ANDROID) - -TEST_F(CastAudioManagerTest, DISABLED_CanMakeStreamProxy) { - SetUpBackendAndDecoder(); - ::media::AudioOutputStream* stream = - audio_manager_->MakeAudioOutputStreamProxy(kDefaultAudioParams, ""); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - if (mock_cma_backend_) { - EXPECT_CALL(*mock_cma_backend_, Start(_)).WillOnce(Return(true)); - } - EXPECT_CALL(mock_source_callback_, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - EXPECT_CALL(mock_source_callback_, OnError(_)).Times(0); - stream->Start(&mock_source_callback_); - RunThreadsUntilIdle(); - - stream->Stop(); - - stream->Close(); - RunThreadsUntilIdle(); - // TODO(steinbock) Figure out why stream is not unregistering itself from - // audio_manager_ -} - -TEST_F(CastAudioManagerTest, CanMakeMixerStream) { - CreateAudioManagerForTesting(true /* use_mixer */); - SetUpBackendAndDecoder(); - ::media::AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream( - kDefaultAudioParams, "", ::media::AudioManager::LogCallback()); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - - if (mock_cma_backend_) { - EXPECT_CALL(*mock_cma_backend_, Start(_)).WillOnce(Return(true)); - } - EXPECT_CALL(mock_source_callback_, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - EXPECT_CALL(mock_source_callback_, OnError(_)).Times(0); - - stream->Start(&mock_source_callback_); - RunThreadsUntilIdle(); - - stream->Stop(); - RunThreadsUntilIdle(); - - stream->Close(); -} - -TEST_F(CastAudioManagerTest, CanMakeCommunicationsStream) { - CreateAudioManagerForTesting(); - SetUpBackendAndDecoder(); - - ::media::AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream( - kDefaultAudioParams, - ::media::AudioDeviceDescription::kCommunicationsDeviceId, - ::media::AudioManager::LogCallback()); - EXPECT_TRUE(stream->Open()); - - EXPECT_CALL(mock_source_callback_, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - EXPECT_CALL(mock_source_callback_, OnError(_)).Times(0); - task_environment_.RunUntilIdle(); - - stream->Stop(); - task_environment_.RunUntilIdle(); - - stream->Close(); -} - -} // namespace chromecast::media diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_mixer.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_mixer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,306 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_mixer.h" - -#include "base/containers/contains.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "chromecast/media/audio/cast_audio_manager.h" -#include "chromecast/media/audio/cast_audio_output_stream.h" -#include "media/base/audio_timestamp_helper.h" -#include "media/base/channel_layout.h" - -namespace { -const int kFramesPerBuffer = 1024; -const int kSampleRate = 48000; -} // namespace - -namespace chromecast { -namespace media { - -class CastAudioMixer::MixerProxyStream - : public ::media::AudioOutputStream, - public ::media::AudioConverter::InputCallback { - public: - MixerProxyStream(const ::media::AudioParameters& input_params, - const ::media::AudioParameters& output_params, - CastAudioMixer* audio_mixer) - : audio_mixer_(audio_mixer), - input_params_(input_params), - output_params_(output_params), - opened_(false), - volume_(1.0), - source_callback_(nullptr) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - } - - MixerProxyStream(const MixerProxyStream&) = delete; - MixerProxyStream& operator=(const MixerProxyStream&) = delete; - - ~MixerProxyStream() override { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - } - - void OnError(ErrorType type) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - if (source_callback_) - source_callback_->OnError(type); - } - - private: - // ResamplerProxy is an intermediate filter between MixerProxyStream and - // CastAudioMixer::output_stream_ whose only responsibility is to resample - // audio to the sample rate expected by CastAudioMixer::output_stream_. - class ResamplerProxy : public ::media::AudioConverter::InputCallback { - public: - ResamplerProxy(::media::AudioConverter::InputCallback* input_callback, - const ::media::AudioParameters& input_params, - const ::media::AudioParameters& output_params) { - resampler_.reset( - new ::media::AudioConverter(input_params, output_params, false)); - resampler_->AddInput(input_callback); - DETACH_FROM_THREAD(backend_thread_checker_); - } - - ResamplerProxy(const ResamplerProxy&) = delete; - ResamplerProxy& operator=(const ResamplerProxy&) = delete; - - ~ResamplerProxy() override {} - - private: - // ::media::AudioConverter::InputCallback implementation - double ProvideInput(::media::AudioBus* audio_bus, - uint32_t frames_delayed, - const ::media::AudioGlitchInfo& glitch_info) override { - DCHECK_CALLED_ON_VALID_THREAD(backend_thread_checker_); - resampler_->ConvertWithInfo(frames_delayed, glitch_info, audio_bus); - // Volume multiplier has already been applied by |resampler_|. - return 1.0; - } - - std::unique_ptr<::media::AudioConverter> resampler_; - - THREAD_CHECKER(backend_thread_checker_); - }; - - // ::media::AudioOutputStream implementation - bool Open() override { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - - ::media::AudioParameters::Format format = input_params_.format(); - DCHECK((format == ::media::AudioParameters::AUDIO_PCM_LINEAR) || - (format == ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY)); - - ::media::ChannelLayout channel_layout = input_params_.channel_layout(); - if ((channel_layout != ::media::CHANNEL_LAYOUT_MONO) && - (channel_layout != ::media::CHANNEL_LAYOUT_STEREO)) { - LOG(WARNING) << "Unsupported channel layout: " << channel_layout; - return false; - } - DCHECK_GE(input_params_.channels(), 1); - DCHECK_LE(input_params_.channels(), 2); - - return opened_ = audio_mixer_->Register(this); - } - - void Close() override { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - - if (proxy_) - Stop(); - if (opened_) - audio_mixer_->Unregister(this); - - // Signal to the manager that we're closed and can be removed. - // This should be the last call in the function as it deletes "this". - audio_mixer_->audio_manager_->ReleaseOutputStream(this); - } - - void Start(AudioSourceCallback* source_callback) override { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DCHECK(source_callback); - - if (!opened_ || proxy_) - return; - source_callback_ = source_callback; - proxy_ = - std::make_unique(this, input_params_, output_params_); - audio_mixer_->AddInput(proxy_.get()); - } - - void Stop() override { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - - if (!proxy_) - return; - audio_mixer_->RemoveInput(proxy_.get()); - // Once the above function returns it is guaranteed that proxy_ or - // source_callback_ would not be used on the backend thread, so it is safe - // to reset them. - proxy_.reset(); - source_callback_ = nullptr; - } - - // There is nothing to flush since the proxy stream is removed during Stop(). - void Flush() override {} - - void SetVolume(double volume) override { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - - base::AutoLock auto_lock(volume_lock_); - volume_ = volume; - } - - void GetVolume(double* volume) override { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - - *volume = volume_; - } - - // ::media::AudioConverter::InputCallback implementation - double ProvideInput(::media::AudioBus* audio_bus, - uint32_t frames_delayed, - const ::media::AudioGlitchInfo& glitch_info) override { - // Called on backend thread. Member variables accessed from both backend - // and audio thread must be thread-safe. - DCHECK(source_callback_); - - const base::TimeDelta delay = ::media::AudioTimestampHelper::FramesToTime( - frames_delayed, input_params_.sample_rate()); - source_callback_->OnMoreData(delay, base::TimeTicks::Now(), glitch_info, - audio_bus); - - base::AutoLock auto_lock(volume_lock_); - return volume_; - } - - CastAudioMixer* const audio_mixer_; - const ::media::AudioParameters input_params_; - const ::media::AudioParameters output_params_; - - bool opened_; - double volume_; - base::Lock volume_lock_; - AudioSourceCallback* source_callback_; - std::unique_ptr proxy_; - - THREAD_CHECKER(audio_thread_checker_); -}; - -CastAudioMixer::CastAudioMixer(CastAudioManager* audio_manager) - : audio_manager_(audio_manager), error_(false), output_stream_(nullptr) { - output_params_ = ::media::AudioParameters( - ::media::AudioParameters::Format::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), kSampleRate, kFramesPerBuffer); - mixer_.reset( - new ::media::AudioConverter(output_params_, output_params_, false)); - DETACH_FROM_THREAD(audio_thread_checker_); -} - -CastAudioMixer::~CastAudioMixer() {} - -::media::AudioOutputStream* CastAudioMixer::MakeStream( - const ::media::AudioParameters& params) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - return new MixerProxyStream(params, output_params_, this); -} - -bool CastAudioMixer::Register(MixerProxyStream* proxy_stream) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DCHECK(!base::Contains(proxy_streams_, proxy_stream)); - - // Do not allow opening new streams while in error state. - if (error_) - return false; - - // Initialize a backend instance if there are no output streams. - // The stream will fail to register if the CastAudioOutputStream - // is not opened properly. - if (proxy_streams_.empty()) { - DCHECK(!output_stream_); - output_stream_ = audio_manager_->MakeMixerOutputStream(output_params_); - if (!output_stream_->Open()) { - output_stream_->Close(); - output_stream_ = nullptr; - return false; - } - } - - proxy_streams_.insert(proxy_stream); - return true; -} - -void CastAudioMixer::Unregister(MixerProxyStream* proxy_stream) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DCHECK(base::Contains(proxy_streams_, proxy_stream)); - - proxy_streams_.erase(proxy_stream); - - // Reset the state once all streams have been unregistered. - if (proxy_streams_.empty()) { - DCHECK(mixer_->empty()); - if (output_stream_) - output_stream_->Close(); - output_stream_ = nullptr; - error_ = false; - } -} - -void CastAudioMixer::AddInput( - ::media::AudioConverter::InputCallback* input_callback) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - - // Start the backend if there are no current inputs. - if (mixer_->empty() && output_stream_) - output_stream_->Start(this); - - base::AutoLock auto_lock(mixer_lock_); - mixer_->AddInput(input_callback); -} - -void CastAudioMixer::RemoveInput( - ::media::AudioConverter::InputCallback* input_callback) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - - { - base::AutoLock auto_lock(mixer_lock_); - mixer_->RemoveInput(input_callback); - } - - // Stop |output_stream_| if there are no inputs and the stream is running. - if (mixer_->empty() && output_stream_) - output_stream_->Stop(); -} - -int CastAudioMixer::OnMoreData(base::TimeDelta delay, - base::TimeTicks /* delay_timestamp */, - const ::media::AudioGlitchInfo& glitch_info, - ::media::AudioBus* dest) { - // Called on backend thread. - uint32_t frames_delayed = ::media::AudioTimestampHelper::TimeToFrames( - delay, output_params_.sample_rate()); - - base::AutoLock auto_lock(mixer_lock_); - mixer_->ConvertWithInfo(frames_delayed, glitch_info, dest); - return dest->frames(); -} - -void CastAudioMixer::OnError(ErrorType type) { - // Called on backend thread. - audio_manager_->GetTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&CastAudioMixer::HandleError, - base::Unretained(this), type)); -} - -void CastAudioMixer::HandleError(ErrorType type) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - - error_ = true; - for (auto it = proxy_streams_.begin(); it != proxy_streams_.end(); ++it) - (*it)->OnError(type); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_mixer.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MIXER_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MIXER_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "media/audio/audio_io.h" -#include "media/base/audio_converter.h" -#include "media/base/audio_parameters.h" - -namespace chromecast { -namespace media { - -class CastAudioManager; - -// CastAudioMixer mixes multiple AudioOutputStreams and passes the mixed -// stream down to a single AudioOutputStream to be rendered by the CMA backend. -class CastAudioMixer : public ::media::AudioOutputStream::AudioSourceCallback { - public: - explicit CastAudioMixer(CastAudioManager* audio_manager); - - CastAudioMixer(const CastAudioMixer&) = delete; - CastAudioMixer& operator=(const CastAudioMixer&) = delete; - - ~CastAudioMixer() override; - - virtual ::media::AudioOutputStream* MakeStream( - const ::media::AudioParameters& params); - - private: - class MixerProxyStream; - - // ::media::AudioOutputStream::AudioSourceCallback implementation - int OnMoreData(base::TimeDelta delay, - base::TimeTicks delay_timestamp, - const ::media::AudioGlitchInfo& glitch_info, - ::media::AudioBus* dest) override; - void OnError(ErrorType type) override; - - // MixedAudioOutputStreams call Register on opening and AddInput on starting. - bool Register(MixerProxyStream* proxy_stream); - void Unregister(MixerProxyStream* proxy_stream); - void AddInput(::media::AudioConverter::InputCallback* input_callback); - void RemoveInput(::media::AudioConverter::InputCallback* input_callback); - void HandleError(ErrorType type); - - CastAudioManager* const audio_manager_; - bool error_; - std::set proxy_streams_; - std::unique_ptr<::media::AudioConverter> mixer_; - base::Lock mixer_lock_; - ::media::AudioParameters output_params_; - ::media::AudioOutputStream* output_stream_; - - THREAD_CHECKER(audio_thread_checker_); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_mixer_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_mixer_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_mixer_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,418 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_mixer.h" - -#include - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/audio/cast_audio_manager.h" -#include "chromecast/media/audio/cast_audio_output_stream.h" -#include "chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h" -#include "media/audio/audio_io.h" -#include "media/audio/test_audio_thread.h" -#include "media/base/audio_glitch_info.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using testing::_; -using testing::Assign; -using testing::Invoke; -using testing::Return; -using testing::SaveArg; -using testing::StrictMock; - -// Utility functions -::media::AudioParameters GetAudioParams() { - return ::media::AudioParameters( - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), 48000, 1024); -} - -void SignalPull( - ::media::AudioOutputStream::AudioSourceCallback* source_callback, - base::TimeDelta delay) { - std::unique_ptr<::media::AudioBus> audio_bus = - ::media::AudioBus::Create(GetAudioParams()); - source_callback->OnMoreData(delay, base::TimeTicks::Now(), {}, - audio_bus.get()); -} - -void SignalError( - ::media::AudioOutputStream::AudioSourceCallback* source_callback) { - source_callback->OnError( - ::media::AudioOutputStream::AudioSourceCallback::ErrorType::kUnknown); -} - -// Mock implementations -class MockAudioSourceCallback - : public ::media::AudioOutputStream::AudioSourceCallback { - public: - MockAudioSourceCallback() { - ON_CALL(*this, OnMoreData(_, _, _, _)) - .WillByDefault(Invoke(this, &MockAudioSourceCallback::OnMoreDataImpl)); - } - - MOCK_METHOD4(OnMoreData, - int(base::TimeDelta, - base::TimeTicks, - const ::media::AudioGlitchInfo&, - ::media::AudioBus*)); - MOCK_METHOD1(OnError, void(ErrorType)); - - private: - int OnMoreDataImpl(base::TimeDelta /* delay */, - base::TimeTicks /* delay_timestamp */, - const ::media::AudioGlitchInfo& /* glitch_info */, - ::media::AudioBus* dest) { - dest->Zero(); - return dest->frames(); - } -}; - -class MockMediaAudioOutputStream : public ::media::AudioOutputStream { - public: - MockMediaAudioOutputStream() {} - - MOCK_METHOD0(Open, bool()); - MOCK_METHOD0(Close, void()); - MOCK_METHOD0(Flush, void()); - MOCK_METHOD1(Start, void(AudioSourceCallback* source_callback)); - MOCK_METHOD0(Stop, void()); - MOCK_METHOD1(SetVolume, void(double volume)); - MOCK_METHOD1(GetVolume, void(double* volume)); -}; - -class MockCastAudioManager : public CastAudioManager { - public: - MockCastAudioManager( - CastAudioManagerHelper::Delegate* delegate, - scoped_refptr media_task_runner) - : CastAudioManager( - std::make_unique<::media::TestAudioThread>(), - nullptr, - delegate, - base::BindRepeating(&MockCastAudioManager::GetCmaBackendFactory, - base::Unretained(this)), - media_task_runner, - media_task_runner, - true /* use_mixer */) { - ON_CALL(*this, ReleaseOutputStream(_)) - .WillByDefault( - Invoke(this, &MockCastAudioManager::ReleaseOutputStreamConcrete)); - } - media::CmaBackendFactory* GetCmaBackendFactory() { return nullptr; } - - MOCK_METHOD1( - MakeMixerOutputStream, - ::media::AudioOutputStream*(const ::media::AudioParameters& params)); - MOCK_METHOD1(ReleaseOutputStream, void(::media::AudioOutputStream* stream)); - - private: - void ReleaseOutputStreamConcrete(::media::AudioOutputStream* stream) { - CastAudioManager::ReleaseOutputStream(stream); - } -}; - -// Generates StrictMocks of Mixer, Manager, and Mixer OutputStream. -class CastAudioMixerTest : public ::testing::Test { - public: - CastAudioMixerTest() - : task_environment_(base::test::TaskEnvironment::MainThreadType::UI), - source_callback_(nullptr) {} - ~CastAudioMixerTest() override {} - - protected: - void SetUp() override { - mock_manager_.reset(new StrictMock( - &delegate_, task_environment_.GetMainThreadTaskRunner())); - mock_mixer_stream_.reset(new StrictMock()); - - ON_CALL(*mock_manager_, MakeMixerOutputStream(_)) - .WillByDefault(Return(mock_mixer_stream_.get())); - ON_CALL(*mock_mixer_stream_, Start(_)) - .WillByDefault(SaveArg<0>(&source_callback_)); - ON_CALL(*mock_mixer_stream_, Stop()) - .WillByDefault(Assign(&source_callback_, nullptr)); - } - - void TearDown() override { mock_manager_->Shutdown(); } - - MockCastAudioManager& mock_manager() { return *mock_manager_; } - MockMediaAudioOutputStream& mock_mixer_stream() { - return *mock_mixer_stream_; - } - - ::media::AudioOutputStream* CreateMixerStream() { - return mock_manager_->MakeAudioOutputStream( - GetAudioParams(), "", ::media::AudioManager::LogCallback()); - } - - base::test::TaskEnvironment task_environment_; - std::unique_ptr mock_manager_; - std::unique_ptr mock_mixer_stream_; - - // Saved params passed to |mock_mixer_stream_|. - ::media::AudioOutputStream::AudioSourceCallback* source_callback_; - MockCastAudioManagerHelperDelegate delegate_; -}; - -TEST_F(CastAudioMixerTest, Volume) { - ::media::AudioOutputStream* stream = CreateMixerStream(); - ASSERT_TRUE(stream); - - double volume; - stream->GetVolume(&volume); - ASSERT_EQ(volume, 1.0); - - stream->SetVolume(.56); - stream->GetVolume(&volume); - ASSERT_EQ(volume, .56); - - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream)); - stream->Close(); -} - -TEST_F(CastAudioMixerTest, MixerCallsCloseOnFailedOpen) { - ::media::AudioOutputStream* stream = CreateMixerStream(); - ASSERT_TRUE(stream); - - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(false)); - EXPECT_CALL(mock_mixer_stream(), Close()); - ASSERT_FALSE(stream->Open()); - - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream)); - stream->Close(); -} - -TEST_F(CastAudioMixerTest, StreamControlOrderMisuse) { - MockAudioSourceCallback source; - ::media::AudioOutputStream* stream = CreateMixerStream(); - ASSERT_TRUE(stream); - - // Close stream without first opening - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream)); - stream->Close(); - - stream = CreateMixerStream(); - ASSERT_TRUE(stream); - - // Should not trigger mixer actions. - stream->Stop(); - stream->Start(&source); - - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(false)); - EXPECT_CALL(mock_mixer_stream(), Close()); - ASSERT_FALSE(stream->Open()); - - // Should not trigger mixer actions. - stream->Start(&source); - stream->Stop(); - - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(true)); - ASSERT_TRUE(stream->Open()); - - EXPECT_CALL(mock_mixer_stream(), Start(_)); - stream->Start(&source); - stream->Start(&source); - - EXPECT_CALL(mock_mixer_stream(), Stop()); - EXPECT_CALL(mock_mixer_stream(), Close()); - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream)); - stream->Close(); // Close abruptly without Stop(), should not fail. -} - -TEST_F(CastAudioMixerTest, SingleStreamCycle) { - MockAudioSourceCallback source; - ::media::AudioOutputStream* stream = CreateMixerStream(); - ASSERT_TRUE(stream); - - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(true)); - ASSERT_TRUE(stream->Open()); - - EXPECT_CALL(mock_mixer_stream(), Start(_)).Times(2); - EXPECT_CALL(mock_mixer_stream(), Stop()).Times(2); - stream->Start(&source); - stream->Stop(); - stream->Start(&source); - stream->Stop(); - - EXPECT_CALL(mock_mixer_stream(), Close()); - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream)); - stream->Close(); -} - -TEST_F(CastAudioMixerTest, MultiStreamCycle) { - // This test will break if run with < 1 stream. - std::vector<::media::AudioOutputStream*> streams(5); - std::vector> sources(streams.size()); - std::generate(streams.begin(), streams.end(), - [this] { return CreateMixerStream(); }); - std::generate(sources.begin(), sources.end(), [] { - return std::unique_ptr( - new StrictMock()); - }); - - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(true)); - for (auto* stream : streams) - ASSERT_TRUE(stream->Open()); - - EXPECT_CALL(mock_mixer_stream(), Start(_)); - for (unsigned int i = 0; i < streams.size(); i++) - streams[i]->Start(sources[i].get()); - - // Individually pull out streams - while (streams.size() > 1) { - ::media::AudioOutputStream* stream = streams.front(); - stream->Stop(); - streams.erase(streams.begin()); - sources.erase(sources.begin()); - - for (auto& source : sources) - EXPECT_CALL(*source, OnMoreData(_, _, _, _)); - SignalPull(source_callback_, base::TimeDelta()); - - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream)); - stream->Close(); - } - - EXPECT_CALL(mock_mixer_stream(), Stop()); - EXPECT_CALL(mock_mixer_stream(), Close()); - EXPECT_CALL(mock_manager(), ReleaseOutputStream(streams.front())); - streams.front()->Close(); -} - -TEST_F(CastAudioMixerTest, TwoStreamRestart) { - MockAudioSourceCallback source; - ::media::AudioOutputStream *stream1, *stream2; - - for (int i = 0; i < 2; i++) { - stream1 = CreateMixerStream(); - stream2 = CreateMixerStream(); - ASSERT_TRUE(stream1); - ASSERT_TRUE(stream2); - - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(true)); - ASSERT_TRUE(stream1->Open()); - ASSERT_TRUE(stream2->Open()); - - EXPECT_CALL(mock_mixer_stream(), Start(_)); - stream1->Start(&source); - stream2->Start(&source); - - stream1->Stop(); - EXPECT_CALL(mock_mixer_stream(), Stop()); - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream2)); - stream2->Close(); - EXPECT_CALL(mock_mixer_stream(), Close()); - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream1)); - stream1->Close(); - } -} - -TEST_F(CastAudioMixerTest, OnError) { - MockAudioSourceCallback source; - std::vector<::media::AudioOutputStream*> streams; - - streams.push_back(CreateMixerStream()); - streams.push_back(CreateMixerStream()); - for (auto* stream : streams) - ASSERT_TRUE(stream); - - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(true)); - for (auto* stream : streams) - ASSERT_TRUE(stream->Open()); - - EXPECT_CALL(mock_mixer_stream(), Start(_)); - streams.front()->Start(&source); - - // Note that error will only be triggered on the first stream because that - // is the only stream that has been started. - EXPECT_CALL(source, OnError(_)); - SignalError(source_callback_); - base::RunLoop().RunUntilIdle(); - - // Try to add another stream. - streams.push_back(CreateMixerStream()); - ASSERT_TRUE(streams.back()); - ASSERT_FALSE(streams.back()->Open()); - - EXPECT_CALL(mock_mixer_stream(), Stop()); - EXPECT_CALL(mock_mixer_stream(), Close()); - for (auto* stream : streams) { - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream)); - stream->Close(); - } - streams.clear(); - - // Now that the state has been refreshed, attempt to open a stream. - streams.push_back(CreateMixerStream()); - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(true)); - ASSERT_TRUE(streams.front()->Open()); - - EXPECT_CALL(mock_mixer_stream(), Start(_)); - streams.front()->Start(&source); - - EXPECT_CALL(mock_mixer_stream(), Stop()); - EXPECT_CALL(mock_mixer_stream(), Close()); - EXPECT_CALL(mock_manager(), ReleaseOutputStream(streams.front())); - streams.front()->Close(); -} - -TEST_F(CastAudioMixerTest, Delay) { - MockAudioSourceCallback source; - ::media::AudioOutputStream* stream = CreateMixerStream(); - - EXPECT_CALL(mock_manager(), MakeMixerOutputStream(_)) - .WillOnce(Return(&mock_mixer_stream())); - EXPECT_CALL(mock_mixer_stream(), Open()).WillOnce(Return(true)); - ASSERT_TRUE(stream->Open()); - - EXPECT_CALL(mock_mixer_stream(), Start(_)); - stream->Start(&source); - - // |delay| is the same because the Mixer and stream are - // using the same AudioParameters. - base::TimeDelta delay = base::Microseconds(1000); - EXPECT_CALL(source, OnMoreData(delay, _, ::media::AudioGlitchInfo(), _)); - SignalPull(source_callback_, delay); - - EXPECT_CALL(mock_mixer_stream(), Stop()); - EXPECT_CALL(mock_mixer_stream(), Close()); - EXPECT_CALL(mock_manager(), ReleaseOutputStream(stream)); - stream->Close(); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_device.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_device.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_device.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_device.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,434 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_output_device.h" - -#include -#include -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "chromecast/media/audio/audio_io_thread.h" -#include "chromecast/media/audio/audio_output_service/audio_output_service.pb.h" -#include "chromecast/media/audio/audio_output_service/output_stream_connection.h" -#include "chromecast/media/base/default_monotonic_clock.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_glitch_info.h" -#include "media/base/audio_parameters.h" -#include "media/base/audio_timestamp_helper.h" -#include "net/base/io_buffer.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr base::TimeDelta kNoBufferReadDelay = base::Milliseconds(50); - -// When to treat lack of audio data in buffer as a underflow. -constexpr base::TimeDelta kBufferUnderflowThreshold = base::Milliseconds(400); - -// Initial renderer buffer size estimation. The value should be smaller than the -// audio renderer start capacity. -constexpr base::TimeDelta kPrefetchRendererBufferSize = base::Seconds(4); -constexpr base::TimeDelta kDefaultRendererBufferSize = base::Milliseconds(160); - -} // namespace - -// Internal helper class. The constructor/StartRender/StopRender are called on -// caller's thread. The other functions including destructor should be used on -// an IO thread. -class CastAudioOutputDevice::Internal - : public audio_output_service::OutputStreamConnection::Delegate { - public: - Internal(const ::media::AudioParameters& audio_params, - RenderCallback* render_callback) - : audio_params_(audio_params), render_callback_(render_callback) { - DCHECK(render_callback_); - } - - Internal(const Internal&) = delete; - Internal& operator=(const Internal&) = delete; - ~Internal() override = default; - - // One time init on IO thread. - void Initialize( - mojo::PendingRemote audio_socket_broker, - const std::string& session_id) { - audio_output_service::CmaBackendParams cma_backend_params; - - audio_output_service::AudioDecoderConfig* audio_config = - cma_backend_params.mutable_audio_decoder_config(); - audio_config->set_audio_codec(audio_service::AudioCodec::AUDIO_CODEC_PCM); - audio_config->set_sample_rate(audio_params_.sample_rate()); - audio_config->set_sample_format( - audio_service::SampleFormat::SAMPLE_FORMAT_INT16_I); - audio_config->set_num_channels(audio_params_.channels()); - - audio_output_service::ApplicationMediaInfo* app_media_info = - cma_backend_params.mutable_application_media_info(); - app_media_info->set_application_session_id(session_id); - - audio_bus_ = ::media::AudioBus::Create(audio_params_); - output_connection_ = - std::make_unique( - this, cma_backend_params, std::move(audio_socket_broker)); - output_connection_->Connect(); - } - - void StartRender() { - base::AutoLock lock(callback_lock_); - active_render_callback_ = render_callback_; - } - - void StopRender() { - base::AutoLock lock(callback_lock_); - active_render_callback_ = nullptr; - } - - void Start() { - playback_started_ = true; - media_pos_frames_ = 0; - renderer_buffer_size_estimate_ = - (audio_params_.effects() & ::media::AudioParameters::AUDIO_PREFETCH) - ? kPrefetchRendererBufferSize - : kDefaultRendererBufferSize; - DCHECK_GT(renderer_buffer_size_estimate_, - audio_params_.GetBufferDuration()); - - media_start_time_ = base::TimeTicks::Now(); - if (!backend_initialized_) { - // Wait for initialization to complete before sending messages through - // `output_connection_`. - return; - } - output_connection_->StartPlayingFrom(0); - } - - void Pause() { - paused_ = true; - - if (!backend_initialized_) { - return; - } - - output_connection_->SetPlaybackRate(0.0f); - push_timer_.Stop(); - } - - void Play() { - paused_ = false; - if (!playback_started_) { - Start(); - } - if (!backend_initialized_) { - return; - } - - last_read_buffer_timestamp_ = base::TimeTicks(); - output_connection_->SetPlaybackRate(1.0f); - } - - void Flush() { - if (!backend_initialized_) { - return; - } - media_pos_frames_ = 0; - media_start_time_ = base::TimeTicks::Now(); - playback_started_ = false; - paused_ = false; - push_timer_.Stop(); - output_connection_->StopPlayback(); - } - - void SetVolume(double volume) { - volume_ = volume; - if (!backend_initialized_) { - return; - } - output_connection_->SetVolume(volume_); - } - - private: - // audio_output_service::OutputStreamConnection::Delegate implementation: - void OnBackendInitialized( - const audio_output_service::BackendInitializationStatus& status) - override { - if (status.status() != - audio_output_service::BackendInitializationStatus::SUCCESS) { - LOG(ERROR) << "Error initializing the audio backend."; - base::AutoLock lock(callback_lock_); - if (active_render_callback_) { - active_render_callback_->OnRenderError(); - } - return; - } - - DCHECK(output_connection_); - backend_initialized_ = true; - output_connection_->SetVolume(volume_); - if (paused_) { - output_connection_->SetPlaybackRate(0.0f); - } - if (!playback_started_) { - // Wait for Start() to be called before schedule reading buffers. - return; - } - output_connection_->StartPlayingFrom(0); - if (!paused_) { - last_read_buffer_timestamp_ = base::TimeTicks(); - output_connection_->SetPlaybackRate(1.0f); - } - } - - void OnNextBuffer(int64_t media_timestamp_microseconds, - int64_t reference_timestamp_microseconds, - int64_t delay_microseconds, - int64_t delay_timestamp_microseconds) override { - rendering_delay_ = base::Microseconds(delay_microseconds); - rendering_delay_timestamp_us_ = delay_timestamp_microseconds; - - TryPushBuffer(); - } - - void TryPushBuffer() { - if (paused_ || !backend_initialized_ || !playback_started_ || - push_timer_.IsRunning()) { - return; - } - - PushBuffer(); - } - - void PushBuffer() { - auto now = base::TimeTicks::Now(); - if (last_read_buffer_timestamp_.is_null()) { - last_read_buffer_timestamp_ = now; - } - - base::TimeDelta elapsed_time = now - last_read_buffer_timestamp_; - base::TimeDelta time_before_underrun = - audio_params_.GetBufferDuration() - - (renderer_buffer_size_estimate_ + elapsed_time); - if (time_before_underrun > base::TimeDelta()) { - // Let renderer buffer more data. - push_timer_.Start(FROM_HERE, now + time_before_underrun, this, - &Internal::TryPushBuffer, - base::subtle::DelayPolicy::kPrecise); - return; - } - - int frames_filled = ReadBuffer(GetDelay(), audio_bus_.get()); - renderer_buffer_size_estimate_ += elapsed_time; - last_read_buffer_timestamp_ = now; - auto media_pos = ::media::AudioTimestampHelper::FramesToTime( - media_pos_frames_, audio_params_.sample_rate()); - if (frames_filled) { - renderer_buffer_size_estimate_ -= - ::media::AudioTimestampHelper::FramesToTime( - frames_filled, audio_params_.sample_rate()); - DCHECK_GE(renderer_buffer_size_estimate_, base::TimeDelta()); - - size_t filled_bytes = frames_filled * audio_params_.GetBytesPerFrame( - ::media::kSampleFormatS16); - size_t io_buffer_size = - audio_output_service::OutputSocket::kAudioMessageHeaderSize + - filled_bytes; - auto io_buffer = - base::MakeRefCounted(io_buffer_size); - audio_bus_->ToInterleaved<::media::SignedInt16SampleTypeTraits>( - frames_filled, - reinterpret_cast( - io_buffer->data() + - audio_output_service::OutputSocket::kAudioMessageHeaderSize)); - - DCHECK(output_connection_); - output_connection_->SendAudioBuffer(std::move(io_buffer), filled_bytes, - media_pos.InMicroseconds()); - media_pos_frames_ += frames_filled; - - // No need to schedule buffer read here since - // `OnNextBuffer` will be called once the current - // buffer is pushed to media backend. - return; - } - - // Avoid spam calling Render() since each call will advance the |AudioClock| - // a little bit if 0 frames are rendered. - // Wait until some rendered data is consumed before retrying Render(). - base::TimeDelta time_left_in_buffer = - media_pos - (base::TimeTicks::Now() - media_start_time_); - if (time_left_in_buffer > kBufferUnderflowThreshold) { - push_timer_.Start(FROM_HERE, base::TimeTicks::Now() + time_left_in_buffer, this, - &Internal::TryPushBuffer, - base::subtle::DelayPolicy::kPrecise); - return; - } - - // No frames filled, schedule read immediately with a small delay. - push_timer_.Start(FROM_HERE, base::TimeTicks::Now() + kNoBufferReadDelay, - this, &Internal::TryPushBuffer, - base::subtle::DelayPolicy::kPrecise); - } - - int ReadBuffer(base::TimeDelta delay, ::media::AudioBus* audio_bus) { - DCHECK(audio_bus); - base::AutoLock lock(callback_lock_); - if (!active_render_callback_) { - return 0; - } - return active_render_callback_->Render(delay, base::TimeTicks(), - /*glitch_info=*/{}, audio_bus); - } - - base::TimeDelta GetDelay() { - base::TimeDelta delay; - if (rendering_delay_ < base::TimeDelta() || - rendering_delay_timestamp_us_ < 0) { - delay = base::TimeDelta(); - } else { - delay = - rendering_delay_ + base::Microseconds(rendering_delay_timestamp_us_ - - MonotonicClockNow()); - if (delay < base::TimeDelta()) { - delay = base::TimeDelta(); - } - } - return delay; - } - - scoped_refptr output_device_; - std::unique_ptr - output_connection_; - - mojo::PendingRemote pending_socket_broker_; - ::media::AudioParameters audio_params_; - size_t media_pos_frames_ = 0; - // When we start playing media. Used to determine the current position in the track. - base::TimeTicks media_start_time_ = base::TimeTicks(); - base::TimeDelta rendering_delay_; - - int64_t rendering_delay_timestamp_us_ = INT64_MIN; - double volume_ = 1.0; - bool paused_ = false; - bool playback_started_ = false; - bool backend_initialized_ = false; - base::DeadlineTimer push_timer_; - std::unique_ptr<::media::AudioBus> audio_bus_; - - // Callback to get audio data. - RenderCallback* const render_callback_; - - // Estimation of the renderer buffer size. We should not pull too much buffer - // from renderer to avoid underrun. - base::TimeDelta renderer_buffer_size_estimate_; - - base::TimeTicks last_read_buffer_timestamp_; - - base::Lock callback_lock_; - // Nullable callback that is only available during StartRender/StopRender. - RenderCallback* active_render_callback_ GUARDED_BY(callback_lock_) = nullptr; -}; - -CastAudioOutputDevice::CastAudioOutputDevice( - mojo::PendingRemote audio_socket_broker, - const std::string& session_id) - : CastAudioOutputDevice(std::move(audio_socket_broker), - session_id, - AudioIoThread::Get()->task_runner()) {} - -CastAudioOutputDevice::CastAudioOutputDevice( - mojo::PendingRemote audio_socket_broker, - const std::string& session_id, - scoped_refptr task_runner) - : task_runner_(std::move(task_runner)), - pending_socket_broker_(std::move(audio_socket_broker)), - session_id_(session_id) {} - -CastAudioOutputDevice::~CastAudioOutputDevice() { - if (!internal_) { - return; - } - - internal_ptr_->StopRender(); -} - -void CastAudioOutputDevice::Initialize(const ::media::AudioParameters& params, - RenderCallback* callback) { - DCHECK(callback); - DCHECK(!internal_); - DCHECK(!internal_ptr_); - - auto internal = std::make_unique(params, callback); - internal_ptr_ = internal.get(); - internal_.emplace(task_runner_, std::move(internal)); - - internal_.AsyncCall(&Internal::Initialize) - .WithArgs(std::move(pending_socket_broker_), session_id_); -} - -void CastAudioOutputDevice::Start() { - internal_ptr_->StartRender(); - internal_.AsyncCall(&Internal::Start); -} - -void CastAudioOutputDevice::Stop() { - internal_ptr_->StopRender(); - Flush(); -} - -void CastAudioOutputDevice::Pause() { - internal_.AsyncCall(&Internal::Pause); -} - -void CastAudioOutputDevice::Play() { - internal_.AsyncCall(&Internal::Play); -} - -void CastAudioOutputDevice::Flush() { - internal_.AsyncCall(&Internal::Flush); -} - -bool CastAudioOutputDevice::SetVolume(double volume) { - internal_.AsyncCall(&Internal::SetVolume).WithArgs(volume); - return true; -} - -::media::OutputDeviceInfo CastAudioOutputDevice::GetOutputDeviceInfo() { - // Same as the set of parameters returned in - // CastAudioManager::GetPreferredOutputStreamParameters. - return ::media::OutputDeviceInfo( - std::string(), ::media::OUTPUT_DEVICE_STATUS_OK, - ::media::AudioParameters(::media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - ::media::ChannelLayoutConfig::Stereo(), 48000, - 480)); -} - -void CastAudioOutputDevice::GetOutputDeviceInfoAsync( - OutputDeviceInfoCB info_cb) { - // Always post to avoid the caller being reentrant. - base::BindPostTaskToCurrentDefault( - base::BindOnce(std::move(info_cb), GetOutputDeviceInfo())) - .Run(); -} - -bool CastAudioOutputDevice::IsOptimizedForHardwareParameters() { - return false; -} - -bool CastAudioOutputDevice::CurrentThreadIsRenderingThread() { - return task_runner_->RunsTasksInCurrentSequence(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_device.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_device.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_device.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_device.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_DEVICE_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_DEVICE_H_ - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/synchronization/lock.h" -#include "base/task/sequenced_task_runner.h" -#include "base/threading/sequence_bound.h" -#include "base/time/time.h" -#include "chromecast/common/mojom/audio_socket.mojom.h" -#include "media/base/audio_renderer_sink.h" -#include "media/mojo/mojom/cast_application_media_info_manager.mojom.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { -namespace media { - -// Cast implementation of ::media::AudioRendererSink. |task_runner| passed in -// the constructor is the rendering sequence task runner. All methods internally -// run on the rendering sequence either directly or by posting a task. -// ::media::AudioRenderSink methods could be triggered on different threads. -class CastAudioOutputDevice : public ::media::AudioRendererSink { - public: - CastAudioOutputDevice( - mojo::PendingRemote audio_socket_broker, - const std::string& session_id); - - CastAudioOutputDevice(const CastAudioOutputDevice&) = delete; - CastAudioOutputDevice& operator=(const CastAudioOutputDevice&) = delete; - - private: - // Only for testing. - CastAudioOutputDevice( - mojo::PendingRemote audio_socket_broker, - const std::string& session_id, - scoped_refptr task_runner); - ~CastAudioOutputDevice() override; - - class Internal; - - // ::media::AudioRendererSink implementation: - void Initialize(const ::media::AudioParameters& params, - RenderCallback* callback) override; - void Start() override; - void Stop() override; - void Pause() override; - void Play() override; - void Flush() override; - bool SetVolume(double volume) override; - ::media::OutputDeviceInfo GetOutputDeviceInfo() override; - void GetOutputDeviceInfoAsync(OutputDeviceInfoCB info_cb) override; - bool IsOptimizedForHardwareParameters() override; - bool CurrentThreadIsRenderingThread() override; - - const scoped_refptr task_runner_; - base::SequenceBound> internal_; - Internal* internal_ptr_ = nullptr; - - mojo::PendingRemote pending_socket_broker_; - const std::string session_id_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_DEVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_stream.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_stream.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,481 +0,0 @@ -// 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 "chromecast/media/audio/cast_audio_output_stream.h" - -#include -#include - -#include "base/bits.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/message_loop/message_pump_type.h" -#include "base/synchronization/lock.h" -#include "base/synchronization/waitable_event.h" -#include "base/task/bind_post_task.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/bind_to_task_runner.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/audio/cast_audio_manager.h" -#include "chromecast/media/audio/cast_audio_output_utils.h" -#include "chromecast/media/audio/cma_audio_output_stream.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/mixer_service/output_stream_connection.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/audio_device_description.h" - -#define POST_TO_CMA_WRAPPER(method, ...) \ - do { \ - DCHECK(cma_wrapper_); \ - audio_manager_->media_task_runner()->PostTask( \ - FROM_HERE, \ - base::BindOnce(&CmaAudioOutputStream::method, \ - base::Unretained(cma_wrapper_.get()), ##__VA_ARGS__)); \ - } while (0) - -#define POST_TO_MIXER_SERVICE_WRAPPER(method, ...) \ - do { \ - DCHECK(mixer_service_wrapper_); \ - mixer_service_wrapper_->io_task_runner()->PostTask( \ - FROM_HERE, \ - base::BindOnce(&MixerServiceWrapper::method, \ - base::Unretained(mixer_service_wrapper_.get()), \ - ##__VA_ARGS__)); \ - } while (0) - -namespace { -// Below are settings for MixerService and the DirectAudio it uses. -constexpr base::TimeDelta kFadeTime = base::Milliseconds(5); -constexpr base::TimeDelta kCommunicationsMaxBufferedFrames = - base::Milliseconds(50); -constexpr base::TimeDelta kMediaMaxBufferedFrames = base::Milliseconds(70); -} // namespace - -namespace chromecast { -namespace media { -namespace { - -AudioContentType GetContentType(const std::string& device_id) { - if (::media::AudioDeviceDescription::IsCommunicationsDevice(device_id)) { - return AudioContentType::kCommunication; - } - return AudioContentType::kMedia; -} - -audio_service::ContentType ConvertContentType(AudioContentType content_type) { - switch (content_type) { - case AudioContentType::kMedia: - return audio_service::CONTENT_TYPE_MEDIA; - case AudioContentType::kCommunication: - return audio_service::CONTENT_TYPE_COMMUNICATION; - default: - NOTREACHED(); - } -} - -} // namespace - -class CastAudioOutputStream::MixerServiceWrapper - : public mixer_service::OutputStreamConnection::Delegate { - public: - MixerServiceWrapper(const ::media::AudioParameters& audio_params, - const std::string& device_id); - - MixerServiceWrapper(const MixerServiceWrapper&) = delete; - MixerServiceWrapper& operator=(const MixerServiceWrapper&) = delete; - - ~MixerServiceWrapper() override = default; - - void SetRunning(bool running); - void Start(AudioSourceCallback* source_callback); - void Stop(base::WaitableEvent* finished); - void Close(base::OnceClosure closure); - void SetVolume(double volume); - int64_t GetMaxBufferedFrames(); - void Flush(); - - base::SingleThreadTaskRunner* io_task_runner() { - return io_task_runner_.get(); - } - - private: - // mixer_service::OutputStreamConnection::Delegate implementation: - void FillNextBuffer(void* buffer, - int frames, - int64_t delay_timestamp, - int64_t delay) override; - // We don't push an EOS buffer. - void OnEosPlayed() override { NOTREACHED(); } - - const ::media::AudioParameters audio_params_; - const std::string device_id_; - std::unique_ptr<::media::AudioBus> audio_bus_; - AudioSourceCallback* source_callback_; - std::unique_ptr mixer_connection_; - double volume_; - int64_t max_buffered_frames_; - - base::Lock running_lock_; - bool running_ = true; - // MixerServiceWrapper must run on an "io thread". - base::Thread io_thread_; - // Task runner on |io_thread_|. - scoped_refptr io_task_runner_; - THREAD_CHECKER(io_thread_checker_); -}; - -CastAudioOutputStream::MixerServiceWrapper::MixerServiceWrapper( - const ::media::AudioParameters& audio_params, - const std::string& device_id) - : audio_params_(audio_params), - device_id_(device_id), - source_callback_(nullptr), - volume_(1.0f), - max_buffered_frames_(GetMaxBufferedFrames()), - io_thread_("CastAudioOutputStream IO") { - DETACH_FROM_THREAD(io_thread_checker_); - - base::Thread::Options options; - options.message_pump_type = base::MessagePumpType::IO; - options.thread_type = base::ThreadType::kRealtimeAudio; - CHECK(io_thread_.StartWithOptions(std::move(options))); - io_task_runner_ = io_thread_.task_runner(); - DCHECK(io_task_runner_); -} - -void CastAudioOutputStream::MixerServiceWrapper::SetRunning(bool running) { - base::AutoLock lock(running_lock_); - running_ = running; -} - -void CastAudioOutputStream::MixerServiceWrapper::Start( - AudioSourceCallback* source_callback) { - DCHECK_CALLED_ON_VALID_THREAD(io_thread_checker_); - - mixer_service::OutputStreamParams params; - params.set_content_type(audio_service::CONTENT_TYPE_MEDIA); - params.set_focus_type(ConvertContentType(GetContentType(device_id_))); - params.set_device_id(device_id_); - params.set_stream_type( - mixer_service::OutputStreamParams::STREAM_TYPE_DEFAULT); - params.set_sample_format(audio_service::SAMPLE_FORMAT_FLOAT_P); - params.set_sample_rate(audio_params_.sample_rate()); - params.set_num_channels(audio_params_.channels()); - - params.set_start_threshold_frames(max_buffered_frames_); - params.set_max_buffered_frames(max_buffered_frames_); - params.set_fill_size_frames(audio_params_.frames_per_buffer()); - - params.set_fade_frames(::media::AudioTimestampHelper::TimeToFrames( - kFadeTime, audio_params_.sample_rate())); - params.set_use_start_timestamp(false); - - source_callback_ = source_callback; - mixer_connection_ = - std::make_unique(this, params); - mixer_connection_->Connect(); - mixer_connection_->SetVolumeMultiplier(volume_); -} - -void CastAudioOutputStream::MixerServiceWrapper::Stop( - base::WaitableEvent* finished) { - DCHECK_CALLED_ON_VALID_THREAD(io_thread_checker_); - mixer_connection_.reset(); - source_callback_ = nullptr; - if (finished) { - finished->Signal(); - } -} - -void CastAudioOutputStream::MixerServiceWrapper::Flush() { - DCHECK_CALLED_ON_VALID_THREAD(io_thread_checker_); - // Nothing to do. - return; -} - -void CastAudioOutputStream::MixerServiceWrapper::Close( - base::OnceClosure closure) { - DCHECK_CALLED_ON_VALID_THREAD(io_thread_checker_); - Stop(nullptr); - std::move(closure).Run(); -} - -int64_t CastAudioOutputStream::MixerServiceWrapper::GetMaxBufferedFrames() { - int fill_size_frames = audio_params_.frames_per_buffer(); - base::TimeDelta target_max_buffered_ms = kMediaMaxBufferedFrames; - if (GetContentType(device_id_) == AudioContentType::kCommunication) { - target_max_buffered_ms = kCommunicationsMaxBufferedFrames; - } - - int64_t target_max_buffered_frames = - ::media::AudioTimestampHelper::TimeToFrames(target_max_buffered_ms, - audio_params_.sample_rate()); - - // Calculate the buffer size necessary to achieve at least the desired buffer - // duration, while minimizing latency. - int64_t max_buffered_frames = 0; - if (fill_size_frames > target_max_buffered_frames) { - max_buffered_frames = target_max_buffered_frames; - } else { - // Find the largest multiple of |fill_size_frames| that is still no larger - // than |target_max_buffered_frames|. - max_buffered_frames = - (target_max_buffered_frames / fill_size_frames) * fill_size_frames; - } - - if (max_buffered_frames != target_max_buffered_frames) { - max_buffered_frames += 1; - } - - return max_buffered_frames; -} - -void CastAudioOutputStream::MixerServiceWrapper::SetVolume(double volume) { - DCHECK_CALLED_ON_VALID_THREAD(io_thread_checker_); - volume_ = volume; - - if (mixer_connection_) - mixer_connection_->SetVolumeMultiplier(volume_); -} - -void CastAudioOutputStream::MixerServiceWrapper::FillNextBuffer( - void* buffer, - int frames, - int64_t delay_timestamp, - int64_t delay) { - DCHECK_CALLED_ON_VALID_THREAD(io_thread_checker_); - - // Round down to closest multiple of 4 to ensure correct channel alignment. - frames = base::bits::AlignDownDeprecatedDoNotUse(frames, 4); - - // Acquire running_lock_ for the scope of this fill call to - // prevent the source callback from closing the output stream - // mid-fill. - base::AutoLock lock(running_lock_); - - // Do not fill more buffers if we have stopped running. - if (!running_) - return; - - int64_t playout_timestamp = - (delay_timestamp == INT64_MIN ? INT64_MIN : delay_timestamp + delay); - if (playout_timestamp < 0) { - // Assume any negative timestamp is invalid. - playout_timestamp = 0; - } - - // Wrap the data buffer so we can write directly into it. - if (!audio_bus_) { - audio_bus_ = ::media::AudioBus::CreateWrapper(audio_params_.channels()); - } - float* channel_data = static_cast(buffer); - for (int c = 0; c < audio_params_.channels(); ++c) { - audio_bus_->SetChannelData(c, channel_data + c * frames); - } - audio_bus_->set_frames(frames); - - base::TimeDelta reported_delay = ::media::AudioTimestampHelper::FramesToTime( - max_buffered_frames_, audio_params_.sample_rate()); - base::TimeTicks reported_delay_timestamp = - base::TimeTicks() + base::Microseconds(playout_timestamp); - - int frames_filled = source_callback_->OnMoreData( - reported_delay, reported_delay_timestamp, {}, audio_bus_.get()); - DCHECK_EQ(frames_filled, frames); - mixer_connection_->SendNextBuffer(frames); -} - -CastAudioOutputStream::CastAudioOutputStream( - CastAudioManagerHelper* audio_manager, - const ::media::AudioParameters& audio_params, - const std::string& device_id_or_group_id, - bool use_mixer_service) - : volume_(1.0), - audio_thread_state_(AudioOutputState::kClosed), - audio_manager_(audio_manager), - audio_params_(audio_params), - device_id_(IsValidDeviceId(device_id_or_group_id) - ? device_id_or_group_id - : ::media::AudioDeviceDescription::kDefaultDeviceId), - group_id_(GetGroupId(device_id_or_group_id)), - use_mixer_service_(use_mixer_service), - audio_weak_factory_(this) { - DCHECK(audio_manager_); - DETACH_FROM_THREAD(audio_thread_checker_); - DVLOG(1) << __func__ << " " << this << " created from group_id=" << group_id_ - << " with audio_params=" << audio_params_.AsHumanReadableString(); - audio_weak_this_ = audio_weak_factory_.GetWeakPtr(); -} - -CastAudioOutputStream::~CastAudioOutputStream() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); -} - -bool CastAudioOutputStream::Open() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DVLOG(1) << this << ": " << __func__; - if (audio_thread_state_ != AudioOutputState::kClosed) - return false; - - // Sanity check the audio parameters. - ::media::AudioParameters::Format format = audio_params_.format(); - DCHECK((format == ::media::AudioParameters::AUDIO_PCM_LINEAR) || - (format == ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY)); - ::media::ChannelLayout channel_layout = audio_params_.channel_layout(); - if ((channel_layout != ::media::CHANNEL_LAYOUT_MONO) && - (channel_layout != ::media::CHANNEL_LAYOUT_STEREO)) { - LOG(WARNING) << "Unsupported channel layout: " << channel_layout; - return false; - } - DCHECK_GE(audio_params_.channels(), 1); - DCHECK_LE(audio_params_.channels(), 2); - - const std::string application_session_id = - audio_manager_->GetSessionId(group_id_); - LOG_IF(WARNING, application_session_id.empty()) << "Session id is empty."; - DVLOG(1) << this << ": " << __func__ - << ", session_id=" << application_session_id; - - if (!use_mixer_service_) { - cma_wrapper_ = std::make_unique( - audio_params_, audio_params_.GetBufferDuration(), device_id_, - audio_manager_->GetCmaBackendFactory()); - POST_TO_CMA_WRAPPER(Initialize, application_session_id); - } else { - DCHECK(!(audio_params_.effects() & ::media::AudioParameters::MULTIZONE)); - - mixer_service_wrapper_ = - std::make_unique(audio_params_, device_id_); - } - - audio_thread_state_ = AudioOutputState::kOpened; - - return true; -} - -void CastAudioOutputStream::Close() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DVLOG(1) << this << ": " << __func__; - - audio_thread_state_ = AudioOutputState::kPendingClose; - base::OnceClosure finish_callback = BindToCurrentThread( - base::BindOnce(&CastAudioOutputStream::FinishClose, audio_weak_this_)); - - if (mixer_service_wrapper_) { - // Synchronously set running to false to guarantee that - // AudioSourceCallback::OnMoreData() will not be called anymore. - mixer_service_wrapper_->SetRunning(false); - POST_TO_MIXER_SERVICE_WRAPPER( - Close, - base::BindPostTask(audio_manager_->audio_manager()->GetTaskRunner(), - std::move(finish_callback))); - } else if (cma_wrapper_) { - // Synchronously set running to false to guarantee that - // AudioSourceCallback::OnMoreData() will not be called anymore. - cma_wrapper_->SetRunning(false); - POST_TO_CMA_WRAPPER(Close, std::move(finish_callback)); - } else { - std::move(finish_callback).Run(); - } -} - -void CastAudioOutputStream::FinishClose() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - // Signal to the manager that we're closed and can be removed. - // This should be the last call during the close process as it deletes "this". - audio_manager_->audio_manager()->ReleaseOutputStream(this); -} - -void CastAudioOutputStream::Start(AudioSourceCallback* source_callback) { - DCHECK(source_callback); - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - // We allow calls to start even in the unopened state. - DCHECK_NE(audio_thread_state_, AudioOutputState::kPendingClose); - DVLOG(2) << this << ": " << __func__; - audio_thread_state_ = AudioOutputState::kStarted; - metrics::CastMetricsHelper::GetInstance()->LogTimeToFirstAudio(); - - // |cma_wrapper_| and |mixer_service_wrapper_| cannot be both active. - DCHECK(!(cma_wrapper_ && mixer_service_wrapper_)); - - if (cma_wrapper_) { - POST_TO_CMA_WRAPPER(Start, source_callback); - } else { - POST_TO_MIXER_SERVICE_WRAPPER(Start, source_callback); - } -} - -void CastAudioOutputStream::Stop() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DVLOG(2) << this << ": " << __func__; - // We allow calls to stop even in the unstarted/unopened state. - if (audio_thread_state_ != AudioOutputState::kStarted) - return; - audio_thread_state_ = AudioOutputState::kOpened; - - // |cma_wrapper_| and |mixer_service_wrapper_| cannot be both active. - DCHECK(!(cma_wrapper_ && mixer_service_wrapper_)); - - base::WaitableEvent finished; - if (cma_wrapper_) { - POST_TO_CMA_WRAPPER(Stop, &finished); - } else if (mixer_service_wrapper_) { - POST_TO_MIXER_SERVICE_WRAPPER(Stop, &finished); - } else { - finished.Signal(); - } - finished.Wait(); -} - -void CastAudioOutputStream::Flush() { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DVLOG(2) << this << ": " << __func__; - - // |cma_wrapper_| and |mixer_service_wrapper_| cannot be both active. - DCHECK(!(cma_wrapper_ && mixer_service_wrapper_)); - - if (cma_wrapper_) { - // Make sure this is not on the same thread as CMA_WRAPPER to prevent - // deadlock. - DCHECK(!audio_manager_->media_task_runner()->BelongsToCurrentThread()); - - base::WaitableEvent finished; - POST_TO_CMA_WRAPPER(Flush, base::Unretained(&finished)); - finished.Wait(); - } else if (mixer_service_wrapper_) { - POST_TO_MIXER_SERVICE_WRAPPER(Flush); - } -} - -void CastAudioOutputStream::SetVolume(double volume) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - DCHECK_NE(audio_thread_state_, AudioOutputState::kPendingClose); - DVLOG(2) << this << ": " << __func__ << "(" << volume << ")"; - volume_ = volume; - - DCHECK(!(cma_wrapper_ && mixer_service_wrapper_)); - - if (cma_wrapper_) { - POST_TO_CMA_WRAPPER(SetVolume, volume); - } else { - POST_TO_MIXER_SERVICE_WRAPPER(SetVolume, volume); - } -} - -void CastAudioOutputStream::GetVolume(double* volume) { - DCHECK_CALLED_ON_VALID_THREAD(audio_thread_checker_); - *volume = volume_; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_stream.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_stream.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,154 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_STREAM_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_STREAM_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/task/single_thread_task_runner.h" -#include "base/threading/thread_checker.h" -#include "base/timer/timer.h" -#include "build/build_config.h" -#include "chromecast/base/task_runner_impl.h" -#include "media/audio/audio_io.h" -#include "media/base/audio_parameters.h" -#include "media/base/audio_timestamp_helper.h" - -namespace chromecast { -namespace media { - -class CmaAudioOutputStream; -class CastAudioManagerHelper; - -// Chromecast implementation of AudioOutputStream. -// This class forwards to MixerService if valid -// |mixer_service_connection_factory| is passed in on the construction call, -// for a lower latency audio playback (using MixerServiceWrapper). Otherwise, -// when a nullptr is passed in as |mixer_service_connection_factory| it forwards -// to CMA backend (using CmaWrapper). -// -// In either case, involved components live on two threads: -// 1. Audio thread -// |CastAudioOutputStream| -// Where the object gets construction from AudioManager. -// How the object gets controlled from AudioManager. -// 2. Media thread or an IO thread opened within |AudioOutputStream|. -// |CastAudioOutputStream::CmaWrapper| or |MixerServiceWrapper| lives on -// this thread. -// -// The interface between AudioManager and AudioOutputStream is synchronous, so -// in order to allow asynchronous thread hops, we: -// * Maintain the current state independently in each thread. -// * Cache function calls like Start() and SetVolume() as bound callbacks. -// -// The individual thread states should nearly always be the same. The only time -// they are expected to be different is when the audio thread has executed a -// task and posted to the media thread/IO thread, but the media thread has not -// executed yet. -// -// The below illustrates the case when CMA backend is used for playback. -// -// Audio Thread |CAOS| Media Thread |CmaWrapper| -// ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ -// *[ Closed ] *[ Closed ] -// | | -// | | -// v v -// [ Opened ] --post open--> [ Opened ] -// | | ^ | | ^ -// | | | | | | -// | | Stop() --post stop--> | | Stop() -// | v | | v | -// | [ Started ] --post start--> | [ Started ] -// | | | | -// | | | | -// v v v v -// **[ Pending Close ] --post close--> **[ Pending Close ] -// | | -// | | -// ( waits for closure ) <--post closure--' -// | -// v -// ( released) -// * Initial states. -// ** Final states. -// -// When MixerService is used in place of CMA backend, the state transition is -// similar but a little simpler. -// MixerServiceWrapper creates a new mixer service connection at Start() and -// destroys the connection at Stop(). When the volume is adjusted between a -// Stop() and the next Start(), the volume is recorded and then applied to the -// mixer service connection after the connection is established on the Start() -// call. - -// TODO(b/117980762): CastAudioOutputStream should be refactored -// to be more unit test friendly. And the unit tests can be improved. - -class CastAudioOutputStream : public ::media::AudioOutputStream { - public: - // When nullptr is passed as |mixer_service_connection_factory|, CmaWrapper - // will be used for audio playback. - // |device_id_or_group_id| describes either the |device_id_| or |group_id_|. - // If the |device_id_or_group_id| matches a valid device_id then the - // |group_id_| is filled in empty. If the |device_id_or_group_id_| does not - // match a valid |device_id|, then the |group_id_| is set to that value, and - // the |device_id_| is set to kDefaultDeviceId. Valid device_id's are either - // ::media::AudioDeviceDescription::kDefaultDeviceId or - // ::media::AudioDeviceDescription::kCommunicationsId. - CastAudioOutputStream(CastAudioManagerHelper* audio_manager, - const ::media::AudioParameters& audio_params, - const std::string& device_id_or_group_id, - bool use_mixer_service); - - CastAudioOutputStream(const CastAudioOutputStream&) = delete; - CastAudioOutputStream& operator=(const CastAudioOutputStream&) = delete; - - ~CastAudioOutputStream() override; - - // ::media::AudioOutputStream implementation. - bool Open() override; - void Close() override; - void Start(AudioSourceCallback* source_callback) override; - void Stop() override; - void SetVolume(double volume) override; - void GetVolume(double* volume) override; - void Flush() override; - - private: - enum class AudioOutputState { - kClosed, - kOpened, - kStarted, - kPendingClose, - }; - - class MixerServiceWrapper; - - void FinishClose(); - - double volume_; - AudioOutputState audio_thread_state_; - CastAudioManagerHelper* const audio_manager_; - const ::media::AudioParameters audio_params_; - // Valid |device_id_| are kDefaultDeviceId, and kCommunicationsDeviceId - const std::string device_id_; - // |group_id_|s are uuids mapped to session_ids for multizone. Should be an - // empty string if group_id is unused. - const std::string group_id_; - const bool use_mixer_service_; - std::unique_ptr cma_wrapper_; - std::unique_ptr mixer_service_wrapper_; - - THREAD_CHECKER(audio_thread_checker_); - base::WeakPtr audio_weak_this_; - base::WeakPtrFactory audio_weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_STREAM_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_stream_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_stream_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_stream_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,879 +0,0 @@ -// 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 "chromecast/media/audio/cast_audio_output_stream.h" - -#include - -#include -#include - -#include "base/functional/bind.h" -#include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/api/test/mock_cma_backend_factory.h" -#include "chromecast/media/audio/cast_audio_manager.h" -#include "chromecast/media/audio/cast_audio_mixer.h" -#include "chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h" -#include "chromecast/media/base/default_monotonic_clock.h" -#include "chromecast/public/task_runner.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/mock_audio_source_callback.h" -#include "media/audio/test_audio_thread.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; -using testing::Invoke; -using testing::NiceMock; -using testing::Return; - -namespace { - -constexpr char kSessionId[] = "01234567-89ab-cdef-0123-456789abcdef"; - -} // namespace - -namespace chromecast { -namespace media { -namespace { -const char kDefaultDeviceId[] = ""; -const int64_t kDelayUs = 123; -const double kDefaultVolume = 1.0f; - -int on_more_data_call_count_ = 0; -int OnMoreData(base::TimeDelta /* delay */, - base::TimeTicks /* delay_timestamp */, - const ::media::AudioGlitchInfo& /* glitch_info */, - ::media::AudioBus* dest) { - on_more_data_call_count_++; - dest->Zero(); - return dest->frames(); -} - -} // namespace - -class NotifyPushBufferCompleteTask : public chromecast::TaskRunner::Task { - public: - explicit NotifyPushBufferCompleteTask(CmaBackend::Decoder::Delegate* delegate) - : delegate_(delegate) {} - ~NotifyPushBufferCompleteTask() override = default; - void Run() override { - delegate_->OnPushBufferComplete(CmaBackend::BufferStatus::kBufferSuccess); - } - - private: - CmaBackend::Decoder::Delegate* const delegate_; -}; - -class FakeAudioDecoder : public CmaBackend::AudioDecoder { - public: - enum TestingPipelineStatus { - PIPELINE_STATUS_OK, - PIPELINE_STATUS_BUSY, - PIPELINE_STATUS_ERROR, - PIPELINE_STATUS_ASYNC_ERROR, - }; - - explicit FakeAudioDecoder(const MediaPipelineDeviceParams& params) - : params_(params), - volume_(kDefaultVolume), - pipeline_status_(PIPELINE_STATUS_OK), - pending_push_(false), - pushed_buffer_count_(0), - delegate_(nullptr) {} - ~FakeAudioDecoder() override {} - - // CmaBackend::AudioDecoder implementation: - void SetDelegate(Delegate* delegate) override { - DCHECK(delegate); - delegate_ = delegate; - } - BufferStatus PushBuffer(scoped_refptr buffer) override { - last_buffer_ = std::move(buffer); - ++pushed_buffer_count_; - - switch (pipeline_status_) { - case PIPELINE_STATUS_OK: - return CmaBackend::BufferStatus::kBufferSuccess; - case PIPELINE_STATUS_BUSY: - pending_push_ = true; - return CmaBackend::BufferStatus::kBufferPending; - case PIPELINE_STATUS_ERROR: - return CmaBackend::BufferStatus::kBufferFailed; - case PIPELINE_STATUS_ASYNC_ERROR: - delegate_->OnDecoderError(); - return CmaBackend::BufferStatus::kBufferSuccess; - default: - NOTREACHED(); - } - } - void GetStatistics(Statistics* statistics) override {} - bool SetConfig(const AudioConfig& config) override { - config_ = config; - return true; - } - bool SetVolume(float volume) override { - volume_ = volume; - return true; - } - RenderingDelay GetRenderingDelay() override { return rendering_delay_; } - AudioTrackTimestamp GetAudioTrackTimestamp() override { - return AudioTrackTimestamp(); - } - int GetStartThresholdInFrames() override { - return 0; - } - bool RequiresDecryption() override { return false; } - - const AudioConfig& config() const { return config_; } - float volume() const { return volume_; } - void set_pipeline_status(TestingPipelineStatus status) { - if (status == PIPELINE_STATUS_OK && pending_push_) { - pending_push_ = false; - params_.task_runner->PostTask(new NotifyPushBufferCompleteTask(delegate_), - 0); - } - pipeline_status_ = status; - } - void set_rendering_delay(RenderingDelay rendering_delay) { - rendering_delay_ = rendering_delay; - } - unsigned pushed_buffer_count() const { return pushed_buffer_count_; } - const DecoderBufferBase* last_buffer() { return last_buffer_.get(); } - - private: - const MediaPipelineDeviceParams params_; - AudioConfig config_; - float volume_; - - TestingPipelineStatus pipeline_status_; - bool pending_push_; - int pushed_buffer_count_; - scoped_refptr last_buffer_; - Delegate* delegate_; - RenderingDelay rendering_delay_; -}; - -class FakeCmaBackend : public CmaBackend { - public: - enum State { kStateStopped, kStateRunning, kStatePaused }; - - explicit FakeCmaBackend(const MediaPipelineDeviceParams& params) - : params_(params), state_(kStateStopped), audio_decoder_(nullptr) {} - ~FakeCmaBackend() override {} - - // CmaBackend implementation: - AudioDecoder* CreateAudioDecoder() override { - DCHECK(!audio_decoder_); - audio_decoder_ = std::make_unique(params_); - return audio_decoder_.get(); - } - VideoDecoder* CreateVideoDecoder() override { NOTREACHED(); } - - bool Initialize() override { return true; } - bool Start(int64_t start_pts) override { - EXPECT_EQ(kStateStopped, state_); - state_ = kStateRunning; - return true; - } - void Stop() override { - EXPECT_TRUE(state_ == kStateRunning || state_ == kStatePaused); - state_ = kStateStopped; - } - bool Pause() override { - EXPECT_EQ(kStateRunning, state_); - state_ = kStatePaused; - return true; - } - bool Resume() override { - EXPECT_EQ(kStatePaused, state_); - state_ = kStateRunning; - return true; - } - int64_t GetCurrentPts() override { return 0; } - bool SetPlaybackRate(float rate) override { return true; } - - void LogicalPause() override {} - void LogicalResume() override {} - - MediaPipelineDeviceParams params() const { return params_; } - State state() const { return state_; } - FakeAudioDecoder* audio_decoder() const { return audio_decoder_.get(); } - - private: - const MediaPipelineDeviceParams params_; - State state_; - std::unique_ptr audio_decoder_; -}; - -class CastAudioOutputStreamTest : public ::testing::Test { - public: - CastAudioOutputStreamTest() - : audio_thread_("CastAudioThread"), - task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME), - format_(::media::AudioParameters::AUDIO_PCM_LINEAR), - channel_layout_config_(::media::ChannelLayoutConfig::Mono()), - sample_rate_(::media::AudioParameters::kAudioCDSampleRate), - frames_per_buffer_(256) {} - - void SetUp() override { - CreateAudioManagerForTesting(); - SetUpCmaBackendFactory(); - } - - void TearDown() override { - RunThreadsUntilIdle(); - audio_manager_->Shutdown(); - audio_thread_.Stop(); - } - - protected: - CmaBackendFactory* GetCmaBackendFactory() { - return mock_backend_factory_.get(); - } - - void CreateAudioManagerForTesting(bool use_mixer = false) { - // Only one AudioManager may exist at a time, so destroy the one we're - // currently holding before creating a new one. - // Flush the message loop to run any shutdown tasks posted by AudioManager. - if (audio_manager_) { - audio_manager_->Shutdown(); - audio_manager_.reset(); - } - - if (audio_thread_.IsRunning()) - audio_thread_.Stop(); - CHECK(audio_thread_.StartAndWaitForTesting()); - mock_backend_factory_ = std::make_unique(); - audio_manager_ = base::WrapUnique(new CastAudioManager( - std::make_unique<::media::TestAudioThread>(), nullptr, &delegate_, - base::BindRepeating(&CastAudioOutputStreamTest::GetCmaBackendFactory, - base::Unretained(this)), - task_environment_.GetMainThreadTaskRunner(), - audio_thread_.task_runner(), use_mixer, - true /* force_use_cma_backend_for_output*/)); - // A few AudioManager implementations post initialization tasks to - // audio thread. Flush the thread to ensure that |audio_manager_| is - // initialized and ready to use before returning from this function. - // TODO(alokp): We should perhaps do this in AudioManager::Create(). - RunThreadsUntilIdle(); - } - - void SetUpCmaBackendFactory() { - EXPECT_CALL(*mock_backend_factory_, CreateBackend(_)) - .WillRepeatedly(Invoke([this](const MediaPipelineDeviceParams& params) { - auto fake_cma_backend = std::make_unique(params); - cma_backend_ = fake_cma_backend.get(); - return fake_cma_backend; - })); - EXPECT_EQ(mock_backend_factory_.get(), - audio_manager_->helper_.GetCmaBackendFactory()); - } - - void RunThreadsUntilIdle() { - task_environment_.RunUntilIdle(); - audio_thread_.FlushForTesting(); - } - - static void PauseAndWait(base::WaitableEvent* pause_event, - base::WaitableEvent* resume_event) { - pause_event->Signal(); - resume_event->Wait(); - } - - // Synchronously pause the audio thread. This function guarantees that - // the audio thread will be paused before it returns. - void PauseAudioThread() { - audio_thread_pause_ = std::make_unique( - base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED); - audio_thread_resume_ = std::make_unique( - base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED); - audio_thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&PauseAndWait, audio_thread_pause_.get(), - audio_thread_resume_.get())); - audio_thread_pause_->Wait(); - } - - // Resume a paused audio thread by signalling to it. - void ResumeAudioThreadAsync() { - if (audio_thread_resume_) { - audio_thread_resume_->Signal(); - } - } - - ::media::AudioParameters GetAudioParams() { - return ::media::AudioParameters(format_, channel_layout_config_, - sample_rate_, frames_per_buffer_); - } - - FakeAudioDecoder* GetAudioDecoder() { - return (cma_backend_ ? cma_backend_->audio_decoder() : nullptr); - } - - ::media::AudioOutputStream* CreateStream() { - return audio_manager_->MakeAudioOutputStream( - GetAudioParams(), kDefaultDeviceId, - ::media::AudioManager::LogCallback()); - } - - base::Thread audio_thread_; - base::test::TaskEnvironment task_environment_; - std::unique_ptr audio_thread_pause_; - std::unique_ptr audio_thread_resume_; - std::unique_ptr mock_backend_factory_; - - FakeCmaBackend* cma_backend_ = nullptr; - MockCastAudioManagerHelperDelegate delegate_; - std::unique_ptr audio_manager_; - - // AudioParameters used to create AudioOutputStream. - // Tests can modify these parameters before calling CreateStream. - ::media::AudioParameters::Format format_; - ::media::ChannelLayoutConfig channel_layout_config_; - int sample_rate_; - int frames_per_buffer_; -}; - -TEST_F(CastAudioOutputStreamTest, CloseWithoutStart) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, CloseWithoutStop) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - - stream->Close(); - RunThreadsUntilIdle(); -} - -TEST_F(CastAudioOutputStreamTest, StartImmediatelyAfterOpen) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - EXPECT_EQ(FakeCmaBackend::kStateRunning, cma_backend_->state()); - - stream->Stop(); - RunThreadsUntilIdle(); - stream->Close(); - RunThreadsUntilIdle(); -} - -TEST_F(CastAudioOutputStreamTest, SetVolumeImmediatelyAfterOpen) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - stream->SetVolume(0.5); - - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - double volume = 0.0; - stream->GetVolume(&volume); - EXPECT_EQ(0.5, volume); - EXPECT_EQ(0.5f, audio_decoder->volume()); - - stream->Stop(); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, StartStopStart) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - stream->Stop(); - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)).Times(0); - RunThreadsUntilIdle(); - testing::Mock::VerifyAndClearExpectations(&source_callback); - - // Ensure we fetch new data when restarting. - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - int last_on_more_data_call_count = on_more_data_call_count_; - stream->Start(&source_callback); - RunThreadsUntilIdle(); - EXPECT_GT(on_more_data_call_count_, last_on_more_data_call_count); - - EXPECT_EQ(FakeCmaBackend::kStateRunning, cma_backend_->state()); - - stream->Stop(); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, StopPreventsCallbacks) { - // Stream API details that Stop is synchronous and prevents calls to callback. - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - stream->SetVolume(0.5); - stream->Stop(); - // TODO(steinbock) Make this fail more reliably when stream->Stop() returns - // asynchronously. - stream->Close(); - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)).Times(0); - RunThreadsUntilIdle(); -} - -TEST_F(CastAudioOutputStreamTest, ClosePreventsCallbacks) { - // Stream API details that Close is synchronous and prevents calls to - // callback. - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - - // Pause the audio thread from running tasks before calling Close() to - // prevent it from processing OnMoreData() calls after setting the - // expectation and before calling Close(). - PauseAudioThread(); - // Once the audio thread resumes work, push/fill calls posted to the audio - // thread should no longer call OnMoreData(). - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)).Times(0); - stream->Close(); - ResumeAudioThreadAsync(); - RunThreadsUntilIdle(); -} - -TEST_F(CastAudioOutputStreamTest, Format) { - ::media::AudioParameters::Format format[] = { - ::media::AudioParameters::AUDIO_PCM_LINEAR, - ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY}; - for (size_t i = 0; i < std::size(format); ++i) { - format_ = format[i]; - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - const AudioConfig& audio_config = audio_decoder->config(); - EXPECT_EQ(kCodecPCM, audio_config.codec); - EXPECT_EQ(kSampleFormatS16, audio_config.sample_format); - EXPECT_EQ(audio_config.encryption_scheme, EncryptionScheme::kUnencrypted); - - stream->Close(); - } -} - -TEST_F(CastAudioOutputStreamTest, ChannelLayout) { - ::media::ChannelLayoutConfig layout[] = { - ::media::ChannelLayoutConfig::Mono(), - ::media::ChannelLayoutConfig::Stereo()}; - for (size_t i = 0; i < std::size(layout); ++i) { - channel_layout_config_ = layout[i]; - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - const AudioConfig& audio_config = audio_decoder->config(); - EXPECT_EQ(::media::ChannelLayoutToChannelCount( - channel_layout_config_.channel_layout()), - audio_config.channel_number); - - stream->Close(); - } -} - -TEST_F(CastAudioOutputStreamTest, SampleRate) { - sample_rate_ = ::media::AudioParameters::kAudioCDSampleRate; - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - const AudioConfig& audio_config = audio_decoder->config(); - EXPECT_EQ(sample_rate_, audio_config.samples_per_second); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, DeviceState) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - ASSERT_TRUE(cma_backend_); - EXPECT_EQ(FakeCmaBackend::kStateStopped, cma_backend_->state()); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - EXPECT_EQ(FakeCmaBackend::kStateRunning, cma_backend_->state()); - - stream->Stop(); - RunThreadsUntilIdle(); - EXPECT_EQ(FakeCmaBackend::kStatePaused, cma_backend_->state()); - - stream->Flush(); - RunThreadsUntilIdle(); - EXPECT_EQ(FakeCmaBackend::kStateStopped, cma_backend_->state()); - - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, PushFrame) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - // Verify initial state. - EXPECT_EQ(0u, audio_decoder->pushed_buffer_count()); - EXPECT_FALSE(audio_decoder->last_buffer()); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - // No error must be reported to source callback. - EXPECT_CALL(source_callback, OnError(_)).Times(0); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - stream->Stop(); - - // Verify that the stream pushed frames to the backend. - EXPECT_LT(0u, audio_decoder->pushed_buffer_count()); - EXPECT_TRUE(audio_decoder->last_buffer()); - - // Verify decoder buffer. - ::media::AudioParameters audio_params = GetAudioParams(); - const size_t expected_frame_size = - audio_params.GetBytesPerBuffer(::media::kSampleFormatS16); - const DecoderBufferBase* buffer = audio_decoder->last_buffer(); - EXPECT_TRUE(buffer->data()); - EXPECT_EQ(expected_frame_size, buffer->data_size()); - EXPECT_FALSE(buffer->decrypt_config()); // Null because of raw audio. - EXPECT_FALSE(buffer->end_of_stream()); - - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, PushFrameAfterStop) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - // No error must be reported to source callback. - EXPECT_CALL(source_callback, OnError(_)).Times(0); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - - // Verify that the stream pushed frames to the backend. - EXPECT_LT(0u, audio_decoder->pushed_buffer_count()); - EXPECT_TRUE(audio_decoder->last_buffer()); - - stream->Stop(); - - ASSERT_TRUE(cma_backend_); - base::TimeDelta duration = GetAudioParams().GetBufferDuration() * 2; - task_environment_.FastForwardBy(duration); - RunThreadsUntilIdle(); - - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, PushFrameAfterClose) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - // No error must be reported to source callback. - EXPECT_CALL(source_callback, OnError(_)).Times(0); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - - // Verify that the stream pushed frames to the backend. - EXPECT_LT(0u, audio_decoder->pushed_buffer_count()); - EXPECT_TRUE(audio_decoder->last_buffer()); - - stream->Close(); - - ASSERT_TRUE(cma_backend_); - base::TimeDelta duration = GetAudioParams().GetBufferDuration() * 2; - task_environment_.FastForwardBy(duration); - RunThreadsUntilIdle(); -} - -// TODO(steinbock) fix test on server and reenable. -TEST_F(CastAudioOutputStreamTest, DISABLED_DeviceBusy) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - audio_decoder->set_pipeline_status(FakeAudioDecoder::PIPELINE_STATUS_BUSY); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - // No error must be reported to source callback. - EXPECT_CALL(source_callback, OnError(_)).Times(0); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - // Make sure that one frame was pushed. - EXPECT_EQ(1u, audio_decoder->pushed_buffer_count()); - - // Sleep for a few frames and verify that more frames were not pushed - // because the backend device was busy. - RunThreadsUntilIdle(); - EXPECT_EQ(1u, audio_decoder->pushed_buffer_count()); - - // Unblock the pipeline and verify that PushFrame resumes. - audio_decoder->set_pipeline_status(FakeAudioDecoder::PIPELINE_STATUS_OK); - - RunThreadsUntilIdle(); - stream->Stop(); - stream->Close(); - RunThreadsUntilIdle(); - EXPECT_LT(1u, audio_decoder->pushed_buffer_count()); -} - -TEST_F(CastAudioOutputStreamTest, DeviceError) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - audio_decoder->set_pipeline_status(FakeAudioDecoder::PIPELINE_STATUS_ERROR); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - // AudioOutputStream must report error to source callback. - EXPECT_CALL(source_callback, OnError(_)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - // Make sure that AudioOutputStream attempted to push the initial frame. - EXPECT_LT(0u, audio_decoder->pushed_buffer_count()); - - stream->Stop(); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, DeviceAsyncError) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - audio_decoder->set_pipeline_status( - FakeAudioDecoder::PIPELINE_STATUS_ASYNC_ERROR); - - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - // AudioOutputStream must report error to source callback. - EXPECT_CALL(source_callback, OnError(_)).Times(testing::AtLeast(1)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - - // Make sure that one frame was pushed. - EXPECT_EQ(1u, audio_decoder->pushed_buffer_count()); - - stream->Stop(); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, Volume) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - - double volume = 0.0; - stream->GetVolume(&volume); - EXPECT_EQ(1.0, volume); - EXPECT_EQ(1.0f, audio_decoder->volume()); - - stream->SetVolume(0.5); - RunThreadsUntilIdle(); - stream->GetVolume(&volume); - EXPECT_EQ(0.5, volume); - EXPECT_EQ(0.5f, audio_decoder->volume()); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, InvalidAudioDelay) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - audio_decoder->set_rendering_delay( - CmaBackend::AudioDecoder::RenderingDelay(-1, 0)); - - ::media::MockAudioSourceCallback source_callback; - const base::TimeDelta delay = base::TimeDelta(); - EXPECT_CALL(source_callback, OnMoreData(delay, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - - stream->Start(&source_callback); - RunThreadsUntilIdle(); - - stream->Stop(); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, AudioDelay) { - ::media::AudioOutputStream* stream = CreateStream(); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - FakeAudioDecoder* audio_decoder = GetAudioDecoder(); - ASSERT_TRUE(audio_decoder); - audio_decoder->set_rendering_delay( - CmaBackend::AudioDecoder::RenderingDelay(kDelayUs, MonotonicClockNow())); - ::media::MockAudioSourceCallback source_callback; - const base::TimeDelta delay(base::Microseconds(kDelayUs)); - // OnMoreData can be called with a shorter delay than the rendering delay in - // order to prefetch audio data faster. - EXPECT_CALL(source_callback, OnMoreData(testing::Le(delay), _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - - stream->Start(&source_callback); - RunThreadsUntilIdle(); - - stream->Stop(); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, SessionId) { - format_ = ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY; - ::media::AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream( - GetAudioParams(), "DummyGroupId", ::media::AudioManager::LogCallback()); - EXPECT_CALL(delegate_, GetSessionId(_)).WillOnce(Return(kSessionId)); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - // We will start/stop the stream, because as a test, we do not care about - // whether the info was fetched during Open() or Start() so we test across - // both. - ::media::MockAudioSourceCallback source_callback; - EXPECT_CALL(source_callback, OnMoreData(_, _, _, _)) - .WillRepeatedly(Invoke(OnMoreData)); - stream->Start(&source_callback); - RunThreadsUntilIdle(); - - // TODO(awolter, b/111669896): Verify that the session id is correct after - // piping has been added. For now, we want to verify that the session id is - // empty, so that basic MZ continues to work. - ASSERT_TRUE(cma_backend_); - MediaPipelineDeviceParams params = cma_backend_->params(); - EXPECT_EQ(params.session_id, kSessionId); - - stream->Stop(); - stream->Close(); -} - -TEST_F(CastAudioOutputStreamTest, CommunicationsDeviceId) { - format_ = ::media::AudioParameters::AUDIO_PCM_LOW_LATENCY; - ::media::AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream( - GetAudioParams(), - ::media::AudioDeviceDescription::kCommunicationsDeviceId, - ::media::AudioManager::LogCallback()); - ASSERT_TRUE(stream); - ASSERT_TRUE(stream->Open()); - RunThreadsUntilIdle(); - - ASSERT_TRUE(cma_backend_); - MediaPipelineDeviceParams params = cma_backend_->params(); - EXPECT_EQ(params.content_type, AudioContentType::kCommunication); - EXPECT_EQ(params.device_id, - ::media::AudioDeviceDescription::kCommunicationsDeviceId); - - stream->Stop(); - stream->Close(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_utils.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_utils.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_utils.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_utils.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_output_utils.h" - -#include "media/audio/audio_device_description.h" - -namespace chromecast { -namespace media { - -bool IsValidDeviceId(const std::string& device_id) { - return device_id == ::media::AudioDeviceDescription::kDefaultDeviceId || - device_id == ::media::AudioDeviceDescription::kCommunicationsDeviceId; -} - -std::string GetGroupId(const std::string& device_id) { - return IsValidDeviceId(device_id) ? "" : device_id; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_utils.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_utils.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_output_utils.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_output_utils.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_UTILS_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_UTILS_H_ - -#include - -namespace chromecast { -namespace media { - -// Returns whether the device is valid. -bool IsValidDeviceId(const std::string& device_id); - -// Returns the group id for provided device id. -std::string GetGroupId(const std::string& device_id); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_OUTPUT_UTILS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_renderer.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_renderer.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_renderer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_renderer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,588 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cast_audio_renderer.h" - -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/notreached.h" -#include "base/numerics/ranges.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "chromecast/media/audio/audio_io_thread.h" -#include "chromecast/media/audio/audio_output_service/audio_output_service.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/decoder_buffer.h" -#include "media/base/renderer_client.h" -#include "media/filters/decrypting_demuxer_stream.h" -#include "net/base/io_buffer.h" -#include "third_party/blink/public/platform/browser_interface_broker_proxy.h" - -#define RUN_ON_MAIN_THREAD(method, ...) \ - main_task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&CastAudioRenderer::method, \ - weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); - -#define MAKE_SURE_MAIN_THREAD(method, ...) \ - if (!main_task_runner_->RunsTasksInCurrentSequence()) { \ - RUN_ON_MAIN_THREAD(method, ##__VA_ARGS__) \ - return; \ - } - -namespace chromecast { -namespace media { - -namespace { - -audio_output_service::AudioDecoderConfig ConvertAudioDecoderConfig( - const ::media::AudioDecoderConfig& audio_decoder_config) { - chromecast::media::AudioConfig audio_config = - DecoderConfigAdapter::ToCastAudioConfig(StreamId::kPrimary, - audio_decoder_config); - audio_output_service::AudioDecoderConfig proto_audio_config; - proto_audio_config.set_audio_codec( - audio_service::ConvertAudioCodec(audio_config.codec)); - proto_audio_config.set_channel_layout( - audio_service::ConvertChannelLayout(audio_config.channel_layout)); - proto_audio_config.set_sample_format( - audio_service::ConvertSampleFormat(audio_config.sample_format)); - proto_audio_config.set_num_channels(audio_config.channel_number); - proto_audio_config.set_sample_rate(audio_config.samples_per_second); - proto_audio_config.set_extra_data( - reinterpret_cast(audio_config.extra_data.data()), - audio_config.extra_data.size()); - return proto_audio_config; -} - -} // namespace - -CastAudioRenderer::CastAudioRenderer( - scoped_refptr media_task_runner, - ::media::MediaLog* media_log, - blink::BrowserInterfaceBrokerProxy* interface_broker) - : media_task_runner_(std::move(media_task_runner)), media_log_(media_log) { - DCHECK(interface_broker); - DETACH_FROM_SEQUENCE(sequence_checker_); - - interface_broker->GetInterface(application_media_info_manager_pending_remote_ - .InitWithNewPipeAndPassReceiver()); - interface_broker->GetInterface( - audio_socket_broker_pending_remote_.InitWithNewPipeAndPassReceiver()); -} - -CastAudioRenderer::~CastAudioRenderer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -void CastAudioRenderer::Initialize(::media::DemuxerStream* stream, - ::media::CdmContext* cdm_context, - ::media::RendererClient* client, - ::media::PipelineStatusCallback init_cb) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!demuxer_stream_); - DCHECK(!init_cb_); - DCHECK(!application_media_info_manager_remote_); - - main_task_runner_ = base::SequencedTaskRunner::GetCurrentDefault(); - init_cb_ = std::move(init_cb); - - demuxer_stream_ = stream; - renderer_client_ = client; - if (demuxer_stream_->audio_decoder_config().is_encrypted()) { - if (!cdm_context) { - LOG(ERROR) << "No CDM context for encrypted stream."; - OnError(::media::AUDIO_RENDERER_ERROR); - return; - } - decrypting_stream_ = std::make_unique<::media::DecryptingDemuxerStream>( - media_task_runner_, media_log_, - base::BindRepeating(&CastAudioRenderer::OnWaiting, - weak_factory_.GetWeakPtr())); - decrypting_stream_->Initialize( - demuxer_stream_, cdm_context, - base::BindOnce(&CastAudioRenderer::OnDecryptingDemuxerInitialized, - weak_factory_.GetWeakPtr())); - demuxer_stream_ = decrypting_stream_.get(); - } - demuxer_stream_->EnableBitstreamConverter(); - - application_media_info_manager_remote_.Bind( - std::move(application_media_info_manager_pending_remote_)); - application_media_info_manager_remote_->GetCastApplicationMediaInfo( - base::BindOnce(&CastAudioRenderer::OnApplicationMediaInfoReceived, - weak_factory_.GetWeakPtr())); -} - -::media::TimeSource* CastAudioRenderer::GetTimeSource() { - return this; -} - -void CastAudioRenderer::Flush(base::OnceClosure callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - renderer_started_ = false; - - DCHECK(!flush_cb_); - if (is_pending_demuxer_read_) { - flush_cb_ = std::move(callback); - return; - } - - FlushInternal(); - - LOG(INFO) << "Flush done."; - std::move(callback).Run(); -} - -void CastAudioRenderer::FlushInternal() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(output_connection_); - - if (last_pushed_timestamp_.is_min()) { - return; - } - - DCHECK(CurrentPlaybackStateEquals(PlaybackState::kStopped) || - is_at_end_of_stream_); - - // At this point, there is no more pending demuxer read, - // so all the previous tasks associated with the current timeline - // can be cancelled. - weak_factory_.InvalidateWeakPtrs(); - - output_connection_.AsyncCall( - &audio_output_service::OutputStreamConnection::StopPlayback); - - SetBufferState(::media::BUFFERING_HAVE_NOTHING); - last_pushed_timestamp_ = base::TimeDelta::Min(); - read_timer_.Stop(); - is_at_end_of_stream_ = false; -} - -void CastAudioRenderer::StartPlaying() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - renderer_started_ = true; - base::TimeDelta media_pos; - { - base::AutoLock lock(timeline_lock_); - media_pos = media_pos_; - if (GetPlaybackState() != PlaybackState::kStopped) { - output_connection_.AsyncCall( - &audio_output_service::OutputStreamConnection::StopPlayback); - } - SetPlaybackState(PlaybackState::kStarting); - } - - output_connection_ - .AsyncCall( - &audio_output_service::OutputStreamConnection::StartPlayingFrom) - .WithArgs(media_pos.InMicroseconds()); - ScheduleFetchNextBuffer(); -} - -void CastAudioRenderer::SetVolume(float volume) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - volume_ = volume; - if (!output_connection_) { - return; - } - output_connection_ - .AsyncCall(&audio_output_service::OutputStreamConnection::SetVolume) - .WithArgs(volume); -} - -void CastAudioRenderer::SetLatencyHint( - std::optional latency_hint) { - NOTIMPLEMENTED(); -} - -void CastAudioRenderer::SetPreservesPitch(bool preverves_pitch) { - NOTIMPLEMENTED(); -} - -void CastAudioRenderer::SetWasPlayedWithUserActivationAndHighMediaEngagement( - bool was_played_with_user_activation_and_high_media_engagement) { - NOTIMPLEMENTED(); -} - -void CastAudioRenderer::StartTicking() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(output_connection_); - DCHECK(!ticking_); - - ticking_ = true; - float playback_rate = 0.0f; - { - base::AutoLock lock(timeline_lock_); - if (playback_rate_ == 0.0f) { - // Wait for SetPlaybackRate() to start the playback. - return; - } - playback_rate = playback_rate_; - } - output_connection_ - .AsyncCall(&audio_output_service::OutputStreamConnection::SetPlaybackRate) - .WithArgs(playback_rate); -} - -void CastAudioRenderer::StopTicking() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!CurrentPlaybackStateEquals(PlaybackState::kStopped)); - DCHECK(output_connection_); - DCHECK(ticking_); - - ticking_ = false; - output_connection_.AsyncCall( - &audio_output_service::OutputStreamConnection::StopPlayback); - - base::AutoLock lock(timeline_lock_); - UpdateTimelineOnStop(); - SetPlaybackState(PlaybackState::kStopped); -} - -void CastAudioRenderer::SetPlaybackRate(double playback_rate) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(output_connection_); - - playback_rate = base::ranges::clamp(playback_rate, 0.0, 2.0); - { - base::AutoLock lock(timeline_lock_); - if (playback_rate == 0.0) { - UpdateTimelineOnStop(); - } - - if (ticking_ && playback_rate_ == 0.0f && playback_rate > 0.0) { - // It is necessary to set the playback state in the `Resume` case since - // `playback_rate_` is changed immediately but the media time should not - // move forward until we received a timestamp update in - // OnNextBuffer(). - SetPlaybackState(PlaybackState::kStarting); - } - playback_rate_ = playback_rate; - } - if (!ticking_) { - // Wait until StartTicking() is called to set the playback rate. - return; - } - output_connection_ - .AsyncCall(&audio_output_service::OutputStreamConnection::SetPlaybackRate) - .WithArgs(playback_rate); -} - -void CastAudioRenderer::SetBufferState(::media::BufferingState buffer_state) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (buffer_state == buffer_state_) { - return; - } - buffer_state_ = buffer_state; - renderer_client_->OnBufferingStateChange( - buffer_state_, ::media::BUFFERING_CHANGE_REASON_UNKNOWN); -} - -void CastAudioRenderer::SetMediaTime(base::TimeDelta time) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(CurrentPlaybackStateEquals(PlaybackState::kStopped) || - CurrentPlaybackStateEquals(PlaybackState::kStarting)); - - { - base::AutoLock lock(timeline_lock_); - media_pos_ = time; - reference_time_ = base::TimeTicks(); - } - - FlushInternal(); -} - -base::TimeDelta CastAudioRenderer::CurrentMediaTime() { - base::AutoLock lock(timeline_lock_); - - if (!IsTimeMoving()) { - return media_pos_; - } - - return CurrentMediaTimeLocked(); -} - -bool CastAudioRenderer::IsTimeMoving() { - return state_ == PlaybackState::kPlaying && playback_rate_ > 0.0f; -} - -void CastAudioRenderer::UpdateTimelineOnStop() { - if (!IsTimeMoving()) { - return; - } - - media_pos_ = CurrentMediaTimeLocked(); - reference_time_ = base::TimeTicks::Now(); -} - -void CastAudioRenderer::UpdateAudioDecoderConfig( - const ::media::AudioDecoderConfig& config) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - audio_output_service::CmaBackendParams backend_params; - *(backend_params.mutable_audio_decoder_config()) = - ConvertAudioDecoderConfig(config); - output_connection_ - .AsyncCall( - &audio_output_service::OutputStreamConnection::UpdateAudioConfig) - .WithArgs(backend_params); -} - -base::TimeDelta CastAudioRenderer::CurrentMediaTimeLocked() { - DCHECK(IsTimeMoving()); - return media_pos_ + - (base::TimeTicks::Now() - reference_time_) * playback_rate_; -} - -bool CastAudioRenderer::GetWallClockTimes( - const std::vector& media_timestamps, - std::vector* wall_clock_times) { - wall_clock_times->reserve(media_timestamps.size()); - auto now = base::TimeTicks::Now(); - - base::AutoLock lock(timeline_lock_); - - const bool is_time_moving = IsTimeMoving(); - - if (media_timestamps.empty()) { - wall_clock_times->push_back(is_time_moving ? now : reference_time_); - return is_time_moving; - } - - base::TimeTicks wall_clock_base = is_time_moving ? reference_time_ : now; - - for (base::TimeDelta timestamp : media_timestamps) { - base::TimeTicks wall_clock_time; - - auto relative_pos = timestamp - media_pos_; - if (is_time_moving) { - relative_pos = relative_pos / playback_rate_; - } - wall_clock_time = wall_clock_base + relative_pos; - wall_clock_times->push_back(wall_clock_time); - } - - return is_time_moving; -} - -void CastAudioRenderer::ScheduleFetchNextBuffer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (!renderer_started_ || !demuxer_stream_ || read_timer_.IsRunning() || - is_pending_demuxer_read_ || is_at_end_of_stream_) { - return; - } - - base::TimeDelta next_read_delay; - if (!last_pushed_timestamp_.is_min()) { - std::vector wall_clock_times; - bool is_time_moving = - GetWallClockTimes({last_pushed_timestamp_}, &wall_clock_times); - base::TimeDelta relative_buffer_pos = - wall_clock_times[0] - base::TimeTicks::Now(); - - if (relative_buffer_pos >= min_lead_time_) { - SetBufferState(::media::BUFFERING_HAVE_ENOUGH); - } - - if (relative_buffer_pos >= max_lead_time_) { - if (!is_time_moving) { - return; - } - next_read_delay = relative_buffer_pos - max_lead_time_; - } - } - - read_timer_.Start(FROM_HERE, next_read_delay, this, - &CastAudioRenderer::FetchNextBuffer); -} - -CastAudioRenderer::PlaybackState CastAudioRenderer::GetPlaybackState() { - return state_; -} - -bool CastAudioRenderer::CurrentPlaybackStateEquals( - CastAudioRenderer::PlaybackState playback_state) { - base::AutoLock lock(timeline_lock_); - return state_ == playback_state; -} - -void CastAudioRenderer::SetPlaybackState(PlaybackState state) { - state_ = state; -} - -void CastAudioRenderer::FetchNextBuffer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(demuxer_stream_); - - DCHECK(!is_pending_demuxer_read_); - is_pending_demuxer_read_ = true; - demuxer_stream_->Read(1, base::BindOnce(&CastAudioRenderer::OnNewBuffersRead, - weak_factory_.GetWeakPtr())); -} - -void CastAudioRenderer::OnNewBuffersRead( - ::media::DemuxerStream::Status status, - ::media::DemuxerStream::DecoderBufferVector buffers_queue) { - CHECK_LE(buffers_queue.size(), 1u) - << "CastAudioRenderer only reads a single-buffer."; - OnNewBuffer(status, - buffers_queue.empty() ? nullptr : std::move(buffers_queue[0])); -} - -void CastAudioRenderer::OnNewBuffer( - ::media::DemuxerStream::Status status, - scoped_refptr<::media::DecoderBuffer> buffer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(output_connection_); - - is_pending_demuxer_read_ = false; - - // Just discard the buffer in the flush stage. - if (flush_cb_) { - FlushInternal(); - std::move(flush_cb_).Run(); - return; - } - - if (status == ::media::DemuxerStream::kAborted) { - DCHECK(!buffer); - return; - } - - if (status == ::media::DemuxerStream::kError) { - OnError(::media::PIPELINE_ERROR_READ); - return; - } - - if (status == ::media::DemuxerStream::kConfigChanged) { - DCHECK(!buffer); - UpdateAudioDecoderConfig(demuxer_stream_->audio_decoder_config()); - renderer_client_->OnAudioConfigChange( - demuxer_stream_->audio_decoder_config()); - return; - } - - DCHECK_EQ(status, ::media::DemuxerStream::kOk); - - size_t filled_bytes = buffer->end_of_stream() ? 0 : buffer->size(); - size_t io_buffer_size = - audio_output_service::OutputSocket::kAudioMessageHeaderSize + - filled_bytes; - auto io_buffer = base::MakeRefCounted(io_buffer_size); - if (buffer->end_of_stream()) { - OnEndOfStream(); - return; - } - - last_pushed_timestamp_ = buffer->timestamp() + buffer->duration(); - memcpy(io_buffer->data() + - audio_output_service::OutputSocket::kAudioMessageHeaderSize, - buffer->data(), buffer->size()); - - output_connection_ - .AsyncCall(&audio_output_service::OutputStreamConnection::SendAudioBuffer) - .WithArgs(std::move(io_buffer), filled_bytes, - buffer->timestamp().InMicroseconds()); -} - -void CastAudioRenderer::OnBackendInitialized( - const audio_output_service::BackendInitializationStatus& status) { - MAKE_SURE_MAIN_THREAD(OnBackendInitialized, status); - DCHECK(init_cb_); - - if (!status.has_status() || - status.status() != - audio_output_service::BackendInitializationStatus::SUCCESS) { - std::move(init_cb_).Run(::media::PIPELINE_ERROR_INITIALIZATION_FAILED); - return; - } - - SetVolume(volume_); - std::move(init_cb_).Run(::media::PIPELINE_OK); -} - -void CastAudioRenderer::OnNextBuffer(int64_t media_timestamp_microseconds, - int64_t reference_timestamp_microseconds, - int64_t delay_microseconds, - int64_t delay_timestamp_microseconds) { - base::AutoLock lock(timeline_lock_); - if (GetPlaybackState() == PlaybackState::kStopped) { - return; - } - if (reference_timestamp_microseconds >= 0l && - media_timestamp_microseconds >= 0l) { - media_pos_ = base::Microseconds(media_timestamp_microseconds); - reference_time_ = - base::TimeTicks::FromInternalValue(reference_timestamp_microseconds); - if (GetPlaybackState() == PlaybackState::kStarting) { - SetPlaybackState(PlaybackState::kPlaying); - } - } - RUN_ON_MAIN_THREAD(ScheduleFetchNextBuffer); -} - -void CastAudioRenderer::OnEndOfStream() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - renderer_client_->OnEnded(); - is_at_end_of_stream_ = true; - SetBufferState(::media::BUFFERING_HAVE_ENOUGH); -} - -void CastAudioRenderer::OnError(::media::PipelineStatus pipeline_status) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - output_connection_.Reset(); - if (init_cb_) { - std::move(init_cb_).Run(pipeline_status); - return; - } - if (renderer_client_) { - renderer_client_->OnError(pipeline_status); - } -} - -void CastAudioRenderer::OnDecryptingDemuxerInitialized( - ::media::PipelineStatus pipeline_status) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (pipeline_status != ::media::PIPELINE_OK) { - OnError(pipeline_status); - } -} - -void CastAudioRenderer::OnWaiting(::media::WaitingReason reason) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - renderer_client_->OnWaiting(reason); -} - -void CastAudioRenderer::OnApplicationMediaInfoReceived( - ::media::mojom::CastApplicationMediaInfoPtr application_media_info) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - audio_output_service::CmaBackendParams backend_params; - backend_params.mutable_application_media_info()->set_application_session_id( - application_media_info->application_session_id); - *(backend_params.mutable_audio_decoder_config()) = - ConvertAudioDecoderConfig(demuxer_stream_->audio_decoder_config()); - - output_connection_ = - base::SequenceBound( - AudioIoThread::Get()->task_runner(), this, std::move(backend_params), - std::move(audio_socket_broker_pending_remote_)); - output_connection_.AsyncCall( - &audio_output_service::OutputStreamConnection::Connect); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_renderer.h chromium-132.0.6834.159/chromecast/media/audio/cast_audio_renderer.h --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_renderer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_renderer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,215 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_RENDERER_H_ -#define CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_RENDERER_H_ - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "base/threading/sequence_bound.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "chromecast/common/mojom/audio_socket.mojom.h" -#include "chromecast/media/audio/audio_output_service/output_stream_connection.h" -#include "media/base/audio_renderer.h" -#include "media/base/buffering_state.h" -#include "media/base/demuxer_stream.h" -#include "media/base/time_source.h" -#include "media/base/waiting.h" -#include "media/mojo/mojom/cast_application_media_info_manager.mojom.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace blink { -class BrowserInterfaceBrokerProxy; -} // namespace blink - -namespace media { -class AudioDecoderConfig; -class DecoderBuffer; -class DecryptingDemuxerStream; -class MediaLog; -} // namespace media - -namespace chromecast { -namespace media { - -// Cast implementation of ::media::AudioRenderer which sends decrypted audio -// buffers to the audio output service for decoding and rendering. -// Threading model: after constructed, ::media::AudioRenderer methods will be -// called on the main thread. ::media::TimeSource methods will be called from -// multiple threads (so lock is required for timeline related fields/methods). -// audio_output_service::OutputStreamConnection::Delegate methods will be called -// from an IO thread. -class CastAudioRenderer - : public ::media::AudioRenderer, - public ::media::TimeSource, - public audio_output_service::OutputStreamConnection::Delegate { - public: - CastAudioRenderer(scoped_refptr media_task_runner, - ::media::MediaLog* media_log, - blink::BrowserInterfaceBrokerProxy* interface_broker); - CastAudioRenderer(const CastAudioRenderer&) = delete; - CastAudioRenderer& operator=(const CastAudioRenderer&) = delete; - ~CastAudioRenderer() override; - - private: - enum class PlaybackState { - kStopped, - - // We've called Start(), but haven't received updated state. |start_time_| - // should not be used yet. - kStarting, - - // Playback is active. When the stream reaches EOS it stays in the kPlaying - // state. - kPlaying, - }; - - // ::media::AudioRenderer implementation: - void Initialize(::media::DemuxerStream* stream, - ::media::CdmContext* cdm_context, - ::media::RendererClient* client, - ::media::PipelineStatusCallback init_cb) override; - ::media::TimeSource* GetTimeSource() override; - void Flush(base::OnceClosure callback) override; - void StartPlaying() override; - void SetVolume(float volume) override; - void SetLatencyHint(std::optional latency_hint) override; - void SetPreservesPitch(bool preserves_pitch) override; - void SetWasPlayedWithUserActivationAndHighMediaEngagement( - bool was_played_with_user_activation_and_high_media_engagement) override; - - // ::media::TimeSource implementation: - void StartTicking() override; - void StopTicking() override; - void SetPlaybackRate(double playback_rate) override; - void SetMediaTime(base::TimeDelta time) override; - base::TimeDelta CurrentMediaTime() override; - bool GetWallClockTimes( - const std::vector& media_timestamps, - std::vector* wall_clock_times) override; - - // audio_output_service::OutputStreamConnection::Delegate implementation: - void OnBackendInitialized( - const audio_output_service::BackendInitializationStatus& status) override; - void OnNextBuffer(int64_t media_timestamp_microseconds, - int64_t reference_timestamp_microseconds, - int64_t delay_microseconds, - int64_t delay_timestamp_microseconds) override; - - void ScheduleFetchNextBuffer(); - void FetchNextBuffer(); - void OnEndOfStream(); - - // Returns current PlaybackState. - PlaybackState GetPlaybackState() EXCLUSIVE_LOCKS_REQUIRED(timeline_lock_); - - // Helper function used with DCHECKs to hold |timeline_lock_|. - bool CurrentPlaybackStateEquals(PlaybackState playback_state); - - // Used to update |state_|. - void SetPlaybackState(PlaybackState state) - EXCLUSIVE_LOCKS_REQUIRED(timeline_lock_); - - // Returns true if media clock is ticking and the rate is above 0.0. - bool IsTimeMoving() EXCLUSIVE_LOCKS_REQUIRED(timeline_lock_); - - // Updates TimelineFunction parameters after StopTicking() or - // SetPlaybackRate(0.0). Normally these parameters are provided by - // the audio output service, but this happens asynchronously and we need to - // make sure that StopTicking() and SetPlaybackRate(0.0) stop the media clock - // synchronously. Must be called before updating the |state_|. - void UpdateTimelineOnStop() EXCLUSIVE_LOCKS_REQUIRED(timeline_lock_); - - void UpdateAudioDecoderConfig(const ::media::AudioDecoderConfig& config); - - base::TimeDelta CurrentMediaTimeLocked() - EXCLUSIVE_LOCKS_REQUIRED(timeline_lock_); - - // Updates buffer state and notifies the |client_| if necessary. - void SetBufferState(::media::BufferingState buffer_state); - - void OnNewBuffersRead( - ::media::DemuxerStream::Status status, - ::media::DemuxerStream::DecoderBufferVector buffers_queue); - void OnNewBuffer(::media::DemuxerStream::Status read_status, - scoped_refptr<::media::DecoderBuffer> buffer); - void OnError(::media::PipelineStatus pipeline_status); - void OnDecryptingDemuxerInitialized(::media::PipelineStatus pipeline_status); - void OnWaiting(::media::WaitingReason reason); - void OnApplicationMediaInfoReceived( - ::media::mojom::CastApplicationMediaInfoPtr application_media_info); - void FlushInternal(); - - const scoped_refptr media_task_runner_; - ::media::MediaLog* const media_log_; - - scoped_refptr main_task_runner_; - ::media::DemuxerStream* demuxer_stream_ = nullptr; - std::unique_ptr<::media::DecryptingDemuxerStream> decrypting_stream_; - ::media::RendererClient* renderer_client_ = nullptr; - base::SequenceBound - output_connection_; - - bool is_pending_demuxer_read_ = false; - ::media::PipelineStatusCallback init_cb_; - base::OnceClosure flush_cb_; - - float volume_ = 1.0f; - - ::media::BufferingState buffer_state_ = ::media::BUFFERING_HAVE_NOTHING; - - base::TimeDelta last_pushed_timestamp_ = base::TimeDelta::Min(); - base::OneShotTimer read_timer_; - - // Indicates that StartPlaying() has been called. Note that playback doesn't - // start until StartTicking() is called. - bool renderer_started_ = false; - - // Indicates that StartTicking() has been called. - bool ticking_ = false; - - bool is_at_end_of_stream_ = false; - - // TimeSource interface is not single-threaded. The lock is used to guard - // fields that are accessed in the TimeSource implementation. - base::Lock timeline_lock_; - - float playback_rate_ GUARDED_BY(timeline_lock_) = 0.0f; - - // Should be changed by calling SetPlaybackState() on the main thread. - PlaybackState state_ GUARDED_BY(timeline_lock_) = PlaybackState::kStopped; - - base::TimeTicks reference_time_ GUARDED_BY(timeline_lock_); - base::TimeDelta media_pos_ GUARDED_BY(timeline_lock_); - - // TODO(b/173250111): update these values based on whether the media session - // is multiroom. - base::TimeDelta min_lead_time_ = base::Milliseconds(100); - base::TimeDelta max_lead_time_ = base::Milliseconds(500); - - mojo::PendingRemote<::media::mojom::CastApplicationMediaInfoManager> - application_media_info_manager_pending_remote_; - mojo::Remote<::media::mojom::CastApplicationMediaInfoManager> - application_media_info_manager_remote_; - mojo::PendingRemote - audio_socket_broker_pending_remote_; - - SEQUENCE_CHECKER(sequence_checker_); - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CAST_AUDIO_RENDERER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_audio_resampler_impl.cc chromium-132.0.6834.159/chromecast/media/audio/cast_audio_resampler_impl.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_audio_resampler_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_audio_resampler_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,169 +0,0 @@ -// 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 -#include -#include -#include - -#include "base/check_op.h" -#include "base/functional/bind.h" -#include "chromecast/media/api/cast_audio_resampler.h" -#include "media/base/sinc_resampler.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr int kRequestFrames = 128; - -class CastAudioResamplerImpl : public CastAudioResampler { - public: - CastAudioResamplerImpl(int channel_count, - int input_sample_rate, - int output_sample_rate) - : channel_count_(channel_count) { - DCHECK_GT(channel_count_, 0); - const double io_sample_rate_ratio = - static_cast(input_sample_rate) / output_sample_rate; - resamplers_.reserve(channel_count_); - buffered_input_.channels.reserve(channel_count_); - for (int c = 0; c < channel_count_; ++c) { - resamplers_.push_back(std::make_unique<::media::SincResampler>( - io_sample_rate_ratio, kRequestFrames, - base::BindRepeating(&CastAudioResamplerImpl::ReadCallback, - base::Unretained(this), c))); - buffered_input_.channels.push_back( - std::make_unique(kRequestFrames)); - } - } - - ~CastAudioResamplerImpl() override = default; - - CastAudioResamplerImpl(const CastAudioResamplerImpl&) = delete; - CastAudioResamplerImpl& operator=(const CastAudioResamplerImpl&) = delete; - - private: - void ResampleOneChunk(std::vector* output_channels) { - int output_frame_offset = output_channels[0].size(); - int output_frames = resamplers_[0]->ChunkSize(); - for (int c = 0; c < channel_count_; ++c) { - output_channels[c].resize(output_frame_offset + output_frames); - resamplers_[c]->Resample(output_frames, - output_channels[c].data() + output_frame_offset); - } - } - - void ReadCallback(int channel_index, int frames, float* dest) { - DCHECK_LE(buffered_input_.frames, frames); - std::copy_n(buffered_input_.channels[channel_index].get(), - buffered_input_.frames, dest); - - int frames_left = frames - buffered_input_.frames; - int dest_offset = buffered_input_.frames; - if (frames_left) { - CopyCurrentInputTo(channel_index, frames_left, dest + dest_offset); - } - - if (channel_index == channel_count_ - 1) { - buffered_input_.frames = 0; - } - } - - void CopyCurrentInputTo(int channel_index, int frames_to_copy, float* dest) { - DCHECK(current_input_.data); - DCHECK_LE(current_input_.frame_offset + frames_to_copy, - current_input_.frames); - std::copy_n(current_input_.data + channel_index * current_input_.frames + - current_input_.frame_offset, - frames_to_copy, dest); - if (channel_index == channel_count_ - 1) { - current_input_.frame_offset += frames_to_copy; - } - } - - // CastAudioResampler implementation: - void Resample(const float* input, - int num_frames, - std::vector* output_channels) override { - current_input_.data = input; - current_input_.frames = num_frames; - current_input_.frame_offset = 0; - - while (buffered_input_.frames + current_input_.frames - - current_input_.frame_offset >= - kRequestFrames) { - ResampleOneChunk(output_channels); - } - - int frames_left = current_input_.frames - current_input_.frame_offset; - DCHECK_LE(buffered_input_.frames + frames_left, kRequestFrames); - for (int c = 0; c < channel_count_; ++c) { - CopyCurrentInputTo( - c, frames_left, - buffered_input_.channels[c].get() + buffered_input_.frames); - } - buffered_input_.frames += frames_left; - - current_input_.data = nullptr; - current_input_.frames = 0; - current_input_.frame_offset = 0; - } - - void Flush(std::vector* output_channels) override { - // TODO(kmackay) May need some additional flushing to get out data stored in - // the SincResamplers. - if (buffered_input_.frames == 0) { - return; - } - - for (int c = 0; c < channel_count_; ++c) { - std::fill_n(buffered_input_.channels[c].get() + buffered_input_.frames, - kRequestFrames - buffered_input_.frames, 0); - } - buffered_input_.frames = kRequestFrames; - while (buffered_input_.frames) { - ResampleOneChunk(output_channels); - } - - for (int c = 0; c < channel_count_; ++c) { - resamplers_[c]->Flush(); - } - } - - int BufferedInputFrames() const override { - return buffered_input_.frames + - std::round(resamplers_[0]->BufferedFrames()); - } - - const int channel_count_; - - std::vector> resamplers_; - - struct InputBuffer { - std::vector> channels; - int frames = 0; - } buffered_input_; - - struct InputData { - const float* data = nullptr; - int frames = 0; - int frame_offset = 0; - } current_input_; -}; - -} // namespace - -// static -std::unique_ptr CastAudioResampler::Create( - int channel_count, - int input_sample_rate, - int output_sample_rate) { - return std::make_unique( - channel_count, input_sample_rate, output_sample_rate); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cast_channel_mixer_impl.cc chromium-132.0.6834.159/chromecast/media/audio/cast_channel_mixer_impl.cc --- chromium-132.0.6834.110/chromecast/media/audio/cast_channel_mixer_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cast_channel_mixer_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/api/cast_channel_mixer.h" - -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "media/base/audio_bus.h" -#include "media/base/channel_layout.h" -#include "media/base/channel_mixer.h" - -namespace chromecast { -namespace media { -namespace { - -void SetChannelData(::media::AudioBus* bus, float* data, int num_frames) { - bus->set_frames(num_frames); - for (int channel = 0; channel < bus->channels(); channel++) { - bus->SetChannelData(channel, data + num_frames * channel); - } -} - -// A wrapper of ::media::ChannelMixer. -class CastChannelMixerImpl : public CastChannelMixer { - public: - CastChannelMixerImpl(ChannelLayout input, ChannelLayout output); - ~CastChannelMixerImpl() override; - - const float* Transform(const float* input, int num_frames) override; - - private: - std::unique_ptr<::media::ChannelMixer> channel_mixer_; - - std::unique_ptr<::media::AudioBus> input_bus_; - std::unique_ptr<::media::AudioBus> output_bus_; - - std::vector output_buffer_; -}; - -CastChannelMixerImpl::CastChannelMixerImpl(ChannelLayout input, - ChannelLayout output) { - ::media::ChannelLayout input_layout = - DecoderConfigAdapter::ToMediaChannelLayout(input); - ::media::ChannelLayout output_layout = - DecoderConfigAdapter::ToMediaChannelLayout(output); - channel_mixer_ = std::make_unique<::media::ChannelMixer>( - input_layout, ::media::ChannelLayoutToChannelCount(input_layout), - output_layout, ::media::ChannelLayoutToChannelCount(output_layout)); - input_bus_ = ::media::AudioBus::CreateWrapper( - ::media::ChannelLayoutToChannelCount(input_layout)); - output_bus_ = ::media::AudioBus::CreateWrapper( - ::media::ChannelLayoutToChannelCount(output_layout)); -} - -CastChannelMixerImpl::~CastChannelMixerImpl() = default; - -const float* CastChannelMixerImpl::Transform(const float* input, - int num_frames) { - SetChannelData(input_bus_.get(), const_cast(input), num_frames); - - if (output_buffer_.size() < - static_cast(num_frames * output_bus_->channels())) { - output_buffer_.resize(num_frames * output_bus_->channels()); - } - SetChannelData(output_bus_.get(), output_buffer_.data(), num_frames); - - channel_mixer_->Transform(input_bus_.get(), output_bus_.get()); - return output_buffer_.data(); -} - -} // namespace - -std::unique_ptr CastChannelMixer::Create( - ChannelLayout input, - ChannelLayout output) { - return std::make_unique(input, output); -} - -} // namespace media -} // namespace chromecast \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cma_audio_output.cc chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output.cc --- chromium-132.0.6834.110/chromecast/media/audio/cma_audio_output.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,210 +0,0 @@ -// 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 "chromecast/media/audio/cma_audio_output.h" - -#include -#include -#include - -#include "base/logging.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/audio_device_description.h" - -namespace chromecast { -namespace media { - -namespace { - -AudioContentType GetContentType(const std::string& device_id) { - if (::media::AudioDeviceDescription::IsCommunicationsDevice(device_id)) { - return AudioContentType::kCommunication; - } - return AudioContentType::kMedia; -} - -int GetSampleSize(SampleFormat sample_format) { - switch (sample_format) { - case kUnknownSampleFormat: - return 0; - case kSampleFormatU8: - case kSampleFormatPlanarU8: - return sizeof(uint8_t); - case kSampleFormatS16: - case kSampleFormatPlanarS16: - return sizeof(int16_t); - case kSampleFormatS32: - case kSampleFormatPlanarS32: - return sizeof(int32_t); - case kSampleFormatF32: - case kSampleFormatPlanarF32: - return sizeof(float); - case kSampleFormatS24: - return 3; - } -} - -} // namespace - -CmaAudioOutput::CmaAudioOutput( - const ::media::AudioParameters& audio_params, - SampleFormat sample_format, - const std::string& device_id, - const std::string& application_session_id, - MediaPipelineDeviceParams::MediaSyncType sync_type, - bool use_hw_av_sync, - int audio_track_session_id, - CmaBackendFactory* cma_backend_factory, - CmaBackend::Decoder::Delegate* delegate) - : audio_params_(audio_params), - sample_size_(GetSampleSize(sample_format)), - use_hw_av_sync_(use_hw_av_sync), - delegate_(delegate), - timestamp_helper_(audio_params_.sample_rate()) { - DCHECK(delegate_); - Initialize(sample_format, device_id, application_session_id, sync_type, - audio_track_session_id, cma_backend_factory); -} - -CmaAudioOutput::~CmaAudioOutput() = default; - -void CmaAudioOutput::Initialize( - SampleFormat sample_format, - const std::string& device_id, - const std::string& application_session_id, - MediaPipelineDeviceParams::MediaSyncType sync_type, - int audio_track_session_id, - CmaBackendFactory* cma_backend_factory) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - DCHECK(cma_backend_factory); - - auto cma_backend_task_runner = std::make_unique(); - MediaPipelineDeviceParams device_params( - sync_type, MediaPipelineDeviceParams::kAudioStreamNormal, - cma_backend_task_runner.get(), GetContentType(device_id), device_id); - device_params.session_id = application_session_id; - auto cma_backend = cma_backend_factory->CreateBackend(device_params); - if (!cma_backend) { - return; - } - - auto* audio_decoder = cma_backend->CreateAudioDecoder(); - if (!audio_decoder) { - return; - } - audio_decoder->SetDelegate(delegate_); - - AudioConfig audio_config; - audio_config.codec = kCodecPCM; - audio_config.channel_layout = - DecoderConfigAdapter::ToChannelLayout(audio_params_.channel_layout()); - audio_config.sample_format = sample_format; - audio_config.bytes_per_channel = sample_size_; - audio_config.channel_number = audio_params_.channels(); - audio_config.samples_per_second = audio_params_.sample_rate(); - audio_config.use_hw_av_sync = use_hw_av_sync_; - audio_config.audio_track_session_id = audio_track_session_id; - DCHECK(IsValidConfig(audio_config)); - // Need to first set the config of the audio decoder then initialize the cma - // backend if succeed. - if (!audio_decoder->SetConfig(audio_config) || !cma_backend->Initialize()) { - return; - } - - cma_backend_task_runner_ = std::move(cma_backend_task_runner); - cma_backend_ = std::move(cma_backend); - audio_decoder_ = audio_decoder; - - timestamp_helper_.SetBaseTimestamp(base::TimeDelta()); -} - -bool CmaAudioOutput::Start(int64_t start_pts) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - if (!cma_backend_ || !cma_backend_->Start(start_pts)) { - return false; - } - return true; -} - -void CmaAudioOutput::Stop() { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - if (cma_backend_) { - cma_backend_->Stop(); - } -} - -bool CmaAudioOutput::Pause() { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - if (!cma_backend_ || !cma_backend_->Pause()) { - return false; - } - return true; -} - -bool CmaAudioOutput::Resume() { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - if (!cma_backend_ || !cma_backend_->Resume()) { - return false; - } - return true; -} - -bool CmaAudioOutput::SetVolume(double volume) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - if (!audio_decoder_) { - return false; - } - return audio_decoder_->SetVolume(volume); -} - -void CmaAudioOutput::PushBuffer( - scoped_refptr decoder_buffer, - bool is_silence) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - DCHECK_GT(decoder_buffer->data_size(), 0u); - DCHECK_EQ( - decoder_buffer->data_size() % (sample_size_ * audio_params_.channels()), - 0u); - DCHECK(audio_decoder_); - - if (!is_silence) { - if (!use_hw_av_sync_) { - // Keep the timestamp of the buffer if the stream is on hardware av sync - // mode. - decoder_buffer->set_timestamp(timestamp_helper_.GetTimestamp()); - } - int frame_count = - decoder_buffer->data_size() / (sample_size_ * audio_params_.channels()); - timestamp_helper_.AddFrames(frame_count); - } - CmaBackend::BufferStatus status = - audio_decoder_->PushBuffer(std::move(decoder_buffer)); - if (status != CmaBackend::BufferStatus::kBufferPending) - delegate_->OnPushBufferComplete(status); -} - -CmaBackend::AudioDecoder::RenderingDelay CmaAudioOutput::GetRenderingDelay() { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - DCHECK(audio_decoder_); - return audio_decoder_->GetRenderingDelay(); -} - -CmaBackend::AudioDecoder::AudioTrackTimestamp -CmaAudioOutput::GetAudioTrackTimestamp() { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - DCHECK(audio_decoder_); - return audio_decoder_->GetAudioTrackTimestamp(); -} - -int64_t CmaAudioOutput::GetTotalFrames() { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - return timestamp_helper_.frame_count(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cma_audio_output.h chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output.h --- chromium-132.0.6834.110/chromecast/media/audio/cma_audio_output.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_AUDIO_CMA_AUDIO_OUTPUT_H_ -#define CHROMECAST_MEDIA_AUDIO_CMA_AUDIO_OUTPUT_H_ - -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/scoped_refptr.h" -#include "base/threading/thread_checker.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "media/base/audio_parameters.h" -#include "media/base/audio_timestamp_helper.h" - -namespace chromecast { - -class TaskRunnerImpl; - -namespace media { - -class CastDecoderBufferImpl; -class CmaBackendFactory; - -class CmaAudioOutput { - public: - CmaAudioOutput(const ::media::AudioParameters& audio_params, - SampleFormat sample_format, - const std::string& device_id, - const std::string& application_session_id, - MediaPipelineDeviceParams::MediaSyncType sync_type, - bool use_hw_av_sync, - int audio_track_session_id, - CmaBackendFactory* cma_backend_factory, - CmaBackend::Decoder::Delegate* delegate); - // Disallow copy and assign. - CmaAudioOutput(const CmaAudioOutput&) = delete; - CmaAudioOutput& operator=(const CmaAudioOutput&) = delete; - ~CmaAudioOutput(); - - bool Start(int64_t start_pts); - void Stop(); - bool Pause(); - bool Resume(); - bool SetVolume(double volume); - - void PushBuffer(scoped_refptr decoder_buffer, - bool is_silence); - CmaBackend::AudioDecoder::RenderingDelay GetRenderingDelay(); - CmaBackend::AudioDecoder::AudioTrackTimestamp GetAudioTrackTimestamp(); - int64_t GetTotalFrames(); - - private: - void Initialize(SampleFormat sample_format, - const std::string& device_id, - const std::string& application_session_id, - MediaPipelineDeviceParams::MediaSyncType sync_type, - int audio_track_session_id, - CmaBackendFactory* cma_backend_factory); - - const ::media::AudioParameters audio_params_; - const int sample_size_; - const bool use_hw_av_sync_; - CmaBackend::Decoder::Delegate* const delegate_; - - ::media::AudioTimestampHelper timestamp_helper_; - std::unique_ptr cma_backend_task_runner_; - std::unique_ptr cma_backend_; - CmaBackend::AudioDecoder* audio_decoder_ = nullptr; - - THREAD_CHECKER(media_thread_checker_); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CMA_AUDIO_OUTPUT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cma_audio_output_stream.cc chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output_stream.cc --- chromium-132.0.6834.110/chromecast/media/audio/cma_audio_output_stream.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output_stream.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,292 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/cma_audio_output_stream.h" - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/synchronization/waitable_event.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/audio/cma_audio_output.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/base/default_monotonic_clock.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/audio_device_description.h" -#include "media/base/audio_bus.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr base::TimeDelta kRenderBufferSize = base::Seconds(4); - -} // namespace - -CmaAudioOutputStream::CmaAudioOutputStream( - const ::media::AudioParameters& audio_params, - base::TimeDelta buffer_duration, - const std::string& device_id, - CmaBackendFactory* cma_backend_factory) - : is_audio_prefetch_(audio_params.effects() & - ::media::AudioParameters::AUDIO_PREFETCH), - audio_params_(audio_params), - device_id_(device_id), - cma_backend_factory_(cma_backend_factory), - buffer_duration_(buffer_duration), - render_buffer_size_estimate_(kRenderBufferSize) { - DCHECK(cma_backend_factory_); - DETACH_FROM_THREAD(media_thread_checker_); - - LOG(INFO) << "Enable audio prefetch: " << is_audio_prefetch_; -} - -CmaAudioOutputStream::~CmaAudioOutputStream() = default; - -void CmaAudioOutputStream::SetRunning(bool running) { - base::AutoLock lock(running_lock_); - running_ = running; -} - -void CmaAudioOutputStream::Initialize( - const std::string& application_session_id) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - DCHECK_EQ(cma_backend_state_, CmaBackendState::kUninitialized); - // If AUDIO_PREFETCH is enabled, we're able to push audio ahead of - // realtime. Set the sync mode to kModeSyncPts to allow cma backend to - // buffer the early pushed data, instead of dropping them. - output_ = std::make_unique( - audio_params_, kSampleFormatS16, device_id_, application_session_id, - audio_params_.effects() & ::media::AudioParameters::AUDIO_PREFETCH - ? MediaPipelineDeviceParams::kModeSyncPts - : MediaPipelineDeviceParams::kModeIgnorePts, - false /*use_hw_av_sync*/, 0 /*audio_track_session_id*/, - cma_backend_factory_, this); - cma_backend_state_ = CmaBackendState::kStopped; - - audio_bus_ = ::media::AudioBus::Create(audio_params_); -} - -void CmaAudioOutputStream::Start( - ::media::AudioOutputStream::AudioSourceCallback* source_callback) { - DCHECK(source_callback); - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - if (cma_backend_state_ == CmaBackendState::kPendingClose) - return; - - source_callback_ = source_callback; - if (encountered_error_) { - source_callback_->OnError( - ::media::AudioOutputStream::AudioSourceCallback::ErrorType::kUnknown); - return; - } - - if (cma_backend_state_ == CmaBackendState::kPaused || - cma_backend_state_ == CmaBackendState::kStopped) { - if (cma_backend_state_ == CmaBackendState::kPaused) { - if (!output_->Resume()) { - encountered_error_ = true; - source_callback_->OnError(::media::AudioOutputStream:: - AudioSourceCallback::ErrorType::kUnknown); - return; - } - } else { - if (!output_->Start(0)) { - encountered_error_ = true; - source_callback_->OnError(::media::AudioOutputStream:: - AudioSourceCallback::ErrorType::kUnknown); - return; - } - render_buffer_size_estimate_ = kRenderBufferSize; - } - next_push_time_ = base::TimeTicks::Now(); - last_push_complete_time_ = base::TimeTicks::Now(); - cma_backend_state_ = CmaBackendState::kStarted; - } - - if (!push_in_progress_) { - PushBuffer(); - } -} - -void CmaAudioOutputStream::Stop(base::WaitableEvent* finished) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - // Prevent further pushes to the audio buffer after stopping. - push_timer_.Stop(); - // Don't actually stop the backend. Stop() gets called when the stream is - // paused. We rely on Flush() to stop the backend. - if (output_) { - output_->Pause(); - cma_backend_state_ = CmaBackendState::kPaused; - } - source_callback_ = nullptr; - finished->Signal(); -} - -void CmaAudioOutputStream::Flush(base::WaitableEvent* finished) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - // Prevent further pushes to the audio buffer after stopping. - push_timer_.Stop(); - - if (output_ && (cma_backend_state_ == CmaBackendState::kPaused || - cma_backend_state_ == CmaBackendState::kStarted)) { - output_->Stop(); - cma_backend_state_ = CmaBackendState::kStopped; - } - push_in_progress_ = false; - source_callback_ = nullptr; - finished->Signal(); -} - -void CmaAudioOutputStream::Close(base::OnceClosure closure) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - // Prevent further pushes to the audio buffer after stopping. - push_timer_.Stop(); - // Only stop the backend if it was started. - if (output_ && cma_backend_state_ != CmaBackendState::kStopped) { - output_->Stop(); - } - push_in_progress_ = false; - source_callback_ = nullptr; - cma_backend_state_ = CmaBackendState::kPendingClose; - - audio_bus_.reset(); - output_.reset(); - - std::move(closure).Run(); -} - -void CmaAudioOutputStream::SetVolume(double volume) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - if (!output_) { - return; - } - if (encountered_error_) { - return; - } - output_->SetVolume(volume); -} - -void CmaAudioOutputStream::PushBuffer() { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - - // Acquire running_lock_ for the scope of this push call to - // prevent the source callback from closing the output stream - // mid-push. - base::AutoLock lock(running_lock_); - DCHECK(!push_in_progress_); - - // Do not fill more buffers if we have stopped running. - if (!running_) - return; - - // It is possible that this function is called when we are stopped. - // Return quickly if so. - if (!source_callback_ || encountered_error_ || - cma_backend_state_ != CmaBackendState::kStarted) { - return; - } - - CmaBackend::AudioDecoder::RenderingDelay rendering_delay = - output_->GetRenderingDelay(); - - base::TimeDelta delay; - if (rendering_delay.delay_microseconds < 0 || - rendering_delay.timestamp_microseconds < 0) { - // This occurs immediately after start/resume when there isn't a good - // estimate of the buffer delay. Use the last known good delay. - delay = last_rendering_delay_; - } else { - // The rendering delay to account for buffering is not included in - // rendering_delay.delay_microseconds but is in delay_timestamp which isn't - // used by AudioOutputStreamImpl. - delay = base::Microseconds(rendering_delay.delay_microseconds + - rendering_delay.timestamp_microseconds - - MonotonicClockNow()); - if (delay.InMicroseconds() < 0) { - delay = base::TimeDelta(); - } - } - last_rendering_delay_ = delay; - - int frame_count = source_callback_->OnMoreData(delay, base::TimeTicks(), {}, - audio_bus_.get()); - - DVLOG(3) << "frames_filled=" << frame_count << " with latency=" << delay; - - if (frame_count == 0) { - OnPushBufferComplete(CmaBackend::BufferStatus::kBufferFailed); - return; - } - auto decoder_buffer = base::MakeRefCounted( - frame_count * audio_bus_->channels() * sizeof(int16_t)); - audio_bus_->ToInterleaved<::media::SignedInt16SampleTypeTraits>( - frame_count, reinterpret_cast(decoder_buffer->writable_data())); - push_in_progress_ = true; - output_->PushBuffer(std::move(decoder_buffer), false /*is_silence*/); -} - -void CmaAudioOutputStream::OnPushBufferComplete(BufferStatus status) { - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - DCHECK_NE(status, CmaBackend::BufferStatus::kBufferPending); - - push_in_progress_ = false; - - if (!source_callback_ || encountered_error_) - return; - - DCHECK_EQ(cma_backend_state_, CmaBackendState::kStarted); - - if (status != CmaBackend::BufferStatus::kBufferSuccess) { - source_callback_->OnError( - ::media::AudioOutputStream::AudioSourceCallback::ErrorType::kUnknown); - return; - } - - // Schedule next push buffer. - const base::TimeTicks now = base::TimeTicks::Now(); - base::TimeDelta delay; - if (is_audio_prefetch_) { - // For multizone-playback, we don't care about AV sync and want to pre-fetch - // audio. - render_buffer_size_estimate_ -= buffer_duration_; - render_buffer_size_estimate_ += now - last_push_complete_time_; - last_push_complete_time_ = now; - - if (render_buffer_size_estimate_ >= buffer_duration_) { - delay = base::Seconds(0); - } else { - delay = buffer_duration_; - } - } else { - next_push_time_ = std::max(now, next_push_time_ + buffer_duration_); - delay = next_push_time_ - now; - } - - DVLOG(3) << "render_buffer_size_estimate_=" << render_buffer_size_estimate_ - << " delay=" << delay << " buffer_duration_=" << buffer_duration_; - - push_timer_.Start(FROM_HERE, delay, this, &CmaAudioOutputStream::PushBuffer); -} - -void CmaAudioOutputStream::OnDecoderError() { - DLOG(INFO) << this << ": " << __func__; - DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); - - encountered_error_ = true; - if (source_callback_) { - source_callback_->OnError( - ::media::AudioOutputStream::AudioSourceCallback::ErrorType::kUnknown); - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/cma_audio_output_stream.h chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output_stream.h --- chromium-132.0.6834.110/chromecast/media/audio/cma_audio_output_stream.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/cma_audio_output_stream.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,105 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_CMA_AUDIO_OUTPUT_STREAM_H_ -#define CHROMECAST_MEDIA_AUDIO_CMA_AUDIO_OUTPUT_STREAM_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/synchronization/lock.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "chromecast/media/api/cma_backend.h" -#include "media/audio/audio_io.h" -#include "media/base/audio_parameters.h" - -namespace base { -class WaitableEvent; -} // namespace base - -namespace media { -class AudioBus; -} // namespace media - -namespace chromecast { - -class TaskRunnerImpl; - -namespace media { - -class CmaAudioOutput; -class CmaBackendFactory; - -class CmaAudioOutputStream : public CmaBackend::Decoder::Delegate { - public: - CmaAudioOutputStream(const ::media::AudioParameters& audio_params, - base::TimeDelta buffer_duration, - const std::string& device_id, - CmaBackendFactory* cma_backend_factory); - - CmaAudioOutputStream(const CmaAudioOutputStream&) = delete; - CmaAudioOutputStream& operator=(const CmaAudioOutputStream&) = delete; - - ~CmaAudioOutputStream() override; - - void SetRunning(bool running); - void Initialize(const std::string& application_session_id); - void Start(::media::AudioOutputStream::AudioSourceCallback* source_callback); - void Stop(base::WaitableEvent* finished); - void Flush(base::WaitableEvent* finished); - void Close(base::OnceClosure closure); - void SetVolume(double volume); - - private: - enum class CmaBackendState { - kUninitialized, - kStopped, - kPaused, - kStarted, - kPendingClose, - }; - - void PushBuffer(); - - // CmaBackend::Decoder::Delegate implementation: - void OnEndOfStream() override {} - void OnDecoderError() override; - void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override {} - void OnVideoResolutionChanged(const Size& size) override {} - void OnPushBufferComplete(BufferStatus status) override; - - const bool is_audio_prefetch_; - - const ::media::AudioParameters audio_params_; - const std::string device_id_; - CmaBackendFactory* const cma_backend_factory_; - std::unique_ptr output_; - - base::Lock running_lock_; - bool running_ = true; - CmaBackendState cma_backend_state_ = CmaBackendState::kUninitialized; - const base::TimeDelta buffer_duration_; - std::unique_ptr<::media::AudioBus> audio_bus_; - base::OneShotTimer push_timer_; - bool push_in_progress_ = false; - bool encountered_error_ = false; - base::TimeTicks next_push_time_; - base::TimeTicks last_push_complete_time_; - base::TimeDelta last_rendering_delay_; - base::TimeDelta render_buffer_size_estimate_; - ::media::AudioOutputStream::AudioSourceCallback* source_callback_ = nullptr; - - THREAD_CHECKER(media_thread_checker_); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_CMA_AUDIO_OUTPUT_STREAM_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/external_audio_pipeline_dummy.cc chromium-132.0.6834.159/chromecast/media/audio/external_audio_pipeline_dummy.cc --- chromium-132.0.6834.110/chromecast/media/audio/external_audio_pipeline_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/external_audio_pipeline_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_INTERNAL_MEDIA_AUDIO_EXTERNAL_AUDIO_PIPELINE_DUMMY_H_ -#define CHROMECAST_INTERNAL_MEDIA_AUDIO_EXTERNAL_AUDIO_PIPELINE_DUMMY_H_ - -#include "chromecast/public/media/external_audio_pipeline_shlib.h" - -// We redefine what is already available in chromium's base/logging.h because -// we want to avoid having that dependency in dummy implementation. When OEMs -// swap in their implementation it complains about missing symbols. -#include // abort() -#define NOTREACHED() abort() - -namespace chromecast { -namespace media { - -bool ExternalAudioPipelineShlib::IsSupported() { - return false; -} - -void ExternalAudioPipelineShlib::AddExternalMediaVolumeChangeRequestObserver( - ExternalMediaVolumeChangeRequestObserver* observer) { - NOTREACHED(); -} - -void ExternalAudioPipelineShlib::RemoveExternalMediaVolumeChangeRequestObserver( - ExternalMediaVolumeChangeRequestObserver* observer) { - NOTREACHED(); -} - -void ExternalAudioPipelineShlib::SetExternalMediaVolume(float level) { - NOTREACHED(); -} - -void ExternalAudioPipelineShlib::SetExternalMediaMuted(bool muted) { - NOTREACHED(); -} - -void ExternalAudioPipelineShlib::AddExternalLoopbackAudioObserver( - LoopbackAudioObserver* observer) { - NOTREACHED(); -} - -void ExternalAudioPipelineShlib::RemoveExternalLoopbackAudioObserver( - LoopbackAudioObserver* observer) { - NOTREACHED(); -} - -void ExternalAudioPipelineShlib::AddExternalMediaMetadataChangeObserver( - ExternalMediaMetadataChangeObserver* observer) { - NOTREACHED(); -} - -void ExternalAudioPipelineShlib::RemoveExternalMediaMetadataChangeObserver( - ExternalMediaMetadataChangeObserver* observer) { - NOTREACHED(); -} - -std::unique_ptr -ExternalAudioPipelineShlib::CreateMixerOutputStream() { - return nullptr; -} - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_INTERNAL_MEDIA_AUDIO_EXTERNAL_AUDIO_PIPELINE_DUMMY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/external_audio_pipeline_sample.cc chromium-132.0.6834.159/chromecast/media/audio/external_audio_pipeline_sample.cc --- chromium-132.0.6834.110/chromecast/media/audio/external_audio_pipeline_sample.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/external_audio_pipeline_sample.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,131 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "base/check.h" -#include "base/ranges/algorithm.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/external_audio_pipeline_shlib.h" -#include "chromecast/public/media/mixer_output_stream.h" - -using ExternalMediaMetadataChangeObserver = chromecast::media:: - ExternalAudioPipelineShlib::ExternalMediaMetadataChangeObserver; - -namespace chromecast { -namespace media { - -class TestLoopBack { - public: - void OnData(const float* data, - int data_size, - MixerOutputStream* stream, - int channels) { - auto delay = stream->GetRenderingDelay(); - int64_t delay_ms = delay.timestamp_microseconds + delay.delay_microseconds; - for (auto* observer : observers_) { - observer->OnLoopbackAudio( - delay_ms, kSampleFormatF32, stream->GetSampleRate(), channels, - reinterpret_cast(const_cast(data)), - data_size * sizeof(float)); - } - } - - void AddObserver( - ExternalAudioPipelineShlib::LoopbackAudioObserver* observer) { - observers_.push_back(observer); - } - - void RemoveObserver( - ExternalAudioPipelineShlib::LoopbackAudioObserver* observer) { - auto it = base::ranges::find(observers_, observer); - if (it != observers_.end()) { - observers_.erase(it); - } - observer->OnRemoved(); - } - - private: - std::vector observers_; -}; - -TestLoopBack g_test_loop_back; - -class MixerOutputStreamTest : public MixerOutputStream { - public: - explicit MixerOutputStreamTest(TestLoopBack* test_loop_back) - : stream_(MixerOutputStream::Create()), test_loop_back_(test_loop_back) { - DCHECK(test_loop_back_); - } - - bool Start(int requested_sample_rate, int channels) override { - channels_ = channels; - return stream_->Start(requested_sample_rate, channels); - } - - int GetSampleRate() override { return stream_->GetSampleRate(); } - - MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelay() - override { - return stream_->GetRenderingDelay(); - } - - int OptimalWriteFramesCount() override { - return stream_->OptimalWriteFramesCount(); - } - - bool Write(const float* data, - int data_size, - bool* out_playback_interrupted) override { - test_loop_back_->OnData(data, data_size, this, channels_); - return stream_->Write(data, data_size, out_playback_interrupted); - } - - void Stop() override { return stream_->Stop(); } - - private: - std::unique_ptr stream_; - TestLoopBack* test_loop_back_; - int channels_ = 0; -}; - -bool ExternalAudioPipelineShlib::IsSupported() { - return true; -} - -void ExternalAudioPipelineShlib::AddExternalMediaVolumeChangeRequestObserver( - ExternalMediaVolumeChangeRequestObserver* observer) {} - -void ExternalAudioPipelineShlib::RemoveExternalMediaVolumeChangeRequestObserver( - ExternalMediaVolumeChangeRequestObserver* observer) {} - -void ExternalAudioPipelineShlib::SetExternalMediaVolume(float level) {} - -void ExternalAudioPipelineShlib::SetExternalMediaMuted(bool muted) {} - -void ExternalAudioPipelineShlib::AddExternalLoopbackAudioObserver( - LoopbackAudioObserver* observer) { - g_test_loop_back.AddObserver(observer); -} - -void ExternalAudioPipelineShlib::RemoveExternalLoopbackAudioObserver( - LoopbackAudioObserver* observer) { - g_test_loop_back.RemoveObserver(observer); -} - -void ExternalAudioPipelineShlib::AddExternalMediaMetadataChangeObserver( - ExternalMediaMetadataChangeObserver* observer) {} - -void ExternalAudioPipelineShlib::RemoveExternalMediaMetadataChangeObserver( - ExternalMediaMetadataChangeObserver* observer) {} - -std::unique_ptr -ExternalAudioPipelineShlib::CreateMixerOutputStream() { - return std::make_unique(&g_test_loop_back); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/fake_external_audio_pipeline.cc chromium-132.0.6834.159/chromecast/media/audio/fake_external_audio_pipeline.cc --- chromium-132.0.6834.110/chromecast/media/audio/fake_external_audio_pipeline.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/fake_external_audio_pipeline.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,277 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "base/check.h" -#include "base/no_destructor.h" -#include "base/ranges/algorithm.h" -#include "chromecast/media/audio/fake_external_audio_pipeline_support.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/external_audio_pipeline_shlib.h" -#include "chromecast/public/media/mixer_output_stream.h" - -namespace chromecast { -namespace media { -namespace { - -// Library implementation for media volume/mute testing part. It stores -// observers for sending volume/mute change requests and stores volume/muted. -class TestMediaVolumeMute { - public: - TestMediaVolumeMute() = default; - - TestMediaVolumeMute(const TestMediaVolumeMute&) = delete; - TestMediaVolumeMute& operator=(const TestMediaVolumeMute&) = delete; - - // Called by library. - void AddExternalMediaVolumeChangeRequestObserver( - ExternalAudioPipelineShlib::ExternalMediaVolumeChangeRequestObserver* - observer) { - volume_change_request_observer_ = observer; - } - void RemoveExternalMediaVolumeChangeRequestObserver( - ExternalAudioPipelineShlib::ExternalMediaVolumeChangeRequestObserver* - observer) { - volume_change_request_observer_ = nullptr; - } - - void SetVolume(float volume) { volume_ = volume; } - void SetMuted(bool muted) { muted_ = muted; } - - protected: - // Used by derived class for FakeExternalAudioPipelineSupport. - ExternalAudioPipelineShlib::ExternalMediaVolumeChangeRequestObserver* - volume_change_request_observer_ = nullptr; - float volume_ = 0; - bool muted_ = false; -}; - -// Library implementation for loopback data testing part. It stores -// CastMediaShlib observers and does loopback audio data to it. -class TestLoopBack { - public: - TestLoopBack() = default; - - TestLoopBack(const TestLoopBack&) = delete; - TestLoopBack& operator=(const TestLoopBack&) = delete; - - // Called from FakeMixerOutputStream. - void OnData(const float* data, - int data_size, - MixerOutputStream* stream, - int channels) { - auto delay = stream->GetRenderingDelay(); - int64_t delay_microseconds = - delay.timestamp_microseconds + delay.delay_microseconds; - for (auto* observer : observers_) { - observer->OnLoopbackAudio( - delay_microseconds, kSampleFormatF32, stream->GetSampleRate(), - channels, reinterpret_cast(const_cast(data)), - data_size * sizeof(float)); - } - } - // Called from library. - void AddExternalLoopbackAudioObserver( - ExternalAudioPipelineShlib::LoopbackAudioObserver* observer) { - observers_.push_back(observer); - } - - void RemoveExternalLoopbackAudioObserver( - ExternalAudioPipelineShlib::LoopbackAudioObserver* observer) { - auto it = base::ranges::find(observers_, observer); - if (it != observers_.end()) { - observers_.erase(it); - } - observer->OnRemoved(); - } - - protected: - // Used by derived class for FakeExternalAudioPipelineSupport. - std::vector observers_; -}; - -class TestMediaMetadata { - public: - TestMediaMetadata() = default; - - TestMediaMetadata(const TestMediaMetadata&) = delete; - TestMediaMetadata& operator=(const TestMediaMetadata&) = delete; - - // Called from library. - void AddExternalMediaMetadataChangeObserver( - ExternalAudioPipelineShlib::ExternalMediaMetadataChangeObserver* - observer) { - media_metadata_change_observer_ = observer; - } - void RemoveExternalMediaMetadataChangeObserver( - ExternalAudioPipelineShlib::ExternalMediaMetadataChangeObserver*) { - media_metadata_change_observer_ = nullptr; - } - - protected: - ExternalAudioPipelineShlib::ExternalMediaMetadataChangeObserver* - media_metadata_change_observer_ = nullptr; -}; - -// Final class includes library implementation for testing media volume/mute -// + loopback and FakeExternalAudioPipelineSupport implementation. -class TestMedia : public TestMediaVolumeMute, - public TestLoopBack, - public TestMediaMetadata, - public testing::FakeExternalAudioPipelineSupport { - public: - TestMedia() = default; - - TestMedia(const TestMedia&) = delete; - TestMedia& operator=(const TestMedia&) = delete; - - bool supported() const { return supported_; } - - // FakeExternalAudioPipelineSupport implementation: - void SetSupported() override { supported_ = true; } - - void Reset() override { - supported_ = false; - volume_change_request_observer_ = nullptr; - volume_ = 0; - muted_ = false; - observers_.clear(); - } - - float GetVolume() const override { return volume_; } - bool IsMuted() const override { return muted_; } - - void OnVolumeChangeRequest(float level) override { - CHECK(volume_change_request_observer_); - volume_change_request_observer_->OnVolumeChangeRequest(level); - } - void OnMuteChangeRequest(bool muted) override { - CHECK(volume_change_request_observer_); - volume_change_request_observer_->OnMuteChangeRequest(muted); - } - - void UpdateExternalMediaMetadata( - const ExternalAudioPipelineShlib::ExternalMediaMetadata& metadata) - override { - if (media_metadata_change_observer_) { - media_metadata_change_observer_->OnExternalMediaMetadataChanged(metadata); - } - } - - private: - bool supported_ = false; -}; - -TestMedia* GetTestMedia() { - static base::NoDestructor g_test_media; - return g_test_media.get(); -} - -// MixerOutputStream implementation, it will be created by -// ExternalAudioPipelineShlib::CreateMixerOutputStream. -class FakeMixerOutputStream : public MixerOutputStream { - public: - FakeMixerOutputStream() : test_loop_back_(GetTestMedia()) {} - - FakeMixerOutputStream(const FakeMixerOutputStream&) = delete; - FakeMixerOutputStream& operator=(const FakeMixerOutputStream&) = delete; - - // MixerOutputStream implementation: - bool Start(int requested_sample_rate, int channels) override { - sample_rate_ = requested_sample_rate; - channels_ = channels; - return true; - } - - void Stop() override {} - - int GetNumChannels() override { return channels_; } - int GetSampleRate() override { return sample_rate_; } - - MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelay() - override { - return MediaPipelineBackend::AudioDecoder::RenderingDelay(); - } - - int OptimalWriteFramesCount() override { return 256; } - - bool Write(const float* data, - int data_size, - bool* out_playback_interrupted) override { - // To check OnLoopbackInterrupted. - *out_playback_interrupted = true; - // Loopback data. - test_loop_back_->OnData(data, data_size, this, channels_); - return true; - } - - private: - int sample_rate_ = 0; - int channels_ = 0; - TestLoopBack* const test_loop_back_; -}; - -} // namespace - -namespace testing { -// Get the interface for interaction with the library from unittests. -FakeExternalAudioPipelineSupport* GetFakeExternalAudioPipelineSupport() { - return GetTestMedia(); -} - -} // namespace testing - -// Library implementation. -bool ExternalAudioPipelineShlib::IsSupported() { - return GetTestMedia()->supported(); -} - -void ExternalAudioPipelineShlib::AddExternalMediaVolumeChangeRequestObserver( - ExternalMediaVolumeChangeRequestObserver* observer) { - GetTestMedia()->AddExternalMediaVolumeChangeRequestObserver(observer); -} - -void ExternalAudioPipelineShlib::RemoveExternalMediaVolumeChangeRequestObserver( - ExternalMediaVolumeChangeRequestObserver* observer) { - GetTestMedia()->RemoveExternalMediaVolumeChangeRequestObserver(observer); -} - -void ExternalAudioPipelineShlib::SetExternalMediaVolume(float level) { - GetTestMedia()->SetVolume(level); -} - -void ExternalAudioPipelineShlib::SetExternalMediaMuted(bool muted) { - GetTestMedia()->SetMuted(muted); -} - -void ExternalAudioPipelineShlib::AddExternalLoopbackAudioObserver( - LoopbackAudioObserver* observer) { - GetTestMedia()->AddExternalLoopbackAudioObserver(observer); -} - -void ExternalAudioPipelineShlib::RemoveExternalLoopbackAudioObserver( - LoopbackAudioObserver* observer) { - GetTestMedia()->RemoveExternalLoopbackAudioObserver(observer); -} - -void ExternalAudioPipelineShlib::AddExternalMediaMetadataChangeObserver( - ExternalMediaMetadataChangeObserver* observer) { - GetTestMedia()->AddExternalMediaMetadataChangeObserver(observer); -} - -void ExternalAudioPipelineShlib::RemoveExternalMediaMetadataChangeObserver( - ExternalMediaMetadataChangeObserver* observer) { - GetTestMedia()->RemoveExternalMediaMetadataChangeObserver(observer); -} - -std::unique_ptr -ExternalAudioPipelineShlib::CreateMixerOutputStream() { - return std::make_unique(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/fake_external_audio_pipeline_support.h chromium-132.0.6834.159/chromecast/media/audio/fake_external_audio_pipeline_support.h --- chromium-132.0.6834.110/chromecast/media/audio/fake_external_audio_pipeline_support.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/fake_external_audio_pipeline_support.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_FAKE_EXTERNAL_AUDIO_PIPELINE_SUPPORT_H_ -#define CHROMECAST_MEDIA_AUDIO_FAKE_EXTERNAL_AUDIO_PIPELINE_SUPPORT_H_ - -#include "chromecast/public/media/external_audio_pipeline_shlib.h" - -namespace chromecast { -namespace media { -namespace testing { - -// Interface class for fake external pipeline library to interact with the -// library from unit tests. -class FakeExternalAudioPipelineSupport { - public: - virtual void SetSupported() = 0; - virtual void Reset() = 0; - // Get last received values. - virtual float GetVolume() const = 0; - virtual bool IsMuted() const = 0; - // Request for change values. - virtual void OnVolumeChangeRequest(float level) = 0; - virtual void OnMuteChangeRequest(bool muted) = 0; - virtual void UpdateExternalMediaMetadata( - const ExternalAudioPipelineShlib::ExternalMediaMetadata& metadata) = 0; - - virtual ~FakeExternalAudioPipelineSupport() {} -}; - -FakeExternalAudioPipelineSupport* GetFakeExternalAudioPipelineSupport(); - -} // namespace testing -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_FAKE_EXTERNAL_AUDIO_PIPELINE_SUPPORT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/interleaved_channel_mixer.cc chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer.cc --- chromium-132.0.6834.110/chromecast/media/audio/interleaved_channel_mixer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/interleaved_channel_mixer.h" - -#include "base/check_op.h" -#include "media/base/channel_mixing_matrix.h" - -namespace chromecast { -namespace media { - -InterleavedChannelMixer::InterleavedChannelMixer( - ::media::ChannelLayout input_layout, - int input_channel_count, - ::media::ChannelLayout output_layout, - int output_channel_count, - int max_frames) - : input_layout_(input_layout), - input_channel_count_(input_channel_count), - output_layout_(output_layout), - output_channel_count_(output_channel_count), - max_frames_(max_frames) { - if (input_layout_ == output_layout_) { - return; - } - - buffer_.resize(max_frames * output_channel_count_); - - std::vector> matrix; - ::media::ChannelMixingMatrix matrix_builder( - input_layout_, input_channel_count_, output_layout_, - output_channel_count_); - matrix_builder.CreateTransformationMatrix(&matrix); - - transform_.reserve(input_channel_count_ * output_channel_count_); - for (const std::vector& output_channel : matrix) { - transform_.insert(transform_.end(), output_channel.begin(), - output_channel.end()); - } -} - -InterleavedChannelMixer::~InterleavedChannelMixer() = default; - -float* InterleavedChannelMixer::Transform(const float* input, int num_frames) { - if (input_layout_ == output_layout_) { - return const_cast(input); - } - - DCHECK_LE(num_frames, max_frames_); - // TODO(kmackay) Could use Eigen, but it's not available in public Chromium. - float* output = buffer_.data(); - for (int f = 0; f < num_frames; ++f) { - // For each frame, multiply the row-major transform matrix by the column- - // major interleaved input. - float* t = transform_.data(); - for (int out_c = 0; out_c < output_channel_count_; ++out_c) { - // Each channel of the output frame is the current transform row times - // the input frame. - float result = 0; - for (int in_c = 0; in_c < input_channel_count_; ++in_c) { - result += *t * input[in_c]; - ++t; - } - *output = result; - ++output; - } - // Move to next input frame. - input += input_channel_count_; - } - - return buffer_.data(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/interleaved_channel_mixer.h chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer.h --- chromium-132.0.6834.110/chromecast/media/audio/interleaved_channel_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_INTERLEAVED_CHANNEL_MIXER_H_ -#define CHROMECAST_MEDIA_AUDIO_INTERLEAVED_CHANNEL_MIXER_H_ - -#include - -#include "media/base/channel_layout.h" - -namespace chromecast { -namespace media { - -// Converts interleaved audio from one channel layout to another. -class InterleavedChannelMixer { - public: - InterleavedChannelMixer(::media::ChannelLayout input_layout, - int input_channel_count, - ::media::ChannelLayout output_layout, - int output_channel_count, - int max_frames); - - InterleavedChannelMixer(const InterleavedChannelMixer&) = delete; - InterleavedChannelMixer& operator=(const InterleavedChannelMixer&) = delete; - - ~InterleavedChannelMixer(); - - int input_channel_count() const { return input_channel_count_; } - int output_channel_count() const { return output_channel_count_; } - - // Transforms the |input| audio from the input channel layout to the output - // channel layout. Returns a pointer to the transformed data. Does not modify - // the contents of |input|. The returned buffer is valid as long as |input| - // is valid, or until |this| is destroyed, whichever is shorter. - float* Transform(const float* input, int num_frames); - - private: - const ::media::ChannelLayout input_layout_; - const int input_channel_count_; - const ::media::ChannelLayout output_layout_; - const int output_channel_count_; - const int max_frames_; - - // Transform matrix; stored in row-major order. - std::vector transform_; - - // Output buffer, if needed. - std::vector buffer_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_INTERLEAVED_CHANNEL_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/interleaved_channel_mixer_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/interleaved_channel_mixer_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/interleaved_channel_mixer_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/interleaved_channel_mixer.h" - -#include -#include -#include - -#include "media/base/audio_bus.h" -#include "media/base/audio_sample_types.h" -#include "media/base/channel_layout.h" -#include "media/base/channel_mixer.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { -const int kNumFrames = 32; -} // namespace - -using TestParams = std::tuple<::media::ChannelLayout /* input layout */, - ::media::ChannelLayout /* output layout */>; - -class InterleavedChannelMixerTest : public testing::TestWithParam { -}; - -TEST_P(InterleavedChannelMixerTest, Transform) { - const TestParams& params = GetParam(); - const ::media::ChannelLayout input_layout = testing::get<0>(params); - const ::media::ChannelLayout output_layout = testing::get<1>(params); - const int num_input_channels = - ::media::ChannelLayoutToChannelCount(input_layout); - const int num_output_channels = - ::media::ChannelLayoutToChannelCount(output_layout); - - auto original = ::media::AudioBus::Create(num_input_channels, kNumFrames); - for (int c = 0; c < num_input_channels; ++c) { - for (int f = 0; f < kNumFrames; ++f) { - original->channel(c)[f] = std::pow(-1, f + c) * 0.01 + - c / static_cast(num_input_channels * 10); - } - } - - auto transformed = ::media::AudioBus::Create(num_output_channels, kNumFrames); - transformed->Zero(); - - // Check that the output of upstream ChannelMixer + interleave is the same - // as the output of interleave + InterleavedChannelMixer. - ::media::ChannelMixer channel_mixer(input_layout, num_input_channels, - output_layout, num_output_channels); - channel_mixer.Transform(original.get(), transformed.get()); - - std::vector original_interleaved(num_input_channels * kNumFrames); - original->ToInterleaved<::media::Float32SampleTypeTraits>( - kNumFrames, original_interleaved.data()); - - InterleavedChannelMixer interleaved_mixer(input_layout, num_input_channels, - output_layout, num_output_channels, - kNumFrames); - float* interleaved_mixed = - interleaved_mixer.Transform(original_interleaved.data(), kNumFrames); - - std::vector transformed_interleaved(num_output_channels * kNumFrames); - transformed->ToInterleaved<::media::Float32SampleTypeTraits>( - kNumFrames, transformed_interleaved.data()); - - for (int f = 0; f < kNumFrames; ++f) { - for (int c = 0; c < num_output_channels; ++c) { - EXPECT_FLOAT_EQ(interleaved_mixed[f * num_output_channels + c], - transformed_interleaved[f * num_output_channels + c]) - << "at frame " << f << ", channel " << c; - } - } -} - -INSTANTIATE_TEST_SUITE_P( - CommonLayouts, - InterleavedChannelMixerTest, - testing::Combine( - ::testing::Values(::media::ChannelLayout::CHANNEL_LAYOUT_MONO, - ::media::ChannelLayout::CHANNEL_LAYOUT_STEREO, - ::media::ChannelLayout::CHANNEL_LAYOUT_5_1), - ::testing::Values(::media::ChannelLayout::CHANNEL_LAYOUT_MONO, - ::media::ChannelLayout::CHANNEL_LAYOUT_STEREO, - ::media::ChannelLayout::CHANNEL_LAYOUT_5_1))); - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/DEPS chromium-132.0.6834.159/chromecast/media/audio/mixer_service/DEPS --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -include_rules = [ - "+chromecast/media/audio/net", - "+chromecast/metrics", - "+chromecast/net", - "+net", -] diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/constants.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/constants.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/constants.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/constants.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/constants.h" - -#include "chromecast/media/audio/mixer_service/buildflags.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -bool HaveFullMixer() { - return BUILDFLAG(HAVE_FULL_MIXER); -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/constants.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/constants.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/constants.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/constants.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_CONSTANTS_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_CONSTANTS_H_ - -#include - -namespace chromecast { -namespace media { -namespace mixer_service { - -constexpr char kDefaultUnixDomainSocketPath[] = "/tmp/mixer-service"; -constexpr int kDefaultTcpPort = 12854; - -// Returns true if the full mixer is present on the system, false otherwise. -bool HaveFullMixer(); - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_CONSTANTS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/control_connection.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/control_connection.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/control_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/control_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,262 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/control_connection.h" - -#include - -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -ControlConnection::ControlConnection() = default; - -ControlConnection::~ControlConnection() = default; - -void ControlConnection::Connect(ConnectedCallback callback) { - connect_callback_ = std::move(callback); - MixerConnection::Connect(); -} - -void ControlConnection::SetVolume(AudioContentType type, - float volume_multiplier) { - if (type == AudioContentType::kOther) { - return; - } - - volume_[type] = volume_multiplier; - if (socket_) { - Generic message; - auto* volume = message.mutable_set_device_volume(); - volume->set_content_type(audio_service::ConvertContentType(type)); - volume->set_volume_multiplier(volume_multiplier); - if (!socket_->SendProto(0, message)) { - OnSendFailed(); - } - } -} - -void ControlConnection::SetMuted(AudioContentType type, bool muted) { - if (type == AudioContentType::kOther) { - return; - } - - muted_[type] = muted; - if (socket_) { - Generic message; - auto* mute_message = message.mutable_set_device_muted(); - mute_message->set_content_type(audio_service::ConvertContentType(type)); - mute_message->set_muted(muted); - if (!socket_->SendProto(0, message)) { - OnSendFailed(); - } - } -} - -void ControlConnection::SetVolumeLimit(AudioContentType type, - float max_volume_multiplier) { - if (type == AudioContentType::kOther) { - return; - } - - volume_limit_[type] = max_volume_multiplier; - if (socket_) { - Generic message; - auto* limit = message.mutable_set_volume_limit(); - limit->set_content_type(audio_service::ConvertContentType(type)); - limit->set_max_volume_multiplier(max_volume_multiplier); - if (!socket_->SendProto(0, message)) { - OnSendFailed(); - } - } -} - -void ControlConnection::ListPostprocessors( - ListPostprocessorsCallback callback) { - list_postprocessors_callbacks_.push_back(std::move(callback)); - if (!socket_) { - return; - } - Generic message; - message.mutable_list_postprocessors(); - if (!socket_->SendProto(0, message)) { - OnSendFailed(); - } -} - -void ControlConnection::ConfigurePostprocessor(std::string postprocessor_name, - std::string config) { - postprocessor_config_.insert_or_assign(postprocessor_name, config); - if (!SendPostprocessorMessageInternal(std::move(postprocessor_name), - std::move(config))) { - OnSendFailed(); - } -} - -void ControlConnection::SendPostprocessorMessage(std::string postprocessor_name, - std::string message) { - SendPostprocessorMessageInternal(std::move(postprocessor_name), - std::move(message)); -} - -bool ControlConnection::SendPostprocessorMessageInternal( - std::string postprocessor_name, - std::string message) { - if (!socket_) { - return true; - } - - // Erase any ? and subsequent substring from the name. - auto q = postprocessor_name.find('?'); - if (q != std::string::npos) { - postprocessor_name.erase(q); - } - - Generic proto; - auto* content = proto.mutable_configure_postprocessor(); - content->set_name(std::move(postprocessor_name)); - content->set_config(std::move(message)); - return socket_->SendProto(0, proto); -} - -void ControlConnection::ReloadPostprocessors() { - if (!socket_) { - return; - } - Generic message; - message.mutable_reload_postprocessors(); - socket_->SendProto(0, message); -} - -void ControlConnection::SetStreamCountCallback(StreamCountCallback callback) { - stream_count_callback_ = std::move(callback); - if (socket_) { - Generic message; - message.mutable_request_stream_count()->set_subscribe( - !stream_count_callback_.is_null()); - if (!socket_->SendProto(0, message)) { - OnSendFailed(); - } - } -} - -void ControlConnection::SetNumOutputChannels(int num_channels) { - num_output_channels_ = num_channels; - if (socket_) { - Generic message; - message.mutable_set_num_output_channels()->set_channels(num_channels); - if (!socket_->SendProto(0, message)) { - OnSendFailed(); - } - } -} - -void ControlConnection::OnConnected(std::unique_ptr socket) { - socket_ = std::move(socket); - socket_->SetDelegate(this); - - for (const auto& item : volume_limit_) { - Generic message; - auto* limit = message.mutable_set_volume_limit(); - limit->set_content_type(audio_service::ConvertContentType(item.first)); - limit->set_max_volume_multiplier(item.second); - if (!socket_->SendProto(0, message)) { - return OnSendFailed(); - } - } - - for (const auto& item : muted_) { - Generic message; - auto* muted = message.mutable_set_device_muted(); - muted->set_content_type(audio_service::ConvertContentType(item.first)); - muted->set_muted(item.second); - if (!socket_->SendProto(0, message)) { - return OnSendFailed(); - } - } - - for (const auto& item : volume_) { - Generic message; - auto* volume = message.mutable_set_device_volume(); - volume->set_content_type(audio_service::ConvertContentType(item.first)); - volume->set_volume_multiplier(item.second); - if (!socket_->SendProto(0, message)) { - return OnSendFailed(); - } - } - - if (stream_count_callback_) { - Generic message; - message.mutable_request_stream_count()->set_subscribe(true); - if (!socket_->SendProto(0, message)) { - return OnSendFailed(); - } - } - - if (num_output_channels_) { - Generic message; - message.mutable_set_num_output_channels()->set_channels( - num_output_channels_); - if (!socket_->SendProto(0, message)) { - return OnSendFailed(); - } - } - - for (const auto& item : postprocessor_config_) { - if (!SendPostprocessorMessageInternal(item.first, item.second)) { - return OnSendFailed(); - } - } - - if (!list_postprocessors_callbacks_.empty()) { - Generic message; - message.mutable_list_postprocessors(); - if (!socket_->SendProto(0, message)) { - return OnSendFailed(); - } - } - - if (connect_callback_) { - connect_callback_.Run(); - } -} - -void ControlConnection::OnSendFailed() { - LOG(WARNING) << "Failed to send a control message"; - OnConnectionError(); -} - -void ControlConnection::OnConnectionError() { - socket_.reset(); - MixerConnection::Connect(); -} - -bool ControlConnection::HandleMetadata(const Generic& message) { - if (stream_count_callback_ && message.has_stream_count()) { - stream_count_callback_.Run(message.stream_count().primary(), - message.stream_count().sfx()); - } - if (message.has_postprocessor_list()) { - std::vector post_processors; - for (const auto& post_processor : - message.postprocessor_list().postprocessors()) { - post_processors.push_back(post_processor); - } - while (!list_postprocessors_callbacks_.empty()) { - std::move(list_postprocessors_callbacks_.front()).Run(post_processors); - list_postprocessors_callbacks_.pop_front(); - } - } - - return true; -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/control_connection.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/control_connection.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/control_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/control_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,123 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_CONTROL_CONNECTION_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_CONTROL_CONNECTION_H_ - -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/functional/callback.h" -#include "chromecast/media/audio/mixer_service/mixer_connection.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -// Mixer service connection for controlling general mixer properties, such as -// device volume and postprocessor configuration. Not thread-safe; all usage of -// a given instance must be on the same sequence. Must be created on an IO -// thread. -class ControlConnection : public MixerConnection, public MixerSocket::Delegate { - public: - using ConnectedCallback = base::RepeatingClosure; - - // Callback to receive mixer stream count changes. - using StreamCountCallback = - base::RepeatingCallback; - - // Callback that handles ListPostProcessors response. - using ListPostprocessorsCallback = - base::OnceCallback&)>; - - ControlConnection(); - - ControlConnection(const ControlConnection&) = delete; - ControlConnection& operator=(const ControlConnection&) = delete; - - ~ControlConnection() override; - - // Connects to the mixer. If the mixer connection is lost, this will - // automatically reconnect. If |callback| is nonempty, it will be called each - // time a connection is (re)established with the mixer. This can be used to - // re-send postprocessor messages, since they are not persisted across - // disconnects. - void Connect(ConnectedCallback callback = ConnectedCallback()); - - // Sets volume multiplier for all streams of a given content type. - void SetVolume(AudioContentType type, float volume_multiplier); - - // Sets mute state all streams of a given content type. - void SetMuted(AudioContentType type, bool muted); - - // Sets the maximum effective volume multiplier for a given content type. - void SetVolumeLimit(AudioContentType type, float max_volume_multiplier); - - // Returns a set of registered builtin post-processors. - void ListPostprocessors(ListPostprocessorsCallback callback); - - // Sends arbitrary config data to a specific postprocessor. Config is saved - // for each unique |name| and will be resent if the mixer disconnects and then - // reconnects. If the |postprocessor_name| contains a '?', that character and - // the remainder of the name string will not be sent to the mixer; this is - // useful for configuring multiple subprocessors (eg for the dynamic range - // processor). - void ConfigurePostprocessor(std::string postprocessor_name, - std::string config); - - // Sends a message a specific postprocessor. Messages are not saved and will - // not be resent if the mixer disconnects and then reconnects. - void SendPostprocessorMessage(std::string postprocessor_name, - std::string message); - - // Instructs the mixer to reload postprocessors based on the config file. - void ReloadPostprocessors(); - - // Sets a callback to receive mixer stream count changes. |callback| may be an - // empty callback to remove it. - void SetStreamCountCallback(StreamCountCallback callback); - - // Sets the desired number of output channels used by the mixer. This will - // cause an audio interruption on any currently active streams. The actual - // output channel count is determined by the output implementation and may not - // match |num_channels|. - void SetNumOutputChannels(int num_channels); - - private: - bool SendPostprocessorMessageInternal(std::string postprocessor_name, - std::string message); - void OnSendFailed(); - - // MixerConnection implementation: - void OnConnected(std::unique_ptr socket) override; - void OnConnectionError() override; - - // MixerSocket::Delegate implementation: - bool HandleMetadata(const Generic& message) override; - - std::unique_ptr socket_; - - ConnectedCallback connect_callback_; - - base::flat_map volume_; - base::flat_map muted_; - base::flat_map volume_limit_; - - base::flat_map postprocessor_config_; - - StreamCountCallback stream_count_callback_; - // Uses std::list to trigger callbacks in FIFO order. - std::list list_postprocessors_callbacks_; - int num_output_channels_ = 0; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_CONTROL_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/loopback_connection.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_connection.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/loopback_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,95 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/loopback_connection.h" - -#include -#include -#include - -#include "base/check.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/net/io_buffer_pool.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -namespace { - -enum MessageTypes : int { - kRequest = 1, -}; - -} - -LoopbackConnection::LoopbackConnection(Delegate* delegate) - : LoopbackConnection(delegate, nullptr) {} - -LoopbackConnection::LoopbackConnection( - Delegate* delegate, - std::unique_ptr connected_socket_for_test) - : delegate_(delegate), socket_(std::move(connected_socket_for_test)) { - DCHECK(delegate_); -} - -LoopbackConnection::~LoopbackConnection() = default; - -void LoopbackConnection::Connect() { - if (socket_) { - OnConnected(std::move(socket_)); - return; - } - MixerConnection::Connect(); -} - -void LoopbackConnection::OnConnected(std::unique_ptr socket) { - format_ = kUnknownSampleFormat; - sample_rate_ = 0; - num_channels_ = 0; - - socket_ = std::move(socket); - socket_->SetDelegate(this); - - Generic message; - message.mutable_loopback_request(); - socket_->SendProto(kRequest, message); -} - -void LoopbackConnection::OnConnectionError() { - delegate_->OnLoopbackInterrupted(LoopbackInterruptReason::kDisconnected); - socket_.reset(); - MixerConnection::Connect(); -} - -bool LoopbackConnection::HandleMetadata(const Generic& message) { - if (message.has_stream_config()) { - format_ = audio_service::ConvertSampleFormat( - message.stream_config().sample_format()); - sample_rate_ = message.stream_config().sample_rate(); - num_channels_ = message.stream_config().num_channels(); - } - if (message.has_stream_interruption()) { - delegate_->OnLoopbackInterrupted(static_cast( - message.stream_interruption().reason())); - } - return true; -} - -bool LoopbackConnection::HandleAudioData(char* data, - size_t size, - int64_t timestamp) { - if (format_ != kUnknownSampleFormat && size > 0) { - delegate_->OnLoopbackAudio(timestamp, format_, sample_rate_, num_channels_, - reinterpret_cast(data), size); - } - return true; -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/loopback_connection.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_connection.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/loopback_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,87 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_LOOPBACK_CONNECTION_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_LOOPBACK_CONNECTION_H_ - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "chromecast/media/audio/mixer_service/loopback_interrupt_reason.h" -#include "chromecast/media/audio/mixer_service/mixer_connection.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/public/media/decoder_config.h" - -namespace chromecast { -namespace media { -namespace mixer_service { -class Generic; - -// Connection for observing loopback audio data from the mixer. Must be created -// and used on an IO thread. -class LoopbackConnection : public MixerConnection, - public MixerSocket::Delegate { - public: - // Observer for audio loopback data. - class Delegate { - public: - // Called whenever loopback audio data is available. The |timestamp| is the - // estimated time in microseconds (relative to the audio clock) that - // the audio will actually be output. |length| is the length of the audio - // |data| in bytes. The format of the data is given by |sample_format| and - // |num_channels|. - virtual void OnLoopbackAudio(int64_t timestamp, - media::SampleFormat sample_format, - int sample_rate, - int num_channels, - uint8_t* data, - int length) = 0; - - // Called if the loopback data is not continuous (ie, does not accurately - // represent the actual output) for any reason. For example, if there is an - // output underflow, or if output is disabled due to no output streams. - virtual void OnLoopbackInterrupted(LoopbackInterruptReason reason) = 0; - - protected: - virtual ~Delegate() = default; - }; - - explicit LoopbackConnection(Delegate* delegate); - // For testing only. - LoopbackConnection(Delegate* delegate, - std::unique_ptr connected_socket_for_test); - - LoopbackConnection(const LoopbackConnection&) = delete; - LoopbackConnection& operator=(const LoopbackConnection&) = delete; - - ~LoopbackConnection() override; - - // Initiates connection to the mixer service. Delegate methods can be called - // at any point after Connect() is called, until this is destroyed. - void Connect(); - - private: - // MixerConnection implementation: - void OnConnected(std::unique_ptr socket) override; - void OnConnectionError() override; - - // MixerSocket::Delegate implementation: - bool HandleMetadata(const Generic& message) override; - bool HandleAudioData(char* data, size_t size, int64_t timestamp) override; - - Delegate* const delegate_; - - std::unique_ptr socket_; - - media::SampleFormat format_ = kUnknownSampleFormat; - int sample_rate_ = 0; - int num_channels_ = 0; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_LOOPBACK_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/loopback_interrupt_reason.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_interrupt_reason.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/loopback_interrupt_reason.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/loopback_interrupt_reason.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_LOOPBACK_INTERRUPT_REASON_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_LOOPBACK_INTERRUPT_REASON_H_ - -namespace chromecast { -namespace media { - -// Reasons for loopback interruption. Should be kept in sync with -// StreamInterruption::InterruptionReason in mixer_service.proto. -enum class LoopbackInterruptReason { - kUnknown = 0, - kDisconnected = 1, // Disconnected from mixer. - kUnderrun = 2, // Mixer output underrun. - kConfigChange = 3, // Mixer output config changed. - kOutputStopped = 4, // Mixer stopped playing out audio. - kSocketOverflow = 5, // Mixer couldn't send over the socket. - kCpuAffinityChanged = 6, // Mixer output underrun caused by losing CPU - // affinity, often happens when CPU cores shutdown. -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_LOOPBACK_INTERRUPT_REASON_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_connection.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_connection.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,121 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/mixer_connection.h" - -#include -#include - -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/media/audio/mixer_service/constants.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/audio/net/audio_socket_service.h" -#include "net/base/net_errors.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -namespace { - -constexpr base::TimeDelta kConnectTimeout = base::Seconds(1); - -} // namespace - -std::unique_ptr CreateLocalMixerServiceConnection() - __attribute__((__weak__)); - -MixerConnection::MixerConnection() : weak_factory_(this) {} - -MixerConnection::~MixerConnection() = default; - -void MixerConnection::Connect() { - DCHECK(!connecting_socket_); - if (CreateLocalMixerServiceConnection) { - auto socket = CreateLocalMixerServiceConnection(); - if (socket) { - OnConnected(std::move(socket)); - return; - } - } - - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - std::string path = - command_line->GetSwitchValueASCII(switches::kMixerServiceEndpoint); - if (path.empty()) { - path = kDefaultUnixDomainSocketPath; - } - int port = GetSwitchValueNonNegativeInt(switches::kMixerServicePort, - kDefaultTcpPort); - connecting_socket_ = AudioSocketService::Connect(path, port); - - int result = connecting_socket_->Connect(base::BindOnce( - &MixerConnection::ConnectCallback, weak_factory_.GetWeakPtr())); - if (result != net::ERR_IO_PENDING) { - ConnectCallback(result); - return; - } - - connection_timeout_.Start(FROM_HERE, kConnectTimeout, this, - &MixerConnection::ConnectTimeout); -} - -void MixerConnection::ConnectCallback(int result) { - DCHECK_NE(result, net::ERR_IO_PENDING); - if (!connecting_socket_) { - return; - } - - connection_timeout_.Stop(); - if (result == net::OK) { - LOG_IF(INFO, !log_timeout_) << "Now connected to mixer service"; - log_connection_failure_ = true; - log_timeout_ = true; - auto socket = - std::make_unique(std::move(connecting_socket_)); - OnConnected(std::move(socket)); - return; - } - - base::TimeDelta delay = kConnectTimeout; - if (log_connection_failure_) { - LOG(ERROR) << "Failed to connect to mixer service: " << result; - log_connection_failure_ = false; - delay = base::TimeDelta(); // No reconnect delay on the first failure. - } - connecting_socket_.reset(); - - base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&MixerConnection::Connect, weak_factory_.GetWeakPtr()), - delay); -} - -void MixerConnection::ConnectTimeout() { - if (!connecting_socket_) { - return; - } - - if (log_timeout_) { - LOG(ERROR) << "Timed out connecting to mixer service"; - log_timeout_ = false; - } - connecting_socket_.reset(); - - base::SequencedTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&MixerConnection::Connect, weak_factory_.GetWeakPtr())); -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_connection.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_connection.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_CONNECTION_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_CONNECTION_H_ - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/timer/timer.h" - -namespace net { -class StreamSocket; -} // namespace net - -namespace chromecast { -namespace media { -namespace mixer_service { -class MixerSocket; - -// Base class for connecting to the mixer service. -class MixerConnection { - public: - MixerConnection(); - - MixerConnection(const MixerConnection&) = delete; - MixerConnection& operator=(const MixerConnection&) = delete; - - virtual ~MixerConnection(); - - // Initiates connection to the mixer service. Will call OnConnected() when - // connection is successful. - void Connect(); - - protected: - // Called when a connection is established to the mixer service. - virtual void OnConnected(std::unique_ptr socket) = 0; - - private: - void ConnectCallback(int result); - void ConnectTimeout(); - - std::unique_ptr connecting_socket_; - base::OneShotTimer connection_timeout_; - - bool log_connection_failure_ = true; - bool log_timeout_ = true; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_control.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_control.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_control.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_control.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/mixer_control.h" - -#include - -#include "base/check.h" -#include "base/location.h" -#include "base/no_destructor.h" -#include "chromecast/media/audio/audio_io_thread.h" -#include "chromecast/media/audio/mixer_service/constants.h" -#include "chromecast/media/audio/mixer_service/control_connection.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -// static -MixerControl* MixerControl::Get() { - if (HaveFullMixer()) { - static base::NoDestructor instance; - return instance.get(); - } - return nullptr; -} - -MixerControl::MixerControl() : control_(AudioIoThread::Get()->task_runner()) { - DCHECK(HaveFullMixer()); - control_.AsyncCall(&ControlConnection::Connect) - .WithArgs(ControlConnection::ConnectedCallback()); -} - -MixerControl::~MixerControl() = default; - -void MixerControl::ConfigurePostprocessor(std::string postprocessor_name, - std::string config) { - control_.AsyncCall(&ControlConnection::ConfigurePostprocessor) - .WithArgs(std::move(postprocessor_name), std::move(config)); -} - -void MixerControl::ListPostprocessors(ListPostprocessorsCallback callback) { - control_.AsyncCall(&ControlConnection::ListPostprocessors) - .WithArgs(std::move(callback)); -} -void MixerControl::ReloadPostprocessors() { - control_.AsyncCall(&ControlConnection::ReloadPostprocessors); -} - -void MixerControl::SetNumOutputChannels(int num_channels) { - control_.AsyncCall(&ControlConnection::SetNumOutputChannels) - .WithArgs(num_channels); -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_control.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_control.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_control.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_control.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_CONTROL_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_CONTROL_H_ - -#include - -#include "base/no_destructor.h" -#include "base/threading/sequence_bound.h" - -namespace chromecast { -namespace media { -namespace mixer_service { -class ControlConnection; - -// Threadsafe process-wide mixer control. -class MixerControl { - public: - using ListPostprocessorsCallback = - base::OnceCallback&)>; - - // Returns the mixer control instance for this process, or nullptr if the - // mixer is not present on this system. - static MixerControl* Get(); - - MixerControl(const MixerControl&) = delete; - MixerControl& operator=(const MixerControl&) = delete; - - // Sends arbitrary config data to a specific postprocessor. - void ConfigurePostprocessor(std::string postprocessor_name, - std::string config); - - // Sends the request to get the builtin postprocessors and run the callback. - void ListPostprocessors(ListPostprocessorsCallback callback); - - // Instructs the mixer to reload postprocessors based on the config file. - void ReloadPostprocessors(); - - // Sets the desired number of output channels used by the mixer. This will - // cause an audio interruption on any currently active streams. The actual - // output channel count is determined by the output implementation and may not - // match |num_channels|. - void SetNumOutputChannels(int num_channels); - - private: - friend class base::NoDestructor; - MixerControl(); - ~MixerControl(); - - base::SequenceBound control_; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_CONTROL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_service_transport.proto chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_service_transport.proto --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_service_transport.proto 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_service_transport.proto 1970-01-01 00:00:00.000000000 +0000 @@ -1,287 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package chromecast.media.mixer_service; - -import "chromecast/media/audio/net/common.proto"; - -message OutputStreamParams { - enum StreamType { - STREAM_TYPE_DEFAULT = 0; - STREAM_TYPE_SFX = 1; - } - optional StreamType stream_type = 1; - - optional audio_service.ContentType content_type = 2; - optional audio_service.SampleFormat sample_format = 3; - - optional string device_id = 4; - - optional int32 sample_rate = 5; - optional int32 num_channels = 6; - optional audio_service.ChannelLayout channel_layout = 7; - optional sint32 channel_selection = 8 [default = -1]; - - optional int32 fill_size_frames = 9; - optional int32 start_threshold_frames = 10; - optional int32 max_buffered_frames = 11; - - optional int32 fade_frames = 12; - - // If |true|, playback will not start until a start timestamp has been - // provided via a SetStartTimestamp message. - optional bool use_start_timestamp = 13; - - // If |true|, this stream will not be included in the mixer's stream counts. - optional bool ignore_for_stream_count = 14; - - // If |true|, the receiver will not close the stream after a period of - // inactivity. - optional bool never_timeout_connection = 15; - - // If present, volume limits apply to this stream based on the |focus_type| - // instead of the |content_type|. - optional audio_service.ContentType focus_type = 16; - - message TimestampedAudioConfig { - // How frequently to change clock rate to fix timestamp errors, in - // microseconds. - optional int64 rate_change_interval = 1; - - // How long to make the linear regression window for smoothing errors, in - // microseconds. - optional int64 linear_regression_window = 2; - - // The maximum current error to ignore, in microseconds. - optional int64 max_ignored_current_error = 3; - - // The maximum current absolute error that should be adjusted for in a - // single clock rate adjustment. - optional double max_current_error_correction = 4; - - // The minimum difference between the optimal clock rate and the current - // clock rate required to actually change the rate. - optional double min_rate_change = 5; - - // Maximum error to allow before a hard correction. - optional int64 max_timestamp_error = 6; - - // If true, audio will always be played, even if it would play late. - optional bool never_crop = 7; - } - - // If present, the PTS value for each audio buffer indicates the desired - // playout time (relative to DefaultMonotonicClock::Now()) of the first frame - // of that buffer (instead of the usual arbitrary PTS value). - optional TimestampedAudioConfig timestamped_audio_config = 17; - - // Enables audio clock simulation for AV sync. - optional bool enable_audio_clock_simulation = 18; -} - -// Indicates that we want to start playing the sample with PTS |start_pts| -// at audio clock timestamp |start_timestamp| in microseconds. May be sent -// multiple times to restart playback at a new timestamp (ie for hard -// corrections). -message SetStartTimestamp { - optional int64 start_timestamp = 1; - optional int64 start_pts = 2; -} - -// Informs the mixer how fast the PTS increases per frame. For example if the -// playback rate is 2.0, then each frame increases the PTS by 2.0 / sample_rate -// seconds. -message SetPlaybackRate { - optional float playback_rate = 1; -} - -// Changes the volume multiplier for an audio output stream. -message StreamVolume { - optional float volume = 1; -} - -// Immediately pauses/resumes playback for an audio output stream. -message SetPaused { - optional bool paused = 1; -} - -// Sets (or simulates setting) the audio clock rate. If the provided rate is -// not supported, the rate will be clamped to the supported range. -message SetAudioClockRate { - optional double rate = 1; -} - -// Indicates that previously pushed audio data has been queued for playback, -// and the next audio data that is pushed to the mixer will start playing at -// |next_playback_timestamp|. -message BufferPushResult { - optional fixed64 delay_timestamp = 1; - optional int64 delay = 2; -} - -// Indicates that EOS for an audio output stream has been played out. -message EosPlayedOut {} - -// Indicates that an audio output stream is ready for playback (ie, has enough -// audio data to exceed the start threshold, and has output delay information). -message ReadyForPlayback { - optional fixed64 delay_microseconds = 1; -} - -// Indicates current stream config for a loopback / redirected audio stream. -// Sent whenever the config changes; will be sent at least once before any audio -// data is sent. -message StreamConfig { - optional audio_service.SampleFormat sample_format = 1; - optional int32 sample_rate = 2; - optional int32 num_channels = 3; - optional int32 data_size = 4; // Expected size of audio data in bytes. -} - -// Sent to indicate that the mixer should stream loopback audio data back over -// this connection. -message LoopbackDataRequest {} - -// Sent when a loopback audio stream is interrupted (ie, is discontinuous). -message StreamInterruption { - enum InterruptionReason { - INTERRUPTED_UNKNOWN = 0; - INTERRUPTED_DISCONNECTED = 1; // Disconnected from mixer. - INTERRUPTED_UNDERRUN = 2; // Mixer output underrun. - INTERRUPTED_CONFIG_CHANGE = 3; // Mixer output config changed. - INTERRUPTED_OUTPUT_STOPPED = 4; // Mixer stopped playing out audio. - INTERRUPTED_SOCKET_OVERFLOW = 5; // Mixer couldn't send over the socket. - } - - optional InterruptionReason reason = 1; -} - -// Sent to indicate that the mixer should redirect specific audio output -// stream data back over this connection. -message RedirectionRequest { - optional int32 order = 1; - optional int32 num_channels = 2; - optional audio_service.ChannelLayout channel_layout = 3; - optional bool apply_volume = 4; - optional int64 extra_delay_microseconds = 5; -} - -// Sets the patterns to determine which audio output streams should be -// redirected. -message RedirectedStreamPatterns { - message Pattern { - optional audio_service.ContentType content_type = 1; - optional string device_id_pattern = 2; - } - repeated Pattern patterns = 1; -} - -// Sets volume multiplier for all streams of a given content type. -message SetDeviceVolume { - optional audio_service.ContentType content_type = 1; - optional float volume_multiplier = 2; -} - -// Sets mute state all streams of a given content type. -message SetDeviceMuted { - optional audio_service.ContentType content_type = 1; - optional bool muted = 2; -} - -// Sets the maximum effective volume multiplier for a given content type. -message SetVolumeLimit { - optional audio_service.ContentType content_type = 1; - optional float max_volume_multiplier = 2; -} - -// Asks the mixer to return a list of registered builtin post processors. -message ListPostprocessors {} - -message PostprocessorList { - repeated string postprocessors = 1; -} - -// Sends arbitrary config data to a specific postprocessor. -message ConfigurePostprocessor { - optional string name = 1; - optional bytes config = 2; -} - -// Instructs the mixer to reload postprocessors based on the config file. -message ReloadPostprocessors {} - -// Asks the mixer to send / stop sending stream count updates. -message RequestStreamCount { - optional bool subscribe = 1; -} - -// Indicates how many output streams are currently being handled by the mixer. -message StreamCount { - optional int32 primary = 1; - optional int32 sfx = 2; -} - -// Sets the desired number of output channels used by the mixer. -message NumOutputChannels { - optional int32 channels = 1; -} - -// Indicates an error on an audio stream. -message Error { - enum Type { - INVALID_STREAM_ERROR = 0; - XRUN_ERROR = 1; // Underrun or overrun. - } - optional Type type = 1; - optional string message = 2; -} - -message MixerUnderrun { - // Keep in sync with OutputStreamConnection::Delegate::MixerUnderrunType - enum Type { - // An underrun was detected on mixer input. - INPUT_UNDERRUN = 0; - // An underrun was detected on mixer output. - OUTPUT_UNDERRUN = 1; - } - optional Type type = 1; -} - -message TimestampAdjustment { - optional int64 adjustment = 1; -} - -message Generic { - optional OutputStreamParams output_stream_params = 1; - optional SetStartTimestamp set_start_timestamp = 2; - optional SetPlaybackRate set_playback_rate = 3; - optional StreamVolume set_stream_volume = 4; - optional SetPaused set_paused = 5; - optional BufferPushResult push_result = 6; - optional EosPlayedOut eos_played_out = 7; - optional ReadyForPlayback ready_for_playback = 8; - optional StreamConfig stream_config = 9; - optional LoopbackDataRequest loopback_request = 10; - optional RedirectionRequest redirection_request = 11; - optional RedirectedStreamPatterns redirected_stream_patterns = 12; - optional SetDeviceVolume set_device_volume = 13; - optional SetDeviceMuted set_device_muted = 14; - optional SetVolumeLimit set_volume_limit = 15; - optional ConfigurePostprocessor configure_postprocessor = 16; - optional ReloadPostprocessors reload_postprocessors = 17; - optional RequestStreamCount request_stream_count = 18; - optional StreamCount stream_count = 19; - optional Error error = 20; - optional NumOutputChannels set_num_output_channels = 21; - optional StreamInterruption stream_interruption = 22; - optional SetAudioClockRate set_audio_clock_rate = 23; - optional MixerUnderrun mixer_underrun = 24; - optional ListPostprocessors list_postprocessors = 25; - optional PostprocessorList postprocessor_list = 26; - optional TimestampAdjustment timestamp_adjustment = 27; -} diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_socket.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_socket.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_socket.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_socket.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,97 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/mixer_socket.h" - -#include - -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/net/io_buffer_pool.h" -#include "net/base/io_buffer.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -bool MixerSocketImpl::Delegate::HandleMetadata(const Generic& message) { - return true; -} - -MixerSocketImpl::MixerSocketImpl(std::unique_ptr socket) - : audio_socket_(std::make_unique(std::move(socket))) { -} - -MixerSocketImpl::MixerSocketImpl() - : audio_socket_(std::make_unique()) {} - -MixerSocketImpl::~MixerSocketImpl() = default; - -void MixerSocketImpl::SetLocalCounterpart( - base::WeakPtr local_counterpart, - scoped_refptr counterpart_task_runner) { - audio_socket_->SetLocalCounterpart(std::move(local_counterpart), - std::move(counterpart_task_runner)); -} - -base::WeakPtr MixerSocketImpl::GetAudioSocketWeakPtr() { - return audio_socket_->GetWeakPtr(); -} - -void MixerSocketImpl::SetDelegate(Delegate* delegate) { - audio_socket_->SetDelegate(delegate); -} - -void MixerSocketImpl::UseBufferPool(scoped_refptr buffer_pool) { - audio_socket_->UseBufferPool(std::move(buffer_pool)); -} - -MixerSocketImpl::AudioSocketExtension::AudioSocketExtension( - std::unique_ptr socket) - : AudioSocket(std::move(socket)) {} - -MixerSocketImpl::AudioSocketExtension::AudioSocketExtension() = default; - -bool MixerSocketImpl::SendAudioBuffer(scoped_refptr audio_buffer, - int filled_bytes, - int64_t timestamp) { - return audio_socket_->SendAudioBuffer(std::move(audio_buffer), filled_bytes, - timestamp); -} - -bool MixerSocketImpl::SendProto(int type, - const google::protobuf::MessageLite& message) { - return audio_socket_->SendProto(type, message); -} - -void MixerSocketImpl::ReceiveMoreMessages() { - audio_socket_->ReceiveMoreMessages(); -} - -MixerSocketImpl::AudioSocketExtension::~AudioSocketExtension() = default; - -void MixerSocketImpl::AudioSocketExtension::SetDelegate( - MixerSocket::Delegate* delegate) { - DCHECK(delegate); - delegate_ = delegate; - AudioSocket::SetDelegate(delegate); -} - -bool MixerSocketImpl::AudioSocketExtension::ParseMetadata(char* data, - size_t size) { - Generic message; - if (!message.ParseFromArray(data, size)) { - LOG(INFO) << "Invalid metadata message from " << this; - delegate_->OnConnectionError(); - return false; - } - - return delegate_->HandleMetadata(message); -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_socket.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_socket.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mixer_socket.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mixer_socket.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,133 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_SOCKET_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_SOCKET_H_ - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/audio/net/audio_socket.h" - -namespace net { -class StreamSocket; -} // namespace net - -namespace chromecast { -class IOBufferPool; - -namespace media { -namespace mixer_service { -class Generic; - -class MixerSocket { - public: - static constexpr int kAudioMessageHeaderSize = - AudioSocket::kAudioMessageHeaderSize; - - class Delegate : public AudioSocket::Delegate { - public: - // Called when metadata is received from the other side of the connection. - // Return |true| if the socket should continue to receive messages. - virtual bool HandleMetadata(const Generic& message); - - protected: - ~Delegate() override = default; - }; - - virtual ~MixerSocket() = default; - - virtual void SetLocalCounterpart( - base::WeakPtr local_counterpart, - scoped_refptr counterpart_task_runner) = 0; - virtual base::WeakPtr GetAudioSocketWeakPtr() = 0; - - // Sets/changes the delegate. Must be called immediately after creation - // (ie, synchronously on the same sequence). - virtual void SetDelegate(Delegate* delegate) = 0; - - // Adds a |buffer_pool| used to allocate buffers to receive messages into, - // and for sending protos. If the pool-allocated buffers are too small for a - // given message, a normal IOBuffer will be dynamically allocated instead. - virtual void UseBufferPool(scoped_refptr buffer_pool) = 0; - - // Prepares |audio_buffer| and then sends it across the connection. Returns - // |false| if the audio could not be sent. - virtual bool SendAudioBuffer(scoped_refptr audio_buffer, - int filled_bytes, - int64_t timestamp) = 0; - - // Sends an arbitrary protobuf across the connection. |type| indicates the - // type of message; if the write cannot complete immediately, one message of - // each type will be stored for later sending; if a newer message is sent with - // the same type, then the previous message is overwritten. When writes become - // available again, the stored messages are written in order of |type| (lowest - // type first). Note that |type| is completely determined by the caller, and - // you can reuse the same type value for different messages as long as they - // are on different socket instances. A type of 0 means to never store the - // message. Returns |false| if the message was not sent or stored. - virtual bool SendProto(int type, - const google::protobuf::MessageLite& message) = 0; - - // Resumes receiving messages. Delegate calls may be called synchronously - // from within this method. - virtual void ReceiveMoreMessages() = 0; -}; - -// AudioSocket implementation for sending and receiving messages to/from the -// mixer service. -class MixerSocketImpl : public MixerSocket { - public: - explicit MixerSocketImpl(std::unique_ptr socket); - MixerSocketImpl(const MixerSocketImpl&) = delete; - MixerSocketImpl& operator=(const MixerSocketImpl&) = delete; - ~MixerSocketImpl() override; - - // Used to create local (in-process) connections. - MixerSocketImpl(); - void SetLocalCounterpart(base::WeakPtr local_counterpart, - scoped_refptr - counterpart_task_runner) override; - base::WeakPtr GetAudioSocketWeakPtr() override; - - void SetDelegate(Delegate* delegate) override; - - void UseBufferPool(scoped_refptr buffer_pool) override; - - bool SendAudioBuffer(scoped_refptr audio_buffer, - int filled_bytes, - int64_t timestamp) override; - bool SendProto(int type, - const google::protobuf::MessageLite& message) override; - void ReceiveMoreMessages() override; - - private: - class AudioSocketExtension : public AudioSocket { - public: - explicit AudioSocketExtension(std::unique_ptr socket); - AudioSocketExtension(const MixerSocketImpl&) = delete; - AudioSocketExtension& operator=(const MixerSocketImpl&) = delete; - ~AudioSocketExtension() override; - - // Used to create local (in-process) connections. - AudioSocketExtension(); - - void SetDelegate(MixerSocket::Delegate* delegate); - - private: - bool ParseMetadata(char* data, size_t size) override; - - MixerSocket::Delegate* delegate_ = nullptr; - }; - - std::unique_ptr audio_socket_ = nullptr; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MIXER_SOCKET_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mock_mixer_socket.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mock_mixer_socket.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mock_mixer_socket.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mock_mixer_socket.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/mock_mixer_socket.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -MockMixerSocket::MockMixerSocket() = default; -MockMixerSocket::~MockMixerSocket() = default; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mock_mixer_socket.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mock_mixer_socket.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/mock_mixer_socket.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/mock_mixer_socket.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MOCK_MIXER_SOCKET_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MOCK_MIXER_SOCKET_H_ -#include "chromecast/media/audio/mixer_service/mixer_socket.h" - -#include "base/task/sequenced_task_runner.h" -#include "chromecast/net/io_buffer_pool.h" -#include "net/base/io_buffer.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -class MockMixerSocket : public MixerSocket { - public: - MockMixerSocket(); - ~MockMixerSocket() override; - - MOCK_METHOD(void, - SetLocalCounterpart, - (base::WeakPtr, - scoped_refptr), - (override)); - MOCK_METHOD(base::WeakPtr, - GetAudioSocketWeakPtr, - (), - (override)); - MOCK_METHOD(void, SetDelegate, (MixerSocket::Delegate*), (override)); - MOCK_METHOD(void, UseBufferPool, (scoped_refptr), (override)); - MOCK_METHOD(bool, - SendAudioBuffer, - (scoped_refptr, int, int64_t), - (override)); - MOCK_METHOD(bool, - SendProto, - (int, const google::protobuf::MessageLite& message), - (override)); - MOCK_METHOD(void, ReceiveMoreMessages, (), (override)); -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_MOCK_MIXER_SOCKET_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/output_stream_connection.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/output_stream_connection.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/output_stream_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/output_stream_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,256 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/output_stream_connection.h" - -#include -#include - -#include "base/logging.h" -#include "base/memory/aligned_memory.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/metrics/metrics_recorder.h" -#include "chromecast/net/io_buffer_pool.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -namespace { - -int GetFrameSize(const OutputStreamParams& params) { - return audio_service::GetSampleSizeBytes(params.sample_format()) * - params.num_channels(); -} - -int GetFillSizeFrames(const OutputStreamParams& params) { - if (params.has_fill_size_frames()) { - return params.fill_size_frames(); - } - // Use 10 ms by default. - return params.sample_rate() / 100; -} - -enum MessageTypes : int { - kInitial = 1, - kStartTimestamp, - kPlaybackRate, - kAudioClockRate, - kStreamVolume, - kPauseResume, - kEndOfStream, - kTimestampAdjustment, -}; - -} // namespace - -OutputStreamConnection::OutputStreamConnection(Delegate* delegate, - const OutputStreamParams& params) - : delegate_(delegate), - params_(std::make_unique(params)), - frame_size_(GetFrameSize(params)), - fill_size_frames_(GetFillSizeFrames(params)), - buffer_pool_(base::MakeRefCounted( - MixerSocket::kAudioMessageHeaderSize + - fill_size_frames_ * frame_size_, - std::numeric_limits::max(), - true /* threadsafe */)), - audio_buffer_(buffer_pool_->GetBuffer()) { - DCHECK(delegate_); - DCHECK_GT(params_->sample_rate(), 0); - DCHECK_GT(params_->num_channels(), 0); - params_->set_fill_size_frames(fill_size_frames_); -} - -OutputStreamConnection::~OutputStreamConnection() = default; - -void OutputStreamConnection::Connect() { - MixerConnection::Connect(); -} - -void OutputStreamConnection::SendNextBuffer(int filled_frames, int64_t pts) { - SendAudioBuffer(std::move(audio_buffer_), filled_frames, pts); - audio_buffer_ = buffer_pool_->GetBuffer(); -} - -void OutputStreamConnection::SendAudioBuffer( - scoped_refptr audio_buffer, - int filled_frames, - int64_t pts) { - if (!socket_) { - LOG(INFO) << "Tried to send buffer without a connection"; - return; - } - if (sent_eos_) { - // Don't send any more data after the EOS buffer. - return; - } - - if (filled_frames == 0) { - // Send explicit end-of-stream message. - sent_eos_ = true; - Generic message; - message.mutable_eos_played_out(); - socket_->SendProto(kEndOfStream, message); - return; - } - if (socket_->SendAudioBuffer(std::move(audio_buffer), - filled_frames * frame_size_, pts)) { - LOG_IF(INFO, dropping_audio_) << "Stopped dropping audio"; - dropping_audio_ = false; - } else { - LOG_IF(WARNING, !dropping_audio_) << "Dropping audio"; - dropping_audio_ = true; - } -} - -void OutputStreamConnection::SetVolumeMultiplier(float multiplier) { - volume_multiplier_ = multiplier; - if (socket_) { - Generic message; - message.mutable_set_stream_volume()->set_volume(multiplier); - socket_->SendProto(kStreamVolume, message); - } -} - -void OutputStreamConnection::SetStartTimestamp(int64_t start_timestamp, - int64_t pts) { - start_timestamp_ = start_timestamp; - start_pts_ = pts; - - if (socket_) { - Generic message; - message.mutable_set_start_timestamp()->set_start_timestamp(start_timestamp); - message.mutable_set_start_timestamp()->set_start_pts(pts); - socket_->SendProto(kStartTimestamp, message); - } -} - -void OutputStreamConnection::SetPlaybackRate(float playback_rate) { - playback_rate_ = playback_rate; - if (socket_) { - Generic message; - message.mutable_set_playback_rate()->set_playback_rate(playback_rate); - socket_->SendProto(kPlaybackRate, message); - } -} - -void OutputStreamConnection::SetAudioClockRate(double rate) { - audio_clock_rate_ = rate; - if (socket_) { - Generic message; - message.mutable_set_audio_clock_rate()->set_rate(rate); - socket_->SendProto(kAudioClockRate, message); - } -} - -void OutputStreamConnection::Pause() { - paused_ = true; - if (socket_) { - Generic message; - message.mutable_set_paused()->set_paused(true); - socket_->SendProto(kPauseResume, message); - } -} - -void OutputStreamConnection::Resume() { - paused_ = false; - if (socket_) { - Generic message; - auto* pause_message = message.mutable_set_paused(); - pause_message->set_paused(false); - socket_->SendProto(kPauseResume, message); - } -} - -void OutputStreamConnection::SendTimestampAdjustment( - int64_t timestamp_adjustment) { - if (socket_) { - Generic message; - auto* adjustment_message = message.mutable_timestamp_adjustment(); - adjustment_message->set_adjustment(timestamp_adjustment); - socket_->SendProto(kTimestampAdjustment, message); - } -} - -void OutputStreamConnection::OnConnected(std::unique_ptr socket) { - socket_ = std::move(socket); - socket_->SetDelegate(this); - - Generic message; - *(message.mutable_output_stream_params()) = *params_; - if (start_timestamp_ != INT64_MIN) { - message.mutable_set_start_timestamp()->set_start_timestamp( - start_timestamp_); - message.mutable_set_start_timestamp()->set_start_pts(start_pts_); - } - if (playback_rate_ != 1.0f) { - message.mutable_set_playback_rate()->set_playback_rate(playback_rate_); - } - if (audio_clock_rate_ != 1.0) { - message.mutable_set_audio_clock_rate()->set_rate(audio_clock_rate_); - } - if (volume_multiplier_ != 1.0f) { - message.mutable_set_stream_volume()->set_volume(volume_multiplier_); - } - if (paused_) { - message.mutable_set_paused()->set_paused(true); - } - socket_->SendProto(kInitial, message); - delegate_->FillNextBuffer( - audio_buffer_->data() + MixerSocket::kAudioMessageHeaderSize, - fill_size_frames_, std::numeric_limits::min(), 0); -} - -void OutputStreamConnection::OnConnectionError() { - socket_.reset(); - if (sent_eos_) { - delegate_->OnEosPlayed(); - return; - } - MixerConnection::Connect(); -} - -bool OutputStreamConnection::HandleMetadata(const Generic& message) { - if (message.has_eos_played_out()) { - delegate_->OnEosPlayed(); - return true; - } - - if (message.has_push_result() && !sent_eos_) { - delegate_->FillNextBuffer( - audio_buffer_->data() + MixerSocket::kAudioMessageHeaderSize, - fill_size_frames_, message.push_result().delay_timestamp(), - message.push_result().delay()); - } - - if (message.has_ready_for_playback()) { - delegate_->OnAudioReadyForPlayback( - message.ready_for_playback().delay_microseconds()); - } - - if (message.has_error()) { - delegate_->OnMixerError(); - } - - if (message.has_mixer_underrun()) { - std::string metric_name = - (message.mixer_underrun().type() == MixerUnderrun::INPUT_UNDERRUN - ? "Platform.Audio.Mixer.StreamUnderrun" - : "Platform.Audio.Mixer.OutputUnderrun"); - std::unique_ptr event = CreateCastEvent(metric_name); - delegate_->ProcessCastEvent(event.get()); - RecordCastEvent(metric_name, std::move(event), - /* verbose_log_level = */ 0); - delegate_->OnMixerUnderrun(static_cast( - message.mixer_underrun().type())); - } - return true; -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/output_stream_connection.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/output_stream_connection.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/output_stream_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/output_stream_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,162 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_OUTPUT_STREAM_CONNECTION_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_OUTPUT_STREAM_CONNECTION_H_ - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "chromecast/media/audio/mixer_service/mixer_connection.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "net/base/io_buffer.h" - -namespace chromecast { -class CastEventBuilder; -class IOBufferPool; - -namespace media { -namespace mixer_service { -class Generic; -class OutputStreamParams; - -// Mixer service connection for an audio output stream. Not thread-safe; all -// usage of a given instance must be on the same sequence. -class OutputStreamConnection : public MixerConnection, - public MixerSocket::Delegate { - public: - class Delegate { - public: - // Keep in sync with mixer_service.proto:MixerUnderrun.Type - enum class MixerUnderrunType { - // An underrun was detected on mixer input. - kStream = 0, - // An underrun was detected on mixer output. - kMixer = 1, - }; - - // Called to fill more audio data. The implementation should write up to - // |frames| frames of audio data into |buffer|, and then call - // SendNextBuffer() with the actual number of frames that were filled (or - // 0 to indicate end-of-stream). The |playout_timestamp| indicates the - // audio clock timestamp in microseconds when the first frame of the filled - // data is expected to play out. - virtual void FillNextBuffer(void* buffer, - int frames, - int64_t delay_timestamp, - int64_t delay) = 0; - - // Called when audio is ready to begin playing out, ie the start threshold - // has been reached. |mixer_delay| is the delay before the first buffered - // audio will start playing out, in microseconds. - virtual void OnAudioReadyForPlayback(int64_t mixer_delay) {} - - // Called when the end of the stream has been played out. At this point it - // is safe to delete the delegate without dropping any audio. - virtual void OnEosPlayed() = 0; - - // Called when a mixer error has occurred; audio from this stream will no - // longer be played out. - virtual void OnMixerError() {} - - // Called when an underrun happens on mixer input/output. - virtual void OnMixerUnderrun(MixerUnderrunType type) {} - - // Called when OutputStreamConnection records a cast event. It allows - // the Delegate to provide some extra data to the event. - virtual void ProcessCastEvent(CastEventBuilder* event) {} - - protected: - virtual ~Delegate() = default; - }; - - OutputStreamConnection(Delegate* delegate, const OutputStreamParams& params); - - OutputStreamConnection(const OutputStreamConnection&) = delete; - OutputStreamConnection& operator=(const OutputStreamConnection&) = delete; - - ~OutputStreamConnection() override; - - // Connects to the mixer. After this is called, delegate methods may start - // to be called. If the mixer connection is lost, this will automatically - // reconnect. - void Connect(); - - // Sends filled audio data (written into the buffer provided to - // FillNextBuffer()) to the mixer. |filled_frames| indicates the number of - // frames of audio that were actually written into the buffer, or 0 to - // indicate end-of-stream. |pts| is the PTS of the first frame of filled - // audio; this is only meaningful when params.use_start_timestamp is |true|. - void SendNextBuffer(int filled_frames, int64_t pts = 0); - - // Sends a preallocated audio buffer. The buffer does not need to be prepared - // first using MixerSocket::PrepareAudioBuffer(), since that is done inside - // this method. - void SendAudioBuffer(scoped_refptr audio_buffer, - int filled_frames, - int64_t pts); - - // Sets the volume multiplier for this audio stream. - void SetVolumeMultiplier(float multiplier); - - // Indicates that playback should (re)start playing PTS |pts| at time - // |start_timestamp| in microseconds relative to the audio clock. - void SetStartTimestamp(int64_t start_timestamp, int64_t pts); - - // Informs the mixer how fast the PTS increases per frame. For example if the - // playback rate is 2.0, then each frame increases the PTS by - // 2.0 / sample_rate seconds. - void SetPlaybackRate(float playback_rate); - - // Changes the audio output clock rate. If the provided |rate| is outside of - // the supported range, the rate will be clamped to the supported range. - void SetAudioClockRate(double rate); - - // Pauses playback. - void Pause(); - - // Resumes playback. - void Resume(); - - // Adjusts timestamps. - void SendTimestampAdjustment(int64_t timestamp_adjustment); - - private: - // MixerConnection implementation: - void OnConnected(std::unique_ptr socket) override; - void OnConnectionError() override; - - // MixerSocket::Delegate implementation: - bool HandleMetadata(const Generic& message) override; - - Delegate* const delegate_; - std::unique_ptr params_; - - const int frame_size_; - const int fill_size_frames_; - - const scoped_refptr buffer_pool_; - scoped_refptr audio_buffer_; - - std::unique_ptr socket_; - float volume_multiplier_ = 1.0f; - - int64_t start_timestamp_ = INT64_MIN; - int64_t start_pts_ = INT64_MIN; - - float playback_rate_ = 1.0f; - double audio_clock_rate_ = 1.0; - - bool paused_ = false; - bool sent_eos_ = false; - - bool dropping_audio_ = false; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_OUTPUT_STREAM_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,227 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/receiver/cma_backend_shim.h" - -#include -#include - -#include "base/compiler_specific.h" -#include "base/containers/span.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/numerics/safe_conversions.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/media/common/media_pipeline_backend_manager.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/media/stream_id.h" -#include "chromecast/public/volume_control.h" -#include "media/base/decoder_buffer.h" -#include "media/base/timestamp_constants.h" - -#define POST_DELEGATE_TASK(callback, ...) \ - if (delegate_task_runner_) { \ - delegate_task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(callback, delegate_, ##__VA_ARGS__)); \ - } - -#define POST_MEDIA_TASK(callback, ...) \ - media_task_runner_->PostTask( \ - FROM_HERE, \ - base::BindOnce(callback, base::Unretained(this), ##__VA_ARGS__)) - -namespace chromecast { -namespace media { - -namespace { - -MediaPipelineDeviceParams::AudioStreamType ConvertStreamType( - mixer_service::OutputStreamParams::StreamType type) { - if (type == mixer_service::OutputStreamParams::STREAM_TYPE_SFX) { - return MediaPipelineDeviceParams::kAudioStreamSoundEffects; - } - return MediaPipelineDeviceParams::kAudioStreamNormal; -} - -AudioChannel ConvertChannelSelection(int channel_selection) { - switch (channel_selection) { - case -1: - return AudioChannel::kAll; - case 0: - return AudioChannel::kLeft; - case 1: - return AudioChannel::kRight; - default: - NOTREACHED(); - } -} - -} // namespace - -namespace mixer_service { - -CmaBackendShim::CmaBackendShim( - base::WeakPtr delegate, - scoped_refptr delegate_task_runner, - const mixer_service::OutputStreamParams& params, - MediaPipelineBackendManager* backend_manager) - : delegate_(std::move(delegate)), - delegate_task_runner_(std::move(delegate_task_runner)), - params_(params), - backend_manager_(backend_manager), - media_task_runner_(backend_manager_->GetMediaTaskRunner()), - backend_task_runner_(backend_manager_->task_runner()), - audio_decoder_(nullptr) { - DETACH_FROM_SEQUENCE(media_sequence_checker_); - POST_MEDIA_TASK(&CmaBackendShim::InitializeOnMediaThread); -} - -CmaBackendShim::~CmaBackendShim() { - DCHECK_CALLED_ON_VALID_SEQUENCE(media_sequence_checker_); - cma_backend_->Stop(); -} - -void CmaBackendShim::Remove() { - POST_MEDIA_TASK(&CmaBackendShim::DestroyOnMediaThread); -} - -void CmaBackendShim::InitializeOnMediaThread() { - DCHECK_CALLED_ON_VALID_SEQUENCE(media_sequence_checker_); - MediaPipelineDeviceParams device_params( - MediaPipelineDeviceParams::kModeIgnorePts, - ConvertStreamType(params_.stream_type()), &backend_task_runner_, - audio_service::ConvertContentType(params_.content_type()), - params_.device_id()); - device_params.audio_channel = - ConvertChannelSelection(params_.channel_selection()); - cma_backend_ = backend_manager_->CreateBackend(device_params); - - audio_decoder_ = cma_backend_->CreateAudioDecoder(); - if (!audio_decoder_) { - LOG(ERROR) << "Failed to create CMA audio decoder"; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } - audio_decoder_->SetDelegate(this); - - AudioConfig audio_config; - audio_config.id = kPrimary; - audio_config.codec = kCodecPCM; - audio_config.channel_layout = - audio_service::ConvertChannelLayout(params_.channel_layout()); - if (audio_config.channel_layout == media::ChannelLayout::UNSUPPORTED || - audio_config.channel_layout == media::ChannelLayout::BITSTREAM) { - audio_config.channel_layout = - ChannelLayoutFromChannelNumber(params_.num_channels()); - } - audio_config.sample_format = - audio_service::ConvertSampleFormat(params_.sample_format()); - audio_config.bytes_per_channel = - audio_service::GetSampleSizeBytes(params_.sample_format()); - audio_config.channel_number = params_.num_channels(); - audio_config.samples_per_second = params_.sample_rate(); - if (!audio_decoder_->SetConfig(audio_config)) { - LOG(ERROR) << "Failed to set CMA audio config"; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } - audio_decoder_->SetVolume(1.0f); - - if (!cma_backend_->Initialize() || !cma_backend_->Start(0)) { - LOG(ERROR) << "Failed to start CMA backend"; - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } -} - -void CmaBackendShim::DestroyOnMediaThread() { - DCHECK_CALLED_ON_VALID_SEQUENCE(media_sequence_checker_); - delete this; -} - -void CmaBackendShim::AddData(char* data, int size) { - scoped_refptr<::media::DecoderBuffer> buffer; - if (size == 0) { - buffer = ::media::DecoderBuffer::CreateEOSBuffer(); - } else { - // TODO(crbug.com/40284755): These functions should use span and size_t. - buffer = ::media::DecoderBuffer::CopyFrom(base::as_bytes( - UNSAFE_TODO(base::span(data, base::checked_cast(size))))); - buffer->set_timestamp(::media::kNoTimestamp); - } - POST_MEDIA_TASK(&CmaBackendShim::AddDataOnMediaThread, std::move(buffer)); -} - -void CmaBackendShim::AddDataOnMediaThread( - scoped_refptr<::media::DecoderBuffer> buffer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(media_sequence_checker_); - if (!audio_decoder_) { - return; - } - pushed_buffer_ = - base::MakeRefCounted(std::move(buffer)); - BufferStatus status = audio_decoder_->PushBuffer(pushed_buffer_); - - if (status != MediaPipelineBackend::kBufferPending) { - OnPushBufferComplete(status); - } -} - -void CmaBackendShim::SetVolumeMultiplier(float multiplier) { - multiplier = std::clamp(multiplier, 0.0f, 1.0f); - POST_MEDIA_TASK(&CmaBackendShim::SetVolumeMultiplierOnMediaThread, - multiplier); -} - -void CmaBackendShim::SetVolumeMultiplierOnMediaThread(float multiplier) { - if (!audio_decoder_) { - return; - } - audio_decoder_->SetVolume(multiplier); -} - -void CmaBackendShim::OnPushBufferComplete(BufferStatus status) { - DCHECK_CALLED_ON_VALID_SEQUENCE(media_sequence_checker_); - pushed_buffer_.reset(); - if (status != MediaPipelineBackend::kBufferSuccess) { - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); - return; - } - if (!audio_decoder_) { - return; - } - - RenderingDelay delay = audio_decoder_->GetRenderingDelay(); - POST_DELEGATE_TASK(&Delegate::OnBufferPushed, delay); -} - -void CmaBackendShim::OnEndOfStream() { - DCHECK_CALLED_ON_VALID_SEQUENCE(media_sequence_checker_); - POST_DELEGATE_TASK(&Delegate::PlayedEos); -} - -void CmaBackendShim::OnDecoderError() { - DCHECK_CALLED_ON_VALID_SEQUENCE(media_sequence_checker_); - POST_DELEGATE_TASK(&Delegate::OnAudioPlaybackError); -} - -void CmaBackendShim::OnKeyStatusChanged(const std::string& /* key_id */, - CastKeyStatus /* key_status */, - uint32_t /* system_code */) { - // Ignored. -} - -void CmaBackendShim::OnVideoResolutionChanged(const Size& /* size */) { - // Ignored. -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/cma_backend_shim.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,123 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_CMA_BACKEND_SHIM_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_CMA_BACKEND_SHIM_H_ - -#include -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace media { -class DecoderBuffer; -} // namespace media - -namespace chromecast { -namespace media { -class MediaPipelineBackendManager; - -namespace mixer_service { - -// A shim to allow the mixer service to use the CMA backend API if the direct -// audio API is not available. May be created and used on any thread; internally -// runs all tasks on the media thread. Deletion must be done using Remove() (or -// using a unique_ptr with custom Deleter); Remove() will eventually delete this -// on the appropriate sequence. -class CmaBackendShim : public CmaBackend::AudioDecoder::Delegate { - public: - using RenderingDelay = CmaBackend::AudioDecoder::RenderingDelay; - - class Delegate { - public: - // Called once data passed to AddData() has been accepted into the queue. - // |rendering_delay| is the estimated rendering delay for the data passed to - // the next call to AddData(), relative to the clock used for audio - // timestamping. - virtual void OnBufferPushed(RenderingDelay rendering_delay) = 0; - - // Called once the end-of-stream has been played out. - virtual void PlayedEos() = 0; - - // Called if an error occurs in audio playback. No more delegate calls will - // be made. - virtual void OnAudioPlaybackError() = 0; - - protected: - virtual ~Delegate() = default; - }; - - // Can be used as a custom deleter for unique_ptr. - struct Deleter { - void operator()(CmaBackendShim* obj) { obj->Remove(); } - }; - - CmaBackendShim(base::WeakPtr delegate, - scoped_refptr delegate_task_runner, - const OutputStreamParams& params, - MediaPipelineBackendManager* backend_manager); - - CmaBackendShim(const CmaBackendShim&) = delete; - CmaBackendShim& operator=(const CmaBackendShim&) = delete; - - // Removes this audio output. Public methods must not be called after Remove() - // is called. - void Remove(); - - // Adds more data to be played out. More data should not be passed to - // AddData() until OnBufferPushed() has been called for the previous AddData() - // call. |size| is the size of |data| in bytes; a size of 0 indicates - // end-of-stream. - void AddData(char* data, int size); - - // Sets the volume multiplier for this stream. - void SetVolumeMultiplier(float multiplier); - - private: - ~CmaBackendShim() override; - - void InitializeOnMediaThread(); - void DestroyOnMediaThread(); - void AddDataOnMediaThread(scoped_refptr<::media::DecoderBuffer> buffer); - void SetVolumeMultiplierOnMediaThread(float multiplier); - - // CmaBackend::AudioDecoder::Delegate implementation: - void OnPushBufferComplete(BufferStatus status) override; - void OnEndOfStream() override; - void OnDecoderError() override; - void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override; - void OnVideoResolutionChanged(const Size& size) override; - - const base::WeakPtr delegate_; - const scoped_refptr delegate_task_runner_; - const OutputStreamParams params_; - MediaPipelineBackendManager* const backend_manager_; - scoped_refptr pushed_buffer_; - - const scoped_refptr media_task_runner_; - TaskRunnerImpl backend_task_runner_; - - SEQUENCE_CHECKER(media_sequence_checker_); - - std::unique_ptr cma_backend_; - CmaBackend::AudioDecoder* audio_decoder_; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_CMA_BACKEND_SHIM_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,183 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/receiver/receiver.h" - -#include -#include - -#include "base/check.h" -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/no_destructor.h" -#include "base/synchronization/lock.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/media/audio/mixer_service/constants.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { -namespace mixer_service { -namespace { - -constexpr int kMaxAcceptLoop = 5; - -std::string GetEndpoint() { - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - std::string path = - command_line->GetSwitchValueASCII(switches::kMixerServiceEndpoint); - if (path.empty()) { - return mixer_service::kDefaultUnixDomainSocketPath; - } - return path; -} - -class LocalReceiverInstance { - public: - LocalReceiverInstance() = default; - - LocalReceiverInstance(const LocalReceiverInstance&) = delete; - LocalReceiverInstance& operator=(const LocalReceiverInstance&) = delete; - - void SetInstance(Receiver* receiver) { - base::AutoLock lock(lock_); - receiver_ = receiver; - } - - void RemoveInstance(Receiver* receiver) { - base::AutoLock lock(lock_); - if (receiver_ == receiver) { - receiver_ = nullptr; - } - } - - std::unique_ptr CreateLocalSocket() { - base::AutoLock lock(lock_); - if (receiver_) { - return receiver_->LocalConnect(); - } - return nullptr; - } - - private: - base::Lock lock_; - Receiver* receiver_ = nullptr; -}; - -LocalReceiverInstance* GetLocalReceiver() { - static base::NoDestructor instance; - return instance.get(); -} - -} // namespace - -std::unique_ptr CreateLocalMixerServiceConnection() { - return GetLocalReceiver()->CreateLocalSocket(); -} - -class Receiver::InitialSocket : public MixerSocket::Delegate { - public: - InitialSocket(Receiver* receiver, std::unique_ptr socket) - : receiver_(receiver), socket_(std::move(socket)) { - DCHECK(receiver_); - socket_->SetDelegate(this); - } - - InitialSocket(const InitialSocket&) = delete; - InitialSocket& operator=(const InitialSocket&) = delete; - - ~InitialSocket() override = default; - - private: - // MixerSocket::Delegate implementation: - bool HandleMetadata(const Generic& message) override { - if (message.has_output_stream_params()) { - receiver_->CreateOutputStream(std::move(socket_), message); - receiver_->RemoveInitialSocket(this); - } else if (message.has_loopback_request()) { - receiver_->CreateLoopbackConnection(std::move(socket_), message); - receiver_->RemoveInitialSocket(this); - } else if (message.has_redirection_request()) { - receiver_->CreateAudioRedirection(std::move(socket_), message); - receiver_->RemoveInitialSocket(this); - } else if (message.has_set_device_volume() || - message.has_set_device_muted() || - message.has_set_volume_limit() || - message.has_configure_postprocessor() || - message.has_reload_postprocessors() || - message.has_request_stream_count() || - message.has_set_num_output_channels()) { - receiver_->CreateControlConnection(std::move(socket_), message); - receiver_->RemoveInitialSocket(this); - } - - return true; - } - - void OnConnectionError() override { receiver_->RemoveInitialSocket(this); } - - Receiver* const receiver_; - std::unique_ptr socket_; -}; - -Receiver::Receiver() - : task_runner_(base::SequencedTaskRunner::GetCurrentDefault()), - socket_service_( - GetEndpoint(), - GetSwitchValueNonNegativeInt(switches::kMixerServicePort, - mixer_service::kDefaultTcpPort), - kMaxAcceptLoop, - this), - weak_factory_(this) { - socket_service_.Accept(); - GetLocalReceiver()->SetInstance(this); -} - -Receiver::~Receiver() { - GetLocalReceiver()->RemoveInstance(this); -} - -std::unique_ptr Receiver::LocalConnect() { - auto receiver_socket = std::make_unique(); - auto caller_socket = std::make_unique(); - - receiver_socket->SetLocalCounterpart( - caller_socket->GetAudioSocketWeakPtr(), - base::SequencedTaskRunner::GetCurrentDefault()); - caller_socket->SetLocalCounterpart(receiver_socket->GetAudioSocketWeakPtr(), - task_runner_); - - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&Receiver::HandleLocalConnection, - weak_factory_.GetWeakPtr(), std::move(receiver_socket))); - - return caller_socket; -} - -void Receiver::HandleAcceptedSocket(std::unique_ptr socket) { - AddInitialSocket(std::make_unique( - this, std::make_unique(std::move(socket)))); -} - -void Receiver::HandleLocalConnection(std::unique_ptr socket) { - AddInitialSocket(std::make_unique(this, std::move(socket))); -} - -void Receiver::AddInitialSocket(std::unique_ptr initial_socket) { - InitialSocket* ptr = initial_socket.get(); - initial_sockets_[ptr] = std::move(initial_socket); -} - -void Receiver::RemoveInitialSocket(InitialSocket* socket) { - initial_sockets_.erase(socket); -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_H_ - -#include - -#include "base/containers/flat_map.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/net/audio_socket_service.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace chromecast { -namespace media { -namespace mixer_service { -class MixerSocket; - -class Receiver : public AudioSocketService::Delegate { - public: - Receiver(); - - Receiver(const Receiver&) = delete; - Receiver& operator=(const Receiver&) = delete; - - ~Receiver() override; - - virtual void CreateOutputStream(std::unique_ptr socket, - const Generic& message) = 0; - virtual void CreateLoopbackConnection(std::unique_ptr socket, - const Generic& message) = 0; - virtual void CreateAudioRedirection(std::unique_ptr socket, - const Generic& message) = 0; - virtual void CreateControlConnection(std::unique_ptr socket, - const Generic& message) = 0; - - // Creates a local (in-process) connection to this receiver. May be called on - // any thread; the returned MixerSocket can only be used on the calling - // thread. The returned socket must have its delegate set immediately. - std::unique_ptr LocalConnect(); - - private: - class InitialSocket; - - // AudioSocketService::Delegate implementation: - void HandleAcceptedSocket(std::unique_ptr socket) override; - - void HandleLocalConnection(std::unique_ptr socket); - - void AddInitialSocket(std::unique_ptr initial_socket); - void RemoveInitialSocket(InitialSocket* socket); - - const scoped_refptr task_runner_; - - AudioSocketService socket_service_; - - base::flat_map> - initial_sockets_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver_cma.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_cma.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver_cma.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_cma.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,236 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/receiver/receiver_cma.h" - -#include -#include - -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/audio/mixer_service/receiver/cma_backend_shim.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -namespace { - -constexpr base::TimeDelta kInactivityTimeout = base::Seconds(5); - -enum MessageTypes : int { - kPushResult = 1, - kEndOfStream, -}; - -} // namespace - -class ReceiverCma::UnusedSocket : public MixerSocket::Delegate { - public: - UnusedSocket(ReceiverCma* receiver, std::unique_ptr socket) - : receiver_(receiver), socket_(std::move(socket)) { - DCHECK(receiver_); - DCHECK(socket_); - socket_->SetDelegate(this); - } - - UnusedSocket(const UnusedSocket&) = delete; - UnusedSocket& operator=(const UnusedSocket&) = delete; - - ~UnusedSocket() override = default; - - private: - // MixerSocket::Delegate implementation: - void OnConnectionError() override { receiver_->RemoveUnusedSocket(this); } - - ReceiverCma* const receiver_; - const std::unique_ptr socket_; -}; - -class ReceiverCma::Stream : public MixerSocket::Delegate, - public CmaBackendShim::Delegate { - public: - Stream(ReceiverCma* receiver, std::unique_ptr socket) - : receiver_(receiver), socket_(std::move(socket)), weak_factory_(this) { - DCHECK(receiver_); - DCHECK(socket_); - - socket_->SetDelegate(this); - - inactivity_timer_.Start(FROM_HERE, kInactivityTimeout, this, - &Stream::OnInactivityTimeout); - } - - Stream(const Stream&) = delete; - Stream& operator=(const Stream&) = delete; - - ~Stream() override = default; - - // MixerSocket::Delegate implementation: - bool HandleMetadata(const mixer_service::Generic& message) override { - last_receive_time_ = base::TimeTicks::Now(); - inactivity_timer_.Reset(); - - if (message.has_output_stream_params()) { - if (cma_audio_) { - LOG(INFO) << "Received stream metadata after stream was already set up"; - return true; - } - - pushed_eos_ = false; - cma_audio_.reset(new mixer_service::CmaBackendShim( - weak_factory_.GetWeakPtr(), - base::SequencedTaskRunner::GetCurrentDefault(), - message.output_stream_params(), receiver_->backend_manager())); - } - - if (message.has_set_stream_volume()) { - if (!cma_audio_) { - LOG(INFO) << "Can't set volume before stream is set up"; - return true; - } - cma_audio_->SetVolumeMultiplier(message.set_stream_volume().volume()); - } - - if (message.has_eos_played_out()) { - // Explicit EOS. - return HandleAudioData(nullptr, 0, INT64_MIN); - } - - return true; - } - - bool HandleAudioData(char* data, size_t size, int64_t timestamp) override { - last_receive_time_ = base::TimeTicks::Now(); - inactivity_timer_.Reset(); - - if (!cma_audio_) { - LOG(INFO) << "Received audio before stream metadata; ignoring"; - return true; - } - - if (size == 0) { - pushed_eos_ = true; - } - cma_audio_->AddData(data, size); - return false; // Don't receive any more messages until the buffer is - // pushed. - } - - void OnConnectionError() override { - LOG(INFO) << "Connection lost for " << this; - receiver_->RemoveStream(this); - } - - private: - void OnInactivityTimeout() { - LOG(INFO) << "Timed out " << this - << " due to inactivity; now = " << base::TimeTicks::Now() - << ", last send = " << last_send_time_ - << ", last receive = " << last_receive_time_; - receiver_->RemoveStream(this); - } - - // CmaBackendShim::Delegate implementation: - void OnBufferPushed(CmaBackendShim::RenderingDelay rendering_delay) override { - if (!pushed_eos_) { - mixer_service::BufferPushResult message; - message.set_delay_timestamp(rendering_delay.timestamp_microseconds); - message.set_delay(rendering_delay.delay_microseconds); - mixer_service::Generic generic; - *(generic.mutable_push_result()) = message; - socket_->SendProto(kPushResult, generic); - last_send_time_ = base::TimeTicks::Now(); - } - - socket_->ReceiveMoreMessages(); - } - - void PlayedEos() override { - LOG(INFO) << "EOS played for " << this; - mixer_service::EosPlayedOut message; - mixer_service::Generic generic; - *generic.mutable_eos_played_out() = message; - socket_->SendProto(kEndOfStream, generic); - last_send_time_ = base::TimeTicks::Now(); - - cma_audio_.reset(); - } - - void OnAudioPlaybackError() override { - LOG(INFO) << "Audio playback error for " << this; - receiver_->RemoveStream(this); - } - - ReceiverCma* const receiver_; - const std::unique_ptr socket_; - - base::OneShotTimer inactivity_timer_; - - std::unique_ptr - cma_audio_; - bool pushed_eos_ = false; - - base::TimeTicks last_send_time_; - base::TimeTicks last_receive_time_; - - base::WeakPtrFactory weak_factory_; -}; - -ReceiverCma::ReceiverCma(MediaPipelineBackendManager* backend_manager) - : backend_manager_(backend_manager) { - DCHECK(backend_manager_); -} - -ReceiverCma::~ReceiverCma() = default; - -void ReceiverCma::CreateOutputStream(std::unique_ptr socket, - const Generic& message) { - auto stream = std::make_unique(this, std::move(socket)); - Stream* ptr = stream.get(); - streams_[ptr] = std::move(stream); - ptr->HandleMetadata(message); -} - -void ReceiverCma::CreateLoopbackConnection(std::unique_ptr socket, - const Generic& message) { - LOG(INFO) << "Unhandled loopback connection"; - AddUnusedSocket(std::move(socket)); -} - -void ReceiverCma::CreateAudioRedirection(std::unique_ptr socket, - const Generic& message) { - LOG(INFO) << "Unhandled redirection connection"; - AddUnusedSocket(std::move(socket)); -} - -void ReceiverCma::CreateControlConnection(std::unique_ptr socket, - const Generic& message) { - LOG(INFO) << "Unhandled control connection"; - AddUnusedSocket(std::move(socket)); -} - -void ReceiverCma::RemoveStream(Stream* stream) { - streams_.erase(stream); -} - -void ReceiverCma::AddUnusedSocket(std::unique_ptr socket) { - auto unused_socket = std::make_unique(this, std::move(socket)); - UnusedSocket* ptr = unused_socket.get(); - unused_sockets_[ptr] = std::move(unused_socket); -} - -void ReceiverCma::RemoveUnusedSocket(UnusedSocket* unused_socket) { - unused_sockets_.erase(unused_socket); -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver_cma.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_cma.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver_cma.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_cma.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_CMA_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_CMA_H_ - -#include - -#include "base/containers/flat_map.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/mixer_service/receiver/receiver.h" - -namespace chromecast { -namespace media { -class MediaPipelineBackendManager; - -namespace mixer_service { -class MixerSocket; - -class ReceiverCma : public Receiver { - public: - explicit ReceiverCma(MediaPipelineBackendManager* backend_manager); - - ReceiverCma(const ReceiverCma&) = delete; - ReceiverCma& operator=(const ReceiverCma&) = delete; - - ~ReceiverCma() override; - - MediaPipelineBackendManager* backend_manager() const { - return backend_manager_; - } - - private: - class Stream; - class UnusedSocket; - - // Receiver implementation: - void CreateOutputStream(std::unique_ptr socket, - const Generic& message) override; - void CreateLoopbackConnection(std::unique_ptr socket, - const Generic& message) override; - void CreateAudioRedirection(std::unique_ptr socket, - const Generic& message) override; - void CreateControlConnection(std::unique_ptr socket, - const Generic& message) override; - - void RemoveStream(Stream* stream); - - void AddUnusedSocket(std::unique_ptr socket); - void RemoveUnusedSocket(UnusedSocket* unused_socket); - - MediaPipelineBackendManager* const backend_manager_; - - base::flat_map> streams_; - base::flat_map> unused_sockets_; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_CMA_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver_creation.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_creation.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver_creation.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_creation.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/receiver/receiver_creation.h" - -#include "base/threading/sequence_bound.h" -#include "chromecast/media/audio/audio_io_thread.h" -#include "chromecast/media/audio/mixer_service/constants.h" -#include "chromecast/media/audio/mixer_service/receiver/receiver_cma.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -namespace { - -class CmaReceiverInstance : public ReceiverInstance { - public: - explicit CmaReceiverInstance(MediaPipelineBackendManager* backend_manager) - : receiver_(AudioIoThread::Get()->task_runner(), backend_manager) {} - - ~CmaReceiverInstance() override = default; - - private: - base::SequenceBound receiver_; -}; - -} // namespace - -std::unique_ptr CreateCmaReceiverIfNeeded( - MediaPipelineBackendManager* backend_manager) { - if (HaveFullMixer()) { - return nullptr; - } - return std::make_unique(backend_manager); -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver_creation.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_creation.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/receiver/receiver_creation.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/receiver/receiver_creation.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_CREATION_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_CREATION_H_ - -#include - -namespace chromecast { -namespace media { -class MediaPipelineBackendManager; - -namespace mixer_service { - -class ReceiverInstance { - public: - virtual ~ReceiverInstance() = default; -}; - -// Creates a mixer service receiver that uses CMA backend for output, if there -// is no real mixer implementation. If there is a real mixer, then returns -// nullptr. -std::unique_ptr CreateCmaReceiverIfNeeded( - MediaPipelineBackendManager* backend_manager); - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_RECEIVER_RECEIVER_CREATION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/redirected_audio_connection.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/redirected_audio_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,125 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/redirected_audio_connection.h" - -#include -#include - -#include "base/check_op.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/net/io_buffer_pool.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -namespace { - -void FillPatterns( - const RedirectedAudioConnection::StreamMatchPatterns& patterns, - Generic* message) { - RedirectedStreamPatterns* patterns_proto = - message->mutable_redirected_stream_patterns(); - for (const auto& p : patterns) { - auto* pattern = patterns_proto->add_patterns(); - pattern->set_content_type(audio_service::ConvertContentType(p.first)); - pattern->set_device_id_pattern(p.second); - } -} - -enum MessageTypes : int { - kRedirectionRequest = 1, - kStreamMatchPatterns, -}; - -} // namespace - -RedirectedAudioConnection::RedirectedAudioConnection(const Config& config, - Delegate* delegate) - : config_(config), delegate_(delegate) { - DCHECK(delegate_); -} - -RedirectedAudioConnection::~RedirectedAudioConnection() = default; - -void RedirectedAudioConnection::SetStreamMatchPatterns( - StreamMatchPatterns patterns) { - stream_match_patterns_ = std::move(patterns); - if (socket_) { - Generic message; - FillPatterns(stream_match_patterns_, &message); - socket_->SendProto(kStreamMatchPatterns, message); - } -} - -void RedirectedAudioConnection::Connect() { - MixerConnection::Connect(); -} - -void RedirectedAudioConnection::ConnectForTest( - std::unique_ptr connected_socket_for_test) { - DCHECK(connected_socket_for_test); - OnConnected(std::move(connected_socket_for_test)); -} - -void RedirectedAudioConnection::OnConnected( - std::unique_ptr socket) { - sample_rate_ = 0; - - socket_ = std::move(socket); - socket_->SetDelegate(this); - - Generic message; - RedirectionRequest* request = message.mutable_redirection_request(); - request->set_order(config_.order); - request->set_num_channels(config_.num_output_channels); - if (config_.output_channel_layout != media::ChannelLayout::UNSUPPORTED && - config_.output_channel_layout != media::ChannelLayout::BITSTREAM) { - request->set_channel_layout( - audio_service::ConvertChannelLayout(config_.output_channel_layout)); - } - request->set_apply_volume(config_.apply_volume); - request->set_extra_delay_microseconds(config_.extra_delay_microseconds); - - if (!stream_match_patterns_.empty()) { - FillPatterns(stream_match_patterns_, &message); - } - socket_->SendProto(kRedirectionRequest, message); -} - -void RedirectedAudioConnection::OnConnectionError() { - socket_.reset(); - MixerConnection::Connect(); -} - -bool RedirectedAudioConnection::HandleMetadata(const Generic& message) { - if (message.has_stream_config()) { - DCHECK_EQ(message.stream_config().sample_format(), - audio_service::SAMPLE_FORMAT_FLOAT_P); - sample_rate_ = message.stream_config().sample_rate(); - DCHECK_EQ(message.stream_config().num_channels(), - config_.num_output_channels); - - delegate_->SetSampleRate(sample_rate_); - } - return true; -} - -bool RedirectedAudioConnection::HandleAudioData(char* data, - size_t size, - int64_t timestamp) { - if (sample_rate_ != 0) { - int frames = size / (sizeof(float) * config_.num_output_channels); - delegate_->OnRedirectedAudio(timestamp, reinterpret_cast(data), - frames); - } - return true; -} - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/redirected_audio_connection.h chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection.h --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/redirected_audio_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,120 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_REDIRECTED_AUDIO_CONNECTION_H_ -#define CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_REDIRECTED_AUDIO_CONNECTION_H_ - -#include -#include -#include -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "chromecast/media/audio/mixer_service/mixer_connection.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { -namespace mixer_service { -class Generic; - -// Connection for redirecting audio from the mixer to somewhere else. Must be -// created and used on an IO thread. -class RedirectedAudioConnection : public MixerConnection, - public MixerSocket::Delegate { - public: - // Offset of start of audio data in an IOBuffer. - static constexpr int kAudioDataOffset = MixerSocket::kAudioMessageHeaderSize; - - using StreamMatchPatterns = std::vector< - std::pair>; - - struct Config { - // The number of output channels to send to the redirected output. - int num_output_channels = 2; - - // Channel layout of the redirected audio, used for up/downmixing if needed. - // Leave as UNSUPPORTED to autodetect based on |num_output_channels|. - media::ChannelLayout output_channel_layout = - media::ChannelLayout::UNSUPPORTED; - - // The order of this redirector (used to determine which output receives the - // audio stream, if more than one redirection applies to a single stream). - int order = 0; - - // Whether or not to apply the normal volume attenuation to the stream - // that is being redirected. - bool apply_volume = false; - - // Any extra delay to apply to the timestamps sent to the redirected output. - // Note that the delayed timestamp will be used internally for AV sync. - int64_t extra_delay_microseconds = 0; - }; - - // Observer for redirected audio data. - class Delegate { - public: - // Called whenever redirected audio data is available. The |timestamp| is - // the estimated time in microseconds (relative to the audio clock) that - // the audio would have been output. |frames| is the number of frames of - // audio data in |data|. The data is always in planar float format, with the - // number of channels as specified in the config. - virtual void OnRedirectedAudio(int64_t timestamp, - float* data, - int frames) = 0; - - // This will be called before OnRedirectedAudio is called for the first - // time, and subsequently whenever the sample rate changes. - virtual void SetSampleRate(int sample_rate) = 0; - - protected: - virtual ~Delegate() = default; - }; - - RedirectedAudioConnection(const Config& config, Delegate* delegate); - - RedirectedAudioConnection(const RedirectedAudioConnection&) = delete; - RedirectedAudioConnection& operator=(const RedirectedAudioConnection&) = - delete; - - ~RedirectedAudioConnection() override; - - // Sets the patterns which determine which audio streams should be redirected. - // If a stream has the same content type and the device ID matches the - // glob-style device ID pattern of any entry in this list, that stream will be - // redirected. - void SetStreamMatchPatterns(StreamMatchPatterns patterns); - - // Initiates connection to the mixer service. Delegate methods can be called - // at any point after Connect() is called, until this is destroyed. - void Connect(); - void ConnectForTest(std::unique_ptr connected_socket_for_test); - - private: - // MixerConnection implementation: - void OnConnected(std::unique_ptr socket) override; - void OnConnectionError() override; - - // MixerSocket::Delegate implementation: - bool HandleMetadata(const Generic& message) override; - bool HandleAudioData(char* data, size_t size, int64_t timestamp) override; - - const Config config_; - Delegate* const delegate_; - - StreamMatchPatterns stream_match_patterns_; - - std::unique_ptr socket_; - - int sample_rate_ = 0; -}; - -} // namespace mixer_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MIXER_SERVICE_REDIRECTED_AUDIO_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mixer_service/redirected_audio_connection_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/mixer_service/redirected_audio_connection_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mixer_service/redirected_audio_connection_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/mixer_service/redirected_audio_connection.h" - -#include - -#include "chromecast/media/audio/mixer_service/mock_mixer_socket.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace mixer_service { - -namespace { - -using ::testing::_; -using ::testing::Return; - -// Copied from redirected_audio_connection.cc -enum MessageTypes : int { - kRedirectionRequest = 1, - kStreamMatchPatterns, -}; - -class MockRedirectedAudioObserver - : public mixer_service::RedirectedAudioConnection::Delegate { - public: - MockRedirectedAudioObserver() { - ON_CALL(*this, OnRedirectedAudio(_, _, _)) - .WillByDefault(::testing::Invoke( - this, &MockRedirectedAudioObserver::OnRedirectedAudioImpl)); - } - - MOCK_METHOD(void, OnRedirectedAudio, (int64_t, float*, int), (override)); - MOCK_METHOD(void, SetSampleRate, (int), (override)); - - private: - void OnRedirectedAudioImpl(int64_t timestamp, float* data, int frames) { - data_.clear(); - // Save received data to local. - data_.insert(data_.end(), data, data + frames); - } - - std::vector data_; -}; - -class RedirectedAudioConnectionTest : public ::testing::Test { - public: - RedirectedAudioConnectionTest() {} -}; - -TEST_F(RedirectedAudioConnectionTest, EmptyConfig) { - RedirectedAudioConnection::Config config; - MockRedirectedAudioObserver observer; - std::unique_ptr socket = std::make_unique(); - MockMixerSocket* socket_ptr = socket.get(); - - RedirectedAudioConnection connection(config, &observer); - - EXPECT_CALL(*socket_ptr, SetDelegate(&connection)); - EXPECT_CALL(*socket_ptr, SendProto(MessageTypes::kRedirectionRequest, _)); - connection.ConnectForTest(std::move(socket)); -} - -} // namespace - -} // namespace mixer_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mock_audio_input_callback.h chromium-132.0.6834.159/chromecast/media/audio/mock_audio_input_callback.h --- chromium-132.0.6834.110/chromecast/media/audio/mock_audio_input_callback.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mock_audio_input_callback.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MOCK_AUDIO_INPUT_CALLBACK_H_ -#define CHROMECAST_MEDIA_AUDIO_MOCK_AUDIO_INPUT_CALLBACK_H_ - -#include "media/audio/audio_io.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { - -class MockAudioInputCallback - : public ::media::AudioInputStream::AudioInputCallback { - public: - MockAudioInputCallback(); - ~MockAudioInputCallback() override; - - MOCK_METHOD3(OnData, void(const ::media::AudioBus*, base::TimeTicks, double)); - MOCK_METHOD0(OnError, void()); -}; - -inline MockAudioInputCallback::MockAudioInputCallback() = default; -inline MockAudioInputCallback::~MockAudioInputCallback() = default; - -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MOCK_AUDIO_INPUT_CALLBACK_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h chromium-132.0.6834.159/chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h --- chromium-132.0.6834.110/chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/mock_cast_audio_manager_helper_delegate.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_MOCK_CAST_AUDIO_MANAGER_HELPER_DELEGATE_H_ -#define CHROMECAST_MEDIA_AUDIO_MOCK_CAST_AUDIO_MANAGER_HELPER_DELEGATE_H_ - -#include "chromecast/media/audio/cast_audio_manager_helper.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace media { - -class MockCastAudioManagerHelperDelegate - : public CastAudioManagerHelper::Delegate { - public: - MockCastAudioManagerHelperDelegate(); - ~MockCastAudioManagerHelperDelegate() override; - - MOCK_METHOD1(GetSessionId, std::string(const std::string&)); - MOCK_METHOD1(IsAudioOnlySession, bool(const std::string&)); - MOCK_METHOD1(IsGroup, bool(const std::string&)); -}; - -inline MockCastAudioManagerHelperDelegate:: - MockCastAudioManagerHelperDelegate() = default; -inline MockCastAudioManagerHelperDelegate:: - ~MockCastAudioManagerHelperDelegate() = default; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_MOCK_CAST_AUDIO_MANAGER_HELPER_DELEGATE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/DEPS chromium-132.0.6834.159/chromecast/media/audio/net/DEPS --- chromium-132.0.6834.110/chromecast/media/audio/net/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -include_rules = [ - "+chromecast/net", - "+net/base/address_list.h", - "+net/base/ip_address.h", - "+net/base/ip_endpoint.h", - "+net/log/net_log_source.h", - "+net/socket/server_socket.h", - "+net/socket/socket_descriptor.h", - "+net/socket/tcp_client_socket.h", - "+net/socket/tcp_server_socket.h", - "+net/socket/unix_domain_client_socket_posix.h", - "+net/socket/unix_domain_server_socket_posix.h", - "+third_party/protobuf/src/google/protobuf/message_lite.h", -] diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket.cc chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket.cc --- chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,388 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/net/audio_socket.h" - -#include -#include -#include - -#include "base/compiler_specific.h" -#include "base/containers/span_writer.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/numerics/byte_conversions.h" -#include "base/numerics/safe_conversions.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/net/io_buffer_pool.h" -#include "net/base/io_buffer.h" -#include "net/socket/stream_socket.h" -#include "third_party/protobuf/src/google/protobuf/message_lite.h" - -namespace chromecast { -namespace media { - -namespace { - -// First 2 bytes of each message indicate if it is metadata (protobuf) or audio. -enum class MessageType : int16_t { - kMetadata, - kAudio, -}; - -bool GetMetaDataPaddingBytes(const char* data, - size_t& size, - int32_t& padding_bytes) { - if (size < sizeof(padding_bytes)) { - LOG(ERROR) << "Invalid metadata message size " << size; - return false; - } - - padding_bytes = - // NOTE: This cast may convert large unsigned values to negative values. - // We check for and reject negative values below. - static_cast(base::numerics::U32FromBigEndian( - base::as_bytes( - // TODO(crbug.com/402847551): This span construction is unsound as - // we can't know that the size is right, the function should be - // receiving a span. - UNSAFE_TODO(base::span(data, size))) - .first())); - size -= sizeof(padding_bytes); - - if (padding_bytes < 0 || padding_bytes > 3) { - LOG(ERROR) << "Invalid padding bytes count: " << padding_bytes; - return false; - } - - if (size < static_cast(padding_bytes)) { - LOG(ERROR) << "Size " << size << " is smaller than padding " - << padding_bytes; - return false; - } - - return true; -} - -} // namespace - -bool AudioSocket::Delegate::HandleAudioData(char* data, - size_t size, - int64_t timestamp) { - return true; -} - -bool AudioSocket::Delegate::HandleAudioBuffer( - scoped_refptr buffer, - char* data, - size_t size, - int64_t timestamp) { - return HandleAudioData(data, size, timestamp); -} - -// static -constexpr size_t AudioSocket::kAudioHeaderSize; -constexpr size_t AudioSocket::kAudioMessageHeaderSize; - -AudioSocket::AudioSocket(std::unique_ptr socket) - : socket_(std::make_unique(this, std::move(socket))) {} - -AudioSocket::AudioSocket() = default; - -AudioSocket::~AudioSocket() { - if (counterpart_task_runner_) { - counterpart_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&AudioSocket::OnEndOfStream, local_counterpart_)); - } -} - -void AudioSocket::SetDelegate(Delegate* delegate) { - DCHECK(delegate); - bool had_delegate = (delegate_ != nullptr); - delegate_ = delegate; - if (socket_ && !had_delegate) { - socket_->ReceiveMessages(); - } -} - -void AudioSocket::SetLocalCounterpart( - base::WeakPtr local_counterpart, - scoped_refptr counterpart_task_runner) { - local_counterpart_ = std::move(local_counterpart); - counterpart_task_runner_ = std::move(counterpart_task_runner); -} - -base::WeakPtr AudioSocket::GetWeakPtr() { - return weak_factory_.GetWeakPtr(); -} - -void AudioSocket::UseBufferPool(scoped_refptr buffer_pool) { - DCHECK(buffer_pool); - DCHECK(buffer_pool->threadsafe()); - - buffer_pool_ = std::move(buffer_pool); - if (socket_) { - socket_->UseBufferPool(buffer_pool_); - } -} - -// static -void AudioSocket::PrepareAudioBuffer(net::IOBuffer* audio_buffer, - int filled_bytes, - int64_t timestamp) { - // Audio message format: - // uint16_t size (for SmallMessageSocket) - // == AudioHeader == - // uint16_t type (audio or metadata) - // uint64_t timestamp - // uint32_t padding - // == End of AudioHeader == - // ... audio data ... - - // The payload size is header + payload. - auto payload_size = - base::checked_cast(kAudioHeaderSize + filled_bytes); - - auto buffer = base::as_writable_bytes(audio_buffer->span()); - - buffer.first().copy_from( - base::numerics::U16ToBigEndian(payload_size)); - buffer = buffer.subspan(sizeof(uint16_t)); - - buffer.first().copy_from( - base::byte_span_from_ref(MessageType::kAudio)); - buffer = buffer.subspan(sizeof(uint16_t)); - - buffer.first().copy_from( - base::byte_span_from_ref(timestamp)); - buffer = buffer.subspan(sizeof(uint64_t)); - - std::ranges::fill(buffer.first(), uint8_t{0}); -} - -bool AudioSocket::SendAudioBuffer(scoped_refptr audio_buffer, - int filled_bytes, - int64_t timestamp) { - PrepareAudioBuffer(audio_buffer.get(), filled_bytes, timestamp); - return SendPreparedAudioBuffer(std::move(audio_buffer)); -} - -bool AudioSocket::SendPreparedAudioBuffer( - scoped_refptr audio_buffer) { - uint16_t payload_size = base::numerics::U16FromBigEndian( - base::as_bytes(base::as_bytes(audio_buffer->span()).first<2>())); - DCHECK_GE(payload_size, kAudioHeaderSize); - return SendBuffer(0, std::move(audio_buffer), - sizeof(uint16_t) + payload_size); -} - -bool AudioSocket::SendProto(int type, - const google::protobuf::MessageLite& message) { - auto packet_type = static_cast(MessageType::kMetadata); - size_t message_size = message.ByteSizeLong(); - uint32_t padding_bytes = (4u - (message_size % 4u)) % 4u; - - int total_size = sizeof(packet_type) + sizeof(padding_bytes) + message_size + - padding_bytes; - - scoped_refptr buffer; - base::span send_buf; - { - void* ptr = socket_ ? socket_->PrepareSend(total_size) : nullptr; - send_buf = - // SAFETY: The `ptr` returned from PrepareSend(), when non-null, - // will always point to at least `total_size` many bytes. - UNSAFE_BUFFERS( - base::span(static_cast(ptr), ptr ? total_size : 0u)); - } - - if (send_buf.empty()) { - if (buffer_pool_ && - buffer_pool_->buffer_size() >= sizeof(uint16_t) + total_size) { - buffer = buffer_pool_->GetBuffer(); - } - if (!buffer) { - buffer = base::MakeRefCounted(sizeof(uint16_t) + - total_size); - } - - base::SpanWriter writer(base::as_writable_bytes(buffer->span())); - writer.WriteU16BigEndian(static_cast(total_size)); - // Move `send_buf` from pointing into `socket_` to pointing into `buffer`. - send_buf = writer.remaining_span(); - } - - { - base::SpanWriter writer(send_buf); - writer.WriteU16BigEndian(packet_type); - writer.WriteU32BigEndian(padding_bytes); - send_buf = writer.remaining_span(); - } - - auto [message_buf, rem1] = send_buf.split_at(message_size); - auto [padding_buf, rem2] = rem1.split_at(padding_bytes); - message.SerializeToArray(message_buf.data(), message_size); - std::ranges::fill(padding_buf, 0u); - - if (!buffer) { - socket_->Send(); - return true; - } - return SendBuffer(type, std::move(buffer), sizeof(uint16_t) + total_size); -} - -bool AudioSocket::SendBuffer(int type, - scoped_refptr buffer, - size_t buffer_size) { - if (counterpart_task_runner_) { - counterpart_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(base::IgnoreResult(&AudioSocket::OnMessageBuffer), - local_counterpart_, std::move(buffer), buffer_size)); - return true; - } - return SendBufferToSocket(type, std::move(buffer), buffer_size); -} - -bool AudioSocket::SendBufferToSocket(int type, - scoped_refptr buffer, - size_t buffer_size) { - DCHECK(socket_); - if (!socket_->SendBuffer(buffer, buffer_size)) { - if (type == 0) { - return false; - } - pending_writes_.insert_or_assign(type, std::move(buffer)); - } - return true; -} - -void AudioSocket::OnSendUnblocked() { - DCHECK(socket_); - base::flat_map> pending; - pending_writes_.swap(pending); - for (auto& m : pending) { - uint16_t message_size = base::numerics::U16FromBigEndian( - base::as_bytes(m.second->span().first<2u>())); - SendBufferToSocket(m.first, std::move(m.second), - sizeof(uint16_t) + message_size); - } -} - -void AudioSocket::ReceiveMoreMessages() { - if (socket_) { - socket_->ReceiveMessagesSynchronously(); - } -} - -void AudioSocket::OnError(int error) { - LOG(ERROR) << "Socket error from " << this << ": " << error; - DCHECK(delegate_); - delegate_->OnConnectionError(); -} - -void AudioSocket::OnEndOfStream() { - DCHECK(delegate_); - delegate_->OnConnectionError(); -} - -bool AudioSocket::OnMessage(char* data, size_t size) { - int16_t packet_type; - if (size < sizeof(packet_type)) { - LOG(ERROR) << "Invalid message size " << size << " from " << this; - delegate_->OnConnectionError(); - return false; - } - - memcpy(&packet_type, data, sizeof(packet_type)); - data += sizeof(packet_type); - size -= sizeof(packet_type); - - switch (static_cast(packet_type)) { - case MessageType::kMetadata: - int32_t padding_bytes; - if (!GetMetaDataPaddingBytes(data, size, padding_bytes)) { - return false; - } - return ParseMetadata(data + sizeof(padding_bytes), size - padding_bytes); - case MessageType::kAudio: - return ParseAudio(data, size); - default: - return true; // Ignore unhandled message types. - } -} - -bool AudioSocket::OnMessageBuffer(scoped_refptr buffer, - size_t size) { - if (size < sizeof(uint16_t) + sizeof(int16_t)) { - LOG(ERROR) << "Invalid buffer size " << size << " from " << this; - delegate_->OnConnectionError(); - return false; - } - - char* data = buffer->data() + sizeof(uint16_t); - size -= sizeof(uint16_t); - int16_t type; - memcpy(&type, data, sizeof(type)); - data += sizeof(type); - size -= sizeof(type); - - switch (static_cast(type)) { - case MessageType::kMetadata: - int32_t padding_bytes; - if (!GetMetaDataPaddingBytes(data, size, padding_bytes)) { - return false; - } - return ParseMetadata(data + sizeof(padding_bytes), size - padding_bytes); - case MessageType::kAudio: - return ParseAudioBuffer(std::move(buffer), data, size); - default: - return true; // Ignore unhandled message types. - } -} - -bool AudioSocket::ParseAudio(char* data, size_t size) { - int64_t timestamp; - if (size < sizeof(timestamp)) { - LOG(ERROR) << "Invalid audio packet size " << size << " from " << this; - delegate_->OnConnectionError(); - return false; - } - - memcpy(×tamp, data, sizeof(timestamp)); - data += sizeof(timestamp); - size -= sizeof(timestamp); - - // Handle padding bytes. - data += sizeof(int32_t); - size -= sizeof(int32_t); - - return delegate_->HandleAudioData(data, size, timestamp); -} - -bool AudioSocket::ParseAudioBuffer(scoped_refptr buffer, - char* data, - size_t size) { - int64_t timestamp; - if (size < sizeof(timestamp)) { - LOG(ERROR) << "Invalid audio buffer size " << size << " from " << this; - delegate_->OnConnectionError(); - return false; - } - - memcpy(×tamp, data, sizeof(timestamp)); - data += sizeof(timestamp); - size -= sizeof(timestamp); - - // Handle padding bytes. - data += sizeof(int32_t); - size -= sizeof(int32_t); - - return delegate_->HandleAudioBuffer(std::move(buffer), data, size, timestamp); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket.h chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket.h --- chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,170 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_NET_AUDIO_SOCKET_H_ -#define CHROMECAST_MEDIA_AUDIO_NET_AUDIO_SOCKET_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/net/small_message_socket.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace google { -namespace protobuf { -class MessageLite; -} // namespace protobuf -} // namespace google - -namespace net { -class IOBuffer; -class StreamSocket; -} // namespace net - -namespace chromecast { -class IOBufferPool; - -namespace media { - -// Base class for sending and receiving messages to/from audio services (e.g. -// mixer service, audio output service). -// Not thread-safe; all usage of a given instance must be on the same IO -// sequence. -class AudioSocket : public SmallMessageSocket::Delegate { - public: - class Delegate { - public: - // Called when audio data is received from the other side of the connection. - // Return |true| if the socket should continue to receive messages. - virtual bool HandleAudioData(char* data, size_t size, int64_t timestamp); - - // Called when audio data is received from the other side of the connection - // using an IOBufferPool. The |buffer| reference may be held as long as - // needed by the delegate implementation. The buffer contains the full - // message header including size; the |data| points to the audio data, and - // the |size| is the size of the audio data. |data| will always be - // kAudioMessageHeaderSize bytes past the start of the buffer. - // Return |true| if the socket should continue to receive messages. - virtual bool HandleAudioBuffer(scoped_refptr buffer, - char* data, - size_t size, - int64_t timestamp); - - // Called when the connection is lost; no further data will be sent or - // received after OnConnectionError() is called. It is safe to delete the - // AudioSocket inside the OnConnectionError() implementation. - virtual void OnConnectionError() {} - - protected: - virtual ~Delegate() = default; - }; - - explicit AudioSocket(std::unique_ptr socket); - AudioSocket(const AudioSocket&) = delete; - AudioSocket& operator=(const AudioSocket&) = delete; - ~AudioSocket() override; - - // Used to create local (in-process) connections. - AudioSocket(); - void SetLocalCounterpart( - base::WeakPtr local_counterpart, - scoped_refptr counterpart_task_runner); - base::WeakPtr GetWeakPtr(); - - // Sets/changes the delegate. Must be called immediately after creation - // (ie, synchronously on the same sequence). - void SetDelegate(Delegate* delegate); - - // Adds a |buffer_pool| used to allocate buffers to receive messages into, - // and for sending protos. If the pool-allocated buffers are too small for a - // given message, a normal IOBuffer will be dynamically allocated instead. - void UseBufferPool(scoped_refptr buffer_pool); - - // 16-bit type and 64-bit timestamp, plus 32-bit padding to align to 16 bytes. - static constexpr size_t kAudioHeaderSize = - sizeof(int16_t) + sizeof(int64_t) + sizeof(int32_t); - // Includes additional 16-bit size field for SmallMessageSocket. - static constexpr size_t kAudioMessageHeaderSize = - sizeof(uint16_t) + kAudioHeaderSize; - - // Fills in the audio message header for |buffer|, so it can later be sent via - // SendPreparedAudioBuffer(). |buffer| should have |kAudioMessageHeaderSize| - // bytes reserved at the start of the buffer, followed by |filled_bytes| of - // audio data. - static void PrepareAudioBuffer(net::IOBuffer* buffer, - int filled_bytes, - int64_t timestamp); - - // Prepares |audio_buffer| and then sends it across the connection. Returns - // |false| if the audio could not be sent. - bool SendAudioBuffer(scoped_refptr audio_buffer, - int filled_bytes, - int64_t timestamp); - - // Sends |audio_buffer| across the connection. |audio_buffer| should have - // previously been prepared using PrepareAudioBuffer(). Returns |false| if the - // audio could not be sent. - bool SendPreparedAudioBuffer(scoped_refptr audio_buffer); - - // Sends an arbitrary protobuf across the connection. |type| indicates the - // type of message; if the write cannot complete immediately, one message of - // each type will be stored for later sending; if a newer message is sent with - // the same type, then the previous message is overwritten. When writes become - // available again, the stored messages are written in order of |type| (lowest - // type first). Note that |type| is completely determined by the caller, and - // you can reuse the same type value for different messages as long as they - // are on different socket instances. A type of 0 means to never store the - // message. Returns |false| if the message was not sent or stored. - bool SendProto(int type, const google::protobuf::MessageLite& message); - - // Resumes receiving messages. Delegate calls may be called synchronously - // from within this method. - void ReceiveMoreMessages(); - - private: - // Parses the meta data received from the connection. - virtual bool ParseMetadata(char* data, size_t size) = 0; - - bool SendBuffer(int type, - scoped_refptr buffer, - size_t buffer_size); - bool SendBufferToSocket(int type, - scoped_refptr buffer, - size_t buffer_size); - - // SmallMessageSocket::Delegate implementation: - void OnSendUnblocked() override; - void OnError(int error) override; - void OnEndOfStream() override; - bool OnMessage(char* data, size_t size) override; - bool OnMessageBuffer(scoped_refptr buffer, - size_t size) override; - - bool ParseAudio(char* data, size_t size); - bool ParseAudioBuffer(scoped_refptr buffer, - char* data, - size_t size); - - Delegate* delegate_ = nullptr; - const std::unique_ptr socket_; - - scoped_refptr buffer_pool_; - base::flat_map> pending_writes_; - - base::WeakPtr local_counterpart_; - scoped_refptr counterpart_task_runner_; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_NET_AUDIO_SOCKET_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service.cc chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service.cc --- chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/net/audio_socket_service.h" - -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "net/base/net_errors.h" -#include "net/socket/server_socket.h" -#include "net/socket/stream_socket.h" - -namespace chromecast { -namespace media { - -AudioSocketService::~AudioSocketService() = default; - -void AudioSocketService::Accept() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - if (!listen_socket_) { - return; - } - - for (int i = 0; i < max_accept_loop_; ++i) { - int result = AcceptOne(); - // If the result is ERR_IO_PENDING, OnAccept() will eventually be - // called; it will resume the accept loop. - if (result == net::ERR_IO_PENDING || !HandleAcceptResult(result)) { - return; - } - } - task_runner_->PostTask(FROM_HERE, base::BindOnce(&AudioSocketService::Accept, - weak_factory_.GetWeakPtr())); -} - -void AudioSocketService::OnAsyncAcceptComplete(int result) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - if (HandleAcceptResult(result)) { - Accept(); - } -} - -bool AudioSocketService::HandleAcceptResult(int result) { - if (result != net::OK) { - LOG(ERROR) << "Accept failed: " << net::ErrorToString(result); - return false; - } - OnAcceptSuccess(); - return true; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service.h chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service.h --- chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_NET_AUDIO_SOCKET_SERVICE_H_ -#define CHROMECAST_MEDIA_AUDIO_NET_AUDIO_SOCKET_SERVICE_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/files/file_descriptor_watcher_posix.h" -#include "base/files/scoped_file.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "net/socket/socket_descriptor.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace net { -class ServerSocket; -class StreamSocket; -} // namespace net - -namespace chromecast { -namespace media { - -// Listens to a server socket and passes accepted sockets to a delegate. It -// is used for creating socket connections to pass audio data between processes. -// Must be created and used on an IO thread. -class AudioSocketService { - public: - class Delegate { - public: - // Handles a newly accepted |socket|. - virtual void HandleAcceptedSocket( - std::unique_ptr socket) = 0; - - protected: - virtual ~Delegate() = default; - }; - - // When |use_socket_descriptor| is true, AudioSocketService will receive a - // socket descriptor from the connection created through |listen_socket_|, and - // then use the received socket descriptor to create the real socket for - // transferring data. This is useful when the actual client of the service is - // not able to create a socket themselves but instead needs a brokered socket - // descriptor (created with socketpair()) to connect. - AudioSocketService(const std::string& endpoint, - int port, - int max_accept_loop, - Delegate* delegate, - bool use_socket_descriptor = false); - AudioSocketService(const AudioSocketService&) = delete; - AudioSocketService& operator=(const AudioSocketService&) = delete; - ~AudioSocketService(); - - // Starts accepting incoming connections. - void Accept(); - - // Creates a connection to an AudioSocketService instance. The |endpoint| is - // used on systems that support Unix domain sockets; otherwise, the |port| is - // used to make a TCP connection. - static std::unique_ptr Connect(const std::string& endpoint, - int port); - - private: - void OnAsyncAcceptComplete(int result); - bool HandleAcceptResult(int result); - - // The following methods are implemented in audio_socket_service_{uds|tcp}.cc. - int AcceptOne(); - void OnAcceptSuccess(); - void ReceiveFdFromSocket(int socket_fd); - - const int max_accept_loop_; - const bool use_socket_descriptor_; - Delegate* const delegate_; // Not owned. - - scoped_refptr task_runner_; - - std::unique_ptr listen_socket_; - std::unique_ptr accepted_socket_; - net::SocketDescriptor accepted_descriptor_ = net::kInvalidSocket; - base::flat_map> - fd_watcher_controllers_; - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_NET_AUDIO_SOCKET_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service_tcp.cc chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_tcp.cc --- chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service_tcp.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_tcp.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/net/audio_socket_service.h" - -#include "base/logging.h" -#include "base/notreached.h" -#include "base/task/sequenced_task_runner.h" -#include "net/base/address_list.h" -#include "net/base/ip_address.h" -#include "net/base/ip_endpoint.h" -#include "net/base/net_errors.h" -#include "net/log/net_log_source.h" -#include "net/socket/stream_socket.h" -#include "net/socket/tcp_client_socket.h" -#include "net/socket/tcp_server_socket.h" - -namespace chromecast { -namespace media { - -namespace { -constexpr int kListenBacklog = 10; -} // namespace - -// static -std::unique_ptr AudioSocketService::Connect( - const std::string& endpoint, - int port) { - net::IPEndPoint ip_endpoint(net::IPAddress::IPv4Localhost(), port); - return std::make_unique(net::AddressList(ip_endpoint), - nullptr, nullptr, nullptr, - net::NetLogSource()); -} - -AudioSocketService::AudioSocketService(const std::string& endpoint, - int port, - int max_accept_loop, - Delegate* delegate, - bool /* use_socket_descriptor */) - : max_accept_loop_(max_accept_loop), - use_socket_descriptor_(false), - delegate_(delegate), - task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) { - DCHECK_GT(max_accept_loop_, 0); - DCHECK(delegate_); - - DCHECK_GE(port, 0); - LOG(INFO) << "Using port " << port; - listen_socket_ = std::make_unique(nullptr /* net_log */, - net::NetLogSource()); - int result = listen_socket_->Listen( - net::IPEndPoint(net::IPAddress::IPv4Localhost(), port), kListenBacklog, - /*ipv6_only=*/std::nullopt); - - if (result != net::OK) { - LOG(ERROR) << "Listen failed: " << net::ErrorToString(result); - listen_socket_.reset(); - } -} - -int AudioSocketService::AcceptOne() { - DCHECK(listen_socket_); - return listen_socket_->Accept( - &accepted_socket_, - base::BindOnce(&AudioSocketService::OnAsyncAcceptComplete, - base::Unretained(this))); -} - -void AudioSocketService::OnAcceptSuccess() { - delegate_->HandleAcceptedSocket(std::move(accepted_socket_)); -} - -void AudioSocketService::ReceiveFdFromSocket(int socket_fd) { - NOTIMPLEMENTED(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service_uds.cc chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_uds.cc --- chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service_uds.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_uds.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,138 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/net/audio_socket_service.h" - -#include - -#include -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/posix/eintr_wrapper.h" -#include "base/posix/safe_strerror.h" -#include "base/posix/unix_domain_socket.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/net/socket_util.h" -#include "net/base/net_errors.h" -#include "net/socket/stream_socket.h" -#include "net/socket/unix_domain_client_socket_posix.h" -#include "net/socket/unix_domain_server_socket_posix.h" - -namespace chromecast { -namespace media { - -namespace { -constexpr int kListenBacklog = 10; -constexpr char kSocketMsg[] = "socket-handle"; - -void CloseSocket(int fd) { - int rv = IGNORE_EINTR(close(fd)); - DPCHECK(rv == 0) << "Error closing socket"; -} - -} // namespace - -// static -std::unique_ptr AudioSocketService::Connect( - const std::string& endpoint, - int port) { - return std::make_unique( - endpoint, true /* use_abstract_namespace */); -} - -AudioSocketService::AudioSocketService(const std::string& endpoint, - int port, - int max_accept_loop, - Delegate* delegate, - bool use_socket_descriptor) - : max_accept_loop_(max_accept_loop), - use_socket_descriptor_(use_socket_descriptor), - delegate_(delegate), - task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) { - DCHECK_GT(max_accept_loop_, 0); - DCHECK(delegate_); - - DCHECK(!endpoint.empty()); - LOG(INFO) << "Using endpoint " << endpoint; - auto unix_socket = std::make_unique( - base::BindRepeating([](const net::UnixDomainServerSocket::Credentials&) { - // Always accept the connection. - return true; - }), - true /* use_abstract_namespace */); - int result = unix_socket->BindAndListen(endpoint, kListenBacklog); - listen_socket_ = std::move(unix_socket); - - if (result != net::OK) { - LOG(ERROR) << "Listen failed: " << net::ErrorToString(result); - listen_socket_.reset(); - } -} - -int AudioSocketService::AcceptOne() { - DCHECK(listen_socket_); - - if (use_socket_descriptor_) { - return static_cast(listen_socket_.get()) - ->AcceptSocketDescriptor( - &accepted_descriptor_, - base::BindOnce(&AudioSocketService::OnAsyncAcceptComplete, - base::Unretained(this))); - } - return listen_socket_->Accept( - &accepted_socket_, - base::BindOnce(&AudioSocketService::OnAsyncAcceptComplete, - base::Unretained(this))); -} - -void AudioSocketService::OnAcceptSuccess() { - if (!use_socket_descriptor_) { - delegate_->HandleAcceptedSocket(std::move(accepted_socket_)); - return; - } - - if (accepted_descriptor_ == net::kInvalidSocket) { - LOG(ERROR) << "Accepted socket descriptor is invalid."; - return; - } - fd_watcher_controllers_.emplace( - accepted_descriptor_, - base::FileDescriptorWatcher::WatchReadable( - accepted_descriptor_, - base::BindRepeating(&AudioSocketService::ReceiveFdFromSocket, - base::Unretained(this), accepted_descriptor_))); - accepted_descriptor_ = net::kInvalidSocket; -} - -void AudioSocketService::ReceiveFdFromSocket(int socket_fd) { - fd_watcher_controllers_.erase(socket_fd); - - char buffer[sizeof(kSocketMsg)]; - std::vector fds; - ssize_t res = - base::UnixDomainSocket::RecvMsg(socket_fd, buffer, sizeof(buffer), &fds); - CloseSocket(socket_fd); - if (res != sizeof(kSocketMsg)) { - LOG(ERROR) << "Failed to receive message from the descriptor " << socket_fd; - return; - } - if (memcmp(buffer, kSocketMsg, sizeof(kSocketMsg)) != 0) { - LOG(ERROR) << "Received invalid message."; - return; - } - if (fds.empty()) { - LOG(ERROR) << "No socket descriptors received."; - return; - } - for (auto& fd : fds) { - delegate_->HandleAcceptedSocket(AdoptUnnamedSocketHandle(std::move(fd))); - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service_uds_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_uds_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/net/audio_socket_service_uds_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/audio_socket_service_uds_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/net/audio_socket_service.h" - -#include -#include -#include - -#include "base/files/scoped_file.h" -#include "base/files/scoped_temp_dir.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/posix/unix_domain_socket.h" -#include "base/run_loop.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "chromecast/net/socket_util.h" -#include "net/base/net_errors.h" -#include "net/socket/stream_socket.h" -#include "net/socket/unix_domain_client_socket_posix.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -using ::testing::_; -using ::testing::Invoke; - -namespace { - -constexpr char kTestSocket[] = "test.socket"; -constexpr char kSocketMsg[] = "socket-handle"; - -class MockAudioSocketServiceDelegate : public AudioSocketService::Delegate { - public: - MockAudioSocketServiceDelegate() = default; - MockAudioSocketServiceDelegate(const MockAudioSocketServiceDelegate&) = - delete; - MockAudioSocketServiceDelegate& operator=( - const MockAudioSocketServiceDelegate&) = delete; - ~MockAudioSocketServiceDelegate() override = default; - - MOCK_METHOD(void, - HandleAcceptedSocket, - (std::unique_ptr), - (override)); -}; - -} // namespace - -class AudioSocketServiceTest : public testing::TestWithParam { - public: - AudioSocketServiceTest() : use_socket_descriptor_(GetParam()) { - EXPECT_TRUE(test_dir_.CreateUniqueTempDir()); - socket_path_ = test_dir_.GetPath().Append(kTestSocket).value(); - } - - ~AudioSocketServiceTest() override { - io_thread_->task_runner()->DeleteSoon(FROM_HERE, - std::move(audio_socket_service_)); - } - - protected: - void InitializeAudioSocketService() { - io_thread_ = std::make_unique("test_io_thread"); - io_thread_->StartWithOptions( - base::Thread::Options(base::MessagePumpType::IO, 0)); - io_thread_->task_runner()->PostTask( - FROM_HERE, - base::BindOnce( - &AudioSocketServiceTest::InitializeAudioSocketServiceOnIoThread, - base::Unretained(this))); - } - - void InitializeAudioSocketServiceOnIoThread() { - delegate_ = std::make_unique(); - audio_socket_service_ = std::make_unique( - socket_path_, /*port=*/0, /*max_accept_loop=*/1, delegate_.get(), - use_socket_descriptor_); - audio_socket_service_->Accept(); - } - - void ConnectToAudioSocketService() { - connecting_socket_ = - std::make_unique(socket_path_, true); - int rv = connecting_socket_->Connect(base::BindOnce( - &AudioSocketServiceTest::OnConnected, base::Unretained(this))); - if (rv != net::ERR_IO_PENDING) { - OnConnected(rv); - } else { - run_loop_.Run(); - } - - if (use_socket_descriptor_) { - base::ScopedFD fd1, fd2; - base::CreateSocketPair(&fd1, &fd2); - connected_socket_ = AdoptUnnamedSocketHandle(std::move(fd1)); - base::UnixDomainSocket::SendMsg( - connecting_socket_->ReleaseConnectedSocket(), kSocketMsg, - sizeof(kSocketMsg), {fd2.get()}); - } - run_loop_.Run(); - } - - void OnConnected(int rv) { - EXPECT_EQ(rv, net::OK); - if (run_loop_.running()) { - run_loop_.Quit(); - } - } - - const bool use_socket_descriptor_; - base::test::SingleThreadTaskEnvironment task_environment_{ - base::test::TaskEnvironment::MainThreadType::IO}; - base::ScopedTempDir test_dir_; - std::string socket_path_; - base::RunLoop run_loop_; - std::unique_ptr io_thread_; - std::unique_ptr delegate_; - std::unique_ptr audio_socket_service_; - std::unique_ptr connecting_socket_; - std::unique_ptr connected_socket_; -}; - -TEST_P(AudioSocketServiceTest, UseSocketDescriptor) { - InitializeAudioSocketService(); - io_thread_->FlushForTesting(); - - EXPECT_CALL(*delegate_, HandleAcceptedSocket(_)) - .WillOnce(Invoke([this](std::unique_ptr socket) { - EXPECT_TRUE(socket); - EXPECT_TRUE(socket->IsConnected()); - run_loop_.Quit(); - })); - - ConnectToAudioSocketService(); -} - -INSTANTIATE_TEST_SUITE_P(ReturnedSocketIsConnected, - AudioSocketServiceTest, - ::testing::Bool() /* use_socket_descriptor */ -); - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/common.proto chromium-132.0.6834.159/chromecast/media/audio/net/common.proto --- chromium-132.0.6834.110/chromecast/media/audio/net/common.proto 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/common.proto 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package chromecast.media.audio_service; - -enum ContentType { - CONTENT_TYPE_MEDIA = 0; - CONTENT_TYPE_ALARM = 1; - CONTENT_TYPE_COMMUNICATION = 2; - CONTENT_TYPE_OTHER = 3; -} - -enum SampleFormat { - // Interleaved formats: - SAMPLE_FORMAT_INT16_I = 0; - SAMPLE_FORMAT_INT32_I = 1; - SAMPLE_FORMAT_FLOAT_I = 2; - // Planar formats: - SAMPLE_FORMAT_INT16_P = 3; - SAMPLE_FORMAT_INT32_P = 4; - SAMPLE_FORMAT_FLOAT_P = 5; -} - -enum ChannelLayout { - CHANNEL_LAYOUT_NONE = 0; - CHANNEL_LAYOUT_MONO = 1; - CHANNEL_LAYOUT_STEREO = 2; - CHANNEL_LAYOUT_5_1 = 3; - CHANNEL_LAYOUT_BITSTREAM = 4; - CHANNEL_LAYOUT_DISCRETE = 5; -} - -enum AudioCodec { - AUDIO_CODEC_UNKNOWN = 0; - AUDIO_CODEC_AAC = 1; - AUDIO_CODEC_MP3 = 2; - AUDIO_CODEC_PCM = 3; - AUDIO_CODEC_PCM_S16BE = 4; - AUDIO_CODEC_VORBIS = 5; - AUDIO_CODEC_OPUS = 6; - AUDIO_CODEC_EAC3 = 7; - AUDIO_CODEC_AC3 = 8; - AUDIO_CODEC_DTS = 9; - AUDIO_CODEC_FLAC = 10; - AUDIO_CODEC_MPEG_H_AUDIO = 11; -} diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/conversions.cc chromium-132.0.6834.159/chromecast/media/audio/net/conversions.cc --- chromium-132.0.6834.110/chromecast/media/audio/net/conversions.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/conversions.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,97 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/net/conversions.h" - -#include "base/notreached.h" - -namespace chromecast { -namespace media { -namespace audio_service { - -media::SampleFormat ConvertSampleFormat(SampleFormat format) { - switch (format) { - case SAMPLE_FORMAT_INT16_I: - return kSampleFormatS16; - case SAMPLE_FORMAT_INT32_I: - return kSampleFormatS32; - case SAMPLE_FORMAT_FLOAT_I: - return kSampleFormatF32; - case SAMPLE_FORMAT_INT16_P: - return kSampleFormatPlanarS16; - case SAMPLE_FORMAT_INT32_P: - return kSampleFormatPlanarS32; - case SAMPLE_FORMAT_FLOAT_P: - return kSampleFormatPlanarF32; - default: - NOTREACHED() << "Unknown sample format " << format; - } -} - -SampleFormat ConvertSampleFormat(media::SampleFormat format) { - switch (format) { - case kSampleFormatS16: - return SAMPLE_FORMAT_INT16_I; - case kSampleFormatS32: - return SAMPLE_FORMAT_INT32_I; - case kSampleFormatF32: - return SAMPLE_FORMAT_FLOAT_I; - case kSampleFormatPlanarS16: - return SAMPLE_FORMAT_INT16_P; - case kSampleFormatPlanarS32: - return SAMPLE_FORMAT_INT32_P; - case kSampleFormatPlanarF32: - return SAMPLE_FORMAT_FLOAT_P; - default: - NOTREACHED() << "Unhandled sample format " << format; - } -} - -int GetSampleSizeBytes(SampleFormat format) { - if (format == SAMPLE_FORMAT_INT16_I || format == SAMPLE_FORMAT_INT16_P) { - return 2; - } - return 4; -} - -static_assert(static_cast(CONTENT_TYPE_MEDIA) == - static_cast(AudioContentType::kMedia), - "Content type enums don't match for media"); -static_assert(static_cast(CONTENT_TYPE_ALARM) == - static_cast(AudioContentType::kAlarm), - "Content type enums don't match for alarm"); -static_assert(static_cast(CONTENT_TYPE_COMMUNICATION) == - static_cast(AudioContentType::kCommunication), - "Content type enums don't match for communication"); -static_assert(static_cast(CONTENT_TYPE_OTHER) == - static_cast(AudioContentType::kOther), - "Content type enums don't match for other"); - -ContentType ConvertContentType(media::AudioContentType content_type) { - return static_cast(content_type); -} - -media::AudioContentType ConvertContentType(ContentType type) { - return static_cast(type); -} - -ChannelLayout ConvertChannelLayout(media::ChannelLayout channel_layout) { - return static_cast(channel_layout); -} - -media::ChannelLayout ConvertChannelLayout(ChannelLayout channel_layout) { - return static_cast(channel_layout); -} - -media::AudioCodec ConvertAudioCodec(AudioCodec codec) { - return static_cast(codec); -} - -AudioCodec ConvertAudioCodec(media::AudioCodec codec) { - return static_cast(codec); -} - -} // namespace audio_service -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/net/conversions.h chromium-132.0.6834.159/chromecast/media/audio/net/conversions.h --- chromium-132.0.6834.110/chromecast/media/audio/net/conversions.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/net/conversions.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_NET_CONVERSIONS_H_ -#define CHROMECAST_MEDIA_AUDIO_NET_CONVERSIONS_H_ - -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { -namespace audio_service { - -media::SampleFormat ConvertSampleFormat(SampleFormat format); -SampleFormat ConvertSampleFormat(media::SampleFormat format); -int GetSampleSizeBytes(SampleFormat format); - -ContentType ConvertContentType(media::AudioContentType content_type); -media::AudioContentType ConvertContentType(ContentType type); - -ChannelLayout ConvertChannelLayout(media::ChannelLayout channel_layout); -media::ChannelLayout ConvertChannelLayout(ChannelLayout channel_layout); - -media::AudioCodec ConvertAudioCodec(AudioCodec codec); -AudioCodec ConvertAudioCodec(media::AudioCodec codec); - -} // namespace audio_service -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_NET_CONVERSIONS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/playback_rate_shifter.cc chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter.cc --- chromium-132.0.6834.110/chromecast/media/audio/playback_rate_shifter.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,173 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/playback_rate_shifter.h" - -#include -#include -#include - -#include "base/check.h" -#include "base/time/time.h" -#include "media/base/audio_buffer.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_parameters.h" -#include "media/filters/audio_renderer_algorithm.h" - -namespace chromecast { -namespace media { - -namespace { -constexpr int kMaxChannels = 32; -constexpr double kPlaybackRateEpsilon = 0.005; -constexpr int kOutputBufferSize = 4096; -} // namespace - -PlaybackRateShifter::PlaybackRateShifter(AudioProvider* provider, - ::media::ChannelLayout channel_layout, - int num_channels, - int sample_rate, - int request_size) - : provider_(provider), - channel_layout_(channel_layout), - num_channels_(num_channels), - sample_rate_(sample_rate), - request_size_(request_size), - audio_buffer_pool_( - base::MakeRefCounted<::media::AudioBufferMemoryPool>()) { - DCHECK(provider_); -} - -PlaybackRateShifter::~PlaybackRateShifter() = default; - -double PlaybackRateShifter::BufferedFrames() const { - if (rate_shifter_) { - return rate_shifter_->DelayInFrames(playback_rate_); - } - return 0; -} - -void PlaybackRateShifter::SetPlaybackRate(double rate) { - if (std::fabs(rate - 1.0) < kPlaybackRateEpsilon) { - rate = 1.0; - } - - if (rate == playback_rate_) { - return; - } - - if (rate != 1.0) { - if (!rate_shifter_) { - rate_shifter_ = - std::make_unique<::media::AudioRendererAlgorithm>(&media_log_); - ::media::AudioParameters parameters( - ::media::AudioParameters::AUDIO_PCM_LINEAR, - {channel_layout_, static_cast(num_channels_)}, sample_rate_, - request_size_); - rate_shifter_->Initialize(parameters, false /* is_encrypted */); - } - - if (!rate_shifter_output_) { - rate_shifter_output_ = - ::media::AudioBus::Create(num_channels_, kOutputBufferSize); - } - } - - playback_rate_ = rate; -} - -int PlaybackRateShifter::FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) { - if (!rate_shifter_ || - (playback_rate_ == 1.0 && rate_shifter_->BufferedFrames() == 0)) { - return provider_->FillFrames(num_frames, playout_timestamp, channel_data); - } - - if (playback_rate_ == 1.0) { - return DrainBufferedData(num_frames, playout_timestamp, channel_data); - } - - int total_filled = 0; - while (total_filled < num_frames) { - int amount = std::min(num_frames - total_filled, kOutputBufferSize); - int filled = rate_shifter_->FillBuffer(rate_shifter_output_.get(), 0, - amount, playback_rate_); - - for (size_t c = 0; c < num_channels_; ++c) { - std::copy_n(rate_shifter_output_->channel(c), amount, - channel_data[c] + total_filled); - } - total_filled += filled; - - if (filled != amount) { - // Get more data and queue it in the rate shifter. - auto buffer = ::media::AudioBuffer::CreateBuffer( - ::media::SampleFormat::kSampleFormatPlanarF32, channel_layout_, - num_channels_, sample_rate_, request_size_, audio_buffer_pool_); - int new_fill = provider_->FillFrames( - request_size_, - playout_timestamp + - FramesToMicroseconds(total_filled + BufferedFrames()), - const_cast( - reinterpret_cast(buffer->channel_data().data()))); - if (new_fill == 0) { - break; - } - buffer->TrimEnd(request_size_ - new_fill); - rate_shifter_->EnqueueBuffer(std::move(buffer)); - } - } - return total_filled; -} - -int PlaybackRateShifter::DrainBufferedData(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) { - // Drain buffered data from rate shifter. - DCHECK_EQ(playback_rate_, 1.0); - - int filled = 0; - while (filled < num_frames) { - int amount = std::min(num_frames - filled, kOutputBufferSize); - int to_copy = rate_shifter_->FillBuffer(rate_shifter_output_.get(), 0, - amount, playback_rate_); - for (size_t c = 0; c < num_channels_; ++c) { - std::copy_n(rate_shifter_output_->channel(c), to_copy, - channel_data[c] + filled); - } - filled += to_copy; - - if (to_copy < amount) { - break; - } - } - - if (filled < num_frames) { - // Now there is no data buffered in the rate shifter. - float* fill_channel_data[kMaxChannels]; - for (size_t c = 0; c < num_channels_; ++c) { - fill_channel_data[c] = channel_data[c] + filled; - } - int64_t timestamp = playout_timestamp + FramesToMicroseconds(filled); - filled += provider_->FillFrames(num_frames - filled, timestamp, - fill_channel_data); - } - return filled; -} - -size_t PlaybackRateShifter::num_channels() const { - return num_channels_; -} - -int PlaybackRateShifter::sample_rate() const { - return sample_rate_; -} - -int64_t PlaybackRateShifter::FramesToMicroseconds(double frames) { - return frames * base::Time::kMicrosecondsPerSecond / sample_rate_; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/playback_rate_shifter.h chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter.h --- chromium-132.0.6834.110/chromecast/media/audio/playback_rate_shifter.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_PLAYBACK_RATE_SHIFTER_H_ -#define CHROMECAST_MEDIA_AUDIO_PLAYBACK_RATE_SHIFTER_H_ - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "chromecast/media/api/audio_provider.h" -#include "media/base/channel_layout.h" -#include "media/base/media_util.h" - -namespace media { -class AudioBufferMemoryPool; -class AudioBus; -class AudioRendererAlgorithm; -} // namespace media - -namespace chromecast { -namespace media { - -// PlaybackRateShifter handles shifting playback rate (eg 0.25x to 4x playback). -// All methods except constructor/destructor must be called on the same thread. -// A fader should be chained after the PlaybackRateShifter, since there can be -// audio discontinuities when the playback rate is changed. -class PlaybackRateShifter : public AudioProvider { - public: - PlaybackRateShifter(AudioProvider* provider, - ::media::ChannelLayout channel_layout, - int num_channels, - int sample_rate, - int request_size); - ~PlaybackRateShifter() override; - - // Returns the effective number of frames buffered, relative to the output - // playback rate. - double BufferedFrames() const; - - // Changes the playback rate. - void SetPlaybackRate(double rate); - - // AudioProvider implementation: - int FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) override; - size_t num_channels() const override; - int sample_rate() const override; - - double playback_rate() const { return playback_rate_; } - - private: - int DrainBufferedData(int num_frames, - int64_t playout_timestamp, - float* const* channel_data); - int64_t FramesToMicroseconds(double frames); - - AudioProvider* const provider_; - const ::media::ChannelLayout channel_layout_; - const size_t num_channels_; - const int sample_rate_; - const int request_size_; - - double playback_rate_ = 1.0; - - ::media::NullMediaLog media_log_; - std::unique_ptr<::media::AudioRendererAlgorithm> rate_shifter_; - std::unique_ptr<::media::AudioBus> rate_shifter_output_; - scoped_refptr<::media::AudioBufferMemoryPool> audio_buffer_pool_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_PLAYBACK_RATE_SHIFTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/playback_rate_shifter_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/playback_rate_shifter_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/playback_rate_shifter_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,209 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/playback_rate_shifter.h" - -#include "base/logging.h" -#include "base/rand_util.h" -#include "base/types/fixed_array.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { -constexpr int kSampleRate = 48000; -constexpr int64_t kMaxTimestampError = 50; -constexpr int kReadSize = 512; -} // namespace - -class PlaybackRateShifterTest : public testing::Test, public AudioProvider { - public: - PlaybackRateShifterTest() - : rate_shifter_(this, - ::media::CHANNEL_LAYOUT_MONO, - 1, - kSampleRate, - kReadSize) { - srand(12345); - } - - ~PlaybackRateShifterTest() override = default; - - int FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) override { - if (expected_playout_timestamp_ != INT64_MIN) { - int64_t error = playout_timestamp - expected_playout_timestamp_; - EXPECT_LT(std::abs(error), kMaxTimestampError) - << "Playout timestamp error from BufferedFrames() is " << error; - expected_playout_timestamp_ = INT64_MIN; - } - - if (next_playout_timestamp_ != INT64_MIN) { - int64_t error = playout_timestamp - next_playout_timestamp_; - EXPECT_LT(std::abs(error), kMaxTimestampError) - << "Playout timestamp error from FillFrames() is " << error; - } - - next_playout_timestamp_ = - playout_timestamp + - FramesToTime(num_frames) / rate_shifter_.playback_rate(); - float* channel = channel_data[0]; - for (int i = 0; i < num_frames; ++i) { - channel[i] = base::RandDouble(); - } - filled_ += num_frames; - return num_frames; - } - - size_t num_channels() const override { return 1; } - int sample_rate() const override { return kSampleRate; } - - void Read(int num_frames) { - int64_t request_timestamp = FramesToTime(num_read_); - double buffered = rate_shifter_.BufferedFrames(); - int64_t filled_before = filled_; - // No more than 50ms of buffer (plus 1 read). - EXPECT_LT(buffered, - (kSampleRate / 20 + kReadSize) / rate_shifter_.playback_rate()); - - expected_playout_timestamp_ = request_timestamp + FramesToTime(buffered); - base::FixedArray buffer(num_frames); - float* data[1] = {buffer.data()}; - int read = rate_shifter_.FillFrames(num_frames, request_timestamp, data); - EXPECT_EQ(read, num_frames); - num_read_ += read; - - int64_t filled_during_read = filled_ - filled_before; - int64_t expected_next_playout_timestamp = - request_timestamp + - FramesToTime(buffered + - filled_during_read / rate_shifter_.playback_rate()); - int64_t next_playout_timestamp = - FramesToTime(num_read_ + rate_shifter_.BufferedFrames()); - int64_t error = expected_next_playout_timestamp - next_playout_timestamp; - EXPECT_LT(std::abs(error), kMaxTimestampError) - << "Playout timestamp error before/after read is " << error; - } - - void ReadAll(int total_frames) { - int read = 0; - while (read < total_frames) { - int frames = (rand() % 32 + 8) * 16; - Read(frames); - read += frames; - } - } - - int64_t FramesToTime(int64_t frames) { - return frames * 1000000 / kSampleRate; - } - - void SetPlaybackRate(double rate) { - LOG(INFO) << "Set rate to " << rate; - rate_shifter_.SetPlaybackRate(rate); - next_playout_timestamp_ = INT64_MIN; - } - - protected: - PlaybackRateShifter rate_shifter_; - - int64_t next_playout_timestamp_ = INT64_MIN; - int64_t num_read_ = 0; - int64_t filled_ = 0; - - int64_t expected_playout_timestamp_ = INT64_MIN; - int64_t next_expected_playout_timestamp_ = INT64_MIN; -}; - -TEST_F(PlaybackRateShifterTest, Normal) { - SetPlaybackRate(1.0); - ReadAll(kSampleRate); -} - -TEST_F(PlaybackRateShifterTest, Slower) { - SetPlaybackRate(0.7); - ReadAll(kSampleRate); -} - -TEST_F(PlaybackRateShifterTest, Slower2) { - SetPlaybackRate(0.5); - ReadAll(kSampleRate); -} - -TEST_F(PlaybackRateShifterTest, Faster) { - SetPlaybackRate(1.5); - ReadAll(kSampleRate); -} - -TEST_F(PlaybackRateShifterTest, Faster2) { - SetPlaybackRate(2.0); - ReadAll(kSampleRate); -} - -TEST_F(PlaybackRateShifterTest, IncreaseTo1) { - SetPlaybackRate(0.7); - ReadAll(kSampleRate); - SetPlaybackRate(1.0); - ReadAll(kSampleRate / 2); -} - -TEST_F(PlaybackRateShifterTest, IncreaseFrom1) { - SetPlaybackRate(1.0); - ReadAll(kSampleRate); - SetPlaybackRate(1.5); - ReadAll(kSampleRate / 2); -} - -TEST_F(PlaybackRateShifterTest, DecreaseTo1) { - SetPlaybackRate(1.3); - ReadAll(kSampleRate); - SetPlaybackRate(1.0); - ReadAll(kSampleRate / 2); -} - -TEST_F(PlaybackRateShifterTest, DecreaseFrom1) { - SetPlaybackRate(1.0); - ReadAll(kSampleRate); - SetPlaybackRate(0.6); - ReadAll(kSampleRate / 2); -} - -TEST_F(PlaybackRateShifterTest, Increasing) { - SetPlaybackRate(0.5); - ReadAll(kSampleRate); - SetPlaybackRate(0.7); - ReadAll(kSampleRate); - SetPlaybackRate(0.99); - ReadAll(kSampleRate); - SetPlaybackRate(1.0); - ReadAll(kSampleRate); - SetPlaybackRate(1.01); - ReadAll(kSampleRate); - SetPlaybackRate(1.4); - ReadAll(kSampleRate); - SetPlaybackRate(2.0); - ReadAll(kSampleRate); -} - -TEST_F(PlaybackRateShifterTest, Decreasing) { - SetPlaybackRate(2.0); - ReadAll(kSampleRate); - SetPlaybackRate(1.6); - ReadAll(kSampleRate); - SetPlaybackRate(1.01); - ReadAll(kSampleRate); - SetPlaybackRate(1.0); - ReadAll(kSampleRate); - SetPlaybackRate(0.99); - ReadAll(kSampleRate); - SetPlaybackRate(0.64); - ReadAll(kSampleRate); - SetPlaybackRate(0.5); - ReadAll(kSampleRate); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/rate_adjuster.cc chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster.cc --- chromium-132.0.6834.110/chromecast/media/audio/rate_adjuster.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,123 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/rate_adjuster.h" - -#include -#include -#include - -#include "base/check.h" - -namespace chromecast { -namespace media { - -namespace { -constexpr auto kMaxRateChangeInterval = base::Minutes(5); -} // namespace - -RateAdjuster::RateAdjuster(const Config& config, - RateChangeCallback change_clock_rate, - double current_clock_rate) - : config_(config), - change_clock_rate_(std::move(change_clock_rate)), - linear_error_(config_.linear_regression_window.InMicroseconds()), - current_clock_rate_(current_clock_rate) { - DCHECK(change_clock_rate_); -} - -RateAdjuster::~RateAdjuster() = default; - -void RateAdjuster::Reserve(int count) { - linear_error_.Reserve(count); -} - -void RateAdjuster::Reset() { - linear_error_.Reset(); - initialized_ = false; - clock_rate_start_timestamp_ = 0; - initial_timestamp_ = 0; - clock_rate_error_base_ = 0.0; -} - -void RateAdjuster::AddError(int64_t error, int64_t timestamp) { - if (!initialized_) { - clock_rate_start_timestamp_ = timestamp; - clock_rate_error_base_ = 0.0; - initial_timestamp_ = timestamp; - initialized_ = true; - } - - int64_t x = timestamp - initial_timestamp_; - - // Error is positive if actions are happening too late. - // We perform |current_clock_rate_| seconds of actions per second of actual - // time. We want to run a linear regression on how the error is changing over - // time, if we ignore the effects of any previous clock rate changes. To do - // this, we correct the error value to what it would have been if we had never - // adjusted the clock rate. - // In the last N seconds, if the clock rate was 1.0 we would have performed - // (1.0 - clock_rate) * N more seconds of actions, so the current action would - // have occurred that much sooner (reducing its error by that amount). We - // also need to take into account the previous "expected error" (due to clock - // rate changes) at the point when we last changed the clock rate. The - // expected error now is the previous expected error, plus the change due to - // the clock rate of (1.0 - clock_rate) * N seconds. - int64_t time_at_current_clock_rate = timestamp - clock_rate_start_timestamp_; - double correction = clock_rate_error_base_ + - (1.0 - current_clock_rate_) * time_at_current_clock_rate; - int64_t corrected_error = error - correction; - linear_error_.AddSample(x, corrected_error, 1.0); - - if (time_at_current_clock_rate < - config_.rate_change_interval.InMicroseconds()) { - // Don't change clock rate too frequently. - return; - } - - int64_t offset; - double slope; - double e; - if (!linear_error_.EstimateY(x, &offset, &e) || - !linear_error_.EstimateSlope(&slope, &e)) { - return; - } - - // Get the smoothed error (linear regression estimate) at the current time, - // translated back into actual error. - int64_t smoothed_error = offset + correction; - - // If slope is positive, a clock rate of 1.0 is too slow (actions are - // occurring progressively later than desired). We wanted to do slope*N - // seconds actions during N seconds than would have been done at rate 1.0. - // Therefore the actual clock rate should be (1.0 + slope). - // However, we also want to correct for any existing offset. We correct so - // that the error should reduce to 0 by the next rate change interval; - // however the rate change is capped to prevent very fast slewing. - double offset_correction = - static_cast(smoothed_error) / - (config_.rate_change_interval.InMicroseconds() * 2); - if (std::abs(smoothed_error) < config_.max_ignored_current_error) { - // Offset is small enough that we can ignore it, but still correct a little - // bit to avoid bouncing in and out of the ignored region. - offset_correction = offset_correction / 4; - } - offset_correction = - std::clamp(offset_correction, -config_.max_current_error_correction, - config_.max_current_error_correction); - double new_rate = (1.0 + slope) + offset_correction; - - // Only change the clock rate if the difference between the desired rate and - // the current rate is larger than the minimum change. - if (std::fabs(new_rate - current_clock_rate_) > config_.min_rate_change || - time_at_current_clock_rate > kMaxRateChangeInterval.InMicroseconds()) { - current_clock_rate_ = - change_clock_rate_.Run(new_rate, slope, smoothed_error); - clock_rate_start_timestamp_ = timestamp; - clock_rate_error_base_ = correction; - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/rate_adjuster.h chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster.h --- chromium-132.0.6834.110/chromecast/media/audio/rate_adjuster.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_RATE_ADJUSTER_H_ -#define CHROMECAST_MEDIA_AUDIO_RATE_ADJUSTER_H_ - -#include - -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "chromecast/base/statistics/weighted_moving_linear_regression.h" - -namespace chromecast { -namespace media { - -// RateAdjuster handles adjusting a clock rate to minimize errors over time. -// This can be used for A/V sync, for example. The RateAdjuster smooths the -// error samples over time using a moving linear regression. It attempts to -// adjust the clock rate to correct the current absolute error, and the slope -// of the change in error, with the goal of maintaining as close as possible to -// 0 errors over time. -class RateAdjuster { - public: - struct Config { - // The minimum interval between clock rate changes. - base::TimeDelta rate_change_interval = base::Seconds(1); - - // How long to make the linear regression window for smoothing errors. - base::TimeDelta linear_regression_window = base::Seconds(10); - - // The maximum current error to ignore, in microseconds. - int64_t max_ignored_current_error = 0; - - // The maximum current absolute error that should be adjusted for in a - // single clock rate adjustment. - double max_current_error_correction = 2.5e-4; - - // The minimum difference between the optimal clock rate and the current - // clock rate required to actually change the rate. - double min_rate_change = 0; - }; - - // Called to change the clock rate. Returns the actual new clock rate. The - // |error_slope| and |current_error| are provided for debugging/logging - // purposes. - using RateChangeCallback = - base::RepeatingCallback; - - RateAdjuster(const Config& config, - RateChangeCallback change_clock_rate, - double current_clock_rate); - ~RateAdjuster(); - - // Adds an error sample at the given |timestamp|. Both the |error| and the - // |timestamp| are in microseconds. The error of some event should be - // calculated as - . Timestamps - // should increase monotonically. The clock rate will be adjusted - // synchronously within this method via the callback, if necessary. - void AddError(int64_t error, int64_t timestamp); - - // Reserves space for |count| error samples, to reduce memory allocation - // during use. - void Reserve(int count); - - // Resets to initial state. - void Reset(); - - private: - const Config config_; - RateChangeCallback change_clock_rate_; - - WeightedMovingLinearRegression linear_error_; - bool initialized_ = false; - int64_t clock_rate_start_timestamp_ = 0; - int64_t initial_timestamp_ = 0; - double clock_rate_error_base_ = 0.0; - double current_clock_rate_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_RATE_ADJUSTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/audio/rate_adjuster_unittest.cc chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster_unittest.cc --- chromium-132.0.6834.110/chromecast/media/audio/rate_adjuster_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/rate_adjuster_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,131 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/audio/rate_adjuster.h" -#include "base/rand_util.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -class RateAdjusterTest : public testing::Test { - public: - RateAdjusterTest() = default; - ~RateAdjusterTest() override = default; - - double clock_rate() const { return clock_rate_; } - int64_t rate_change_count() const { return rate_change_count_; } - - void set_underlying_rate(double rate) { underlying_rate_ = rate; } - - void Configure(const RateAdjuster::Config& config) { - rate_adjuster_ = std::make_unique( - config, - base::BindRepeating(&RateAdjusterTest::ChangeRate, - base::Unretained(this)), - clock_rate_); - } - - void AddSample(int64_t timestamp, int max_jitter) { - int64_t delta = timestamp - base_timestamp_; - // Clock rate < 1 causes the events to happen later than they should. - int64_t value = base_value_ + delta / (clock_rate_ * underlying_rate_); - last_timestamp_ = timestamp; - last_value_ = value; - - int64_t jittered_value = value + base::RandInt(-max_jitter, max_jitter); - - rate_adjuster_->AddError(jittered_value - timestamp, timestamp); - } - - private: - double ChangeRate(double desired_clock_rate, - double error_slope, - double current_error) { - ++rate_change_count_; - clock_rate_ = desired_clock_rate; - base_timestamp_ = last_timestamp_; - base_value_ = last_value_; - return clock_rate_; - } - - int64_t base_timestamp_ = 0; - int64_t last_timestamp_ = 0; - - int64_t base_value_ = 0; - int64_t last_value_ = 0; - - double clock_rate_ = 1.0; - double underlying_rate_ = 1.0; - - int64_t rate_change_count_ = 0; - - std::unique_ptr rate_adjuster_; -}; - -TEST_F(RateAdjusterTest, NoError) { - RateAdjuster::Config config; - config.max_ignored_current_error = 0; - config.min_rate_change = 0; - Configure(config); - - for (int i = 0; i < 600; ++i) { - AddSample(i * 100000, 0); - } - - EXPECT_EQ(clock_rate(), 1.0); - EXPECT_EQ(rate_change_count(), 0); -} - -TEST_F(RateAdjusterTest, MaxInterval) { - RateAdjuster::Config config; - config.max_ignored_current_error = 0; - config.min_rate_change = 0; - Configure(config); - - for (int i = 0; i < 302; ++i) { - AddSample(i * 1000000, 0); - } - - EXPECT_EQ(clock_rate(), 1.0); - EXPECT_EQ(rate_change_count(), 1); -} - -TEST_F(RateAdjusterTest, SlowUnderlying) { - constexpr double kUnderlyingRate = 0.9995; - set_underlying_rate(kUnderlyingRate); - - RateAdjuster::Config config; - config.max_ignored_current_error = 0; - config.min_rate_change = 0; - Configure(config); - - for (int i = 0; i < 600; ++i) { - AddSample(i * 20000, 0); - } - - EXPECT_NEAR(clock_rate() * kUnderlyingRate, 1.0, 1e-5); - EXPECT_GT(rate_change_count(), 1); -} - -TEST_F(RateAdjusterTest, FastUnderlyingWithJitter) { - constexpr double kUnderlyingRate = 1.0005; - set_underlying_rate(kUnderlyingRate); - - RateAdjuster::Config config; - config.max_ignored_current_error = 0; - config.min_rate_change = 0; - Configure(config); - - // Need more samples to converge. - for (int i = 0; i < 3000; ++i) { - AddSample(i * 20000, 200); - } - - EXPECT_NEAR(clock_rate() * kUnderlyingRate, 1.0, 5e-5); - EXPECT_GT(rate_change_count(), 1); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/audio/wav_header.h chromium-132.0.6834.159/chromecast/media/audio/wav_header.h --- chromium-132.0.6834.110/chromecast/media/audio/wav_header.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/audio/wav_header.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AUDIO_WAV_HEADER_H_ -#define CHROMECAST_MEDIA_AUDIO_WAV_HEADER_H_ - -#include - -namespace chromecast { -namespace media { - -// This is a header for a .wav file. It can be written directly to file (e.g. -// with reinterpret_cast) after SetDataSize(), SetNumChannels(), and -// SetSampleRate() have been called. It defaults to contain float-point data. -// From http://soundfile.sapp.org/doc/WaveFormat/ and -// http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html -struct __attribute__((packed)) WavHeader { - const char riff[4] = {'R', 'I', 'F', 'F'}; - uint32_t chunk_size; // size of file - 8 - const char wave[4] = {'W', 'A', 'V', 'E'}; - const char fmt[4] = {'f', 'm', 't', ' '}; - const uint32_t subchunk_size = 18; - uint16_t audio_format = 3; // FLOAT - uint16_t num_channels; - uint32_t sample_rate; - uint32_t byte_rate; // sample_rate * num_channels * bytes per sample - uint16_t block_align; // num_channels * bytes per sample - uint16_t bits_per_sample = 32; - uint16_t extension_size = 0; - const char data[4] = {'d', 'a', 't', 'a'}; - uint32_t subchunk_2_size; // bytes in the data - - enum AudioFormat { kInteger8, kInteger16, kInteger32, kFloat32 }; - - WavHeader(); - ~WavHeader() = default; - - void SetAudioFormat(AudioFormat audio_format_in) { - switch (audio_format_in) { - case kInteger8: - audio_format = 1; - bits_per_sample = 8; - break; - case kInteger16: - audio_format = 1; - bits_per_sample = 16; - break; - case kInteger32: - audio_format = 1; - bits_per_sample = 32; - break; - case kFloat32: - audio_format = 3; - bits_per_sample = 32; - break; - } - byte_rate = sample_rate * num_channels * bits_per_sample / 8; - block_align = num_channels * bits_per_sample / 8; - } - - void SetDataSize(int size_bytes) { - chunk_size = 36 + size_bytes; - subchunk_2_size = size_bytes; - } - - void SetNumChannels(int num_channels_in) { - num_channels = num_channels_in; - byte_rate = sample_rate * num_channels * bits_per_sample / 8; - block_align = num_channels * bits_per_sample / 8; - } - - void SetSampleRate(int sample_rate_in) { - sample_rate = sample_rate_in; - byte_rate = sample_rate * num_channels * bits_per_sample / 8; - } -}; - -inline WavHeader::WavHeader() = default; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AUDIO_WAV_HEADER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/avsettings/avsettings_dummy.cc chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_dummy.cc --- chromium-132.0.6834.110/chromecast/media/avsettings/avsettings_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/avsettings/avsettings_dummy.h" - -namespace chromecast { - -AvSettingsDummy::AvSettingsDummy() : delegate_(nullptr) {} - -AvSettingsDummy::~AvSettingsDummy() = default; - -void AvSettingsDummy::Initialize(Delegate* delegate) { - delegate_ = delegate; -} - -void AvSettingsDummy::Finalize() { - delegate_ = nullptr; -} - -AvSettings::ActiveState AvSettingsDummy::GetActiveState() { - return ActiveState::UNKNOWN; -} - -bool AvSettingsDummy::TurnActive(bool switch_to_cast) { - return false; -} - -bool AvSettingsDummy::TurnStandby() { - return false; -} - -bool AvSettingsDummy::KeepSystemAwake(int time_millis) { - return false; -} - -AvSettings::AudioVolumeControlType -AvSettingsDummy::GetAudioVolumeControlType() { - return MASTER_VOLUME; -} - -bool AvSettingsDummy::GetAudioVolumeStepInterval(float* step_interval) { - return false; // Use default intervals per control type -} - -int AvSettingsDummy::GetAudioCodecsSupported() { - return 0; -} - -int AvSettingsDummy::GetMaxAudioChannels(AudioCodec codec) { - return 0; -} - -bool AvSettingsDummy::GetScreenResolution(int* width, int* height) { - return false; -} - -int AvSettingsDummy::GetHDCPVersion() { - return 0; -} - -int AvSettingsDummy::GetSupportedEotfs() { - return 0; -} - -int AvSettingsDummy::GetDolbyVisionFlags() { - return 0; -} - -int AvSettingsDummy::GetScreenWidthMm() { - return 0; -} - -int AvSettingsDummy::GetScreenHeightMm() { - return 0; -} - -bool AvSettingsDummy::GetOutputRestrictions(OutputRestrictions* restrictions) { - return false; -} - -void AvSettingsDummy::ApplyOutputRestrictions( - const OutputRestrictions& restrictions) {} - -AvSettings::WakeOnCastStatus AvSettingsDummy::GetWakeOnCastStatus() { - return WAKE_ON_CAST_NOT_SUPPORTED; -} - -bool AvSettingsDummy::EnableWakeOnCast(bool enabled) { - return false; -} - -AvSettings::HdrOutputType AvSettingsDummy::GetHdrOutputType() { - return HDR_OUTPUT_SDR; -} - -bool AvSettingsDummy::SetHdmiVideoMode(bool allow_4k, - int optimize_for_fps, - AvSettings::HdrOutputType output_type) { - return false; -} - -bool AvSettingsDummy::IsHdrOutputSupportedByCurrentHdmiVideoMode( - HdrOutputType output_type) { - return false; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/avsettings/avsettings_dummy.h chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_dummy.h --- chromium-132.0.6834.110/chromecast/media/avsettings/avsettings_dummy.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_dummy.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_AVSETTINGS_AVSETTINGS_DUMMY_H_ -#define CHROMECAST_MEDIA_AVSETTINGS_AVSETTINGS_DUMMY_H_ - -#include "chromecast/public/avsettings.h" - -namespace chromecast { - -// Dummy implementation of AvSettings. -class AvSettingsDummy : public AvSettings { - public: - AvSettingsDummy(); - ~AvSettingsDummy() override; - - // AvSettings implementation: - void Initialize(Delegate* delegate) override; - void Finalize() override; - ActiveState GetActiveState() override; - bool TurnActive(bool switch_to_cast) override; - bool TurnStandby() override; - bool KeepSystemAwake(int time_millis) override; - AudioVolumeControlType GetAudioVolumeControlType() override; - bool GetAudioVolumeStepInterval(float* step_interval) override; - int GetAudioCodecsSupported() override; - int GetMaxAudioChannels(AudioCodec codec) override; - bool GetScreenResolution(int* width, int* height) override; - int GetHDCPVersion() override; - int GetSupportedEotfs() override; - int GetDolbyVisionFlags() override; - int GetScreenWidthMm() override; - int GetScreenHeightMm() override; - bool GetOutputRestrictions(OutputRestrictions* restrictions) override; - void ApplyOutputRestrictions(const OutputRestrictions& restrictions) override; - WakeOnCastStatus GetWakeOnCastStatus() override; - bool EnableWakeOnCast(bool enabled) override; - HdrOutputType GetHdrOutputType() override; - bool SetHdmiVideoMode(bool allow_4k, - int optimize_for_fps, - HdrOutputType output_type) override; - bool IsHdrOutputSupportedByCurrentHdmiVideoMode( - HdrOutputType output_type) override; - - private: - Delegate* delegate_; - - // Disallow copy and assign. - AvSettingsDummy(const AvSettingsDummy&) = delete; - AvSettingsDummy& operator=(const AvSettingsDummy&) = delete; -}; - -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_AVSETTINGS_AVSETTINGS_DUMMY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/avsettings/avsettings_shlib.cc chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_shlib.cc --- chromium-132.0.6834.110/chromecast/media/avsettings/avsettings_shlib.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/avsettings/avsettings_shlib.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include - -#include "chromecast/media/avsettings/avsettings_buildflags.h" -#include "chromecast/media/avsettings/avsettings_dummy.h" -#include "chromecast/public/avsettings.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { - -// static -AvSettings* AvSettingsShlib::Create(const std::vector& argv) { - return new AvSettingsDummy(); -} - -#if BUILDFLAG(VOLUME_CONTROL_IN_AVSETTINGS_SHLIB) -namespace media { - -void VolumeControl::Initialize(const std::vector& argv) {} -void VolumeControl::Finalize() {} -void VolumeControl::AddVolumeObserver(VolumeObserver* observer) {} -void VolumeControl::RemoveVolumeObserver(VolumeObserver* observer) {} - -float VolumeControl::GetVolume(AudioContentType type) { - return 0.0f; -} - -void VolumeControl::SetVolume(VolumeChangeSource source, - AudioContentType type, - float level) {} - -bool VolumeControl::IsMuted(AudioContentType type) { - return false; -} - -void VolumeControl::SetMuted(VolumeChangeSource source, - AudioContentType type, - bool muted) {} - -void VolumeControl::SetOutputLimit(AudioContentType type, float limit) {} - -float VolumeControl::VolumeToDbFS(float volume) { - return 0.0f; -} - -float VolumeControl::DbFSToVolume(float db) { - return 0.0f; -} - -void VolumeControl::SetPowerSaveMode(bool power_save_on) {} - -} // namespace media -#endif // BUILDFLAG(VOLUME_CONTROL_IN_AVSETTINGS_SHLIB) - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/aligned_buffer.h chromium-132.0.6834.159/chromecast/media/base/aligned_buffer.h --- chromium-132.0.6834.110/chromecast/media/base/aligned_buffer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/aligned_buffer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,97 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_ALIGNED_BUFFER_H_ -#define CHROMECAST_MEDIA_BASE_ALIGNED_BUFFER_H_ - -#include -#include - -#include "base/memory/aligned_memory.h" - -namespace { -const int kAlignment = 16; -} // namespace - -namespace chromecast { -namespace media { - -// Convenient class for 16-byte aligned buffers. -template -class AlignedBuffer { - public: - AlignedBuffer() : size_(0), data_(nullptr) {} - - explicit AlignedBuffer(size_t size) - : size_(size), - data_(static_cast( - base::AlignedAlloc(size_ * sizeof(T), kAlignment))) {} - - AlignedBuffer(int size, const T& val) : AlignedBuffer(size) { - std::fill_n(data_.get(), size_, val); - } - - // Copy constructor - AlignedBuffer(const AlignedBuffer& other) - : size_(other.size()), - data_(static_cast( - base::AlignedAlloc(size_ * sizeof(T), kAlignment))) { - std::memcpy(data_.get(), other.data(), size_ * sizeof(T)); - } - - ~AlignedBuffer() = default; - - // Assignment operator - void operator=(const AlignedBuffer& other) { - size_ = other.size(); - data_.reset( - static_cast(base::AlignedAlloc(size_ * sizeof(T), kAlignment))); - std::memcpy(data_.get(), other.data(), size_ * sizeof(T)); - } - - // Move operator - AlignedBuffer& operator=(AlignedBuffer&& other) { - size_ = other.size(); - data_ = std::move(other.data_); - return *this; - } - - void resize(size_t new_size) { - std::unique_ptr new_data( - static_cast(base::AlignedAlloc(new_size * sizeof(T), kAlignment))); - size_t size_to_copy = std::min(new_size, size_); - std::memcpy(new_data.get(), data_.get(), size_to_copy * sizeof(T)); - size_ = new_size; - data_ = std::move(new_data); - } - - void assign(size_t n, const T& val) { - size_ = n; - data_.reset( - static_cast(base::AlignedAlloc(size_ * sizeof(T), kAlignment))); - std::fill_n(data_.get(), size_, val); - } - - // Returns a pointer to the underlying data. - T* data() { return data_.get(); } - const T* data() const { return data_.get(); } - - T& operator[](size_t i) { return data()[i]; } - - const T& operator[](size_t i) const { return data()[i]; } - - // Returns number of elements. - size_t size() const { return size_; } - - bool empty() const { return size_ == 0; } - - private: - size_t size_; - std::unique_ptr data_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_ALIGNED_BUFFER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/audio_device_ids.cc chromium-132.0.6834.159/chromecast/media/base/audio_device_ids.cc --- chromium-132.0.6834.110/chromecast/media/base/audio_device_ids.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/audio_device_ids.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/audio_device_ids.h" - -namespace chromecast { -namespace media { - -const char kLocalAudioDeviceId[] = "local"; -const char kPlatformAudioDeviceId[] = "platform"; -const char kAlarmAudioDeviceId[] = "assistant-alarm"; -const char kTtsAudioDeviceId[] = "assistant-tts"; -const char kBypassAudioDeviceId[] = "bypass"; -const char kNoDelayDeviceId[] = "no_delay"; -const char kDefaultDeviceId[] = "default"; -const char kLowLatencyDeviceId[] = "low_latency"; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/audio_device_ids.h chromium-132.0.6834.159/chromecast/media/base/audio_device_ids.h --- chromium-132.0.6834.110/chromecast/media/base/audio_device_ids.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/audio_device_ids.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_AUDIO_DEVICE_IDS_H_ -#define CHROMECAST_MEDIA_BASE_AUDIO_DEVICE_IDS_H_ - -namespace chromecast { -namespace media { - -// Local-only audio (don't send over multiroom). -extern const char kLocalAudioDeviceId[]; - -extern const char kPlatformAudioDeviceId[]; - -extern const char kAlarmAudioDeviceId[]; - -extern const char kNoDelayDeviceId[]; - -// TODO(kmackay|bshaya) Remove this, just use -// ::media::AudioDeviceDescription::kCommunicationsDeviceId. -extern const char kTtsAudioDeviceId[]; - -// Local-only audio (don't send over multiroom) that should not be affected by -// post-processors. -extern const char kBypassAudioDeviceId[]; - -extern const char kDefaultDeviceId[]; - -extern const char kLowLatencyDeviceId[]; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_AUDIO_DEVICE_IDS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/cast_decoder_buffer_impl.cc chromium-132.0.6834.159/chromecast/media/base/cast_decoder_buffer_impl.cc --- chromium-132.0.6834.110/chromecast/media/base/cast_decoder_buffer_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/cast_decoder_buffer_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// 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 "chromecast/media/base/cast_decoder_buffer_impl.h" - -namespace chromecast { -namespace media { - -CastDecoderBufferImpl::CastDecoderBufferImpl(size_t size, StreamId stream_id) - : stream_id_(stream_id), - size_(size), - data_(std::make_unique(size_)) {} - -CastDecoderBufferImpl::CastDecoderBufferImpl(size_t size) - : CastDecoderBufferImpl(size, kPrimary) {} - -CastDecoderBufferImpl::CastDecoderBufferImpl(StreamId stream_id) - : stream_id_(stream_id), size_(0), data_(nullptr) {} - -CastDecoderBufferImpl::~CastDecoderBufferImpl() = default; - -// static -scoped_refptr CastDecoderBufferImpl::CreateEOSBuffer() { - return CreateEOSBuffer(kPrimary); -} - -// static -scoped_refptr CastDecoderBufferImpl::CreateEOSBuffer( - StreamId stream_id) { - return base::WrapRefCounted(new CastDecoderBufferImpl(stream_id)); -} - -StreamId CastDecoderBufferImpl::stream_id() const { - return stream_id_; -} - -int64_t CastDecoderBufferImpl::timestamp() const { - DCHECK(!end_of_stream()); - return timestamp_.InMicroseconds(); -} - -void CastDecoderBufferImpl::set_timestamp(base::TimeDelta timestamp) { - DCHECK(!end_of_stream()); - timestamp_ = timestamp; -} - -const uint8_t* CastDecoderBufferImpl::data() const { - DCHECK(!end_of_stream()); - return data_.get(); -} - -uint8_t* CastDecoderBufferImpl::writable_data() const { - DCHECK(!end_of_stream()); - return data_.get(); -} - -size_t CastDecoderBufferImpl::data_size() const { - DCHECK(!end_of_stream()); - return size_; -} - -const CastDecryptConfig* CastDecoderBufferImpl::decrypt_config() const { - return nullptr; -} - -bool CastDecoderBufferImpl::end_of_stream() const { - return data_ == nullptr; -} - -bool CastDecoderBufferImpl::is_key_frame() const { - return false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/cast_decoder_buffer_impl.h chromium-132.0.6834.159/chromecast/media/base/cast_decoder_buffer_impl.h --- chromium-132.0.6834.110/chromecast/media/base/cast_decoder_buffer_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/cast_decoder_buffer_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_BASE_CAST_DECODER_BUFFER_IMPL_H_ -#define CHROMECAST_MEDIA_BASE_CAST_DECODER_BUFFER_IMPL_H_ - -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" - -namespace chromecast { -namespace media { - -class CastDecoderBufferImpl : public DecoderBufferBase { - public: - // Using explicit constructor without providing stream id will set it to - // kPrimary by default. - explicit CastDecoderBufferImpl(size_t size); - CastDecoderBufferImpl(size_t size, StreamId stream_id); - - static scoped_refptr CreateEOSBuffer(); - static scoped_refptr CreateEOSBuffer( - StreamId stream_id); - - // DecoderBufferBase implementation: - StreamId stream_id() const override; - int64_t timestamp() const override; - void set_timestamp(base::TimeDelta timestamp) override; - const uint8_t* data() const override; - uint8_t* writable_data() const override; - size_t data_size() const override; - const CastDecryptConfig* decrypt_config() const override; - bool end_of_stream() const override; - bool is_key_frame() const override; - - private: - // This constructor is used by CreateEOSBuffer. - explicit CastDecoderBufferImpl(StreamId stream_id); - ~CastDecoderBufferImpl() override; - - const StreamId stream_id_; - const size_t size_; - const std::unique_ptr data_; - base::TimeDelta timestamp_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_CAST_DECODER_BUFFER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/decrypt_context_impl.cc chromium-132.0.6834.159/chromecast/media/base/decrypt_context_impl.cc --- chromium-132.0.6834.110/chromecast/media/base/decrypt_context_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/decrypt_context_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/decrypt_context_impl.h" - -#include -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "chromecast/public/media/cast_decoder_buffer.h" - -namespace chromecast { -namespace media { -namespace { -void BufferDecryptCB(bool* called, bool* ret, bool success) { - DCHECK(called); - DCHECK(ret); - *called = true; - *ret = success; -} -} - -DecryptContextImpl::DecryptContextImpl(CastKeySystem key_system) - : key_system_(key_system) {} - -DecryptContextImpl::~DecryptContextImpl() {} - -CastKeySystem DecryptContextImpl::GetKeySystem() { - return key_system_; -} - -bool DecryptContextImpl::Decrypt(CastDecoderBuffer* buffer, - uint8_t* opaque_handle, - size_t data_offset) { - bool called = false; - bool success = false; - DecryptAsync(buffer, opaque_handle, data_offset, false /* clear_output */, - base::BindOnce(&BufferDecryptCB, &called, &success)); - CHECK(called) << "Sync Decrypt isn't supported"; - - return success; -} - -void DecryptContextImpl::DecryptAsync(CastDecoderBuffer* buffer, - uint8_t* output_or_handle, - size_t data_offset, - bool clear_output, - DecryptCB decrypt_cb) { - std::move(decrypt_cb).Run(false); -} - -DecryptContextImpl::OutputType DecryptContextImpl::GetOutputType() const { - return OutputType::kSecure; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/decrypt_context_impl.h chromium-132.0.6834.159/chromecast/media/base/decrypt_context_impl.h --- chromium-132.0.6834.110/chromecast/media/base/decrypt_context_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/decrypt_context_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_DECRYPT_CONTEXT_IMPL_H_ -#define CHROMECAST_MEDIA_BASE_DECRYPT_CONTEXT_IMPL_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "chromecast/public/media/cast_key_system.h" -#include "chromecast/public/media/decrypt_context.h" - -namespace chromecast { -namespace media { - -// Base class of a decryption context: a decryption context gathers all the -// information needed to decrypt frames with a given key id. -// Each CDM should implement this and add fields needed to fully describe a -// decryption context. -class DecryptContextImpl : public DecryptContext { - public: - using DecryptCB = base::OnceCallback; - - // Type for the output buffer: - // |kSecure| means the decrypted data will be put in a secured buffer, where - // normal CPU can't access. - // |kClearAllowed| means the license allows the decrypted data to be accessed - // by normal CPU. Caller can decide where is the decrypted data. - // |kClearRequired| means the CDM or platform doesn't support secure buffer. - enum class OutputType { kSecure, kClearAllowed, kClearRequired }; - - explicit DecryptContextImpl(CastKeySystem key_system); - - DecryptContextImpl(const DecryptContextImpl&) = delete; - DecryptContextImpl& operator=(const DecryptContextImpl&) = delete; - - ~DecryptContextImpl() override; - - // DecryptContext implementation: - CastKeySystem GetKeySystem() final; - bool Decrypt(CastDecoderBuffer* buffer, - uint8_t* opaque_handle, - size_t data_offset) final; - - // Similar as the above one. Decryption success or not will be returned in - // |decrypt_cb|. |output_or_handle| is a pointer to the normal memory, if - // |clear_output| is true. Otherwise, it's an opaque handle to the secure - // memory which is only accessible in TEE. |decrypt_cb| will be called on - // caller's thread. - virtual void DecryptAsync(CastDecoderBuffer* buffer, - uint8_t* output_or_handle, - size_t data_offset, - bool clear_output, - DecryptCB decrypt_cb); - - // Returns the type of output buffer. - virtual OutputType GetOutputType() const; - - private: - CastKeySystem key_system_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_DECRYPT_CONTEXT_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/default_monotonic_clock.cc chromium-132.0.6834.159/chromecast/media/base/default_monotonic_clock.cc --- chromium-132.0.6834.110/chromecast/media/base/default_monotonic_clock.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/default_monotonic_clock.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/default_monotonic_clock.h" - -#include - -#include - -#include "base/time/time.h" -#include "build/build_config.h" - -#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -#include "chromecast/media/base/buildflags.h" -#endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || - // BUILDFLAG(IS_CHROMEOS) - -#if BUILDFLAG(IS_FUCHSIA) -#include -#endif // BUILDFLAG(IS_FUCHSIA) - -namespace chromecast { -namespace media { - -// static -std::unique_ptr MonotonicClock::Create() { - return std::make_unique(); -} - -#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -int64_t MonotonicClockNow() { - timespec now = {0, 0}; -#if BUILDFLAG(MEDIA_CLOCK_MONOTONIC_RAW) - clock_gettime(CLOCK_MONOTONIC_RAW, &now); -#else - clock_gettime(CLOCK_MONOTONIC, &now); -#endif // MEDIA_CLOCK_MONOTONIC_RAW - return base::TimeDelta::FromTimeSpec(now).InMicroseconds(); -} - -#elif BUILDFLAG(IS_FUCHSIA) -int64_t MonotonicClockNow() { - return zx_clock_get_monotonic() / 1000; -} - -#endif - -DefaultMonotonicClock::DefaultMonotonicClock() = default; - -DefaultMonotonicClock::~DefaultMonotonicClock() = default; - -int64_t DefaultMonotonicClock::Now() const { - return MonotonicClockNow(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/default_monotonic_clock.h chromium-132.0.6834.159/chromecast/media/base/default_monotonic_clock.h --- chromium-132.0.6834.110/chromecast/media/base/default_monotonic_clock.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/default_monotonic_clock.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_DEFAULT_MONOTONIC_CLOCK_H_ -#define CHROMECAST_MEDIA_BASE_DEFAULT_MONOTONIC_CLOCK_H_ - -#include - -#include "chromecast/media/api/monotonic_clock.h" - -namespace chromecast { -namespace media { - -// Returns the monotonic time (from CLOCK_MONOTONIC) in microseconds. -// Why not use base::TimeTicks? Because we explicitly need time from -// CLOCK_MONOTONIC to match the timestamps from CMA GetRenderingDelay(), and -// base::TimeTicks has no guarantees about which clock it uses (and it could -// change whenever they feel like it upstream). -int64_t MonotonicClockNow(); - -// Default implementation of MonotonicClock that uses MonotonicClockNow(). -class DefaultMonotonicClock : public MonotonicClock { - public: - DefaultMonotonicClock(); - ~DefaultMonotonicClock() override; - - // MonotonicClock implementation: - int64_t Now() const override; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_DEFAULT_MONOTONIC_CLOCK_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/key_systems_common.cc chromium-132.0.6834.159/chromecast/media/base/key_systems_common.cc --- chromium-132.0.6834.110/chromecast/media/base/key_systems_common.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/key_systems_common.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/key_systems_common.h" - -#include - -#include "third_party/widevine/cdm/buildflags.h" - -#if BUILDFLAG(ENABLE_WIDEVINE) -#include "third_party/widevine/cdm/widevine_cdm_common.h" // nogncheck -#endif - -namespace chromecast { -namespace media { - -CastKeySystem GetKeySystemByName(const std::string& key_system_name) { -#if BUILDFLAG(ENABLE_WIDEVINE) - if (key_system_name == kWidevineKeySystem) { - return KEY_SYSTEM_WIDEVINE; - } -#endif // BUILDFLAG(ENABLE_WIDEVINE) - - return KEY_SYSTEM_NONE; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/key_systems_common.h chromium-132.0.6834.159/chromecast/media/base/key_systems_common.h --- chromium-132.0.6834.110/chromecast/media/base/key_systems_common.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/key_systems_common.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_KEY_SYSTEMS_COMMON_H_ -#define CHROMECAST_MEDIA_BASE_KEY_SYSTEMS_COMMON_H_ - -#include - -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/public/media/cast_key_system.h" - -namespace chromecast { -namespace media { - -// Translates a key system string into a CastKeySystem, calling into the -// platform for known key systems if needed. -CastKeySystem GetKeySystemByName(const std::string& key_system_name); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_KEY_SYSTEMS_COMMON_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/media_caps.cc chromium-132.0.6834.159/chromecast/media/base/media_caps.cc --- chromium-132.0.6834.110/chromecast/media/base/media_caps.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/media_caps.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -// 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 "chromecast/media/base/media_caps.h" - -#include "base/command_line.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/public/avsettings.h" - -namespace chromecast { -namespace media { - -int MediaCapabilities::g_hdcp_version = 0; -int MediaCapabilities::g_supported_eotfs = 0; -int MediaCapabilities::g_dolby_vision_flags = 0; -bool MediaCapabilities::g_cur_mode_supports_hdr = false; -bool MediaCapabilities::g_cur_mode_supports_dv = false; -gfx::Size MediaCapabilities::g_screen_resolution(0, 0); - -void MediaCapabilities::ScreenResolutionChanged(const gfx::Size& res) { - LOG(INFO) << __FUNCTION__ << " resolution=" << res.ToString(); - g_screen_resolution = res; - - auto* cmd_line = base::CommandLine::ForCurrentProcess(); - const auto& kHeightSwitch = switches::kForceMediaResolutionHeight; - int height = 0; - if (cmd_line->HasSwitch(kHeightSwitch) && - base::StringToInt(cmd_line->GetSwitchValueASCII(kHeightSwitch), - &height) && - height > 0) { - LOG(INFO) << __func__ << ": overridden screen height=" << height; - g_screen_resolution.set_height(height); - } - const auto& kWidthSwitch = switches::kForceMediaResolutionWidth; - int width = 0; - if (cmd_line->HasSwitch(kWidthSwitch) && - base::StringToInt(cmd_line->GetSwitchValueASCII(kWidthSwitch), &width) && - width > 0) { - LOG(INFO) << __func__ << ": overridden screen width=" << width; - g_screen_resolution.set_width(width); - } -} - -void MediaCapabilities::ScreenInfoChanged(int hdcp_version, - int supported_eotfs, - int dolby_vision_flags, - int screen_width_mm, - int screen_height_mm, - bool cur_mode_supports_hdr, - bool cur_mode_supports_dv) { - LOG(INFO) << __FUNCTION__ << " HDCP version=" << hdcp_version - << " Supported EOTFs=" << supported_eotfs - << " DolbyVision flags=" << dolby_vision_flags - << " Screen size(mm): " << screen_width_mm << "x" - << screen_height_mm << " cur mode HDR=" << cur_mode_supports_hdr - << " cur mode DV=" << cur_mode_supports_dv; - g_hdcp_version = hdcp_version; - g_supported_eotfs = supported_eotfs; - g_dolby_vision_flags = dolby_vision_flags; - g_cur_mode_supports_hdr = cur_mode_supports_hdr; - g_cur_mode_supports_dv = cur_mode_supports_dv; -} - -int MediaCapabilities::GetHdcpVersion() { - return g_hdcp_version; -} - -bool MediaCapabilities::HdmiSinkSupportsEOTF_SDR() { - return g_supported_eotfs & AvSettings::EOTF_SDR; -} - -bool MediaCapabilities::HdmiSinkSupportsEOTF_HDR() { - return g_supported_eotfs & AvSettings::EOTF_HDR; -} - -bool MediaCapabilities::HdmiSinkSupportsEOTF_SMPTE_ST_2084() { - return g_supported_eotfs & AvSettings::EOTF_SMPTE_ST_2084; -} - -bool MediaCapabilities::HdmiSinkSupportsEOTF_HLG() { - return g_supported_eotfs & AvSettings::EOTF_HLG; -} - -bool MediaCapabilities::HdmiSinkSupportsDolbyVision() { - return g_dolby_vision_flags & AvSettings::DOLBY_SUPPORTED; -} - -bool MediaCapabilities::HdmiSinkSupportsDolbyVision_4K_p60() { - return g_dolby_vision_flags & AvSettings::DOLBY_4K_P60_SUPPORTED; -} - -bool MediaCapabilities::HdmiSinkSupportsDolbyVision_422_12bit() { - return g_dolby_vision_flags & AvSettings::DOLBY_422_12BIT_SUPPORTED; -} - -bool MediaCapabilities::CurrentHdmiModeSupportsHDR() { - return g_cur_mode_supports_hdr; -} - -bool MediaCapabilities::CurrentHdmiModeSupportsDolbyVision() { - return g_cur_mode_supports_dv; -} - -gfx::Size MediaCapabilities::GetScreenResolution() { - return g_screen_resolution; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/media_caps.h chromium-132.0.6834.159/chromecast/media/base/media_caps.h --- chromium-132.0.6834.110/chromecast/media/base/media_caps.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/media_caps.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_MEDIA_CAPS_H_ -#define CHROMECAST_MEDIA_BASE_MEDIA_CAPS_H_ - -#include "ui/gfx/geometry/size.h" - -namespace chromecast { -namespace media { - -// The MediaCapabitlies is a convenience API which makes various audio/video -// capabitlies exposed by AvSettings available both in the browser and -// renderer processes in the Chrome sandboxed model (the AvSettings API is -// currently only available in the browser process). -class MediaCapabilities { - public: - static void ScreenResolutionChanged(const gfx::Size& res); - static void ScreenInfoChanged(int hdcp_version, - int supported_eotfs, - int dolby_vision_flags, - int screen_width_mm, - int screen_height_mm, - bool cur_mode_supports_hdr, - bool cur_mode_supports_dv); - // HDCP version multiplied by 10, e.g. 22 means HDCP 2.2. - static int GetHdcpVersion(); - // HdmiSinkSupports* functions check for display support independent of - // current HDMI mode. - static bool HdmiSinkSupportsEOTF_SDR(); - static bool HdmiSinkSupportsEOTF_HDR(); - static bool HdmiSinkSupportsEOTF_SMPTE_ST_2084(); - static bool HdmiSinkSupportsEOTF_HLG(); - static bool HdmiSinkSupportsDolbyVision(); - static bool HdmiSinkSupportsDolbyVision_4K_p60(); - static bool HdmiSinkSupportsDolbyVision_422_12bit(); - // Check for HDR support (i.e. >= 10-bit) and DV support in current HDMI - // mode. - static bool CurrentHdmiModeSupportsHDR(); - static bool CurrentHdmiModeSupportsDolbyVision(); - static gfx::Size GetScreenResolution(); - - private: - static unsigned int g_hdmi_codecs; - static int g_hdcp_version; - static int g_supported_eotfs; - static int g_dolby_vision_flags; - static bool g_cur_mode_supports_hdr; - static bool g_cur_mode_supports_dv; - static gfx::Size g_screen_resolution; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_MEDIA_CAPS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/media_codec_support.cc chromium-132.0.6834.159/chromecast/media/base/media_codec_support.cc --- chromium-132.0.6834.110/chromecast/media/base/media_codec_support.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/media_codec_support.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,198 +0,0 @@ -// 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 "chromecast/media/base/media_codec_support.h" - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/strings/string_util.h" - -namespace chromecast { -namespace media { - -AudioCodec ToCastAudioCodec(const ::media::AudioCodec codec) { - switch (codec) { - case ::media::AudioCodec::kAAC: - return kCodecAAC; - case ::media::AudioCodec::kMP3: - return kCodecMP3; - case ::media::AudioCodec::kPCM: - return kCodecPCM; - case ::media::AudioCodec::kPCM_S16BE: - return kCodecPCM_S16BE; - case ::media::AudioCodec::kVorbis: - return kCodecVorbis; - case ::media::AudioCodec::kOpus: - return kCodecOpus; - case ::media::AudioCodec::kEAC3: - return kCodecEAC3; - case ::media::AudioCodec::kAC3: - return kCodecAC3; - case ::media::AudioCodec::kDTS: - return kCodecDTS; - case ::media::AudioCodec::kDTSXP2: - return kCodecDTSXP2; - case ::media::AudioCodec::kDTSE: - return kCodecDTSE; - case ::media::AudioCodec::kFLAC: - return kCodecFLAC; - case ::media::AudioCodec::kMpegHAudio: - return kCodecMpegHAudio; - default: - LOG(ERROR) << "Unsupported audio codec " << codec; - } - return kAudioCodecUnknown; -} - -VideoCodec ToCastVideoCodec(const ::media::VideoCodec video_codec, - const ::media::VideoCodecProfile codec_profile) { - switch (video_codec) { - case ::media::VideoCodec::kH264: - return kCodecH264; - case ::media::VideoCodec::kVP8: - return kCodecVP8; - case ::media::VideoCodec::kVP9: - return kCodecVP9; - case ::media::VideoCodec::kHEVC: - return kCodecHEVC; - case ::media::VideoCodec::kDolbyVision: - if (codec_profile == ::media::DOLBYVISION_PROFILE0 || - codec_profile == ::media::DOLBYVISION_PROFILE9) { - return kCodecDolbyVisionH264; - } else if (codec_profile == ::media::DOLBYVISION_PROFILE5 || - codec_profile == ::media::DOLBYVISION_PROFILE7 || - codec_profile == ::media::DOLBYVISION_PROFILE8) { - return kCodecDolbyVisionHEVC; - } - LOG(ERROR) << "Unsupported video codec profile " << codec_profile; - break; - case ::media::VideoCodec::kAV1: - return kCodecAV1; - default: - LOG(ERROR) << "Unsupported video codec " << video_codec; - } - return kVideoCodecUnknown; -} - -VideoProfile ToCastVideoProfile( - const ::media::VideoCodecProfile codec_profile) { - switch (codec_profile) { - case ::media::H264PROFILE_BASELINE: - return kH264Baseline; - case ::media::H264PROFILE_MAIN: - return kH264Main; - case ::media::H264PROFILE_EXTENDED: - return kH264Extended; - case ::media::H264PROFILE_HIGH: - return kH264High; - case ::media::H264PROFILE_HIGH10PROFILE: - return kH264High10; - case ::media::H264PROFILE_HIGH422PROFILE: - return kH264High422; - case ::media::H264PROFILE_HIGH444PREDICTIVEPROFILE: - return kH264High444Predictive; - case ::media::H264PROFILE_SCALABLEBASELINE: - return kH264ScalableBaseline; - case ::media::H264PROFILE_SCALABLEHIGH: - return kH264ScalableHigh; - case ::media::H264PROFILE_STEREOHIGH: - return kH264StereoHigh; - case ::media::H264PROFILE_MULTIVIEWHIGH: - return kH264MultiviewHigh; - case ::media::HEVCPROFILE_MAIN: - return kHEVCMain; - case ::media::HEVCPROFILE_MAIN10: - return kHEVCMain10; - case ::media::HEVCPROFILE_MAIN_STILL_PICTURE: - return kHEVCMainStillPicture; - case ::media::HEVCPROFILE_REXT: - return kHEVCRext; - case ::media::HEVCPROFILE_HIGH_THROUGHPUT: - return kHEVCHighThroughput; - case ::media::HEVCPROFILE_MULTIVIEW_MAIN: - return kHEVCMultiviewMain; - case ::media::HEVCPROFILE_SCALABLE_MAIN: - return kHEVCScalableMain; - case ::media::HEVCPROFILE_3D_MAIN: - return kHEVC3dMain; - case ::media::HEVCPROFILE_SCREEN_EXTENDED: - return kHEVCScreenExtended; - case ::media::HEVCPROFILE_SCALABLE_REXT: - return kHEVCScalableRext; - case ::media::HEVCPROFILE_HIGH_THROUGHPUT_SCREEN_EXTENDED: - return kHEVCHighThroughputScreenExtended; - case ::media::VP8PROFILE_ANY: - return kVP8ProfileAny; - case ::media::VP9PROFILE_PROFILE0: - return kVP9Profile0; - case ::media::VP9PROFILE_PROFILE1: - return kVP9Profile1; - case ::media::VP9PROFILE_PROFILE2: - return kVP9Profile2; - case ::media::VP9PROFILE_PROFILE3: - return kVP9Profile3; - case ::media::DOLBYVISION_PROFILE0: - return kDolbyVisionProfile0; - case ::media::DOLBYVISION_PROFILE5: - return kDolbyVisionProfile5; - case ::media::DOLBYVISION_PROFILE7: - return kDolbyVisionProfile7; - case ::media::DOLBYVISION_PROFILE8: - return kDolbyVisionProfile8; - case ::media::DOLBYVISION_PROFILE9: - return kDolbyVisionProfile9; - case ::media::AV1PROFILE_PROFILE_MAIN: - return kAV1ProfileMain; - case ::media::AV1PROFILE_PROFILE_HIGH: - return kAV1ProfileHigh; - case ::media::AV1PROFILE_PROFILE_PRO: - return kAV1ProfilePro; - case ::media::VVCPROFILE_MAIN10: - return kVVCProfileMain10; - case ::media::VVCPROFILE_MAIN12: - return kVVCProfileMain12; - case ::media::VVCPROFILE_MAIN12_INTRA: - return kVVCProfileMain12Intra; - case ::media::VVCPROIFLE_MULTILAYER_MAIN10: - return kVVCProfileMultilayerMain10; - case ::media::VVCPROFILE_MAIN10_444: - return kVVCProfileMain10444; - case ::media::VVCPROFILE_MAIN12_444: - return kVVCProfileMain12444; - case ::media::VVCPROFILE_MAIN16_444: - return kVVCProfileMain16444; - case ::media::VVCPROFILE_MAIN12_444_INTRA: - return kVVCProfileMain12444Intra; - case ::media::VVCPROFILE_MAIN16_444_INTRA: - return kVVCProfileMain16444Intra; - case ::media::VVCPROFILE_MULTILAYER_MAIN10_444: - return kVVCProfileMain10444; - case ::media::VVCPROFILE_MAIN10_STILL_PICTURE: - return kVVCProfileMain10Still; - case ::media::VVCPROFILE_MAIN12_STILL_PICTURE: - return kVVCProfileMain12Still; - case ::media::VVCPROFILE_MAIN10_444_STILL_PICTURE: - return kVVCProfileMain10444Still; - case ::media::VVCPROFILE_MAIN12_444_STILL_PICTURE: - return kVVCProfileMain12444Still; - case ::media::VVCPROFILE_MAIN16_444_STILL_PICTURE: - return kVVCProfileMain16444Still; - default: - LOG(INFO) << "Unsupported video codec profile " << codec_profile; - } - return kVideoProfileUnknown; -} - -CodecProfileLevel ToCastCodecProfileLevel( - const ::media::CodecProfileLevel& codec_profile_level) { - CodecProfileLevel result; - result.codec = - ToCastVideoCodec(codec_profile_level.codec, codec_profile_level.profile); - result.profile = ToCastVideoProfile(codec_profile_level.profile); - result.level = codec_profile_level.level; - return result; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/media_codec_support.h chromium-132.0.6834.159/chromecast/media/base/media_codec_support.h --- chromium-132.0.6834.110/chromecast/media/base/media_codec_support.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/media_codec_support.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_BASE_MEDIA_CODEC_SUPPORT_H_ -#define CHROMECAST_MEDIA_BASE_MEDIA_CODEC_SUPPORT_H_ - -#include "base/functional/callback.h" -#include "chromecast/public/media/decoder_config.h" -#include "media/base/audio_codecs.h" -#include "media/base/mime_util.h" -#include "media/base/video_codecs.h" - -namespace chromecast { -namespace media { - -// Converts ::media::AudioCodec to chromecast::media::AudioCodec. Any unknown or -// unsupported codec will be converted to chromecast::media::kCodecUnknown. -AudioCodec ToCastAudioCodec(const ::media::AudioCodec codec); - -// Converts ::media::VideoCodec to chromecast::media::VideoCodec. Any unknown or -// unsupported codec will be converted to chromecast::media::kCodecUnknown. Note -// |codec_profile| is ignored for codecs other than Dolby Vision. -// TODO(erickung): Remove |codec_profile| parameter by changing VideoCodec enum -// to align with ::media::VideoCodecs. -VideoCodec ToCastVideoCodec(const ::media::VideoCodec codec, - const ::media::VideoCodecProfile codec_profile); - -// Converts ::media::VideoCodecProfile to chromecast::media::VideoProfile. -VideoProfile ToCastVideoProfile(const ::media::VideoCodecProfile profile); -CodecProfileLevel ToCastCodecProfileLevel( - const ::media::CodecProfileLevel& codec_profile_level); -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_MEDIA_CODEC_SUPPORT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/slew_volume.cc chromium-132.0.6834.159/chromecast/media/base/slew_volume.cc --- chromium-132.0.6834.110/chromecast/media/base/slew_volume.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/slew_volume.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,236 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/slew_volume.h" - -#include -#include -#include - -#include "base/check_op.h" -#include "media/base/vector_math.h" - -namespace { - -// The time to slew from current volume to target volume. -const int kMaxSlewTimeMs = 100; -const int kDefaultSampleRate = 44100; - -} // namespace - -struct FMACTraits { - static void ProcessBulkData(const float* src, - float volume, - int frames, - float* dest) { - ::media::vector_math::FMAC(src, volume, frames, dest); - } - - static void ProcessSingleDatum(const float* src, float volume, float* dest) { - (*dest) += (*src) * volume; - } - - static void ProcessZeroVolume(const float* src, int frames, float* dest) {} - - static void ProcessUnityVolume(const float* src, int frames, float* dest) { - ProcessBulkData(src, 1.0, frames, dest); - } -}; - -struct FMULTraits { - static void ProcessBulkData(const float* src, - float volume, - int frames, - float* dest) { - ::media::vector_math::FMUL(src, volume, frames, dest); - } - - static void ProcessSingleDatum(const float* src, float volume, float* dest) { - (*dest) = (*src) * volume; - } - - static void ProcessZeroVolume(const float* src, int frames, float* dest) { - std::memset(dest, 0, frames * sizeof(*dest)); - } - - static void ProcessUnityVolume(const float* src, int frames, float* dest) { - if (src == dest) { - return; - } - std::memcpy(dest, src, frames * sizeof(*dest)); - } -}; - -namespace chromecast { -namespace media { - -SlewVolume::SlewVolume() : SlewVolume(kMaxSlewTimeMs) {} - -SlewVolume::SlewVolume(int max_slew_time_ms) - : SlewVolume(max_slew_time_ms, false) {} - -SlewVolume::SlewVolume(int max_slew_time_ms, bool use_cosine_slew) - : sample_rate_(kDefaultSampleRate), - max_slew_time_ms_(max_slew_time_ms), - max_slew_per_sample_(1000.0 / (max_slew_time_ms_ * sample_rate_)), - use_cosine_slew_(use_cosine_slew) {} - -void SlewVolume::SetSampleRate(int sample_rate) { - CHECK_GT(sample_rate, 0); - - sample_rate_ = sample_rate; - SetVolume(volume_scale_); -} - -void SlewVolume::SetVolume(double volume_scale) { - volume_scale_ = volume_scale; - if (interrupted_) { - current_volume_ = volume_scale_; - last_starting_volume_ = current_volume_; - } - - // Slew rate should be volume_to_slew / slew_time / sample_rate, but use a - // minimum volume_to_slew of 0.1 to avoid very small slew per sample. - double volume_diff = - std::max(0.1, std::fabs(volume_scale_ - current_volume_)); - max_slew_per_sample_ = - volume_diff * 1000.0 / (max_slew_time_ms_ * sample_rate_); - - if (use_cosine_slew_) { - // Set initial state for cosine slew. Cosine fading always lasts - // max_slew_time_ms_. - slew_counter_ = max_slew_time_ms_ * 0.001 * sample_rate_; - slew_angle_ = sin(M_PI / slew_counter_); - slew_offset_ = (current_volume_ + volume_scale_) * 0.5; - slew_cos_ = (current_volume_ - volume_scale_) * 0.5; - slew_sin_ = 0.0; - } -} - -float SlewVolume::LastBufferMaxMultiplier() { - return std::max(current_volume_, last_starting_volume_); -} - -void SlewVolume::SetMaxSlewTimeMs(int max_slew_time_ms) { - CHECK_GE(max_slew_time_ms, 0); - - max_slew_time_ms_ = max_slew_time_ms; -} - -void SlewVolume::Interrupted() { - interrupted_ = true; - current_volume_ = volume_scale_; -} - -void SlewVolume::ProcessFMAC(bool repeat_transition, - const float* src, - int frames, - int channels, - float* dest) { - ProcessData(repeat_transition, src, frames, channels, dest); -} - -void SlewVolume::ProcessFMUL(bool repeat_transition, - const float* src, - int frames, - int channels, - float* dest) { - ProcessData(repeat_transition, src, frames, channels, dest); -} - -template -void SlewVolume::ProcessData(bool repeat_transition, - const float* src, - int frames, - int channels, - float* dest) { - DCHECK(src); - DCHECK(dest); - // Ensure |src| and |dest| are 16-byte aligned. - DCHECK_EQ(0u, reinterpret_cast(src) & - (::media::vector_math::kRequiredAlignment - 1)); - DCHECK_EQ(0u, reinterpret_cast(dest) & - (::media::vector_math::kRequiredAlignment - 1)); - - if (!frames) { - return; - } - - interrupted_ = false; - if (repeat_transition) { - current_volume_ = last_starting_volume_; - } else { - last_starting_volume_ = current_volume_; - } - - if (current_volume_ == volume_scale_) { - if (current_volume_ == 0.0) { - Traits::ProcessZeroVolume(src, frames * channels, dest); - return; - } - if (current_volume_ == 1.0) { - Traits::ProcessUnityVolume(src, frames * channels, dest); - return; - } - Traits::ProcessBulkData(src, current_volume_, frames * channels, dest); - return; - } - - if (use_cosine_slew_) { - int slew_frames = std::min(slew_counter_, frames); - frames -= slew_frames; - slew_counter_ -= slew_frames; - for (; slew_frames > 0; --slew_frames) { - slew_cos_ -= slew_sin_ * slew_angle_; - slew_sin_ += slew_cos_ * slew_angle_; - current_volume_ = std::clamp(slew_offset_ + slew_cos_, 0.0, 1.0); - for (int i = 0; i < channels; ++i) { - Traits::ProcessSingleDatum(src, current_volume_, dest); - ++src; - ++dest; - } - } - if (!slew_counter_) { - current_volume_ = volume_scale_; - } - } else if (current_volume_ < volume_scale_) { - do { - for (int i = 0; i < channels; ++i) { - Traits::ProcessSingleDatum(src, current_volume_, dest); - ++src; - ++dest; - } - --frames; - current_volume_ += max_slew_per_sample_; - } while (current_volume_ < volume_scale_ && frames); - current_volume_ = std::min(current_volume_, volume_scale_); - } else { // current_volume_ > volume_scale_ - do { - for (int i = 0; i < channels; ++i) { - Traits::ProcessSingleDatum(src, current_volume_, dest); - ++src; - ++dest; - } - --frames; - current_volume_ -= max_slew_per_sample_; - } while (current_volume_ > volume_scale_ && frames); - current_volume_ = std::max(current_volume_, volume_scale_); - } - while (frames && (reinterpret_cast(src) & - (::media::vector_math::kRequiredAlignment - 1))) { - for (int i = 0; i < channels; ++i) { - Traits::ProcessSingleDatum(src, current_volume_, dest); - ++src; - ++dest; - } - --frames; - } - if (!frames) { - return; - } - Traits::ProcessBulkData(src, current_volume_, frames * channels, dest); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/slew_volume.h chromium-132.0.6834.159/chromecast/media/base/slew_volume.h --- chromium-132.0.6834.110/chromecast/media/base/slew_volume.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/slew_volume.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,95 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Scale volume with slew rate limiting - -#ifndef CHROMECAST_MEDIA_BASE_SLEW_VOLUME_H_ -#define CHROMECAST_MEDIA_BASE_SLEW_VOLUME_H_ - -#include - -namespace chromecast { -namespace media { - -class SlewVolume { - public: - SlewVolume(); - explicit SlewVolume(int max_slew_time_ms); - // Use raised negative cosine function when |use_cosine_slew| is true and - // linear otherwise. - SlewVolume(int max_slew_time_ms, bool use_cosine_slew); - - SlewVolume(const SlewVolume&) = delete; - SlewVolume& operator=(const SlewVolume&) = delete; - - ~SlewVolume() = default; - - void SetSampleRate(int sample_rate); - void SetVolume(double volume_scale); - - // Return the largest multiplier that was applied in the last call to - // ProcessFMAC() or ProcessFMUL(). The largest multiplier is used because - // that determines the largest possible value in the buffer. - float LastBufferMaxMultiplier(); - void SetMaxSlewTimeMs(int max_slew_time_ms); - - // Called to indicate that the stream was interrupted; volume changes can be - // applied immediately. - void Interrupted(); - - // Smoothly calculates dest[i] += src[i] * |volume_scale|. - // |volume_scale| will always be consistent across a frame. - // |src| and |dest| are interleaved buffers with |channels| channels and at - // least |frames| frames (|channels| * |frames| total size). - // |src| and |dest| may be the same. - // |src| and |dest| must be 16-byte aligned. - // If using planar data, |repeat_transition| should be true for channels 2 - // through n, which will cause the slewing process to be repeated. - void ProcessFMAC(bool repeat_transition, - const float* src, - int frames, - int channels, - float* dest); - - // Smoothly calculates dest[i] = src[i] * |volume_scale|. - // |volume_scale| will always be consistent across a frame. - // |src| and |dest| are interleaved buffers with |channels| channels and at - // least |frames| frames (|channels| * |frames| total size). - // |src| and |dest| may be the same. - // |src| and |dest| must be 16-byte aligned. - // If using planar data, |repeat_transition| should be true for channels 2 - // through n, which will cause the slewing process to be repeated. - void ProcessFMUL(bool repeat_transition, - const float* src, - int frames, - int channels, - float* dest); - - private: - template - void ProcessData(bool repeat_transition, - const float* src, - int frames, - int channels, - float* dest); - - double sample_rate_; - double volume_scale_ = 1.0; - double current_volume_ = 1.0; - double last_starting_volume_ = 1.0; - double max_slew_time_ms_; - double max_slew_per_sample_; - bool interrupted_ = true; - bool use_cosine_slew_ = false; - int slew_counter_; - double slew_angle_; - double slew_offset_; - double slew_cos_; - double slew_sin_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_SLEW_VOLUME_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/slew_volume_unittests.cc chromium-132.0.6834.159/chromecast/media/base/slew_volume_unittests.cc --- chromium-132.0.6834.110/chromecast/media/base/slew_volume_unittests.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/slew_volume_unittests.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,544 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include -#include -#include - -#include "base/check.h" -#include "chromecast/media/base/slew_volume.h" -#include "media/base/audio_bus.h" -#include "media/base/vector_math.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { - -const int kNumChannels = 2; -const int kNumFrames = 100; -const float kSinFrequency = 1.0f / kNumFrames; -const int kBytesPerSample = sizeof(int32_t); - -// Frequency is in frames (frequency = frequency_in_hz / sample rate). -std::unique_ptr<::media::AudioBus> GetSineData(size_t frames, float frequency) { - auto data = ::media::AudioBus::Create(kNumChannels, frames); - std::vector sine(frames * 2); - for (size_t i = 0; i < frames; ++i) { - // Offset by 1 because sin(0) = 0 and the first value is a special case. - sine[i * 2] = sin(static_cast(i + 1) * frequency * 2 * M_PI) * - std::numeric_limits::max(); - sine[i * 2 + 1] = cos(static_cast(i + 1) * frequency * 2 * M_PI) * - std::numeric_limits::max(); - } - data->FromInterleaved<::media::SignedInt32SampleTypeTraits>(sine.data(), - frames); - return data; -} - -// Gets pointers to the data in an audiobus. -// If |swapped| is true, the channel order will be swapped. -std::vector GetDataChannels(::media::AudioBus* audio, - bool swapped = false) { - std::vector data(kNumChannels); - for (int i = 0; i < kNumChannels; ++i) { - int source_channel = swapped ? (i + 1) % kNumChannels : i; - data[i] = audio->channel(source_channel); - } - return data; -} - -void ScaleData(const std::vector& data, int frames, float scale) { - for (size_t ch = 0; ch < data.size(); ++ch) { - for (int f = 0; f < frames; ++f) { - data[ch][f] *= scale; - } - } -} - -void CompareDataPartial(const std::vector& expected, - const std::vector& actual, - int start, - int end) { - ASSERT_GE(start, 0); - ASSERT_LT(start, end); - ASSERT_EQ(expected.size(), actual.size()); - - for (size_t ch = 0; ch < expected.size(); ++ch) { - for (int f = start; f < end; ++f) { - EXPECT_FLOAT_EQ(expected[ch][f], actual[ch][f]) - << "ch: " << ch << " f: " << f; - } - } -} - -} // namespace - -class SlewVolumeBaseTest : public ::testing::Test { - public: - SlewVolumeBaseTest(const SlewVolumeBaseTest&) = delete; - SlewVolumeBaseTest& operator=(const SlewVolumeBaseTest&) = delete; - - protected: - SlewVolumeBaseTest() = default; - ~SlewVolumeBaseTest() override = default; - - void SetUp() override { - slew_volume_ = std::make_unique(); - slew_volume_->Interrupted(); - MakeData(kNumFrames); - } - - void MakeData(int num_frames) { - num_frames_ = num_frames; - data_bus_ = GetSineData(num_frames_, kSinFrequency); - data_bus_2_ = GetSineData(num_frames_, kSinFrequency); - expected_bus_ = GetSineData(num_frames_, kSinFrequency); - data_ = GetDataChannels(data_bus_.get()); - data_2_ = GetDataChannels(data_bus_2_.get(), true /* swapped */); - expected_ = GetDataChannels(expected_bus_.get()); - } - - void CompareBuffers(int start = 0, int end = -1) { - if (end == -1) { - end = num_frames_; - } - - ASSERT_GE(start, 0); - ASSERT_LT(start, end); - ASSERT_LE(end, num_frames_); - - CompareDataPartial(expected_, data_, start, end); - } - - void ClearInterrupted() { - float throwaway __attribute__((__aligned__(16))) = 0.0f; - slew_volume_->ProcessFMUL(false, &throwaway, 1, 1, &throwaway); - } - - int num_frames_; - - std::unique_ptr slew_volume_; - std::unique_ptr<::media::AudioBus> data_bus_; - std::unique_ptr<::media::AudioBus> data_bus_2_; - std::unique_ptr<::media::AudioBus> expected_bus_; - std::vector data_; - std::vector data_2_; - std::vector expected_; -}; - -// ASSERT_DEATH isn't implemented on Fuchsia. -#if defined(ASSERT_DEATH) - -TEST_F(SlewVolumeBaseTest, BadSampleRate) { -// String arguments aren't passed to CHECK() in official builds. -#if defined(OFFICIAL_BUILD) && defined(NDEBUG) - ASSERT_DEATH(slew_volume_->SetSampleRate(0), ""); -#else - ASSERT_DEATH(slew_volume_->SetSampleRate(0), "sample_rate"); -#endif -} - -TEST_F(SlewVolumeBaseTest, BadSlewTime) { - ASSERT_DEATH(slew_volume_->SetMaxSlewTimeMs(-1), ""); -} - -#endif // defined(ASSERT_DEATH) - -TEST_F(SlewVolumeBaseTest, InstantVolumeDecreasing) { - slew_volume_->SetMaxSlewTimeMs(10); - slew_volume_->SetSampleRate(10000); - // Max slew per sample = 1000 / (max_time * sample_rate) - // = 0.01 - slew_volume_->SetVolume(1.0); - ClearInterrupted(); - slew_volume_->SetVolume(0.0); - const int kFramesPerTransaction = 10; - // LastVolume lags, so 101 steps are needed. - for (int i = 0; i < 101; i += kFramesPerTransaction) { - for (size_t ch = 0; ch < data_.size(); ++ch) { - slew_volume_->ProcessFMAC(ch != 0, data_[ch], 10, 1, data_2_[ch]); - } - ASSERT_FLOAT_EQ(1.0 - (0.01 * i), slew_volume_->LastBufferMaxMultiplier()); - } -} - -TEST_F(SlewVolumeBaseTest, InstantVolumeIncreasing) { - slew_volume_->SetMaxSlewTimeMs(10); - slew_volume_->SetSampleRate(10000); - // Max slew per sample = 1000 / (max_time * sample_rate) - // = 0.01 - slew_volume_->SetVolume(0.0); - ClearInterrupted(); - slew_volume_->SetVolume(1.0); - const int kFramesPerTransaction = 10; - // LastVolume leads, so 100 steps are needed. - for (int i = 0; i < 100; i += kFramesPerTransaction) { - for (size_t ch = 0; ch < data_.size(); ++ch) { - slew_volume_->ProcessFMAC(ch != 0, data_[ch], 10, 1, data_2_[ch]); - } - ASSERT_FLOAT_EQ(0.01 * (i + kFramesPerTransaction), - slew_volume_->LastBufferMaxMultiplier()); - } -} - -class SlewVolumeSteadyStateTest : public SlewVolumeBaseTest { - public: - SlewVolumeSteadyStateTest(const SlewVolumeSteadyStateTest&) = delete; - SlewVolumeSteadyStateTest& operator=(const SlewVolumeSteadyStateTest&) = - delete; - - protected: - SlewVolumeSteadyStateTest() = default; - ~SlewVolumeSteadyStateTest() override = default; - - void SetUp() override { - SlewVolumeBaseTest::SetUp(); - slew_volume_->Interrupted(); - } -}; - -TEST_F(SlewVolumeSteadyStateTest, FMULNoOp) { - slew_volume_->SetVolume(1.0f); - - slew_volume_->ProcessFMUL(false /* repeat transition */, data_[0], - num_frames_, 1, data_[0]); - slew_volume_->ProcessFMUL(true /* repeat transition */, data_[1], num_frames_, - 1, data_[1]); - CompareBuffers(); -} - -TEST_F(SlewVolumeSteadyStateTest, FMULCopy) { - slew_volume_->SetVolume(1.0f); - - slew_volume_->ProcessFMUL(false /* repeat transition */, data_2_[0], - num_frames_, 1, data_[0]); - slew_volume_->ProcessFMUL(true /* repeat transition */, data_2_[1], - num_frames_, 1, data_[1]); - CompareDataPartial(data_2_, data_, 0, num_frames_); -} - -TEST_F(SlewVolumeSteadyStateTest, FMULZero) { - slew_volume_->SetVolume(0.0f); - slew_volume_->ProcessFMUL(false, /* repeat transition */ - data_[0], num_frames_, 1, data_[0]); - slew_volume_->ProcessFMUL(true, data_[1], num_frames_, 1, data_[1]); - - for (size_t ch = 0; ch < data_.size(); ++ch) { - for (int f = 0; f < num_frames_; ++f) { - EXPECT_EQ(0.0f, data_[ch][f]) << "at ch " << ch << "frame " << f; - } - } -} - -TEST_F(SlewVolumeSteadyStateTest, FMULInterrupted) { - float volume = 0.6f; - slew_volume_->SetVolume(volume); - - slew_volume_->ProcessFMUL(false, data_[0], num_frames_, 1, data_[0]); - slew_volume_->ProcessFMUL(true, data_[1], num_frames_, 1, data_[1]); - ScaleData(expected_, num_frames_, volume); - CompareBuffers(); -} - -TEST_F(SlewVolumeSteadyStateTest, FMACNoOp) { - slew_volume_->SetVolume(0.0f); - slew_volume_->ProcessFMAC(false, data_2_[0], num_frames_, 1, data_[0]); - slew_volume_->ProcessFMAC(false, data_2_[1], num_frames_, 1, data_[1]); - CompareBuffers(); -} - -class SlewVolumeDynamicTest - : public SlewVolumeBaseTest, - public ::testing::WithParamInterface> { - public: - SlewVolumeDynamicTest(const SlewVolumeDynamicTest&) = delete; - SlewVolumeDynamicTest& operator=(const SlewVolumeDynamicTest&) = delete; - - protected: - SlewVolumeDynamicTest() = default; - ~SlewVolumeDynamicTest() override = default; - - void SetUp() override { - SlewVolumeBaseTest::SetUp(); - channels_ = 2; - sample_rate_ = std::get<0>(GetParam()); - slew_time_ms_ = std::get<1>(GetParam()); - slew_time_frames_ = sample_rate_ * slew_time_ms_ / 1000; - slew_volume_->SetSampleRate(sample_rate_); - slew_volume_->SetMaxSlewTimeMs(slew_time_ms_); - // +2 frames for numeric errors. - int num_frames = slew_time_frames_ + 2; - max_frame_ = num_frames - 1; - ASSERT_GE(num_frames, 1); - MakeData(num_frames); - } - - // Checks data_ = slew_volume_(expected_). - void CheckSlewMUL(double start_vol, double end_vol) { - for (size_t ch = 0; ch < data_.size(); ++ch) { - // First value should have original scaling applied. - EXPECT_FLOAT_EQ(Expected(ch, 0) * start_vol, Data(ch, 0)) << ch; - for (int f = 1; f < slew_time_frames_; ++f) { - // Can't calculate gain if input is 0. - if (Expected(ch, f) == 0.0) - continue; - double actual_gain = Data(ch, f) / Expected(ch, f); - // Interpolate to get expected gain. - double frame_gain_change = (end_vol - start_vol) / (slew_time_frames_); - double expected_gain = frame_gain_change * f + start_vol; - EXPECT_LE(std::abs(actual_gain - expected_gain), - std::abs(frame_gain_change)) - << ch << " " << f; - } - // Steady state should have final scaling applied. - int f = max_frame_; - EXPECT_FLOAT_EQ(Expected(ch, f) * end_vol, Data(ch, f)) - << ch << " " << f - << " Actual gain = " << Data(ch, f) / Expected(ch, f); - } - } - - // Checks data_ = expected_ + slew_volume_(data_2_). - void CheckSlewMAC(double start_vol, double end_vol) { - for (int ch = 0; ch < channels_; ++ch) { - // First value should have original scaling applied. - EXPECT_FLOAT_EQ(Expected(ch, 0) + Data2(ch, 0) * start_vol, Data(ch, 0)) - << ch; - for (int f = 1; f < slew_time_frames_; ++f) { - // Can't calculate gain if input is 0. - if (Data2(ch, f) == 0.0) - continue; - double actual_gain = (Data(ch, f) - Expected(ch, f)) / Data2(ch, f); - // Interpolate to get expected gain. - double frame_gain_change = (end_vol - start_vol) / (slew_time_frames_); - double expected_gain = frame_gain_change * f + start_vol; - EXPECT_LE(std::abs(actual_gain - expected_gain), - std::abs(frame_gain_change)) - << f; - } - // Steady state should have final gain applied. - int f = max_frame_; - EXPECT_FLOAT_EQ(Expected(ch, f) + Data2(ch, f) * end_vol, Data(ch, f)) - << ch << " " << f << " Actual gain = " - << (Data(ch, f) - Expected(ch, f)) / Data2(ch, f); - } - } - - // Data accessors. Override to change access method of CheckSlewM[AC/UL]. - virtual float Data(int channel, int frame) { return data_[channel][frame]; } - - virtual float Data2(int channel, int frame) { - return data_2_[channel][frame]; - } - - virtual float Expected(int channel, int frame) { - return expected_[channel][frame]; - } - - int sample_rate_; - int slew_time_ms_; - int slew_time_frames_; - int channels_; - int max_frame_; -}; - -TEST_P(SlewVolumeDynamicTest, FMULRampUp) { - double start = 0.0; - double end = 1.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - slew_volume_->ProcessFMUL(false, data_[0], num_frames_, 1, data_[0]); - slew_volume_->ProcessFMUL(true, data_[1], num_frames_, 1, data_[1]); - CheckSlewMUL(start, end); -} - -TEST_P(SlewVolumeDynamicTest, FMULRampDown) { - double start = 1.0; - double end = 0.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - slew_volume_->ProcessFMUL(false, data_[0], num_frames_, 1, data_[0]); - slew_volume_->ProcessFMUL(true, data_[1], num_frames_, 1, data_[1]); - CheckSlewMUL(start, end); -} - -// Provide data as small buffers. -TEST_P(SlewVolumeDynamicTest, FMULRampDownByParts) { - double start = 1.0; - double end = 0.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - int frame_step = ::media::vector_math::kRequiredAlignment / kBytesPerSample; - int f; - for (f = 0; f < num_frames_; f += frame_step) { - // Process any remaining samples in the last step. - if (num_frames_ - f < frame_step * 2) { - frame_step = num_frames_ - f; - } - slew_volume_->ProcessFMUL(false, expected_[0] + f, frame_step, 1, - data_[0] + f); - slew_volume_->ProcessFMUL(true, expected_[1] + f, frame_step, 1, - data_[1] + f); - } - ASSERT_EQ(num_frames_, f); - CheckSlewMUL(start, end); -} - -TEST_P(SlewVolumeDynamicTest, FMACRampUp) { - double start = 0.0; - double end = 1.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - slew_volume_->ProcessFMAC(false, data_2_[0], num_frames_, 1, data_[0]); - slew_volume_->ProcessFMAC(true, data_2_[1], num_frames_, 1, data_[1]); - CheckSlewMAC(start, end); -} - -TEST_P(SlewVolumeDynamicTest, FMACRampDown) { - double start = 1.0; - double end = 0.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - slew_volume_->ProcessFMAC(false, data_2_[0], num_frames_, 1, data_[0]); - slew_volume_->ProcessFMAC(true, data_2_[1], num_frames_, 1, data_[1]); - CheckSlewMAC(start, end); -} - -// Provide data as small buffers. -TEST_P(SlewVolumeDynamicTest, FMACRampUpByParts) { - double start = 0.0; - double end = 1.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - int frame_step = ::media::vector_math::kRequiredAlignment / kBytesPerSample; - int f; - for (f = 0; f < num_frames_; f += frame_step) { - // Process any remaining samples in the last step. - if (num_frames_ - f < frame_step * 2) { - frame_step = num_frames_ - f; - } - slew_volume_->ProcessFMAC(false, data_2_[0] + f, frame_step, 1, - data_[0] + f); - slew_volume_->ProcessFMAC(true, data_2_[1] + f, frame_step, 1, - data_[1] + f); - } - ASSERT_EQ(num_frames_, f); - CheckSlewMAC(start, end); -} - -INSTANTIATE_TEST_SUITE_P(SingleBufferSlew, - SlewVolumeDynamicTest, - ::testing::Combine(::testing::Values(44100, 48000), - ::testing::Values(0, 15, 100))); - -class SlewVolumeInterleavedTest : public SlewVolumeDynamicTest { - public: - SlewVolumeInterleavedTest(const SlewVolumeInterleavedTest&) = delete; - SlewVolumeInterleavedTest& operator=(const SlewVolumeInterleavedTest&) = - delete; - - protected: - SlewVolumeInterleavedTest() = default; - ~SlewVolumeInterleavedTest() override = default; - - void SetUp() override { - slew_volume_ = std::make_unique(); - slew_volume_->Interrupted(); - - channels_ = std::get<0>(GetParam()); - sample_rate_ = 16000; - slew_time_ms_ = 20; - slew_time_frames_ = sample_rate_ * slew_time_ms_ / 1000; - slew_volume_->SetMaxSlewTimeMs(slew_time_ms_); - slew_volume_->SetSampleRate(sample_rate_); - num_frames_ = (2 + slew_time_frames_) * channels_; - max_frame_ = num_frames_ / channels_ - 1; - MakeData(num_frames_); - } - - float Data(int channel, int frame) override { - return data_[0][channels_ * frame + channel]; - } - - float Data2(int channel, int frame) override { - return data_2_[0][channels_ * frame + channel]; - } - - float Expected(int channel, int frame) override { - return expected_[0][channels_ * frame + channel]; - } -}; - -TEST_P(SlewVolumeInterleavedTest, FMACRampDown) { - double start = 1.0; - double end = 0.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - slew_volume_->ProcessFMAC(false, data_2_[0], num_frames_ / channels_, - channels_, data_[0]); - CheckSlewMAC(start, end); -} - -TEST_P(SlewVolumeInterleavedTest, FMACRampUp) { - double start = 0.0; - double end = 1.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - slew_volume_->ProcessFMAC(false, data_2_[0], num_frames_ / channels_, - channels_, data_[0]); - CheckSlewMAC(start, end); -} - -TEST_P(SlewVolumeInterleavedTest, FMULRampDown) { - double start = 1.0; - double end = 0.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - slew_volume_->ProcessFMUL(false, data_[0], num_frames_ / channels_, channels_, - data_[0]); - - CheckSlewMUL(start, end); -} - -TEST_P(SlewVolumeInterleavedTest, FMULRampUp) { - double start = 0.0; - double end = 1.0; - slew_volume_->SetVolume(start); - ClearInterrupted(); - - slew_volume_->SetVolume(end); - slew_volume_->ProcessFMUL(false, data_[0], num_frames_ / channels_, channels_, - data_[0]); - CheckSlewMUL(start, end); -} - -INSTANTIATE_TEST_SUITE_P(Interleaved, - SlewVolumeInterleavedTest, - ::testing::Combine(::testing::Values(2, 4), - ::testing::Values(0))); - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/supported_codec_profile_levels_memo.cc chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo.cc --- chromium-132.0.6834.110/chromecast/media/base/supported_codec_profile_levels_memo.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/supported_codec_profile_levels_memo.h" - -#include "base/logging.h" -#include "chromecast/public/media/decoder_config.h" - -namespace chromecast { -namespace media { - -SupportedCodecProfileLevelsMemo::SupportedCodecProfileLevelsMemo() {} - -SupportedCodecProfileLevelsMemo::~SupportedCodecProfileLevelsMemo() {} - -void SupportedCodecProfileLevelsMemo::AddSupportedCodecProfileLevel( - CodecProfileLevel codec_profile_level) { - DVLOG(2) << __func__ << "(" << codec_profile_level.codec << ", " - << codec_profile_level.profile << ", " << codec_profile_level.level - << ")"; - base::AutoLock lock(lock_); - codec_profile_levels_.push_back(codec_profile_level); -} - -bool SupportedCodecProfileLevelsMemo::IsSupportedVideoConfig( - VideoCodec codec, - VideoProfile profile, - int level) const { - DVLOG(1) << __func__ << "(" << codec << ", " << profile << ", " << level - << ")"; - base::AutoLock lock(lock_); - for (const auto& supported_profile_info : codec_profile_levels_) { - if (codec == supported_profile_info.codec && - profile == supported_profile_info.profile && - level <= supported_profile_info.level) { - return true; - } - } - return false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/supported_codec_profile_levels_memo.h chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo.h --- chromium-132.0.6834.110/chromecast/media/base/supported_codec_profile_levels_memo.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_SUPPORTED_CODEC_PROFILE_LEVELS_MEMO_H_ -#define CHROMECAST_MEDIA_BASE_SUPPORTED_CODEC_PROFILE_LEVELS_MEMO_H_ - -#include - -#include "base/synchronization/lock.h" -#include "chromecast/public/media/decoder_config.h" - -namespace chromecast { -namespace media { - -// Keeps a memo in the render process for a list of supported codecs and -// profiles obtained from the browser process. -// All calls should be made in the main renderer thread. -class SupportedCodecProfileLevelsMemo { - public: - SupportedCodecProfileLevelsMemo(); - - SupportedCodecProfileLevelsMemo(const SupportedCodecProfileLevelsMemo&) = - delete; - SupportedCodecProfileLevelsMemo& operator=( - const SupportedCodecProfileLevelsMemo&) = delete; - - ~SupportedCodecProfileLevelsMemo(); - void AddSupportedCodecProfileLevel(CodecProfileLevel codec_profile_level); - bool IsSupportedVideoConfig(VideoCodec codec, - VideoProfile profile, - int level) const; - - private: - mutable base::Lock lock_; - std::vector codec_profile_levels_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_SUPPORTED_CODEC_PROFILE_LEVELS_MEMO_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/supported_codec_profile_levels_memo_unittest.cc chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo_unittest.cc --- chromium-132.0.6834.110/chromecast/media/base/supported_codec_profile_levels_memo_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/supported_codec_profile_levels_memo_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/supported_codec_profile_levels_memo.h" - -#include "chromecast/public/media/decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -class SupportedCodecProfileLevelsMemoTest : public ::testing::Test { - protected: - SupportedCodecProfileLevelsMemo memo_; -}; - -TEST_F(SupportedCodecProfileLevelsMemoTest, - IsSupportedVideoConfig_NoProfilesAdded) { - EXPECT_FALSE(memo_.IsSupportedVideoConfig(kCodecH264, kH264Baseline, 10)); - EXPECT_FALSE(memo_.IsSupportedVideoConfig(kCodecHEVC, kHEVCMain, 30)); - EXPECT_FALSE(memo_.IsSupportedVideoConfig(kCodecVP8, kVP8ProfileAny, 0)); - EXPECT_FALSE(memo_.IsSupportedVideoConfig(kCodecVP9, kVP9Profile0, 10)); -} - -TEST_F(SupportedCodecProfileLevelsMemoTest, - IsSupportedVideoConfig_ProfileAdded) { - memo_.AddSupportedCodecProfileLevel({kCodecH264, kH264Baseline, 10}); - EXPECT_TRUE(memo_.IsSupportedVideoConfig(kCodecH264, kH264Baseline, 10)); - EXPECT_FALSE(memo_.IsSupportedVideoConfig(kCodecH264, kH264Main, 10)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/video_mode_switcher.cc chromium-132.0.6834.159/chromecast/media/base/video_mode_switcher.cc --- chromium-132.0.6834.110/chromecast/media/base/video_mode_switcher.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/video_mode_switcher.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/video_mode_switcher.h" - -namespace chromecast { -namespace media { - -VideoModeSwitcher::~VideoModeSwitcher() {} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/video_mode_switcher.h chromium-132.0.6834.159/chromecast/media/base/video_mode_switcher.h --- chromium-132.0.6834.110/chromecast/media/base/video_mode_switcher.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/video_mode_switcher.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_VIDEO_MODE_SWITCHER_H_ -#define CHROMECAST_MEDIA_BASE_VIDEO_MODE_SWITCHER_H_ - -#include - -#include "base/functional/callback_forward.h" - -namespace media { -class VideoDecoderConfig; -} // namespace media - -namespace chromecast { -namespace media { - -// Interface that implements video mode switching for CastRenderer. -class VideoModeSwitcher { - public: - virtual ~VideoModeSwitcher(); - - // Input parameter is true if mode switch succeeded (or wasn't needed) and - // playback should proceed. False indicates failed mode switch. - using CompletionCB = base::OnceCallback; - - // The |video_configs| describe input streams (potentially multiple streams in - // case of dual layer content). The |mode_switch_completion_cb| will be - // invoked to notify the caller about mode switch result. - virtual void SwitchMode( - const std::vector<::media::VideoDecoderConfig>& video_configs, - CompletionCB mode_switch_completion_cb) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_VIDEO_MODE_SWITCHER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/video_plane_controller.cc chromium-132.0.6834.159/chromecast/media/base/video_plane_controller.cc --- chromium-132.0.6834.110/chromecast/media/base/video_plane_controller.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/video_plane_controller.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,337 +0,0 @@ -// 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 "chromecast/media/base/video_plane_controller.h" - -#include -#include - -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/public/cast_media_shlib.h" -#include "media/base/video_transformation.h" -#include "ui/gfx/geometry/rect.h" - -namespace chromecast { -namespace media { - -namespace { - -bool RectFEqual(const RectF& r1, const RectF& r2) { - return r1.x == r2.x && r1.y == r2.y && r1.width == r2.width && - r1.height == r2.height; -} - -bool SizeEqual(const Size& s1, const Size& s2) { - return s1.width == s2.width && s1.height == s2.height; -} - -bool DisplayRectFValid(const RectF& r) { - return r.width >= 0 && r.height >= 0; -} - -bool ResolutionSizeValid(const Size& s) { - return s.width >= 0 && s.height >= 0; -} - -// Translates a gfx::OverlayTransform into a VideoPlane::Transform. -// Could be just a lookup table once we have unit tests for this code -// to ensure it stays in sync with OverlayTransform. -chromecast::media::VideoPlane::Transform ConvertTransform( - gfx::OverlayTransform transform) { - switch (transform) { - case gfx::OVERLAY_TRANSFORM_NONE: - return chromecast::media::VideoPlane::TRANSFORM_NONE; - case gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL: - return chromecast::media::VideoPlane::FLIP_HORIZONTAL; - case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL: - return chromecast::media::VideoPlane::FLIP_VERTICAL; - case gfx::OVERLAY_TRANSFORM_ROTATE_CLOCKWISE_90: - return chromecast::media::VideoPlane::ROTATE_90; - case gfx::OVERLAY_TRANSFORM_ROTATE_CLOCKWISE_180: - return chromecast::media::VideoPlane::ROTATE_180; - case gfx::OVERLAY_TRANSFORM_ROTATE_CLOCKWISE_270: - return chromecast::media::VideoPlane::ROTATE_270; - default: - NOTREACHED(); - } -} - -chromecast::media::VideoPlane::Transform ConvertTransform( - const ::media::VideoTransformation& transformation) { - if (!transformation.mirrored) { - switch (transformation.rotation) { - case ::media::VIDEO_ROTATION_0: - return chromecast::media::VideoPlane::TRANSFORM_NONE; - case ::media::VIDEO_ROTATION_90: - return chromecast::media::VideoPlane::ROTATE_90; - case ::media::VIDEO_ROTATION_180: - return chromecast::media::VideoPlane::ROTATE_180; - case ::media::VIDEO_ROTATION_270: - return chromecast::media::VideoPlane::ROTATE_270; - } - } else if (transformation.rotation == ::media::VIDEO_ROTATION_0) { - return chromecast::media::VideoPlane::FLIP_HORIZONTAL; - } - - NOTREACHED(); -} - -} // namespace - -// Helper class for calling VideoPlane::SetGeometry with rate-limiting. -// SetGeometry can take on the order of 100ms to run in some implementations -// and can be called on the order of 20x / second (as fast as graphics frames -// are produced). This creates an ever-growing backlog of tasks on the media -// thread. -// This class measures the time taken to run SetGeometry to determine a -// reasonable frequency at which to call it. Excess calls are coalesced -// to just set the most recent geometry. -class VideoPlaneController::RateLimitedSetVideoPlaneGeometry - : public base::RefCountedThreadSafe { - public: - RateLimitedSetVideoPlaneGeometry( - const scoped_refptr& task_runner) - : pending_display_rect_(0, 0, 0, 0), - pending_set_geometry_(false), - min_calling_interval_ms_(0), - sample_counter_(0), - task_runner_(task_runner) {} - - RateLimitedSetVideoPlaneGeometry(const RateLimitedSetVideoPlaneGeometry&) = - delete; - RateLimitedSetVideoPlaneGeometry& operator=( - const RateLimitedSetVideoPlaneGeometry&) = delete; - - void SetGeometry(const chromecast::RectF& display_rect, - VideoPlane::Transform transform) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(DisplayRectFValid(display_rect)); - - base::TimeTicks now = base::TimeTicks::Now(); - base::TimeDelta elapsed = now - last_set_geometry_time_; - - if (elapsed < base::Milliseconds(min_calling_interval_ms_)) { - if (!pending_set_geometry_) { - pending_set_geometry_ = true; - - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce( - &RateLimitedSetVideoPlaneGeometry::ApplyPendingSetGeometry, - this), - base::Milliseconds(2 * min_calling_interval_ms_)); - } - - pending_display_rect_ = display_rect; - pending_transform_ = transform; - return; - } - last_set_geometry_time_ = now; - - LOG(INFO) << __FUNCTION__ << " rect=" << display_rect.width << "x" - << display_rect.height << " @" << display_rect.x << "," - << display_rect.y << " transform " << transform; - - VideoPlane* video_plane = CastMediaShlib::GetVideoPlane(); - CHECK(video_plane); - base::TimeTicks start = base::TimeTicks::Now(); - video_plane->SetGeometry(display_rect, transform); - - base::TimeDelta set_geometry_time = base::TimeTicks::Now() - start; - UpdateAverageTime(set_geometry_time.InMilliseconds()); - } - - private: - friend class base::RefCountedThreadSafe; - ~RateLimitedSetVideoPlaneGeometry() {} - - void UpdateAverageTime(int64_t sample) { - const size_t kSampleCount = 5; - if (samples_.size() < kSampleCount) - samples_.push_back(sample); - else - samples_[sample_counter_++ % kSampleCount] = sample; - int64_t total = 0; - for (int64_t s : samples_) - total += s; - min_calling_interval_ms_ = 2 * total / samples_.size(); - } - - void ApplyPendingSetGeometry() { - if (pending_set_geometry_) { - pending_set_geometry_ = false; - SetGeometry(pending_display_rect_, pending_transform_); - } - } - - RectF pending_display_rect_; - VideoPlane::Transform pending_transform_; - bool pending_set_geometry_; - base::TimeTicks last_set_geometry_time_; - - // Don't call SetGeometry faster than this interval. - int64_t min_calling_interval_ms_; - - // Min calling interval is computed as double average of last few time samples - // (i.e. allow at least as much time between calls as the call itself takes). - std::vector samples_; - size_t sample_counter_; - - scoped_refptr task_runner_; -}; - -VideoPlaneController::VideoPlaneController( - const Size& graphics_resolution, - scoped_refptr media_task_runner) - : is_paused_(false), - have_screen_res_(false), - screen_res_(0, 0), - graphics_plane_res_(graphics_resolution), - coordinates_(VideoPlane::GetCoordinates ? VideoPlane::GetCoordinates() - : VideoPlane::kScreen), - have_video_plane_geometry_(false), - video_plane_display_rect_(0, 0), - video_plane_transform_(VideoPlane::TRANSFORM_NONE), - media_task_runner_(media_task_runner), - video_plane_wrapper_( - new RateLimitedSetVideoPlaneGeometry(media_task_runner_)) {} - -VideoPlaneController::~VideoPlaneController() {} - -void VideoPlaneController::SetGeometry(const gfx::RectF& gfx_display_rect, - gfx::OverlayTransform gfx_transform) { - SetGeometryInternal(gfx_display_rect, ConvertTransform(gfx_transform)); -} - -void VideoPlaneController::SetGeometryFromMediaType( - const gfx::Rect& gfx_display_rect, - const ::media::VideoTransformation& transform) { - SetGeometryInternal(gfx::RectF(gfx_display_rect), - ConvertTransform(transform)); -} - -void VideoPlaneController::SetGeometryInternal( - const gfx::RectF& gfx_display_rect, - VideoPlane::Transform transform) { - if (!thread_checker_.CalledOnValidThread()) { - media_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&VideoPlaneController::SetGeometryInternal, - weak_factory_.GetWeakPtr(), gfx_display_rect, - transform)); - return; - } - const RectF display_rect(gfx_display_rect.x(), gfx_display_rect.y(), - gfx_display_rect.width(), gfx_display_rect.height()); - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(DisplayRectFValid(display_rect)); - if (have_video_plane_geometry_ && - RectFEqual(display_rect, video_plane_display_rect_) && - transform == video_plane_transform_) { - DVLOG(2) << "No change found in geometry parameters."; - return; - } - - LOG(INFO) << "New geometry parameters " - << " rect=" << display_rect.width << "x" << display_rect.height - << " @" << display_rect.x << "," << display_rect.y << " transform " - << transform; - - have_video_plane_geometry_ = true; - video_plane_display_rect_ = display_rect; - video_plane_transform_ = transform; - - MaybeRunSetGeometry(); -} - -void VideoPlaneController::SetScreenResolution(const Size& resolution) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(ResolutionSizeValid(resolution)); - if (have_screen_res_ && SizeEqual(resolution, screen_res_)) { - DVLOG(2) << "No change found in screen resolution."; - return; - } - - LOG(INFO) << "New screen resolution " << resolution.width << "x" - << resolution.height; - - have_screen_res_ = true; - screen_res_ = resolution; - - MaybeRunSetGeometry(); -} - -void VideoPlaneController::Pause() { - DCHECK(thread_checker_.CalledOnValidThread()); - LOG(INFO) << "Pausing controller. No more VideoPlane SetGeometry calls."; - is_paused_ = true; -} - -void VideoPlaneController::Resume() { - DCHECK(thread_checker_.CalledOnValidThread()); - LOG(INFO) << "Resuming controller. VideoPlane SetGeometry calls are active."; - is_paused_ = false; - ClearVideoPlaneGeometry(); -} - -bool VideoPlaneController::is_paused() const { - DCHECK(thread_checker_.CalledOnValidThread()); - return is_paused_; -} - -void VideoPlaneController::MaybeRunSetGeometry() { - if (is_paused_) { - DVLOG(2) - << "All VideoPlane SetGeometry calls are paused. Ignoring request."; - return; - } - - if (!HaveDataForSetGeometry()) { - DVLOG(2) << "Don't have all VideoPlane SetGeometry data. Ignoring request."; - return; - } - - DCHECK(graphics_plane_res_.width != 0 && graphics_plane_res_.height != 0); - - RectF scaled_rect = video_plane_display_rect_; - // Note that graphics coordinates do not need to be scaled, since the received - // values are already in those coordinates. - if (coordinates_ != VideoPlane::Coordinates::kGraphics && - (graphics_plane_res_.width != screen_res_.width || - graphics_plane_res_.height != screen_res_.height)) { - float sx = - static_cast(screen_res_.width) / graphics_plane_res_.width; - float sy = - static_cast(screen_res_.height) / graphics_plane_res_.height; - scaled_rect.x *= sx; - scaled_rect.y *= sy; - scaled_rect.width *= sx; - scaled_rect.height *= sy; - } - - media_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&RateLimitedSetVideoPlaneGeometry::SetGeometry, - video_plane_wrapper_, scaled_rect, - video_plane_transform_)); -} - -bool VideoPlaneController::HaveDataForSetGeometry() const { - const bool screen_res_set_or_unnecessary = - have_screen_res_ || (coordinates_ == VideoPlane::Coordinates::kGraphics); - return screen_res_set_or_unnecessary && have_video_plane_geometry_; -} - -void VideoPlaneController::ClearVideoPlaneGeometry() { - have_video_plane_geometry_ = false; - video_plane_display_rect_ = RectF(0, 0); - video_plane_transform_ = VideoPlane::TRANSFORM_NONE; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/video_plane_controller.h chromium-132.0.6834.159/chromecast/media/base/video_plane_controller.h --- chromium-132.0.6834.110/chromecast/media/base/video_plane_controller.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/video_plane_controller.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,125 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_BASE_VIDEO_PLANE_CONTROLLER_H_ -#define CHROMECAST_MEDIA_BASE_VIDEO_PLANE_CONTROLLER_H_ - -#include "base/memory/ref_counted.h" -#include "base/memory/singleton.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/video_plane.h" -#include "ui/gfx/geometry/rect_f.h" -#include "ui/gfx/overlay_transform.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace gfx { -class Rect; -} // namespace gfx - -namespace media { -struct VideoTransformation; -} // namespace media - -namespace chromecast { -namespace media { - -// Provides main interface for setting video plane geometry. All callsites -// should use this over VideoPlane::SetGeometry. Reasons for this: -// * provides conversion between graphics plane coordinates and screen -// resolution coordinates -// * updates VideoPlane when screen resolution changes -// * handles threading correctly (posting SetGeometry to media thread). -// * coalesces multiple calls in short space of time to prevent flooding the -// media thread with SetGeometry calls (which are expensive on many -// platforms). -// All public methods should be called from the same thread that the class was -// constructed on. -class VideoPlaneController { - public: - VideoPlaneController( - const Size& graphics_resolution, - scoped_refptr media_task_runner); - - VideoPlaneController(const VideoPlaneController&) = delete; - VideoPlaneController& operator=(const VideoPlaneController&) = delete; - - ~VideoPlaneController(); - - // Sets the video plane geometry in *graphics plane coordinates*. If there is - // no change to video plane parameters from the last call to this method, it - // is a no-op. - void SetGeometry(const gfx::RectF& display_rect, - gfx::OverlayTransform transform); - void SetGeometryFromMediaType(const gfx::Rect& display_rect, - const ::media::VideoTransformation& transform); - - // Sets physical screen resolution. This must be called at least once when - // the final output resolution (HDMI signal or panel resolution) is known, - // then later when it changes. If there is no change to the screen resolution - // from the last call to this method, it is a no-op. - void SetScreenResolution(const Size& resolution); - - // After Pause is called, no further calls to VideoPlane::SetGeometry will be - // made except for any pending calls already scheduled on the media thread. - // The Set methods will however update cached parameters that will take - // effect once the class is resumed. Safe to call multiple times. - // TODO(esum): Handle the case where there are pending calls already on the - // media thread. When this returns, the caller needs to know that absolutely - // no more SetGeometry calls will be made. - void Pause(); - // Makes class active again, and clears any cached video plane geometry - // parameters. Safe to call multiple times. - void Resume(); - bool is_paused() const; - - private: - class RateLimitedSetVideoPlaneGeometry; - friend struct base::DefaultSingletonTraits; - - void SetGeometryInternal(const gfx::RectF& display_rect, - VideoPlane::Transform transform); - - // Check if HaveDataForSetGeometry. If not, this method is a no-op. Otherwise - // it scales the display rect from graphics to device resolution coordinates. - // Then posts task to media thread for VideoPlane::SetGeometry. - void MaybeRunSetGeometry(); - // Checks if all data has been collected to make calls to - // VideoPlane::SetGeometry. - bool HaveDataForSetGeometry() const; - // Clears any cached video plane geometry parameters. - void ClearVideoPlaneGeometry(); - - bool is_paused_; - - // Current resolutions - bool have_screen_res_; - Size screen_res_; - const Size graphics_plane_res_; - - // Which coordinates to use for transforms (e.g. graphics coordinates or - // screen coordinates). - const VideoPlane::Coordinates coordinates_; - - // Saved video plane parameters (in graphics plane coordinates) - // for use when screen resolution changes. - bool have_video_plane_geometry_; - RectF video_plane_display_rect_; - VideoPlane::Transform video_plane_transform_; - - scoped_refptr media_task_runner_; - scoped_refptr video_plane_wrapper_; - - base::ThreadChecker thread_checker_; - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_VIDEO_PLANE_CONTROLLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/base/video_plane_controller_test.cc chromium-132.0.6834.159/chromecast/media/base/video_plane_controller_test.cc --- chromium-132.0.6834.110/chromecast/media/base/video_plane_controller_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/video_plane_controller_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,166 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/video_plane_controller.h" - -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "chromecast/public/cast_media_shlib.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/geometry/rect_f.h" -#include "ui/gfx/overlay_transform.h" - -namespace chromecast { -namespace media { - -namespace { - -using ::testing::AllOf; -using ::testing::Field; -using ::testing::FloatEq; -using ::testing::Matcher; -using ::testing::NotNull; - -// Returns a matcher that matches a chromecast::RectF's x, y, width, and height -// values. -auto RectFEquals(float x, float y, float width, float height) { - return AllOf(Field(&chromecast::RectF::x, FloatEq(x)), - Field(&chromecast::RectF::y, FloatEq(y)), - Field(&chromecast::RectF::width, FloatEq(width)), - Field(&chromecast::RectF::height, FloatEq(height))); -} - -class MockVideoPlane : public VideoPlane { - public: - MockVideoPlane() : VideoPlane() {} - ~MockVideoPlane() override = default; - - MOCK_METHOD(void, SetGeometry, (const RectF&, Transform), (override)); -}; - -MockVideoPlane* g_video_plane = nullptr; - -VideoPlane::Coordinates g_video_plane_coordinates = - VideoPlane::Coordinates::kScreen; - -} // namespace - -// Static function definitions for CastMediaShlib and VideoPlane. - -void CastMediaShlib::Initialize(const std::vector& argv) { - CHECK(g_video_plane == nullptr); - g_video_plane = new MockVideoPlane; -} - -VideoPlane* CastMediaShlib::GetVideoPlane() { - return g_video_plane; -} - -void CastMediaShlib::Finalize() { - if (g_video_plane) { - delete g_video_plane; - g_video_plane = nullptr; - } -} - -// Tests can set g_video_plane_coordinates to influence how VideoPlaneController -// should report coordinates (screen resolution vs graphics resolution). -VideoPlane::Coordinates VideoPlane::GetCoordinates() { - return g_video_plane_coordinates; -} - -// End of static function definitions. - -namespace { - -const chromecast::Size kDefaultSize(1920, 1080); - -// A test fixture is used to ensure that CastMediaShlib is -// initialized/finalized, and to control the lifetime of the -// SingleThreadTaskEnvironment. -class VideoPlaneControllerTest : public ::testing::Test { - protected: - VideoPlaneControllerTest() { CastMediaShlib::Initialize({}); } - - ~VideoPlaneControllerTest() override { CastMediaShlib::Finalize(); } - - base::test::SingleThreadTaskEnvironment environment_; -}; - -TEST_F(VideoPlaneControllerTest, SetsGeometryOnVideoPlane) { - VideoPlaneController controller( - kDefaultSize, base::SingleThreadTaskRunner::GetCurrentDefault()); - controller.SetScreenResolution(kDefaultSize); - - const gfx::RectF video_geometry(1280, 720); - - ASSERT_THAT(g_video_plane, NotNull()); - EXPECT_CALL(*g_video_plane, - SetGeometry(RectFEquals(0, 0, 1280, 720), - VideoPlane::Transform::TRANSFORM_NONE)) - .Times(1); - - controller.SetGeometry(video_geometry, - gfx::OverlayTransform::OVERLAY_TRANSFORM_NONE); - - base::RunLoop().RunUntilIdle(); -} - -TEST_F(VideoPlaneControllerTest, - SetsGeometryOnVideoPlaneAndTranslatesToScreenCoordinates) { - g_video_plane_coordinates = VideoPlane::Coordinates::kScreen; - - const chromecast::Size kScreenResolution(3840, 2160); - const chromecast::Size kGraphicsResolution(1920, 1080); - - VideoPlaneController controller( - kGraphicsResolution, base::SingleThreadTaskRunner::GetCurrentDefault()); - controller.SetScreenResolution(kScreenResolution); - - const gfx::RectF video_geometry(960, 0, 960, 1080); - - ASSERT_THAT(g_video_plane, NotNull()); - // Note that the expected rect is scaled to the physical screen resolution. - EXPECT_CALL(*g_video_plane, - SetGeometry(RectFEquals(1920, 0, 1920, 2160), - VideoPlane::Transform::TRANSFORM_NONE)) - .Times(1); - - controller.SetGeometry(video_geometry, - gfx::OverlayTransform::OVERLAY_TRANSFORM_NONE); - - base::RunLoop().RunUntilIdle(); -} - -TEST_F(VideoPlaneControllerTest, - SetsGeometryOnVideoPlaneAndDoesNotScaleForGraphicsCoordinates) { - g_video_plane_coordinates = VideoPlane::Coordinates::kGraphics; - - const chromecast::Size kScreenResolution(3840, 2160); - const chromecast::Size kGraphicsResolution(1920, 1080); - - VideoPlaneController controller( - kGraphicsResolution, base::SingleThreadTaskRunner::GetCurrentDefault()); - controller.SetScreenResolution(kScreenResolution); - - const gfx::RectF video_geometry(960, 0, 960, 1080); - - ASSERT_THAT(g_video_plane, NotNull()); - // Note that the expected rect is NOT scaled to the physical screen - // resolution, due to the value of g_video_plane_coordinates. - EXPECT_CALL(*g_video_plane, - SetGeometry(RectFEquals(960, 0, 960, 1080), - VideoPlane::Transform::TRANSFORM_NONE)) - .Times(1); - - controller.SetGeometry(video_geometry, - gfx::OverlayTransform::OVERLAY_TRANSFORM_NONE); - - base::RunLoop().RunUntilIdle(); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/video_resolution_policy.cc chromium-132.0.6834.159/chromecast/media/base/video_resolution_policy.cc --- chromium-132.0.6834.110/chromecast/media/base/video_resolution_policy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/video_resolution_policy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/base/video_resolution_policy.h" - -namespace chromecast { -namespace media { - -VideoResolutionPolicy::~VideoResolutionPolicy() {} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/base/video_resolution_policy.h chromium-132.0.6834.159/chromecast/media/base/video_resolution_policy.h --- chromium-132.0.6834.110/chromecast/media/base/video_resolution_policy.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/base/video_resolution_policy.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_BASE_VIDEO_RESOLUTION_POLICY_H_ -#define CHROMECAST_MEDIA_BASE_VIDEO_RESOLUTION_POLICY_H_ - -namespace gfx { -class Size; -} // namespace gfx - -namespace chromecast { -namespace media { - -// Interface allowing renderer to check for whether certain video resolutions -// should have playback blocked. -// TODO(halliwell): remove this mechanism once we have PR3. -class VideoResolutionPolicy { - public: - // Observer allows policy subclass to notify renderer when some - // conditions have changed. Renderer should re-check current - // resolution. - class Observer { - public: - virtual void OnVideoResolutionPolicyChanged() = 0; - - protected: - virtual ~Observer() {} - }; - - virtual ~VideoResolutionPolicy(); - - virtual void AddObserver(Observer* observer) = 0; - virtual void RemoveObserver(Observer* observer) = 0; - - virtual bool ShouldBlock(const gfx::Size& size) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_BASE_VIDEO_RESOLUTION_POLICY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/DIR_METADATA chromium-132.0.6834.159/chromecast/media/cdm/DIR_METADATA --- chromium-132.0.6834.110/chromecast/media/cdm/DIR_METADATA 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/DIR_METADATA 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -monorail: { - component: "Internals>Media>Encrypted" -} -buganizer_public: { - component_id: 1456426 -} diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm.cc chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm.cc --- chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,202 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cdm/cast_cdm.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/base/decrypt_context_impl.h" -#include "chromecast/media/common/media_resource_tracker.h" -#include "media/base/cdm_key_information.h" -#include "media/base/cdm_promise.h" -#include "media/base/decryptor.h" -#include "url/gurl.h" - -namespace chromecast { -namespace media { -namespace { - -using KeyStatus = ::media::CdmKeyInformation::KeyStatus; - -constexpr size_t kKeyStatusCount = - static_cast(KeyStatus::KEY_STATUS_MAX) + 1; - -class CastCdmContextImpl : public CastCdmContext { - public: - explicit CastCdmContextImpl(CastCdm* cast_cdm) : cast_cdm_(cast_cdm) { - DCHECK(cast_cdm_); - } - - CastCdmContextImpl(const CastCdmContextImpl&) = delete; - CastCdmContextImpl& operator=(const CastCdmContextImpl&) = delete; - - ~CastCdmContextImpl() override = default; - - std::unique_ptr<::media::CallbackRegistration> RegisterEventCB( - EventCB event_cb) override { - return cast_cdm_->RegisterEventCB(std::move(event_cb)); - } - - std::unique_ptr GetDecryptContext( - const std::string& key_id, - EncryptionScheme encryption_scheme) override { - return cast_cdm_->GetDecryptContext(key_id, encryption_scheme); - } - - void SetKeyStatus(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override { - cast_cdm_->SetKeyStatus(key_id, key_status, system_code); - } - - void SetVideoResolution(int width, int height) override { - cast_cdm_->SetVideoResolution(width, height); - } - - private: - // The CastCdm object which owns |this|. - CastCdm* const cast_cdm_; -}; - -// Returns the HDCP version multiplied by ten. -int HdcpVersionX10(::media::HdcpVersion hdcp_version) { - switch (hdcp_version) { - case ::media::HdcpVersion::kHdcpVersionNone: - return 0; - case ::media::HdcpVersion::kHdcpVersion1_0: - return 10; - case ::media::HdcpVersion::kHdcpVersion1_1: - return 11; - case ::media::HdcpVersion::kHdcpVersion1_2: - return 12; - case ::media::HdcpVersion::kHdcpVersion1_3: - return 13; - case ::media::HdcpVersion::kHdcpVersion1_4: - return 14; - case ::media::HdcpVersion::kHdcpVersion2_0: - return 20; - case ::media::HdcpVersion::kHdcpVersion2_1: - return 21; - case ::media::HdcpVersion::kHdcpVersion2_2: - return 22; - case ::media::HdcpVersion::kHdcpVersion2_3: - return 23; - - default: - NOTREACHED(); - } -} - -} // namespace - -CastCdm::CastCdm(MediaResourceTracker* media_resource_tracker) - : media_resource_tracker_(media_resource_tracker), - cast_cdm_context_(new CastCdmContextImpl(this)) { - thread_checker_.DetachFromThread(); -} - -CastCdm::~CastCdm() { - DCHECK(thread_checker_.CalledOnValidThread()); -} - -void CastCdm::Initialize( - const ::media::SessionMessageCB& session_message_cb, - const ::media::SessionClosedCB& session_closed_cb, - const ::media::SessionKeysChangeCB& session_keys_change_cb, - const ::media::SessionExpirationUpdateCB& session_expiration_update_cb) { - DCHECK(thread_checker_.CalledOnValidThread()); - - if (media_resource_tracker_) { - media_resource_usage_ = std::make_unique( - media_resource_tracker_); - } - - session_message_cb_ = session_message_cb; - session_closed_cb_ = session_closed_cb; - session_keys_change_cb_ = session_keys_change_cb; - session_expiration_update_cb_ = session_expiration_update_cb; - - InitializeInternal(); -} - -std::unique_ptr<::media::CallbackRegistration> CastCdm::RegisterEventCB( - ::media::CdmContext::EventCB event_cb) { - return event_callbacks_.Register(std::move(event_cb)); -} - -::media::CdmContext* CastCdm::GetCdmContext() { - return cast_cdm_context_.get(); -} - -void CastCdm::GetStatusForPolicy( - ::media::HdcpVersion min_hdcp_version, - std::unique_ptr<::media::KeyStatusCdmPromise> promise) { - int min_hdcp_x10 = HdcpVersionX10(min_hdcp_version); - // TODO(sanfin): Implement a function to get the current HDCP version in the - // browser process. - int cur_hdcp_x10 = 0; - promise->resolve(cur_hdcp_x10 >= min_hdcp_x10 ? KeyStatus::USABLE - : KeyStatus::OUTPUT_RESTRICTED); -} - -void CastCdm::OnSessionMessage(const std::string& session_id, - const std::vector& message, - ::media::CdmMessageType message_type) { - session_message_cb_.Run(session_id, message_type, message); -} - -void CastCdm::OnSessionClosed(const std::string& session_id, - ::media::CdmSessionClosedReason reason) { - session_closed_cb_.Run(session_id, reason); -} - -void CastCdm::OnSessionKeysChange(const std::string& session_id, - bool newly_usable_keys, - ::media::CdmKeysInfo keys_info) { - logging::LogMessage log_message(__FILE__, __LINE__, logging::LOGGING_INFO); - log_message.stream() << "keystatuseschange "; - int status_count[kKeyStatusCount] = {0}; - for (const auto& key_info : keys_info) { - status_count[key_info->status]++; - } - for (int i = 0; i != ::media::CdmKeyInformation::KEY_STATUS_MAX; ++i) { - if (status_count[i] == 0) - continue; - log_message.stream() << status_count[i] << " " << static_cast(i) - << " "; - } - - session_keys_change_cb_.Run(session_id, newly_usable_keys, - std::move(keys_info)); - - if (newly_usable_keys) { - event_callbacks_.Notify( - ::media::CdmContext::Event::kHasAdditionalUsableKey); - } -} - -void CastCdm::OnSessionExpirationUpdate(const std::string& session_id, - base::Time new_expiry_time) { - session_expiration_update_cb_.Run(session_id, new_expiry_time); -} - -void CastCdm::KeyIdAndKeyPairsToInfo(const ::media::KeyIdAndKeyPairs& keys, - ::media::CdmKeysInfo* keys_info) { - DCHECK(keys_info); - for (const std::pair& key : keys) { - keys_info->push_back(std::make_unique<::media::CdmKeyInformation>( - key.first, ::media::CdmKeyInformation::USABLE, 0)); - } -} - -// A default empty implementation for subclasses that don't need to provide -// any key system specific initialization. -void CastCdm::InitializeInternal() {} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm.h chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm.h --- chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CDM_CAST_CDM_H_ -#define CHROMECAST_MEDIA_CDM_CAST_CDM_H_ - -#include - -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/task/sequenced_task_runner_helpers.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "chromecast/media/cdm/cast_cdm_context.h" -#include "chromecast/media/common/media_resource_tracker.h" -#include "chromecast/public/media/cast_key_status.h" -#include "media/base/callback_registry.h" -#include "media/base/content_decryption_module.h" -#include "media/cdm/json_web_key.h" - -namespace chromecast { -namespace media { -class DecryptContextImpl; - -// CastCdm is an extension of ContentDecryptionModule that provides common -// functionality across CDM implementations. -// All these additional functions are synchronous so: -// - either both the CDM and the media pipeline must be running on the same -// thread, -// - or CastCdm implementations must use some locks. -// -class CastCdm : public ::media::ContentDecryptionModule { - public: - explicit CastCdm(MediaResourceTracker* media_resource_tracker); - - CastCdm(const CastCdm&) = delete; - CastCdm& operator=(const CastCdm&) = delete; - - void Initialize( - const ::media::SessionMessageCB& session_message_cb, - const ::media::SessionClosedCB& session_closed_cb, - const ::media::SessionKeysChangeCB& session_keys_change_cb, - const ::media::SessionExpirationUpdateCB& session_expiration_update_cb); - - std::unique_ptr<::media::CallbackRegistration> RegisterEventCB( - ::media::CdmContext::EventCB event_cb); - - // Returns the decryption context needed to decrypt frames encrypted with - // |key_id|. Returns null if |key_id| is not available. - virtual std::unique_ptr GetDecryptContext( - const std::string& key_id, - EncryptionScheme encryption_scheme) const = 0; - - // Notifies that key status has changed (e.g. if expiry is detected by - // hardware decoder). - virtual void SetKeyStatus(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) = 0; - - // Notifies of current decoded video resolution. - virtual void SetVideoResolution(int width, int height) = 0; - - // ::media::ContentDecryptionModule implementation. - ::media::CdmContext* GetCdmContext() override; - - // Cast video products always provide HDCP or equivalent content protection. - void GetStatusForPolicy( - ::media::HdcpVersion min_hdcp_version, - std::unique_ptr<::media::KeyStatusCdmPromise> promise) final; - - protected: - ~CastCdm() override; - - void OnSessionMessage(const std::string& session_id, - const std::vector& message, - ::media::CdmMessageType message_type); - void OnSessionClosed(const std::string& session_id, - ::media::CdmSessionClosedReason reason); - void OnSessionKeysChange(const std::string& session_id, - bool newly_usable_keys, - ::media::CdmKeysInfo keys_info); - void OnSessionExpirationUpdate(const std::string& session_id, - base::Time new_expiry_time); - - void KeyIdAndKeyPairsToInfo(const ::media::KeyIdAndKeyPairs& keys, - ::media::CdmKeysInfo* key_info); - - private: - // Allow subclasses to override to provide key sysytem specific - // initialization. - virtual void InitializeInternal(); - - ::media::SessionMessageCB session_message_cb_; - ::media::SessionClosedCB session_closed_cb_; - ::media::SessionKeysChangeCB session_keys_change_cb_; - ::media::SessionExpirationUpdateCB session_expiration_update_cb_; - - // Track the usage for hardware resource. nullptr means the implementation - // doesn't need hardware resource. - MediaResourceTracker* const media_resource_tracker_; - std::unique_ptr media_resource_usage_; - - std::unique_ptr cast_cdm_context_; - - ::media::CallbackRegistry<::media::CdmContext::EventCB::RunType> - event_callbacks_; - - base::ThreadChecker thread_checker_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CDM_CAST_CDM_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_context.cc chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_context.cc --- chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_context.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_context.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cdm/cast_cdm_context.h" - -namespace chromecast { -namespace media { - -::media::Decryptor* CastCdmContext::GetDecryptor() { - // Subclasses providing CdmContext for a ClearKey CDM implementation must - // override this method to provide the Decryptor. Subclasses providing DRM - // implementations should return nullptr here. - return nullptr; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_context.h chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_context.h --- chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_context.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_context.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CDM_CAST_CDM_CONTEXT_H_ -#define CHROMECAST_MEDIA_CDM_CAST_CDM_CONTEXT_H_ - -#include -#include - -#include "chromecast/public/media/cast_decrypt_config.h" -#include "chromecast/public/media/cast_key_status.h" -#include "media/base/cdm_context.h" - -namespace chromecast { -namespace media { - -class DecryptContextImpl; - -// CdmContext implementation + some extra APIs needed by CastRenderer. -class CastCdmContext : public ::media::CdmContext { - public: - // ::media::CdmContext implementation. - ::media::Decryptor* GetDecryptor() override; - - // Returns the decryption context needed to decrypt frames encrypted with - // |key_id|. Returns null if |key_id| is not available. - virtual std::unique_ptr GetDecryptContext( - const std::string& key_id, - EncryptionScheme encryption_scheme) = 0; - - // Notifies that key status has changed (e.g. if expiry is detected by - // hardware decoder). - virtual void SetKeyStatus(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) = 0; - - // Notifies of current decoded video resolution (used for licence policy - // enforcement). - virtual void SetVideoResolution(int width, int height) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CDM_CAST_CDM_CONTEXT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_factory.cc chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_factory.cc --- chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cdm/cast_cdm_factory.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/media/cdm/cast_cdm.h" -#include "media/base/cdm_config.h" -#include "media/base/cdm_key_information.h" -#include "url/origin.h" - -namespace chromecast { -namespace media { - -CastCdmFactory::CastCdmFactory( - scoped_refptr task_runner, - const url::Origin& cdm_origin, - MediaResourceTracker* media_resource_tracker) - : media_resource_tracker_(media_resource_tracker), - task_runner_(task_runner), - cdm_origin_(cdm_origin) { - DCHECK(media_resource_tracker_); - DCHECK(task_runner_); -} - -CastCdmFactory::~CastCdmFactory() {} - -void CastCdmFactory::Create( - const ::media::CdmConfig& cdm_config, - const ::media::SessionMessageCB& session_message_cb, - const ::media::SessionClosedCB& session_closed_cb, - const ::media::SessionKeysChangeCB& session_keys_change_cb, - const ::media::SessionExpirationUpdateCB& session_expiration_update_cb, - ::media::CdmCreatedCB cdm_created_cb) { - // Bound |cdm_created_cb| so we always fire it asynchronously. - ::media::CdmCreatedCB bound_cdm_created_cb = - base::BindPostTaskToCurrentDefault(std::move(cdm_created_cb)); - - CastKeySystem cast_key_system(GetKeySystemByName(cdm_config.key_system)); - - DCHECK((cast_key_system == chromecast::media::KEY_SYSTEM_PLAYREADY) || - (cast_key_system == chromecast::media::KEY_SYSTEM_WIDEVINE)); - - scoped_refptr cast_cdm = - CreatePlatformBrowserCdm(cast_key_system, cdm_origin_, cdm_config); - - if (!cast_cdm) { - LOG(INFO) << "No matching key system found: " << cast_key_system; - std::move(bound_cdm_created_cb) - .Run(nullptr, ::media::CreateCdmStatus::kUnsupportedKeySystem); - return; - } - - const int packed_cdm_config = (cdm_config.allow_distinctive_identifier << 2) | - (cdm_config.allow_persistent_state << 1) | - cdm_config.use_hw_secure_codecs; - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEventWithValue( - "Cast.Platform.CreateCdm." + cdm_config.key_system, packed_cdm_config); - - task_runner_->PostTask( - FROM_HERE, - base::BindOnce( - &CastCdm::Initialize, base::Unretained(cast_cdm.get()), - base::BindPostTaskToCurrentDefault(session_message_cb), - base::BindPostTaskToCurrentDefault(session_closed_cb), - base::BindPostTaskToCurrentDefault(session_keys_change_cb), - base::BindPostTaskToCurrentDefault(session_expiration_update_cb))); - std::move(bound_cdm_created_cb) - .Run(cast_cdm, ::media::CreateCdmStatus::kSuccess); -} - -scoped_refptr CastCdmFactory::CreatePlatformBrowserCdm( - const CastKeySystem& cast_key_system, - const url::Origin& cdm_origin, - const ::media::CdmConfig& cdm_config) { - return nullptr; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_factory.h chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_factory.h --- chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CDM_CAST_CDM_FACTORY_H_ -#define CHROMECAST_MEDIA_CDM_CAST_CDM_FACTORY_H_ - -#include "chromecast/media/base/key_systems_common.h" -#include "chromecast/media/common/media_resource_tracker.h" -#include "media/base/cdm_factory.h" -#include "url/origin.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace media { -struct CdmConfig; -} // namespace media - -namespace chromecast { -namespace media { - -class CastCdm; - -class CastCdmFactory : public ::media::CdmFactory { - public: - // CDM factory will use |task_runner| to initialize the CDM. - CastCdmFactory(scoped_refptr task_runner, - const url::Origin& cdm_origin, - MediaResourceTracker* media_resource_tracker); - - CastCdmFactory(const CastCdmFactory&) = delete; - CastCdmFactory& operator=(const CastCdmFactory&) = delete; - - ~CastCdmFactory() override; - - // ::media::CdmFactory implementation: - void Create( - const ::media::CdmConfig& cdm_config, - const ::media::SessionMessageCB& session_message_cb, - const ::media::SessionClosedCB& session_closed_cb, - const ::media::SessionKeysChangeCB& session_keys_change_cb, - const ::media::SessionExpirationUpdateCB& session_expiration_update_cb, - ::media::CdmCreatedCB cdm_created_cb) override; - - // Provides a platform-specific BrowserCdm instance. - virtual scoped_refptr CreatePlatformBrowserCdm( - const CastKeySystem& cast_key_system, - const url::Origin& cdm_origin, - const ::media::CdmConfig& cdm_config); - - protected: - MediaResourceTracker* media_resource_tracker_; - - private: - scoped_refptr task_runner_; - const url::Origin cdm_origin_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CDM_CAST_CDM_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_origin_provider.cc chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_origin_provider.cc --- chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_origin_provider.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_origin_provider.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// 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 "chromecast/media/cdm/cast_cdm_origin_provider.h" - -#include "media/mojo/mojom/frame_interface_factory.mojom.h" -#include "mojo/public/cpp/bindings/sync_call_restrictions.h" - -namespace chromecast { - -// static -bool CastCdmOriginProvider::GetCdmOrigin( - ::media::mojom::FrameInterfaceFactory* interfaces, - url::Origin* cdm_origin) { - mojo::SyncCallRestrictions::ScopedAllowSyncCall allow_sync_call; - return interfaces->GetCdmOrigin(cdm_origin); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_origin_provider.h chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_origin_provider.h --- chromium-132.0.6834.110/chromecast/media/cdm/cast_cdm_origin_provider.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/cast_cdm_origin_provider.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CDM_CAST_CDM_ORIGIN_PROVIDER_H_ -#define CHROMECAST_MEDIA_CDM_CAST_CDM_ORIGIN_PROVIDER_H_ - -namespace media { -namespace mojom { -class FrameInterfaceFactory; -} // namespace mojom -} // namespace media - -namespace url { -class Origin; -} // namespace url - -namespace chromecast { - -class CastCdmOriginProvider { - public: - // Util function to call sync mojo API to get cdm origin. - // TODO(159346933) Remove once the origin isolation logic is moved outside of - // media service. - static bool GetCdmOrigin(::media::mojom::FrameInterfaceFactory* interfaces, - url::Origin* cdm_origin); -}; - -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CDM_CAST_CDM_ORIGIN_PROVIDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/chromecast_init_data.cc chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data.cc --- chromium-132.0.6834.110/chromecast/media/cdm/chromecast_init_data.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ -// 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 "chromecast/media/cdm/chromecast_init_data.h" - -#include "base/check.h" -#include "media/base/bit_reader.h" -#include "media/cdm/cenc_utils.h" - -namespace chromecast { -namespace media { - -#define RCHECK(x) \ - do { \ - if (!(x)) \ - return false; \ - } while (0) - -namespace { - -const uint8_t kChromecastPlayreadyUuid[] = { - 0x2b, 0xf8, 0x66, 0x80, 0xc6, 0xe5, 0x4e, 0x24, - 0xbe, 0x23, 0x0f, 0x81, 0x5a, 0x60, 0x6e, 0xb2}; - -} // namespace - -ChromecastInitData::ChromecastInitData() { -} - -ChromecastInitData::~ChromecastInitData() { -} - -bool FindChromecastInitData(const std::vector& init_data, - InitDataMessageType type, - ChromecastInitData* chromecast_init_data_out) { - // Chromecast initData assumes a CENC data format and searches for PSSH boxes - // with SystemID |kChromecastPlayreadyUuid|. The PSSH box content is as - // follows: - // * |type| (2 bytes, InitDataMessageType) - // * |data| (all remaining bytes) - // Data may or may not be present and is specific to the given |type|. - - std::vector pssh_data; - if (!::media::GetPsshData( - init_data, std::vector(kChromecastPlayreadyUuid, - kChromecastPlayreadyUuid + - sizeof(kChromecastPlayreadyUuid)), - &pssh_data)) { - return false; - } - - ::media::BitReader reader(pssh_data.data(), pssh_data.size()); - - uint16_t msg_type; - RCHECK(reader.ReadBits(2 * 8, &msg_type)); - RCHECK(msg_type < static_cast(InitDataMessageType::END)); - RCHECK(msg_type == static_cast(type)); - - chromecast_init_data_out->type = static_cast(msg_type); - chromecast_init_data_out->data.assign( - pssh_data.begin() + reader.bits_read() / 8, pssh_data.end()); - return true; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/chromecast_init_data.h chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data.h --- chromium-132.0.6834.110/chromecast/media/cdm/chromecast_init_data.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CDM_CHROMECAST_INIT_DATA_H_ -#define CHROMECAST_MEDIA_CDM_CHROMECAST_INIT_DATA_H_ - -#include - -#include - -namespace chromecast { -namespace media { - -enum class InitDataMessageType { - UNKNOWN = 0x0, - CUSTOM_DATA = 0x1, - ENABLE_SECURE_STOP = 0x2, - END -}; - -// Structured data for EME initialization as parsed from an initData blob. -struct ChromecastInitData { - ChromecastInitData(); - ~ChromecastInitData(); - - InitDataMessageType type; - std::vector data; -}; - -// Searches for a ChromecastInitData blob inside a CENC |init_data| message of -// type |type|. If such a blob is found, returns true and fills -// |chromecast_init_data_out|. If not found, returns false. -bool FindChromecastInitData(const std::vector& init_data, - InitDataMessageType type, - ChromecastInitData* chromecast_init_data_out); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CDM_CHROMECAST_INIT_DATA_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cdm/chromecast_init_data_unittest.cc chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cdm/chromecast_init_data_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cdm/chromecast_init_data_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,101 +0,0 @@ -// 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 "chromecast/media/cdm/chromecast_init_data.h" - -#include - -#include - -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -TEST(ChromecastInitDataTest, TestPsshCustomData) { - const uint8_t kInitDataBlob[] = { - 0x00, 0x00, 0x00, 0x32, // length - 0x70, 0x73, 0x73, 0x68, // 'pssh' - 0x00, 0x00, 0x00, 0x00, // version / flags - 0x2B, 0xF8, 0x66, 0x80, 0xC6, 0xE5, 0x4E, 0x24, 0xBE, - 0x23, 0x0F, 0x81, 0x5A, 0x60, 0x6E, 0xB2, // UUID - 0x00, 0x00, 0x00, 0x12, // data size - 0x00, 0x01, // message type (CUSTOM_DATA) - 0x54, 0x65, 0x73, 0x74, 0x20, 0x63, 0x75, 0x73, 0x74, - 0x6F, 0x6D, 0x20, 0x64, 0x61, 0x74, 0x61 // 'Test custom data' - }; - - ChromecastInitData init_data; - EXPECT_TRUE(FindChromecastInitData( - std::vector(kInitDataBlob, - kInitDataBlob + sizeof(kInitDataBlob)), - InitDataMessageType::CUSTOM_DATA, &init_data)); - - EXPECT_EQ(InitDataMessageType::CUSTOM_DATA, init_data.type); - EXPECT_EQ(16u, init_data.data.size()); - EXPECT_EQ("Test custom data", - std::string(init_data.data.begin(), init_data.data.end())); -} - -TEST(ChromecastInitDataTest, TestPsshCustomData_NoSize) { - const uint8_t kInitDataBlob[] = { - 0x00, 0x00, 0x00, 0x2E, // length - 0x70, 0x73, 0x73, 0x68, // 'pssh' - 0x00, 0x00, 0x00, 0x00, // version / flags - 0x2B, 0xF8, 0x66, 0x80, 0xC6, 0xE5, 0x4E, 0x24, 0xBE, - 0x23, 0x0F, 0x81, 0x5A, 0x60, 0x6E, 0xB2, // UUID - // [missing size should be present here]. - 0x00, 0x01, // message type (CUSTOM_DATA) - 0x54, 0x65, 0x73, 0x74, 0x20, 0x63, 0x75, 0x73, 0x74, - 0x6F, 0x6D, 0x20, 0x64, 0x61, 0x74, 0x61 // 'Test custom data' - }; - - ChromecastInitData init_data; - EXPECT_FALSE(FindChromecastInitData( - std::vector(kInitDataBlob, - kInitDataBlob + sizeof(kInitDataBlob)), - InitDataMessageType::CUSTOM_DATA, &init_data)); -} - -TEST(ChromecastInitDataTest, TestPsshSecureStop) { - const uint8_t kInitDataBlob[] = { - 0x00, 0x00, 0x00, 0x22, // length - 0x70, 0x73, 0x73, 0x68, // 'pssh' - 0x00, 0x00, 0x00, 0x00, // version / flags - 0x2B, 0xF8, 0x66, 0x80, 0xC6, 0xE5, 0x4E, 0x24, - 0xBE, 0x23, 0x0F, 0x81, 0x5A, 0x60, 0x6E, 0xB2, // UUID - 0x00, 0x00, 0x00, 0x02, // data size - 0x00, 0x02, // message type (ENABLE_SECURE_STOP) - }; - - ChromecastInitData init_data; - EXPECT_TRUE(FindChromecastInitData( - std::vector(kInitDataBlob, - kInitDataBlob + sizeof(kInitDataBlob)), - InitDataMessageType::ENABLE_SECURE_STOP, &init_data)); - - EXPECT_EQ(InitDataMessageType::ENABLE_SECURE_STOP, init_data.type); - EXPECT_EQ(0u, init_data.data.size()); -} - -TEST(ChromecastInitDataTest, TestPsshSecureStop_NoSize) { - const uint8_t kInitDataBlob[] = { - 0x00, 0x00, 0x00, 0x1E, // length - 0x70, 0x73, 0x73, 0x68, // 'pssh' - 0x00, 0x00, 0x00, 0x00, // version / flags - 0x2B, 0xF8, 0x66, 0x80, 0xC6, 0xE5, 0x4E, 0x24, - 0xBE, 0x23, 0x0F, 0x81, 0x5A, 0x60, 0x6E, 0xB2, // UUID - // [missing size should be present here]. - 0x00, 0x02, // message type (ENABLE_SECURE_STOP) - }; - - ChromecastInitData init_data; - EXPECT_FALSE(FindChromecastInitData( - std::vector(kInitDataBlob, - kInitDataBlob + sizeof(kInitDataBlob)), - InitDataMessageType::ENABLE_SECURE_STOP, &init_data)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/DEPS chromium-132.0.6834.159/chromecast/media/cma/DEPS --- chromium-132.0.6834.110/chromecast/media/cma/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+third_party/grpc", - "+third_party/cast_core/public/src", -] diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/DEPS chromium-132.0.6834.159/chromecast/media/cma/backend/DEPS --- chromium-132.0.6834.110/chromecast/media/cma/backend/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+chromecast/net", - "+media/filters", -] diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_fsm.dot chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_fsm.dot --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_fsm.dot 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_fsm.dot 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -digraph { -// This specifies a diagram using the DOT language. It can be interactively -// viewed with xdot or can generate an image using -// `dot -Tpng alsa_fsm.dot > alsa_fsm.png` - -// This was build out of the state transition information from -// linux/sound/core/pcm_native.c and linux/sound/core/pcm_lib.c. Since it is -// intended to help with writing software which uses ALSA's PCM interface, it -// includes every possible transition, even if they are unlikely, rather than -// trying to model a more typical software path. - -// snd_pcm_hw_free is called as a result of snd_pcm_close -// snd_pcm_hwsync is called before querying any hardware state such as in -// snd_pcm_avail. - -// From the perspective of the state machine, snd_pcm_capture_rewind and -// snd_pcm_playback rewind are the same function so they are not -// distinguished in this diagram. This also holds for the forward -// functions. - -// For all states the a SND_PCM_STATE_ prefix has been omitted to clarify -// the state machine. - -// For all transitions the snd_pcm_ prefix has been omitted to clarify -// the state machine. - -rankdir=BT; - -// Bulk processing -ANY [label = "any state"]; -ANY -> SUSPENDED [label = suspend]; -SUSPENDED -> ANY [label = resume]; - -// snd_pcm_dev_disconnect is the only kernel-only ALSA function included in -// this diagram because it is the only way to transition into the -// SNDRV_PCM_STATE_DISCONNECTED state and that state should be accounted for -// when designing code which directly interacts with ALSA and might use USB -// audio devices which may be disconnected in use. -ANY -> DISCONNECTED [label = dev_disconnect]; -ANY -> ANY [label = "info/hw_refine/unlink/sync_ptr/tstamp"]; - -NOT_OPEN [label = "any state but OPEN"] -NOT_OPEN -> NOT_OPEN [label = "sw_params/channel_info/link"]; - -// State-specific transitions. -unitialized [label="", shape=none]; -unitialized -> OPEN [label = open]; - -OPEN -> OPEN [label = hw_params]; -OPEN -> SETUP [label = hw_params]; - -SETUP -> OPEN [label = hw_free]; -SETUP -> SETUP [label = "hw_params/drain/drop"]; -SETUP -> PREPARED [label = prepare]; - -PREPARED -> OPEN [label = "hw_free/reset"]; -PREPARED -> SETUP [label = "hw_params/drop"]; -PREPARED -> PREPARED [label = "prepare/rewind/forward/hwsync/delay"]; -PREPARED -> RUNNING [label = "start/writei"]; -PREPARED -> DRAINING [label = drain]; - -RUNNING -> OPEN [label = reset]; -RUNNING -> SETUP [label = "drain/drop"]; -RUNNING -> RUNNING [label = "rewind/forward/hwsync/delay/writei"]; -RUNNING -> XRUN [label = "xrun/hwsync/writei"]; -RUNNING -> DRAINING [label = drain]; -RUNNING -> PAUSED [label = pause]; - -// snd_pcm_xrun is called if an xrun is detected by -// snd_pcm_hw_avail_update. It puts the kernel-based ALSA code into the -// SNDRV_PCM_STATE_XRUN state. -XRUN -> SETUP[label = "drain/drop"]; -XRUN -> PREPARED [label = prepare]; -XRUN -> XRUN [label = xrun]; - -DRAINING -> SETUP [label = "sw_params/status/drain/drop/delay"]; -DRAINING -> PREPARED [label = prepare]; -DRAINING -> DRAINING [label = "drain/rewind/forward"]; - -PAUSED -> OPEN [label = reset]; -PAUSED -> SETUP [label = "drain/drop"]; -PAUSED -> PREPARED [label = prepare]; -PAUSED -> RUNNING [label = pause]; -PAUSED -> DRAINING [label = drain]; -PAUSED -> PAUSED [label = "forward/writei"]; - -SUSPENDED -> OPEN [label = reset]; -SUSPENDED -> PREPARED [label = prepare]; -SUSPENDED -> SUSPENDED [label = "hwsync/delay"]; - -} diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_volume_control.cc chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_volume_control.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,394 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/alsa/alsa_volume_control.h" - -#include -#include - -#include "base/check.h" -#include "base/command_line.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/strings/string_split.h" -#include "base/task/current_thread.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/media/cma/backend/alsa/scoped_alsa_mixer.h" -#include "media/base/media_switches.h" - -#define ALSA_ASSERT(func, ...) \ - do { \ - int err = alsa_->func(__VA_ARGS__); \ - LOG_ASSERT(err >= 0) << #func " error: " << alsa_->StrError(err); \ - } while (0) - -namespace chromecast { -namespace media { - -namespace { - -const char kAlsaDefaultDeviceName[] = "default"; -const char kAlsaDefaultVolumeElementName[] = "Master"; -const char kAlsaMuteMixerElementName[] = "Mute"; - -constexpr base::TimeDelta kPowerSaveCheckTime = base::Minutes(5); - -} // namespace - -// static -std::string AlsaVolumeControl::GetVolumeElementName() { - std::string mixer_element_name = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kAlsaVolumeElementName); - if (mixer_element_name.empty()) { - mixer_element_name = kAlsaDefaultVolumeElementName; - } - return mixer_element_name; -} - -// static -std::string AlsaVolumeControl::GetVolumeDeviceName() { - auto* command_line = base::CommandLine::ForCurrentProcess(); - std::string mixer_device_name = - command_line->GetSwitchValueASCII(switches::kAlsaVolumeDeviceName); - if (!mixer_device_name.empty()) { - return mixer_device_name; - } - - // If the output device was overridden, then the mixer should default to - // that device. - mixer_device_name = - command_line->GetSwitchValueASCII(switches::kAlsaOutputDevice); - if (!mixer_device_name.empty()) { - return mixer_device_name; - } - return kAlsaDefaultDeviceName; -} - -// Mixers that are implemented with ALSA's softvol plugin don't have mute -// switches available. This function allows ALSA-based AvSettings to fall back -// on another mixer which solely implements mute for the system. -// static -std::string AlsaVolumeControl::GetMuteElementName( - ::media::AlsaWrapper* alsa, - const std::string& mixer_device_name, - const std::string& mixer_element_name, - const std::string& mute_device_name) { - DCHECK(alsa); - std::string mute_element_name = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kAlsaMuteElementName); - if (!mute_element_name.empty()) { - return mute_element_name; - } - - ScopedAlsaMixer mixer(alsa, mixer_device_name, mixer_element_name); - if (!mixer.element) { - LOG(WARNING) << "The default ALSA mixer element does not exist."; - return mixer_element_name; - } - if (alsa->MixerSelemHasPlaybackSwitch(mixer.element)) { - return mixer_element_name; - } - - ScopedAlsaMixer mute(alsa, mute_device_name, kAlsaMuteMixerElementName); - if (!mute.element) { - LOG(WARNING) << "The default ALSA mixer does not have a playback switch " - "and a fallback mute element was not found, " - "mute will not work."; - return mixer_element_name; - } - if (alsa->MixerSelemHasPlaybackSwitch(mute.element)) { - return kAlsaMuteMixerElementName; - } - - LOG(WARNING) << "The default ALSA mixer does not have a playback switch " - "and the fallback mute element does not have a playback " - "switch, mute will not work."; - return mixer_element_name; -} - -// static -std::string AlsaVolumeControl::GetMuteDeviceName() { - std::string mute_device_name = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kAlsaMuteDeviceName); - if (!mute_device_name.empty()) { - return mute_device_name; - } - - // If the mute mixer device was not specified directly, use the same device as - // the volume mixer. - return GetVolumeDeviceName(); -} - -// static -std::vector AlsaVolumeControl::GetAmpElementNames() { - std::vector mixer_element_names = base::SplitString( - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kAlsaAmpElementName), - ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - - return mixer_element_names; -} - -// static -std::string AlsaVolumeControl::GetAmpDeviceName() { - auto* command_line = base::CommandLine::ForCurrentProcess(); - std::string mixer_device_name = - command_line->GetSwitchValueASCII(switches::kAlsaAmpDeviceName); - if (!mixer_device_name.empty()) { - return mixer_device_name; - } - - // If the amp mixer device was not specified directly, use the same device as - // the volume mixer. - return GetVolumeDeviceName(); -} - -AlsaVolumeControl::AlsaVolumeControl(Delegate* delegate, - std::unique_ptr<::media::AlsaWrapper> alsa) - : delegate_(delegate), - alsa_(std::move(alsa)), - volume_mixer_device_name_(GetVolumeDeviceName()), - volume_mixer_element_name_(GetVolumeElementName()), - mute_mixer_device_name_(GetMuteDeviceName()), - mute_mixer_element_name_(GetMuteElementName(alsa_.get(), - volume_mixer_device_name_, - volume_mixer_element_name_, - mute_mixer_device_name_)), - amp_mixer_device_name_(GetAmpDeviceName()), - amp_mixer_element_names_(GetAmpElementNames()), - volume_range_min_(0), - volume_range_max_(0), - mute_mixer_ptr_(nullptr) { - DCHECK(delegate_); - LOG(INFO) << "Volume device = " << volume_mixer_device_name_ - << ", element = " << volume_mixer_element_name_; - LOG(INFO) << "Mute device = " << mute_mixer_device_name_ - << ", element = " << mute_mixer_element_name_; - - std::string amp_element_name_list = "["; - for (const auto& amp_mixer_element_name : amp_mixer_element_names_) { - amp_element_name_list += amp_mixer_element_name; - amp_element_name_list += ","; - } - if (!amp_mixer_element_names_.empty()) { - amp_element_name_list.pop_back(); - } - amp_element_name_list += "]"; - - LOG(INFO) << "Idle device = " << amp_mixer_device_name_ - << ", elements = " << amp_element_name_list; - - volume_mixer_ = std::make_unique( - alsa_.get(), volume_mixer_device_name_, volume_mixer_element_name_); - if (volume_mixer_->element) { - ALSA_ASSERT(MixerSelemGetPlaybackVolumeRange, volume_mixer_->element, - &volume_range_min_, &volume_range_max_); - volume_mixer_->WatchForEvents( - &AlsaVolumeControl::VolumeOrMuteChangeCallback, - reinterpret_cast(this)); - } - - if (mute_mixer_element_name_ != volume_mixer_element_name_) { - mute_mixer_ = std::make_unique( - alsa_.get(), mute_mixer_device_name_, mute_mixer_element_name_); - if (mute_mixer_->element) { - mute_mixer_ptr_ = mute_mixer_.get(); - mute_mixer_->WatchForEvents( - &AlsaVolumeControl::VolumeOrMuteChangeCallback, - reinterpret_cast(this)); - } - } else { - mute_mixer_ptr_ = volume_mixer_.get(); - } - - for (const auto& amp_mixer_element_name : amp_mixer_element_names_) { - amp_mixers_.emplace_back(std::make_unique( - alsa_.get(), amp_mixer_device_name_, amp_mixer_element_name)); - if (amp_mixers_.back()->element) { - amp_mixers_.back()->WatchForEvents(nullptr, nullptr); - } - } -} - -AlsaVolumeControl::~AlsaVolumeControl() = default; - -float AlsaVolumeControl::GetRoundtripVolume(float volume) { - if (volume_range_max_ == volume_range_min_) { - return 0.0f; - } - - long level = 0; // NOLINT(runtime/int) - level = std::round((std::clamp(volume, 0.0f, 1.0f) * - (volume_range_max_ - volume_range_min_)) + - volume_range_min_); - return static_cast(level - volume_range_min_) / - static_cast(volume_range_max_ - volume_range_min_); -} - -float AlsaVolumeControl::VolumeLevelToDb(float volume) { - long level = 0; // NOLINT(runtime/int) - if (volume_range_max_ == volume_range_min_) { - level = volume_range_max_; - } else { - level = std::round((volume * (volume_range_max_ - volume_range_min_)) + - volume_range_min_); - } - long volume_db = 0; // NOLINT(runtime/int) - ALSA_ASSERT(MixerSelemAskPlaybackVolDb, volume_mixer_->element, level, - &volume_db); - return static_cast(volume_db * 0.01f); -} - -float AlsaVolumeControl::DbToVolumeLevel(float volume_db) { - if (volume_range_max_ == volume_range_min_) { - return 0.0f; - } - long level = 0.0f; // NOLINT(runtime/int) - ALSA_ASSERT(MixerSelemAskPlaybackDbVol, volume_mixer_->element, - std::round(volume_db * 100.0f), &level); - return static_cast(level - volume_range_min_) / - static_cast(volume_range_max_ - volume_range_min_); -} - -float AlsaVolumeControl::GetVolume() { - if (!volume_mixer_->element) { - return 0.0f; - } - long level = 0; // NOLINT(runtime/int) - ALSA_ASSERT(MixerSelemGetPlaybackVolume, volume_mixer_->element, - SND_MIXER_SCHN_MONO, &level); - return static_cast(level - volume_range_min_) / - static_cast(volume_range_max_ - volume_range_min_); -} - -void AlsaVolumeControl::SetVolume(float level) { - if (!volume_mixer_->element) { - return; - } - float volume = std::round((level * (volume_range_max_ - volume_range_min_)) + - volume_range_min_); - ALSA_ASSERT(MixerSelemSetPlaybackVolumeAll, volume_mixer_->element, volume); -} - -bool AlsaVolumeControl::IsMuted() { - return IsElementAllMuted(mute_mixer_ptr_).value_or(false); -} - -void AlsaVolumeControl::SetMuted(bool muted) { - if (!SetElementMuted(mute_mixer_ptr_, muted)) { - LOG(ERROR) << "Mute failed: no mute switch on mixer element."; - } -} - -void AlsaVolumeControl::SetPowerSave(bool power_save_on) { - for (const auto& amp_mixer : amp_mixers_) { - amp_mixer->RefreshElement(); - if (IsElementAllMuted(amp_mixer.get()).value_or(false) == power_save_on) { - LOG(INFO) << "Power Save already set to: " << power_save_on; - continue; - } - if (last_power_save_on_ == power_save_on) { - LOG(WARNING) << "Power Save was set to: " << !last_power_save_on_ - << " by others"; - metrics::CastMetricsHelper::GetInstance()->RecordSimpleAction( - (last_power_save_on_ - ? "Cast.Platform.VolumeControl.PowerSaveDisturbedOff" - : "Cast.Platform.VolumeControl.PowerSaveDisturbedOn")); - } - if (!SetElementMuted(amp_mixer.get(), power_save_on)) { - LOG(ERROR) << "Failed to set Power Save to " << power_save_on - << ": no amp switch on mixer element."; - metrics::CastMetricsHelper::GetInstance()->RecordSimpleAction( - (power_save_on ? "Cast.Platform.VolumeControl.PowerSaveFailedOn" - : "Cast.Platform.VolumeControl.PowerSaveFailedOff")); - } else { - LOG(INFO) << "Set Power Save to: " << power_save_on; - } - } - last_power_save_on_ = power_save_on; - if (last_power_save_on_) { - // Schedule a checker so underruns will not wake up the amplifier - // for a long time. - power_save_timer_.Start(FROM_HERE, kPowerSaveCheckTime, this, - &AlsaVolumeControl::CheckPowerSave); - } else { - power_save_timer_.Stop(); - } -} - -void AlsaVolumeControl::SetLimit(float limit) {} - -bool AlsaVolumeControl::SetElementMuted(ScopedAlsaMixer* mixer, bool muted) { - if (!mixer || !mixer->element || - !alsa_->MixerSelemHasPlaybackSwitch(mixer->element)) { - return false; - } - bool success = true; - for (int32_t channel = 0; channel <= SND_MIXER_SCHN_LAST; ++channel) { - int err = alsa_->MixerSelemSetPlaybackSwitch( - mixer->element, static_cast(channel), - !muted); - if (err != 0) { - success = false; - LOG(ERROR) << "MixerSelemSetPlaybackSwitch: " << alsa_->StrError(err); - } - } - return success; -} - -std::optional AlsaVolumeControl::IsElementAllMuted( - ScopedAlsaMixer* mixer) { - if (!mixer || !mixer->element || - !alsa_->MixerSelemHasPlaybackSwitch(mixer->element)) { - return std::nullopt; - } - for (int32_t channel = 0; channel <= SND_MIXER_SCHN_LAST; ++channel) { - int channel_unmuted; - int err = alsa_->MixerSelemGetPlaybackSwitch( - mixer->element, static_cast(channel), - &channel_unmuted); - if (err != 0) { - LOG(ERROR) << "MixerSelemGetPlaybackSwitch: " << alsa_->StrError(err); - return std::nullopt; - } - if (channel_unmuted) { - return false; - } - } - return true; -} - -void AlsaVolumeControl::OnVolumeOrMuteChanged() { - delegate_->OnSystemVolumeOrMuteChange(GetVolume(), IsMuted()); -} - -void AlsaVolumeControl::CheckPowerSave() { - SetPowerSave(last_power_save_on_); -} - -// static -int AlsaVolumeControl::VolumeOrMuteChangeCallback(snd_mixer_elem_t* elem, - unsigned int mask) { - if (!(mask & SND_CTL_EVENT_MASK_VALUE)) - return 0; - - AlsaVolumeControl* instance = static_cast( - snd_mixer_elem_get_callback_private(elem)); - instance->OnVolumeOrMuteChanged(); - return 0; -} - -// static -std::unique_ptr SystemVolumeControl::Create( - Delegate* delegate) { - return std::make_unique( - delegate, std::make_unique<::media::AlsaWrapper>()); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_volume_control.h chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_volume_control.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ALSA_ALSA_VOLUME_CONTROL_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ALSA_ALSA_VOLUME_CONTROL_H_ - -#include -#include -#include -#include - -#include "base/timer/timer.h" -#include "chromecast/media/cma/backend/system_volume_control.h" -#include "media/audio/alsa/alsa_wrapper.h" - -namespace chromecast { -namespace media { -class ScopedAlsaMixer; - -// SystemVolumeControl implementation for ALSA. -class AlsaVolumeControl : public SystemVolumeControl { - public: - AlsaVolumeControl(Delegate* delegate, - std::unique_ptr<::media::AlsaWrapper> alsa); - - AlsaVolumeControl(const AlsaVolumeControl&) = delete; - AlsaVolumeControl& operator=(const AlsaVolumeControl&) = delete; - - ~AlsaVolumeControl() override; - - // SystemVolumeControl interface. - float GetRoundtripVolume(float volume) override; - float DbToVolumeLevel(float db_volume) override; - float VolumeLevelToDb(float level) override; - float GetVolume() override; - void SetVolume(float level) override; - bool IsMuted() override; - void SetMuted(bool muted) override; - void SetPowerSave(bool power_save_on) override; - void SetLimit(float limit) override; - - private: - static std::string GetVolumeElementName(); - static std::string GetVolumeDeviceName(); - static std::string GetMuteElementName(::media::AlsaWrapper* alsa, - const std::string& mixer_card_name, - const std::string& mixer_element_name, - const std::string& mute_card_name); - static std::string GetMuteDeviceName(); - static std::vector GetAmpElementNames(); - static std::string GetAmpDeviceName(); - - static int VolumeOrMuteChangeCallback(snd_mixer_elem_t* elem, - unsigned int mask); - - bool SetElementMuted(ScopedAlsaMixer* mixer, bool muted); - // Returns true if all channels are muted, returns std::nullopt if element - // state is not accessible. - std::optional IsElementAllMuted(ScopedAlsaMixer* mixer); - - void OnVolumeOrMuteChanged(); - - void CheckPowerSave(); - - Delegate* const delegate_; - - const std::unique_ptr<::media::AlsaWrapper> alsa_; - const std::string volume_mixer_device_name_; - const std::string volume_mixer_element_name_; - const std::string mute_mixer_device_name_; - const std::string mute_mixer_element_name_; - const std::string amp_mixer_device_name_; - const std::vector amp_mixer_element_names_; - - long volume_range_min_; // NOLINT(runtime/int) - long volume_range_max_; // NOLINT(runtime/int) - - std::unique_ptr volume_mixer_; - std::unique_ptr mute_mixer_; - ScopedAlsaMixer* mute_mixer_ptr_; - std::vector> amp_mixers_; - - bool last_power_save_on_ = false; - base::OneShotTimer power_save_timer_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ALSA_ALSA_VOLUME_CONTROL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_volume_control_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_volume_control_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_volume_control_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#include "chromecast/media/cma/backend/alsa/alsa_volume_control.h" - -#include - -#include "base/test/task_environment.h" -#include "chromecast/media/cma/backend/system_volume_control.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { - -class MockDelegate : public SystemVolumeControl::Delegate { - public: - MockDelegate() = default; - ~MockDelegate() override = default; - - MOCK_METHOD(void, - OnSystemVolumeOrMuteChange, - (float new_volume, bool new_mute), - (override)); -}; - -TEST(AlsaVolumeControlTest, Construct) { - base::test::TaskEnvironment task_environment( - base::test::TaskEnvironment::MainThreadType::IO); - MockDelegate delegate; - AlsaVolumeControl alsa_volume_control( - &delegate, std::make_unique<::media::AlsaWrapper>()); -} - -} // namespace - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_wrapper.cc chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_wrapper.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -// 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 "chromecast/media/cma/backend/alsa/alsa_wrapper.h" - -#include "chromecast/media/cma/backend/audio_buildflags.h" - -namespace chromecast { -namespace media { - -#if BUILDFLAG(MEDIA_CLOCK_MONOTONIC_RAW) -const int kAlsaTstampTypeMonotonicRaw = - static_cast(SND_PCM_TSTAMP_TYPE_MONOTONIC_RAW); -#else -const int kAlsaTstampTypeMonotonicRaw = 0; -#endif // BUILDFLAG(MEDIA_CLOCK_MONOTONIC_RAW) - -AlsaWrapper::AlsaWrapper() { -} - -AlsaWrapper::~AlsaWrapper() { -} - -int AlsaWrapper::PcmPause(snd_pcm_t* handle, int enable) { - return snd_pcm_pause(handle, enable); -} - -int AlsaWrapper::PcmStatusMalloc(snd_pcm_status_t** ptr) { - return snd_pcm_status_malloc(ptr); -} - -void AlsaWrapper::PcmStatusFree(snd_pcm_status_t* obj) { - snd_pcm_status_free(obj); -} - -int AlsaWrapper::PcmStatus(snd_pcm_t* handle, snd_pcm_status_t* status) { - return snd_pcm_status(handle, status); -} - -snd_pcm_sframes_t AlsaWrapper::PcmStatusGetDelay(const snd_pcm_status_t* obj) { - return snd_pcm_status_get_delay(obj); -} - -snd_pcm_uframes_t AlsaWrapper::PcmStatusGetAvail(const snd_pcm_status_t* obj) { - return snd_pcm_status_get_avail(obj); -} - -void AlsaWrapper::PcmStatusGetHtstamp(const snd_pcm_status_t* obj, - snd_htimestamp_t* ptr) { - snd_pcm_status_get_htstamp(obj, ptr); -} - -snd_pcm_state_t AlsaWrapper::PcmStatusGetState(const snd_pcm_status_t* obj) { - return snd_pcm_status_get_state(obj); -} - -int AlsaWrapper::PcmHwParamsCurrent(snd_pcm_t* handle, - snd_pcm_hw_params_t* params) { - return snd_pcm_hw_params_current(handle, params); -} - -int AlsaWrapper::PcmHwParamsCanPause(const snd_pcm_hw_params_t* params) { - return snd_pcm_hw_params_can_pause(params); -} - -int AlsaWrapper::PcmHwParamsTestRate(snd_pcm_t* handle, - snd_pcm_hw_params_t* params, - unsigned int rate, - int dir) { - return snd_pcm_hw_params_test_rate(handle, params, rate, dir); -} - -int AlsaWrapper::PcmSwParamsSetTstampMode(snd_pcm_t* handle, - snd_pcm_sw_params_t* obj, - snd_pcm_tstamp_t val) { - return snd_pcm_sw_params_set_tstamp_mode(handle, obj, val); -} - -int AlsaWrapper::PcmSwParamsSetTstampType(snd_pcm_t* handle, - snd_pcm_sw_params_t* obj, - int val) { -#if BUILDFLAG(MEDIA_CLOCK_MONOTONIC_RAW) - return snd_pcm_sw_params_set_tstamp_type( - handle, obj, static_cast(val)); -#else - return 0; -#endif // BUILDFLAG(MEDIA_CLOCK_MONOTONIC_RAW) -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_wrapper.h chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_wrapper.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/alsa_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/alsa_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ALSA_ALSA_WRAPPER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ALSA_ALSA_WRAPPER_H_ - -#include "media/audio/alsa/alsa_wrapper.h" - -namespace chromecast { -namespace media { - -extern const int kAlsaTstampTypeMonotonicRaw; - -// Extends the Chromium AlsaWrapper, adding additional functions that we use. -class AlsaWrapper : public ::media::AlsaWrapper { - public: - AlsaWrapper(); - - AlsaWrapper(const AlsaWrapper&) = delete; - AlsaWrapper& operator=(const AlsaWrapper&) = delete; - - ~AlsaWrapper() override; - - virtual int PcmPause(snd_pcm_t* handle, int enable); - - virtual int PcmStatusMalloc(snd_pcm_status_t** ptr); - virtual void PcmStatusFree(snd_pcm_status_t* obj); - virtual int PcmStatus(snd_pcm_t* handle, snd_pcm_status_t* status); - virtual snd_pcm_sframes_t PcmStatusGetDelay(const snd_pcm_status_t* obj); - virtual snd_pcm_uframes_t PcmStatusGetAvail(const snd_pcm_status_t* obj); - virtual void PcmStatusGetHtstamp(const snd_pcm_status_t* obj, - snd_htimestamp_t* ptr); - virtual snd_pcm_state_t PcmStatusGetState(const snd_pcm_status_t* obj); - virtual int PcmHwParamsCurrent(snd_pcm_t* handle, - snd_pcm_hw_params_t* params); - virtual int PcmHwParamsCanPause(const snd_pcm_hw_params_t* params); - virtual int PcmHwParamsTestRate(snd_pcm_t* handle, - snd_pcm_hw_params_t* params, - unsigned int rate, - int dir); - - virtual int PcmSwParamsSetTstampMode(snd_pcm_t* handle, - snd_pcm_sw_params_t* obj, - snd_pcm_tstamp_t val); - virtual int PcmSwParamsSetTstampType(snd_pcm_t* handle, - snd_pcm_sw_params_t* obj, - int val); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ALSA_ALSA_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/cast_media_shlib.cc chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/cast_media_shlib.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/cast_media_shlib.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/cast_media_shlib.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,165 +0,0 @@ -// 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 - -#include "base/command_line.h" -#include "base/logging.h" -#include "chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/video_plane.h" -#include "media/base/media.h" -#include "media/base/media_switches.h" - -#define RETURN_ON_ALSA_ERROR(snd_func, ...) \ - do { \ - int err = snd_func(__VA_ARGS__); \ - if (err < 0) { \ - LOG(ERROR) << #snd_func " error: " << snd_strerror(err); \ - return; \ - } \ - } while (0) - -namespace chromecast { -namespace media { -namespace { - -const char kDefaultPcmDevice[] = "hw:0"; -const int kSoundControlBlockingMode = 0; -const char kRateOffsetInterfaceName[] = "PCM Playback Rate Offset"; - -// 1 MHz reference allows easy translation between frequency and PPM. -const double kOneMhzReference = 1e6; -const double kMaxAdjustmentHz = 500; -const double kGranularityHz = 1.0; - -class DefaultVideoPlane : public VideoPlane { - public: - ~DefaultVideoPlane() override {} - - void SetGeometry(const RectF& display_rect, Transform transform) override {} -}; - -snd_hctl_t* g_hardware_controls = nullptr; -snd_ctl_elem_id_t* g_rate_offset_id = nullptr; -snd_ctl_elem_value_t* g_rate_offset_ppm = nullptr; -snd_hctl_elem_t* g_rate_offset_element = nullptr; - -void InitializeAlsaControls() { - RETURN_ON_ALSA_ERROR(snd_ctl_elem_id_malloc, &g_rate_offset_id); - RETURN_ON_ALSA_ERROR(snd_ctl_elem_value_malloc, &g_rate_offset_ppm); - - std::string alsa_device_name = kDefaultPcmDevice; - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kAlsaOutputDevice)) { - alsa_device_name = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kAlsaOutputDevice); - } - RETURN_ON_ALSA_ERROR(snd_hctl_open, &g_hardware_controls, - alsa_device_name.c_str(), kSoundControlBlockingMode); - RETURN_ON_ALSA_ERROR(snd_hctl_load, g_hardware_controls); - snd_ctl_elem_id_set_interface(g_rate_offset_id, SND_CTL_ELEM_IFACE_PCM); - snd_ctl_elem_id_set_name(g_rate_offset_id, kRateOffsetInterfaceName); - g_rate_offset_element = - snd_hctl_find_elem(g_hardware_controls, g_rate_offset_id); - if (g_rate_offset_element) { - snd_ctl_elem_value_set_id(g_rate_offset_ppm, g_rate_offset_id); - } else { - LOG(ERROR) << "snd_hctl_find_elem failed to find the rate offset element."; - } -} - -DefaultVideoPlane* g_video_plane = nullptr; - -} // namespace - -void CastMediaShlib::Initialize(const std::vector& argv) { - InitializeAlsaControls(); - ::media::InitializeMediaLibrary(); -} - -void CastMediaShlib::Finalize() { - if (g_hardware_controls) - snd_hctl_close(g_hardware_controls); - snd_ctl_elem_value_free(g_rate_offset_ppm); - snd_ctl_elem_id_free(g_rate_offset_id); - - g_hardware_controls = nullptr; - g_rate_offset_id = nullptr; - g_rate_offset_ppm = nullptr; - g_rate_offset_element = nullptr; - - delete g_video_plane; - g_video_plane = nullptr; -} - -VideoPlane* CastMediaShlib::GetVideoPlane() { - if (!g_video_plane) { - g_video_plane = new DefaultVideoPlane(); - } - return g_video_plane; -} - -MediaPipelineBackend* CastMediaShlib::CreateMediaPipelineBackend( - const MediaPipelineDeviceParams& params) { - return new MediaPipelineBackendForMixer(params); -} - -double CastMediaShlib::GetMediaClockRate() { - int ppm = 0; - if (!g_rate_offset_element) { - LOG(INFO) << "g_rate_offset_element is null, ALSA rate offset control will " - "not be possible."; - return kOneMhzReference; - } - snd_ctl_elem_value_t* rate_offset_ppm; - snd_ctl_elem_value_alloca(&rate_offset_ppm); - int err = snd_hctl_elem_read(g_rate_offset_element, rate_offset_ppm); - if (err < 0) { - LOG(ERROR) << "snd_htcl_elem_read error: " << snd_strerror(err); - return kOneMhzReference; - } - ppm = snd_ctl_elem_value_get_integer(rate_offset_ppm, 0); - return kOneMhzReference + ppm; -} - -double CastMediaShlib::MediaClockRatePrecision() { - return kGranularityHz; -} - -void CastMediaShlib::MediaClockRateRange(double* minimum_rate, - double* maximum_rate) { - DCHECK(minimum_rate); - DCHECK(maximum_rate); - - *minimum_rate = kOneMhzReference - kMaxAdjustmentHz; - *maximum_rate = kOneMhzReference + kMaxAdjustmentHz; -} - -bool CastMediaShlib::SetMediaClockRate(double new_rate) { - int new_ppm = new_rate - kOneMhzReference; - if (!g_rate_offset_element) { - LOG(INFO) << "g_rate_offset_element is null, ALSA rate offset control will " - "not be possible."; - return false; - } - snd_ctl_elem_value_t* rate_offset_ppm; - snd_ctl_elem_value_alloca(&rate_offset_ppm); - snd_ctl_elem_value_set_integer(rate_offset_ppm, 0, new_ppm); - int err = snd_hctl_elem_write(g_rate_offset_element, rate_offset_ppm); - if (err < 0) { - LOG(ERROR) << "snd_htcl_elem_write error: " << snd_strerror(err); - return false; - } - return true; -} - -bool CastMediaShlib::SupportsMediaClockRateChange() { - return g_rate_offset_element != nullptr; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,550 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h" - -#include -#include -#include - -#include "base/command_line.h" -#include "base/logging.h" -#include "base/notreached.h" -#include "base/threading/platform_thread.h" -#include "base/time/time.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/media/cma/backend/alsa/alsa_wrapper.h" -#include "media/base/audio_sample_types.h" -#include "media/base/media_switches.h" - -#define RETURN_FALSE_ON_ERROR(snd_func, ...) \ - do { \ - int a_err = alsa_->snd_func(__VA_ARGS__); \ - if (a_err < 0) { \ - LOG(ERROR) << #snd_func " error: " << alsa_->StrError(a_err); \ - return false; \ - } \ - } while (0) - -#define RETURN_ERROR_CODE(snd_func, ...) \ - do { \ - int a_err = alsa_->snd_func(__VA_ARGS__); \ - if (a_err < 0) { \ - LOG(ERROR) << #snd_func " error: " << alsa_->StrError(a_err); \ - return a_err; \ - } \ - } while (0) - -#define CHECK_PCM_INITIALIZED() \ - if (!pcm_ || !pcm_hw_params_) { \ - LOG(WARNING) << __FUNCTION__ << "() called after failed initialization"; \ - return false; \ - } - -namespace chromecast { -namespace media { - -namespace { - -template -void ToFixedPoint(const float* input, - int frames, - typename TargetSampleTypeTraits::ValueType* dest_buffer) { - for (int f = 0; f < frames; ++f) { - dest_buffer[f] = TargetSampleTypeTraits::FromFloat(input[f]); - } -} - -void ToFixedPoint(const float* input, - int frames, - int bytes_per_sample, - uint8_t* dest_buffer) { - switch (bytes_per_sample) { - case 1: - ToFixedPoint<::media::UnsignedInt8SampleTypeTraits>( - input, frames, reinterpret_cast(dest_buffer)); - break; - case 2: - ToFixedPoint<::media::SignedInt16SampleTypeTraits>( - input, frames, reinterpret_cast(dest_buffer)); - break; - case 4: - ToFixedPoint<::media::SignedInt32SampleTypeTraits>( - input, frames, reinterpret_cast(dest_buffer)); - break; - default: - NOTREACHED() << "Unsupported bytes per sample encountered: " - << bytes_per_sample; - } -} - -constexpr int64_t kNoTimestamp = std::numeric_limits::min(); - -constexpr char kOutputDeviceDefaultName[] = "default"; - -constexpr bool kPcmRecoverIsSilent = false; -constexpr int kDefaultOutputBufferSizeFrames = 1024; - -// A list of supported sample rates. -// TODO(jyw): move this up into chromecast/public for 1) documentation and -// 2) to help when implementing IsSampleRateSupported() -// clang-format off -constexpr int kSupportedSampleRates[] = - { 8000, 11025, 12000, - 16000, 22050, 24000, - 32000, 44100, 48000, - 64000, 88200, 96000}; -// clang-format on - -// Arbitrary sample rate in Hz to mix all audio to when a new primary input has -// a sample rate that is not directly supported, and a better fallback sample -// rate cannot be determined. 48000 is the highest supported non-hi-res sample -// rate. 96000 is the highest supported hi-res sample rate. -constexpr unsigned int kFallbackSampleRate = 48000; -constexpr unsigned int kFallbackSampleRateHiRes = 96000; - -// The snd_pcm_(hw|sw)_params_set_*_near families of functions will report what -// direction they adjusted the requested parameter in, but since we read the -// output param and then log the information, this module doesn't need to get -// the direction explicitly. -constexpr int* kAlsaDirDontCare = nullptr; - -// The snd_pcm_resume function can return EAGAIN error code, so call should be -// retried. Below constants define retries params. -constexpr int kRestoreAfterSuspensionAttempts = 10; -constexpr base::TimeDelta kRestoreAfterSuspensionAttemptDelay = - base::Milliseconds(20); - -// These sample formats will be tried in order. 32 bit samples is ideal, but -// some devices do not support 32 bit samples. -constexpr snd_pcm_format_t kPreferredSampleFormats[] = { - SND_PCM_FORMAT_FLOAT, SND_PCM_FORMAT_S32, SND_PCM_FORMAT_S16}; - -int64_t TimespecToMicroseconds(struct timespec time) { - return static_cast(time.tv_sec) * - base::Time::kMicrosecondsPerSecond + - time.tv_nsec / 1000; -} - -} // namespace - -// static -std::unique_ptr MixerOutputStream::Create() { - return std::make_unique(); -} - -MixerOutputStreamAlsa::MixerOutputStreamAlsa() { - DefineAlsaParameters(); -} - -MixerOutputStreamAlsa::~MixerOutputStreamAlsa() { - Stop(); -} - -void MixerOutputStreamAlsa::SetAlsaWrapperForTest( - std::unique_ptr alsa) { - DCHECK(!alsa_); - alsa_ = std::move(alsa); -} - -bool MixerOutputStreamAlsa::Start(int sample_rate, int channels) { - if (!alsa_) { - alsa_ = std::make_unique(); - } - - num_output_channels_ = channels; - - // Open PCM devices when Start() is called for the first time. - if (!pcm_) { - std::string device_name = kOutputDeviceDefaultName; - if (base::CommandLine::InitializedForCurrentProcess() && - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kAlsaOutputDevice)) { - device_name = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kAlsaOutputDevice); - } - - RETURN_FALSE_ON_ERROR(PcmOpen, &pcm_, device_name.c_str(), - SND_PCM_STREAM_PLAYBACK, 0); - LOG(INFO) << "snd_pcm_open: handle=" << pcm_; - } - - // Some OEM-developed Cast for Audio devices don't accurately report their - // support for different output formats, so this tries 32-bit output and then - // 16-bit output if that fails. - // - // TODO(cleichner): Replace this with more specific device introspection. - // b/24747205 - int err = SetAlsaPlaybackParams(sample_rate); - if (err < 0) { - LOG(ERROR) << "Error setting ALSA playback parameters: " - << alsa_->StrError(err); - return false; - } - - RETURN_FALSE_ON_ERROR(PcmPrepare, pcm_); - RETURN_FALSE_ON_ERROR(PcmStatusMalloc, &pcm_status_); - - rendering_delay_.timestamp_microseconds = kNoTimestamp; - rendering_delay_.delay_microseconds = 0; - first_write_ = true; - - return true; -} - -int MixerOutputStreamAlsa::GetNumChannels() { - return num_output_channels_; -} - -int MixerOutputStreamAlsa::GetSampleRate() { - return sample_rate_; -} - -MediaPipelineBackend::AudioDecoder::RenderingDelay -MixerOutputStreamAlsa::GetRenderingDelay() { - return rendering_delay_; -} - -int MixerOutputStreamAlsa::OptimalWriteFramesCount() { - CHECK_PCM_INITIALIZED(); - return alsa_period_size_; -} - -bool MixerOutputStreamAlsa::Write(const float* data, - int data_size, - bool* out_playback_interrupted) { - CHECK_PCM_INITIALIZED(); - *out_playback_interrupted = false; - int frames = data_size / num_output_channels_; - ssize_t bytes_per_sample = alsa_->PcmFormatSize(pcm_format_, 1); - const uint8_t* output_data; - if (pcm_format_ == SND_PCM_FORMAT_FLOAT) { - output_data = reinterpret_cast(data); - } else { - // Resize interleaved if necessary. - size_t output_data_size = data_size * bytes_per_sample; - if (output_buffer_.size() < output_data_size) { - output_buffer_.resize(output_data_size); - } - ToFixedPoint(data, data_size, bytes_per_sample, output_buffer_.data()); - output_data = output_buffer_.data(); - } - - // If the PCM has been drained it will be in SND_PCM_STATE_SETUP and need - // to be prepared in order for playback to work. - if (alsa_->PcmState(pcm_) == SND_PCM_STATE_SETUP) { - RETURN_FALSE_ON_ERROR(PcmPrepare, pcm_); - } - - int frames_left = frames; - while (frames_left) { - int frames_or_error; - while ((frames_or_error = - alsa_->PcmWritei(pcm_, output_data, frames_left)) < 0) { - if (!first_write_) { - *out_playback_interrupted = true; - } - if (frames_or_error == -EBADFD && - MaybeRecoverDeviceFromSuspendedState()) { - // Write data again, if recovered. - continue; - } - RETURN_FALSE_ON_ERROR(PcmRecover, pcm_, frames_or_error, - kPcmRecoverIsSilent); - } - frames_left -= frames_or_error; - DCHECK_GE(frames_left, 0); - output_data += frames_or_error * num_output_channels_ * bytes_per_sample; - } - first_write_ = false; - UpdateRenderingDelay(); - - return true; -} - -void MixerOutputStreamAlsa::Stop() { - if (alsa_) { - alsa_->PcmStatusFree(pcm_status_); - alsa_->PcmHwParamsFree(pcm_hw_params_); - } - - pcm_status_ = nullptr; - pcm_hw_params_ = nullptr; - - if (!pcm_) { - return; - } - - // If |pcm_| is RUNNING, drain all pending data. - if (alsa_->PcmState(pcm_) == SND_PCM_STATE_RUNNING) { - int err = alsa_->PcmDrain(pcm_); - if (err < 0) { - LOG(ERROR) << "snd_pcm_drain error: " << alsa_->StrError(err); - } - } else { - int err = alsa_->PcmDrop(pcm_); - if (err < 0) { - LOG(ERROR) << "snd_pcm_drop error: " << alsa_->StrError(err); - } - } - - LOG(INFO) << "snd_pcm_close: handle=" << pcm_; - int err = alsa_->PcmClose(pcm_); - if (err < 0) { - LOG(ERROR) << "snd_pcm_close error, leaking handle: " - << alsa_->StrError(err); - } - pcm_ = nullptr; -} - -int MixerOutputStreamAlsa::SetAlsaPlaybackParams(int requested_sample_rate) { - int err = 0; - // Set hardware parameters. - DCHECK(pcm_); - DCHECK(!pcm_hw_params_); - RETURN_ERROR_CODE(PcmHwParamsMalloc, &pcm_hw_params_); - RETURN_ERROR_CODE(PcmHwParamsAny, pcm_, pcm_hw_params_); - RETURN_ERROR_CODE(PcmHwParamsSetAccess, pcm_, pcm_hw_params_, - SND_PCM_ACCESS_RW_INTERLEAVED); - if (pcm_format_ == SND_PCM_FORMAT_UNKNOWN) { - for (const auto& pcm_format : kPreferredSampleFormats) { - err = alsa_->PcmHwParamsTestFormat(pcm_, pcm_hw_params_, pcm_format); - if (err < 0) { - LOG(WARNING) << "PcmHwParamsTestFormat: " << alsa_->StrError(err); - } else { - pcm_format_ = pcm_format; - break; - } - } - if (pcm_format_ == SND_PCM_FORMAT_UNKNOWN) { - LOG(ERROR) << "Could not find a valid PCM format. Running " - << "/bin/alsa_api_test may be instructive."; - return err; - } - } - - RETURN_ERROR_CODE(PcmHwParamsSetFormat, pcm_, pcm_hw_params_, pcm_format_); - RETURN_ERROR_CODE(PcmHwParamsSetChannels, pcm_, pcm_hw_params_, - num_output_channels_); - - // Set output rate, allow resampling with a warning if the device doesn't - // support the rate natively. - RETURN_ERROR_CODE(PcmHwParamsSetRateResample, pcm_, pcm_hw_params_, - false /* Don't allow resampling. */); - - unsigned int new_sample_rate = DetermineOutputRate(requested_sample_rate); - RETURN_ERROR_CODE(PcmHwParamsSetRateNear, pcm_, pcm_hw_params_, - &new_sample_rate, kAlsaDirDontCare); - if (requested_sample_rate != static_cast(new_sample_rate)) { - LOG(WARNING) << "Requested sample rate (" << requested_sample_rate - << " Hz) does not match the actual sample rate (" - << new_sample_rate - << " Hz). This may lead to lower audio quality."; - } - LOG(INFO) << "Sample rate changed from " << sample_rate_ << " to " - << new_sample_rate; - sample_rate_ = static_cast(new_sample_rate); - - snd_pcm_uframes_t requested_buffer_size = alsa_buffer_size_; - RETURN_ERROR_CODE(PcmHwParamsSetBufferSizeNear, pcm_, pcm_hw_params_, - &alsa_buffer_size_); - if (requested_buffer_size != alsa_buffer_size_) { - LOG(WARNING) << "Requested buffer size (" << requested_buffer_size - << " frames) does not match the actual buffer size (" - << alsa_buffer_size_ - << " frames). This may lead to an increase in " - "either audio latency or audio underruns."; - - if (alsa_period_size_ >= alsa_buffer_size_) { - snd_pcm_uframes_t new_period_size = alsa_buffer_size_ / 2; - LOG(DFATAL) << "Configured period size (" << alsa_period_size_ - << ") is >= actual buffer size (" << alsa_buffer_size_ - << "); reducing to " << new_period_size; - alsa_period_size_ = new_period_size; - } - // Scale the start threshold and avail_min based on the new buffer size. - float original_buffer_size = static_cast(requested_buffer_size); - float avail_min_ratio = original_buffer_size / alsa_avail_min_; - alsa_avail_min_ = alsa_buffer_size_ / avail_min_ratio; - float start_threshold_ratio = original_buffer_size / alsa_start_threshold_; - alsa_start_threshold_ = alsa_buffer_size_ / start_threshold_ratio; - } - - snd_pcm_uframes_t requested_period_size = alsa_period_size_; - RETURN_ERROR_CODE(PcmHwParamsSetPeriodSizeNear, pcm_, pcm_hw_params_, - &alsa_period_size_, kAlsaDirDontCare); - if (requested_period_size != alsa_period_size_) { - LOG(WARNING) << "Requested period size (" << requested_period_size - << " frames) does not match the actual period size (" - << alsa_period_size_ - << " frames). This may lead to an increase in " - "CPU usage or an increase in audio latency."; - } - RETURN_ERROR_CODE(PcmHwParams, pcm_, pcm_hw_params_); - - // Set software parameters. - snd_pcm_sw_params_t* swparams; - RETURN_ERROR_CODE(PcmSwParamsMalloc, &swparams); - RETURN_ERROR_CODE(PcmSwParamsCurrent, pcm_, swparams); - RETURN_ERROR_CODE(PcmSwParamsSetStartThreshold, pcm_, swparams, - alsa_start_threshold_); - if (alsa_start_threshold_ > alsa_buffer_size_) { - LOG(ERROR) << "Requested start threshold (" << alsa_start_threshold_ - << " frames) is larger than the buffer size (" - << alsa_buffer_size_ - << " frames). Audio playback will not start."; - } - - RETURN_ERROR_CODE(PcmSwParamsSetAvailMin, pcm_, swparams, alsa_avail_min_); - RETURN_ERROR_CODE(PcmSwParamsSetTstampMode, pcm_, swparams, - SND_PCM_TSTAMP_ENABLE); - RETURN_ERROR_CODE(PcmSwParamsSetTstampType, pcm_, swparams, - kAlsaTstampTypeMonotonicRaw); - err = alsa_->PcmSwParams(pcm_, swparams); - alsa_->PcmSwParamsFree(swparams); - return err; -} - -void MixerOutputStreamAlsa::DefineAlsaParameters() { - // Get the ALSA output configuration from the command line. - - if (base::CommandLine::InitializedForCurrentProcess()) { - alsa_buffer_size_ = GetSwitchValueNonNegativeInt( - switches::kAlsaOutputBufferSize, kDefaultOutputBufferSizeFrames); - alsa_period_size_ = GetSwitchValueNonNegativeInt( - switches::kAlsaOutputPeriodSize, alsa_buffer_size_ / 2); - } else { - alsa_buffer_size_ = kDefaultOutputBufferSizeFrames; - alsa_period_size_ = alsa_buffer_size_ / 2; - } - - if (alsa_period_size_ >= alsa_buffer_size_) { - LOG(DFATAL) << "ALSA period size must be smaller than the buffer size"; - alsa_period_size_ = alsa_buffer_size_ / 2; - } - - LOG(INFO) << "ALSA buffer = " << alsa_buffer_size_ - << ", period = " << alsa_period_size_; - - if (base::CommandLine::InitializedForCurrentProcess()) { - alsa_start_threshold_ = GetSwitchValueNonNegativeInt( - switches::kAlsaOutputStartThreshold, - (alsa_buffer_size_ / alsa_period_size_) * alsa_period_size_); - } else { - alsa_start_threshold_ = - (alsa_buffer_size_ / alsa_period_size_) * alsa_period_size_; - } - if (alsa_start_threshold_ > alsa_buffer_size_) { - LOG(DFATAL) << "ALSA start threshold must be no larger than " - << "the buffer size"; - alsa_start_threshold_ = - (alsa_buffer_size_ / alsa_period_size_) * alsa_period_size_; - } - - // By default, allow the transfer when at least period_size samples can be - // processed. - if (base::CommandLine::InitializedForCurrentProcess()) { - alsa_avail_min_ = GetSwitchValueNonNegativeInt( - switches::kAlsaOutputAvailMin, alsa_period_size_); - } else { - alsa_avail_min_ = alsa_period_size_; - } - if (alsa_avail_min_ > alsa_buffer_size_) { - LOG(DFATAL) << "ALSA avail min must be no larger than the buffer size"; - alsa_avail_min_ = alsa_period_size_; - } -} - -int MixerOutputStreamAlsa::DetermineOutputRate(int requested_sample_rate) { - unsigned int unsigned_output_sample_rate = requested_sample_rate; - - // Try the requested sample rate. If the ALSA driver doesn't know how to deal - // with it, try the nearest supported sample rate instead. Lastly, try some - // common sample rates as a fallback. Note that PcmHwParamsSetRateNear - // doesn't always choose a rate that's actually near the given input sample - // rate when the input sample rate is not supported. - const int* kSupportedSampleRatesEnd = - kSupportedSampleRates + std::size(kSupportedSampleRates); - auto* nearest_sample_rate = - std::min_element(kSupportedSampleRates, kSupportedSampleRatesEnd, - [requested_sample_rate](int r1, int r2) -> bool { - return abs(requested_sample_rate - r1) < - abs(requested_sample_rate - r2); - }); - // Resample audio with sample rates deemed to be too low (i.e. below 32kHz) - // because some common AV receivers don't support optical out at these - // frequencies. See b/26385501 - unsigned int first_choice_sample_rate = requested_sample_rate; - const unsigned int preferred_sample_rates[] = { - first_choice_sample_rate, static_cast(*nearest_sample_rate), - kFallbackSampleRateHiRes, kFallbackSampleRate}; - int err; - for (const auto& sample_rate : preferred_sample_rates) { - err = alsa_->PcmHwParamsTestRate(pcm_, pcm_hw_params_, sample_rate, - 0 /* try exact rate */); - if (err == 0) { - unsigned_output_sample_rate = sample_rate; - break; - } - } - LOG_IF(ERROR, err != 0) << "Even the fallback sample rate isn't supported! " - << "Have you tried /bin/alsa_api_test on-device?"; - return unsigned_output_sample_rate; -} - -void MixerOutputStreamAlsa::UpdateRenderingDelay() { - if (alsa_->PcmStatus(pcm_, pcm_status_) != 0 || - alsa_->PcmStatusGetState(pcm_status_) != SND_PCM_STATE_RUNNING) { - rendering_delay_.timestamp_microseconds = kNoTimestamp; - rendering_delay_.delay_microseconds = 0; - return; - } - - snd_htimestamp_t status_timestamp = {}; - alsa_->PcmStatusGetHtstamp(pcm_status_, &status_timestamp); - if (status_timestamp.tv_sec == 0 && status_timestamp.tv_nsec == 0) { - // ALSA didn't actually give us a timestamp. - rendering_delay_.timestamp_microseconds = kNoTimestamp; - rendering_delay_.delay_microseconds = 0; - return; - } - - rendering_delay_.timestamp_microseconds = - TimespecToMicroseconds(status_timestamp); - snd_pcm_sframes_t delay_frames = alsa_->PcmStatusGetDelay(pcm_status_); - rendering_delay_.delay_microseconds = static_cast(delay_frames) * - base::Time::kMicrosecondsPerSecond / - sample_rate_; -} - -bool MixerOutputStreamAlsa::MaybeRecoverDeviceFromSuspendedState() { - if (alsa_->PcmState(pcm_) != SND_PCM_STATE_SUSPENDED) { - LOG(WARNING) << "Alsa output is not suspended"; - return false; - } - if (alsa_->PcmHwParamsCanResume(pcm_hw_params_)) { - LOG(INFO) << "Trying to resume output"; - for (int attempt = 0; attempt < kRestoreAfterSuspensionAttempts; - ++attempt) { - int err = alsa_->PcmResume(pcm_); - if (err == 0) { - LOG(INFO) << "ALSA output is resumed from suspended state"; - return true; - } - if (err != -EAGAIN) { - // If PcmResume failed or device doesn't support resume, try to use - // PcmPrepare. - err = alsa_->PcmPrepare(pcm_); - LOG_IF(INFO, err == 0) - << "ALSA output is recovered from suspended state"; - return err == 0; - } - base::PlatformThread::Sleep(kRestoreAfterSuspensionAttemptDelay); - } - } - return false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/mixer_output_stream_alsa.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ALSA_MIXER_OUTPUT_STREAM_ALSA_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ALSA_MIXER_OUTPUT_STREAM_ALSA_H_ - -#include - -#include -#include - -#include "chromecast/public/media/mixer_output_stream.h" - -namespace chromecast { -namespace media { - -class AlsaWrapper; - -// MixerOutputStream implementation for ALSA -class MixerOutputStreamAlsa : public MixerOutputStream { - public: - MixerOutputStreamAlsa(); - - MixerOutputStreamAlsa(const MixerOutputStreamAlsa&) = delete; - MixerOutputStreamAlsa& operator=(const MixerOutputStreamAlsa&) = delete; - - ~MixerOutputStreamAlsa() override; - - void SetAlsaWrapperForTest(std::unique_ptr alsa); - - // MixerOutputStream implementation: - bool Start(int requested_sample_rate, int channels) override; - int GetNumChannels() override; - int GetSampleRate() override; - MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelay() - override; - int OptimalWriteFramesCount() override; - bool Write(const float* data, - int data_size, - bool* out_playback_interrupted) override; - void Stop() override; - - private: - // Reads the buffer size, period size, start threshold, and avail min value - // from the provided command line flags or uses default values if no flags are - // provided. - void DefineAlsaParameters(); - - // Takes the provided ALSA config and sets all ALSA output hardware/software - // playback parameters. It will try to select sane fallback parameters based - // on what the output hardware supports and will log warnings if it does so. - // If any ALSA function returns an unexpected error code, the error code will - // be returned by this function. Otherwise, it will return 0. - int SetAlsaPlaybackParams(int requested_rate); - - // Determines output sample rate based on the requested rate and the sample - // rate the device supports. - int DetermineOutputRate(int requested_rate); - - void UpdateRenderingDelay(); - - // Checks ALSA output for current state and if it's suspended, tries to - // recover. - // Returns true if ALSA device is recovered successfully. - bool MaybeRecoverDeviceFromSuspendedState(); - - std::unique_ptr alsa_; - - snd_pcm_t* pcm_ = nullptr; - snd_pcm_hw_params_t* pcm_hw_params_ = nullptr; - snd_pcm_status_t* pcm_status_ = nullptr; - snd_pcm_format_t pcm_format_ = SND_PCM_FORMAT_UNKNOWN; - - int num_output_channels_ = 0; - int sample_rate_ = kInvalidSampleRate; - - // User-configurable ALSA parameters. This caches the results, so the code - // only has to interact with the command line parameters once. - snd_pcm_uframes_t alsa_buffer_size_ = 0; - snd_pcm_uframes_t alsa_period_size_ = 0; - snd_pcm_uframes_t alsa_start_threshold_ = 0; - snd_pcm_uframes_t alsa_avail_min_ = 0; - - bool first_write_ = false; - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay_; - - std::vector output_buffer_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ALSA_MIXER_OUTPUT_STREAM_ALSA_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.cc chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,134 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/alsa/scoped_alsa_mixer.h" - -#include "base/check.h" -#include "base/logging.h" -#include "base/task/current_thread.h" -#include "base/types/fixed_array.h" - -#define ALSA_ASSERT(func, ...) \ - do { \ - int err = alsa_->func(__VA_ARGS__); \ - LOG_ASSERT(err >= 0) << #func " error: " << alsa_->StrError(err); \ - } while (0) - -namespace chromecast { -namespace media { - -ScopedAlsaMixer::ScopedAlsaMixer(::media::AlsaWrapper* alsa, - const std::string& mixer_device_name, - const std::string& mixer_element_name) - : alsa_(alsa), - mixer_device_name_(mixer_device_name), - mixer_element_name_(mixer_element_name) { - DCHECK(alsa_); - RefreshElement(); -} - -ScopedAlsaMixer::~ScopedAlsaMixer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - file_descriptor_watchers_.clear(); - - if (element) { - alsa_->MixerElemSetCallback(element, nullptr); - alsa_->MixerElemSetCallbackPrivate(element, nullptr); - } - if (mixer_) { - alsa_->MixerClose(mixer_); - } -} - -snd_mixer_t* ScopedAlsaMixer::GetMixerForTest() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return mixer_; -} - -void ScopedAlsaMixer::RefreshElement() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (mixer_) { - alsa_->MixerClose(mixer_); - DVLOG(2) << "Reopening mixer element \"" << mixer_element_name_ - << "\" on device \"" << mixer_device_name_ << "\""; - } else { - LOG(INFO) << "Opening mixer element \"" << mixer_element_name_ - << "\" on device \"" << mixer_device_name_ << "\""; - } - mixer_ = nullptr; - element = nullptr; - int alsa_err = alsa_->MixerOpen(&mixer_, 0); - if (alsa_err < 0) { - LOG(ERROR) << "MixerOpen error: " << alsa_->StrError(alsa_err); - mixer_ = nullptr; - return; - } - alsa_err = alsa_->MixerAttach(mixer_, mixer_device_name_.c_str()); - if (alsa_err < 0) { - LOG(ERROR) << "MixerAttach error: " << alsa_->StrError(alsa_err); - alsa_->MixerClose(mixer_); - mixer_ = nullptr; - return; - } - ALSA_ASSERT(MixerElementRegister, mixer_, nullptr, nullptr); - alsa_err = alsa_->MixerLoad(mixer_); - if (alsa_err < 0) { - LOG(ERROR) << "MixerLoad error: " << alsa_->StrError(alsa_err); - alsa_->MixerClose(mixer_); - mixer_ = nullptr; - return; - } - snd_mixer_selem_id_t* sid = nullptr; - ALSA_ASSERT(MixerSelemIdMalloc, &sid); - alsa_->MixerSelemIdSetIndex(sid, 0); - alsa_->MixerSelemIdSetName(sid, mixer_element_name_.c_str()); - element = alsa_->MixerFindSelem(mixer_, sid); - if (!element) { - LOG(ERROR) << "Simple mixer control element \"" << mixer_element_name_ - << "\" not found."; - } - alsa_->MixerSelemIdFree(sid); -} - -void ScopedAlsaMixer::WatchForEvents(snd_mixer_elem_callback_t cb, - void* cb_private_value) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!element || !cb) { - return; - } - - alsa_->MixerElemSetCallback(element, cb); - alsa_->MixerElemSetCallbackPrivate(element, cb_private_value); - - int num_fds = alsa_->MixerPollDescriptorsCount(mixer_); - DCHECK_GT(num_fds, 0); - base::FixedArray pfds(num_fds); - num_fds = alsa_->MixerPollDescriptors(mixer_, pfds.data(), num_fds); - DCHECK_GT(num_fds, 0); - file_descriptor_watchers_.clear(); - for (int i = 0; i < num_fds; ++i) { - auto watcher = - std::make_unique(FROM_HERE); - base::CurrentIOThread::Get()->WatchFileDescriptor( - pfds[i].fd, true /* persistent */, base::MessagePumpForIO::WATCH_READ, - watcher.get(), this); - file_descriptor_watchers_.push_back(std::move(watcher)); - } -} - -void ScopedAlsaMixer::OnFileCanReadWithoutBlocking(int fd) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!mixer_) { - return; - } - alsa_->MixerHandleEvents(mixer_); -} - -void ScopedAlsaMixer::OnFileCanWriteWithoutBlocking(int fd) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - // Nothing to do. -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.h chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ALSA_SCOPED_ALSA_MIXER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ALSA_SCOPED_ALSA_MIXER_H_ - -#include - -#include "base/message_loop/message_pump_for_io.h" -#include "base/sequence_checker.h" -#include "media/audio/alsa/alsa_wrapper.h" - -namespace chromecast { -namespace media { - -class ScopedAlsaMixer : public base::MessagePumpForIO::FdWatcher { - public: - ScopedAlsaMixer(::media::AlsaWrapper* alsa, - const std::string& mixer_device_name, - const std::string& mixer_element_name); - ~ScopedAlsaMixer() override; - ScopedAlsaMixer(const ScopedAlsaMixer&) = delete; - ScopedAlsaMixer& operator=(const ScopedAlsaMixer&) = delete; - - // (Re)open the mixer and update the |element| pointer to a value that is - // either nullable or valid. - void RefreshElement(); - // Register a callback to invoke on new mixer events. - void WatchForEvents(snd_mixer_elem_callback_t cb, void* cb_private_value); - - // base::MessagePumpForIO::FdWatcher implementation: - void OnFileCanReadWithoutBlocking(int fd) override; - void OnFileCanWriteWithoutBlocking(int fd) override; - - snd_mixer_t* GetMixerForTest(); - // TODO(jyw) stop exposing bare |element| - snd_mixer_elem_t* element = nullptr; - - private: - SEQUENCE_CHECKER(sequence_checker_); - - ::media::AlsaWrapper* const alsa_; - snd_mixer_t* mixer_ GUARDED_BY_CONTEXT(sequence_checker_) = nullptr; - - const std::string mixer_device_name_; - const std::string mixer_element_name_; - - std::vector> - file_descriptor_watchers_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ALSA_SCOPED_ALSA_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/scoped_alsa_mixer_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/alsa/scoped_alsa_mixer_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/alsa/scoped_alsa_mixer_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,387 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/alsa/scoped_alsa_mixer.h" - -#include "base/containers/span.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/test/mock_log.h" -#include "base/test/task_environment.h" -#include "media/audio/alsa/mock_alsa_wrapper.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { -using ::testing::_; -using ::testing::DoAll; -using ::testing::HasSubstr; -using ::testing::Return; -using ::testing::SetArgPointee; -using ::testing::StrEq; - -constexpr char kMixerDeviceName[] = "test-device"; -constexpr char kMixerElementName[] = "test-element"; - -const int kSuccess = 0; -const int kFailure = -1; - -int MixerEventCallback(snd_mixer_elem_t*, unsigned int) { - return 0; -} - -class ScopedAlsaMixerEventTest : public ::testing::Test { - public: - ScopedAlsaMixerEventTest() - : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {} - - void SetUp() override { - ASSERT_EQ(0, pipe(pipe_fds_)); - - EXPECT_CALL(alsa_, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer_), Return(kSuccess))); - EXPECT_CALL(alsa_, MixerAttach(mixer_, StrEq(kMixerDeviceName))) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa_, MixerElementRegister(mixer_, nullptr, nullptr)) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa_, MixerLoad(mixer_)).WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa_, MixerSelemIdMalloc(_)) - .WillOnce(DoAll(SetArgPointee<0>(mixer_selem_id_), Return(kSuccess))); - EXPECT_CALL(alsa_, MixerSelemIdSetIndex(mixer_selem_id_, 0)); - EXPECT_CALL(alsa_, - MixerSelemIdSetName(mixer_selem_id_, StrEq(kMixerElementName))); - EXPECT_CALL(alsa_, MixerFindSelem(mixer_, mixer_selem_id_)) - .WillOnce(Return(element_)); - EXPECT_CALL(alsa_, MixerSelemIdFree(mixer_selem_id_)); - - alsa_mixer_ = std::make_unique(&alsa_, kMixerDeviceName, - kMixerElementName); - } - - void TearDown() override { - EXPECT_CALL(alsa_, MixerElemSetCallback(_, nullptr)); - EXPECT_CALL(alsa_, MixerElemSetCallbackPrivate(_, nullptr)); - EXPECT_CALL(alsa_, MixerClose(mixer_)); - alsa_mixer_.reset(); - EXPECT_EQ(0, IGNORE_EINTR(close(pipe_fds_[0]))); - EXPECT_EQ(0, IGNORE_EINTR(close(pipe_fds_[1]))); - } - - void ReadByte() { - char buffer; - ASSERT_TRUE(base::ReadFromFD(pipe_fds_[0], base::span_from_ref(buffer))); - } - - void WriteByte() { - constexpr char kByte = '!'; - ASSERT_TRUE(base::WriteFileDescriptor(pipe_fds_[1], - base::byte_span_from_ref(kByte))); - } - - base::test::TaskEnvironment task_environment_; - int pipe_fds_[2]; - - ::testing::StrictMock<::media::MockAlsaWrapper> alsa_; - snd_mixer_t* mixer_ = reinterpret_cast(0x00001111); - snd_mixer_selem_id_t* mixer_selem_id_ = - reinterpret_cast(0x00002222); - snd_mixer_elem_t* element_ = reinterpret_cast(0x00003333); - void* cb_private_data_ = reinterpret_cast(0x00004444); - - std::unique_ptr alsa_mixer_ = nullptr; -}; - -} // namespace - -TEST(ScopedAlsaMixerTest, NormalLifeCycle) { - ::testing::StrictMock<::media::MockAlsaWrapper> alsa; - snd_mixer_t* mixer = reinterpret_cast(0x00001111); - snd_mixer_selem_id_t* mixer_selem_id = - reinterpret_cast(0x00002222); - snd_mixer_elem_t* element = reinterpret_cast(0x00003333); - - EXPECT_CALL(alsa, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer), Return(kSuccess))); - EXPECT_CALL(alsa, MixerAttach(mixer, StrEq(kMixerDeviceName))) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerElementRegister(mixer, nullptr, nullptr)) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerLoad(mixer)).WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerSelemIdMalloc(_)) - .WillOnce(DoAll(SetArgPointee<0>(mixer_selem_id), Return(kSuccess))); - EXPECT_CALL(alsa, MixerSelemIdSetIndex(mixer_selem_id, 0)); - EXPECT_CALL(alsa, - MixerSelemIdSetName(mixer_selem_id, StrEq(kMixerElementName))); - EXPECT_CALL(alsa, MixerFindSelem(mixer, mixer_selem_id)) - .WillOnce(Return(element)); - EXPECT_CALL(alsa, MixerSelemIdFree(mixer_selem_id)); - - ScopedAlsaMixer alsa_mixer(&alsa, kMixerDeviceName, kMixerElementName); - EXPECT_EQ(alsa_mixer.GetMixerForTest(), mixer); - EXPECT_EQ(alsa_mixer.element, element); - - EXPECT_CALL(alsa, MixerElemSetCallback(element, nullptr)); - EXPECT_CALL(alsa, MixerElemSetCallbackPrivate(element, nullptr)); - EXPECT_CALL(alsa, MixerClose(mixer)); -} - -TEST(ScopedAlsaMixerTest, RefreshElement) { - ::testing::NiceMock<::media::MockAlsaWrapper> alsa; - snd_mixer_t* mixer = reinterpret_cast(0x00001111); - snd_mixer_selem_id_t* mixer_selem_id = - reinterpret_cast(0x00002222); - snd_mixer_elem_t* element = reinterpret_cast(0x00003333); - ScopedAlsaMixer alsa_mixer(&alsa, kMixerDeviceName, kMixerElementName); - - EXPECT_CALL(alsa, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer), Return(kSuccess))); - EXPECT_CALL(alsa, MixerAttach(mixer, StrEq(kMixerDeviceName))) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerElementRegister(mixer, nullptr, nullptr)) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerLoad(mixer)).WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerSelemIdMalloc(_)) - .WillOnce(DoAll(SetArgPointee<0>(mixer_selem_id), Return(kSuccess))); - EXPECT_CALL(alsa, MixerSelemIdSetIndex(mixer_selem_id, 0)); - EXPECT_CALL(alsa, - MixerSelemIdSetName(mixer_selem_id, StrEq(kMixerElementName))); - EXPECT_CALL(alsa, MixerFindSelem(mixer, mixer_selem_id)) - .WillOnce(Return(element)); - EXPECT_CALL(alsa, MixerSelemIdFree(mixer_selem_id)); - - alsa_mixer.RefreshElement(); - - EXPECT_CALL(alsa, MixerClose(mixer)); -} - -TEST(ScopedAlsaMixerTest, MixerOpenFailure) { - ::testing::StrictMock<::media::MockAlsaWrapper> alsa; - snd_mixer_t* mixer = reinterpret_cast(0x00001111); - base::test::MockLog mock_log; - - EXPECT_CALL(alsa, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer), Return(kFailure))); - EXPECT_CALL(mock_log, Log(logging::LOGGING_INFO, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, /*str=*/_)); - EXPECT_CALL(alsa, StrError(kFailure)).WillOnce(Return("")); - EXPECT_CALL( - mock_log, - Log(logging::LOGGING_ERROR, ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, /*str=*/HasSubstr("MixerOpen error"))); - - mock_log.StartCapturingLogs(); - ScopedAlsaMixer alsa_mixer(&alsa, kMixerDeviceName, kMixerElementName); - EXPECT_EQ(alsa_mixer.GetMixerForTest(), nullptr); - EXPECT_EQ(alsa_mixer.element, nullptr); - mock_log.StopCapturingLogs(); -} - -TEST(ScopedAlsaMixerTest, MixerAttachFailure) { - ::testing::StrictMock<::media::MockAlsaWrapper> alsa; - snd_mixer_t* mixer = reinterpret_cast(0x00001111); - base::test::MockLog mock_log; - - EXPECT_CALL(alsa, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer), Return(kSuccess))); - EXPECT_CALL(alsa, MixerAttach(mixer, StrEq(kMixerDeviceName))) - .WillOnce(Return(kFailure)); - EXPECT_CALL(mock_log, Log(logging::LOGGING_INFO, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, /*str=*/_)); - EXPECT_CALL(alsa, StrError(kFailure)).WillOnce(Return("")); - EXPECT_CALL( - mock_log, - Log(logging::LOGGING_ERROR, ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, HasSubstr("MixerAttach error"))); - EXPECT_CALL(alsa, MixerClose(mixer)); - - mock_log.StartCapturingLogs(); - ScopedAlsaMixer alsa_mixer(&alsa, kMixerDeviceName, kMixerElementName); - EXPECT_EQ(alsa_mixer.GetMixerForTest(), nullptr); - EXPECT_EQ(alsa_mixer.element, nullptr); - mock_log.StopCapturingLogs(); -} - -TEST(ScopedAlsaMixerTest, MixerLoadFailure) { - ::testing::StrictMock<::media::MockAlsaWrapper> alsa; - snd_mixer_t* mixer = reinterpret_cast(0x00001111); - base::test::MockLog mock_log; - - EXPECT_CALL(alsa, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer), Return(kSuccess))); - EXPECT_CALL(alsa, MixerAttach(mixer, StrEq(kMixerDeviceName))) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerElementRegister(mixer, nullptr, nullptr)) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerLoad(mixer)).WillOnce(Return(kFailure)); - EXPECT_CALL(mock_log, Log(logging::LOGGING_INFO, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, /*str=*/_)); - EXPECT_CALL(alsa, StrError(kFailure)).WillOnce(Return("")); - EXPECT_CALL(mock_log, Log(logging::LOGGING_ERROR, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, HasSubstr("MixerLoad error"))); - EXPECT_CALL(alsa, MixerClose(mixer)); - - mock_log.StartCapturingLogs(); - ScopedAlsaMixer alsa_mixer(&alsa, kMixerDeviceName, kMixerElementName); - EXPECT_EQ(alsa_mixer.GetMixerForTest(), nullptr); - EXPECT_EQ(alsa_mixer.element, nullptr); - mock_log.StopCapturingLogs(); -} - -TEST(ScopedAlsaMixerTest, MixerFindSelemFailure) { - ::testing::StrictMock<::media::MockAlsaWrapper> alsa; - snd_mixer_t* mixer = reinterpret_cast(0x00001111); - snd_mixer_selem_id_t* mixer_selem_id = - reinterpret_cast(0x00002222); - base::test::MockLog mock_log; - - EXPECT_CALL(alsa, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer), Return(kSuccess))); - EXPECT_CALL(alsa, MixerAttach(mixer, StrEq(kMixerDeviceName))) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerElementRegister(mixer, nullptr, nullptr)) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerLoad(mixer)).WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerSelemIdMalloc(_)) - .WillOnce(DoAll(SetArgPointee<0>(mixer_selem_id), Return(kSuccess))); - EXPECT_CALL(alsa, MixerSelemIdSetIndex(mixer_selem_id, 0)); - EXPECT_CALL(alsa, - MixerSelemIdSetName(mixer_selem_id, StrEq(kMixerElementName))); - EXPECT_CALL(alsa, MixerFindSelem(mixer, mixer_selem_id)) - .WillOnce(Return(nullptr)); - EXPECT_CALL(mock_log, Log(logging::LOGGING_INFO, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, /*str=*/_)); - EXPECT_CALL(mock_log, Log(logging::LOGGING_ERROR, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, /*str=*/_)); - EXPECT_CALL(alsa, MixerSelemIdFree(mixer_selem_id)); - - mock_log.StartCapturingLogs(); - ScopedAlsaMixer alsa_mixer(&alsa, kMixerDeviceName, kMixerElementName); - EXPECT_EQ(alsa_mixer.GetMixerForTest(), mixer); - EXPECT_EQ(alsa_mixer.element, nullptr); - mock_log.StopCapturingLogs(); - - EXPECT_CALL(alsa, MixerClose(mixer)); -} - -TEST(ScopedAlsaMixerDeathTest, MixerElementRegisterFailure) { - EXPECT_DEATH( - { - ::testing::StrictMock<::media::MockAlsaWrapper> alsa; - snd_mixer_t* mixer = reinterpret_cast(0x00001111); - base::test::MockLog mock_log; - - EXPECT_CALL(alsa, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer), Return(kSuccess))); - EXPECT_CALL(alsa, MixerAttach(mixer, StrEq(kMixerDeviceName))) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerElementRegister(mixer, nullptr, nullptr)) - .WillOnce(Return(kFailure)); - EXPECT_CALL(mock_log, Log(logging::LOGGING_INFO, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, /*str=*/_)); - EXPECT_CALL(alsa, StrError(kFailure)).WillOnce(Return("")); - EXPECT_CALL(mock_log, Log(logging::LOGGING_FATAL, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, - HasSubstr("MixerElementRegister error"))); - - mock_log.StartCapturingLogs(); - ScopedAlsaMixer alsa_mixer(&alsa, kMixerDeviceName, kMixerElementName); - mock_log.StopCapturingLogs(); - }, - _); -} - -TEST(ScopedAlsaMixerDeathTest, MixerSelemIdMallocFailure) { - EXPECT_DEATH( - { - ::testing::StrictMock<::media::MockAlsaWrapper> alsa; - snd_mixer_t* mixer = reinterpret_cast(0x00001111); - snd_mixer_selem_id_t* mixer_selem_id = - reinterpret_cast(0x00002222); - base::test::MockLog mock_log; - - EXPECT_CALL(alsa, MixerOpen(_, 0)) - .WillOnce(DoAll(SetArgPointee<0>(mixer), Return(kSuccess))); - EXPECT_CALL(alsa, MixerAttach(mixer, StrEq(kMixerDeviceName))) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerElementRegister(mixer, nullptr, nullptr)) - .WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerLoad(mixer)).WillOnce(Return(kSuccess)); - EXPECT_CALL(alsa, MixerSelemIdMalloc(_)) - .WillOnce( - DoAll(SetArgPointee<0>(mixer_selem_id), Return(kFailure))); - EXPECT_CALL(mock_log, Log(logging::LOGGING_INFO, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, /*str=*/_)); - EXPECT_CALL(alsa, StrError(kFailure)).WillOnce(Return("")); - EXPECT_CALL(mock_log, Log(logging::LOGGING_FATAL, - ::testing::EndsWith("/scoped_alsa_mixer.cc"), - /*line=*/_, - /*message_start=*/_, - HasSubstr("MixerSelemIdMalloc error"))); - - mock_log.StartCapturingLogs(); - ScopedAlsaMixer alsa_mixer(&alsa, kMixerDeviceName, kMixerElementName); - mock_log.StopCapturingLogs(); - }, - _); -} - -TEST_F(ScopedAlsaMixerEventTest, NullableCallback) { - EXPECT_CALL(alsa_, MixerElemSetCallback(_, _)).Times(0); - EXPECT_CALL(alsa_, MixerElemSetCallbackPrivate(_, _)).Times(0); -} - -TEST_F(ScopedAlsaMixerEventTest, RealCallback) { - base::RunLoop run_loop; - - EXPECT_CALL(alsa_, MixerElemSetCallback(element_, &MixerEventCallback)); - EXPECT_CALL(alsa_, MixerElemSetCallbackPrivate(element_, cb_private_data_)); - - EXPECT_CALL(alsa_, MixerPollDescriptorsCount(mixer_)).WillOnce(Return(1)); - EXPECT_CALL(alsa_, MixerPollDescriptors(mixer_, _, 1)) - .WillOnce(testing::Invoke( - [this](snd_mixer_t* mixer_, struct pollfd* pfds, unsigned int space) { - for (unsigned int i = 0; i < space; ++i) { - pfds[i].fd = pipe_fds_[0]; - } - return space; - })); - - EXPECT_EQ(alsa_mixer_->element, element_); - alsa_mixer_->WatchForEvents(&MixerEventCallback, cb_private_data_); - - EXPECT_CALL(alsa_, MixerHandleEvents(mixer_)) - .WillOnce(testing::Invoke([this, &run_loop]() { - ReadByte(); - run_loop.Quit(); - return 0; - })); - WriteByte(); - - run_loop.Run(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/DEPS chromium-132.0.6834.159/chromecast/media/cma/backend/android/DEPS --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+jni", - "+media/filters", -] diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_decoder_android.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_decoder_android.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_decoder_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_decoder_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,702 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/android/audio_decoder_android.h" - -#include - -#include -#include - -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/trace_event/trace_event.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/backend/android/media_pipeline_backend_android.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "media/base/audio_bus.h" -#include "media/base/channel_layout.h" -#include "media/base/decoder_buffer.h" -#include "media/base/sample_format.h" -#include "media/filters/audio_renderer_algorithm.h" - -#define TRACE_FUNCTION_ENTRY0() TRACE_EVENT0("cma", __FUNCTION__) - -#define TRACE_FUNCTION_ENTRY1(arg1) \ - TRACE_EVENT1("cma", __FUNCTION__, #arg1, arg1) - -#define TRACE_FUNCTION_ENTRY2(arg1, arg2) \ - TRACE_EVENT2("cma", __FUNCTION__, #arg1, arg1, #arg2, arg2) - -namespace chromecast { -namespace media { - -namespace { - -const int kDefaultFramesPerBuffer = 1024; -const int kSilenceBufferFrames = 2048; -const int kMaxOutputMs = 20; -const int kMillisecondsPerSecond = 1000; - -const double kPlaybackRateEpsilon = 0.001; - -const CastAudioDecoder::OutputFormat kDecoderSampleFormat = - CastAudioDecoder::kOutputPlanarFloat; - -const int64_t kInvalidTimestamp = std::numeric_limits::min(); - -const int64_t kNoPendingOutput = -1; - -bool IsValidChannelNumber(int channel_number) { - // Currently, we only support following channel numbers. - return (channel_number == 1) || (channel_number == 2) || - (channel_number == 4) || (channel_number == 6) || - (channel_number == 8); -} - -} // namespace - -AudioDecoderAndroid::RateShifterInfo::RateShifterInfo(float playback_rate) - : rate(playback_rate), input_frames(0), output_frames(0) {} - -// static -int64_t MediaPipelineBackend::AudioDecoder::GetMinimumBufferedTime( - const AudioConfig& config) { - return AudioSinkAndroid::GetMinimumBufferedTime(config); -} - -AudioDecoderAndroid::AudioDecoderAndroid(MediaPipelineBackendAndroid* backend, - bool is_apk_audio) - : backend_(backend), - is_apk_audio_(is_apk_audio), - task_runner_(backend->GetTaskRunner()), - delegate_(nullptr), - pending_buffer_complete_(false), - got_eos_(false), - pushed_eos_(false), - sink_error_(false), - current_pts_(kInvalidTimestamp), - pending_output_frames_(kNoPendingOutput), - volume_multiplier_(1.0f), - pool_(new ::media::AudioBufferMemoryPool()), - weak_factory_(this) { - LOG(INFO) << __func__ << ":"; - TRACE_FUNCTION_ENTRY0(); - DCHECK(backend_); - DCHECK(task_runner_.get()); - DCHECK(task_runner_->BelongsToCurrentThread()); -} - -AudioDecoderAndroid::~AudioDecoderAndroid() { - LOG(INFO) << __func__ << ":"; - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); -} - -void AudioDecoderAndroid::SetDelegate( - MediaPipelineBackend::Decoder::Delegate* delegate) { - LOG(INFO) << __func__ << ":"; - DCHECK(delegate); - delegate_ = delegate; -} - -void AudioDecoderAndroid::Initialize() { - LOG(INFO) << __func__ << ":"; - TRACE_FUNCTION_ENTRY0(); - DCHECK(delegate_); - stats_ = Statistics(); - pending_buffer_complete_ = false; - got_eos_ = false; - pushed_eos_ = false; - current_pts_ = kInvalidTimestamp; - pending_output_frames_ = kNoPendingOutput; -} - -bool AudioDecoderAndroid::Start(int64_t start_pts) { - LOG(INFO) << __func__ << ": start_pts=" << start_pts; - TRACE_FUNCTION_ENTRY0(); - current_pts_ = start_pts; - DCHECK(IsValidConfig(config_)); - DCHECK(IsValidChannelNumber(config_.channel_number)); - if (!sink_.Create(this, config_.channel_number, config_.samples_per_second, - config_.audio_track_session_id, backend_->Primary(), - is_apk_audio_, config_.use_hw_av_sync, backend_->DeviceId(), - backend_->ContentType())) { - return false; - } - - sink_->SetStreamVolumeMultiplier(volume_multiplier_); - // Create decoder_ if necessary. This can happen if Stop() was called, and - // SetConfig() was not called since then. - if (!decoder_) { - CreateDecoder(); - } - if (!rate_shifter_) { - CreateRateShifter(config_); - } - sink_->SetPaused(false); - return true; -} - -void AudioDecoderAndroid::Stop() { - LOG(INFO) << __func__ << ":"; - TRACE_FUNCTION_ENTRY0(); - decoder_.reset(); - sink_.Reset(); - rate_shifter_.reset(); - weak_factory_.InvalidateWeakPtrs(); - - Initialize(); -} - -bool AudioDecoderAndroid::Pause() { - LOG(INFO) << __func__ << ":"; - TRACE_FUNCTION_ENTRY0(); - DCHECK(sink_); - sink_->SetPaused(true); - return true; -} - -bool AudioDecoderAndroid::Resume() { - LOG(INFO) << __func__ << ":"; - TRACE_FUNCTION_ENTRY0(); - DCHECK(sink_); - sink_->SetPaused(false); - return true; -} - -bool AudioDecoderAndroid::SetPlaybackRate(float rate) { - LOG(INFO) << __func__ << ": rate=" << rate; - if (std::abs(rate - 1.0) < kPlaybackRateEpsilon) { - // AudioRendererAlgorithm treats values close to 1 as exactly 1. - rate = 1.0f; - } - LOG(INFO) << "SetPlaybackRate to " << rate; - - // Remove info for rates that have no pending output left. - while (!rate_shifter_info_.empty()) { - RateShifterInfo* rate_info = &rate_shifter_info_.back(); - int64_t possible_output_frames = rate_info->input_frames / rate_info->rate; - DCHECK_GE(possible_output_frames, rate_info->output_frames); - if (rate_info->output_frames == possible_output_frames) { - rate_shifter_info_.pop_back(); - } else { - break; - } - } - - rate_shifter_info_.push_back(RateShifterInfo(rate)); - return true; -} - -AudioDecoderAndroid::BufferStatus AudioDecoderAndroid::PushBuffer( - CastDecoderBuffer* buffer) { - if (buffer->end_of_stream()) { - DVLOG(3) << __func__ << ": EOS"; - } else { - DVLOG(3) << __func__ << ":" - << " size=" << buffer->data_size() - << " pts=" << buffer->timestamp(); - } - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(buffer); - DCHECK(!got_eos_); - DCHECK(!sink_error_); - DCHECK(!pending_buffer_complete_); - - uint64_t input_bytes = buffer->end_of_stream() ? 0 : buffer->data_size(); - scoped_refptr buffer_base( - static_cast(buffer)); - if (!buffer->end_of_stream()) { - current_pts_ = buffer->timestamp(); - } - - // If the buffer is already decoded, do not attempt to decode. Call - // OnBufferDecoded asynchronously on the main thread. - if (BypassDecoder()) { - DCHECK(!decoder_); - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&AudioDecoderAndroid::OnBufferDecoded, - weak_factory_.GetWeakPtr(), input_bytes, - CastAudioDecoder::Status::kDecodeOk, config_, - std::move(buffer_base))); - return MediaPipelineBackendAndroid::kBufferPending; - } - - DCHECK(decoder_); - // Decode the buffer. - decoder_->Decode(std::move(buffer_base), - base::BindOnce(&AudioDecoderAndroid::OnBufferDecoded, - base::Unretained(this), input_bytes)); - return MediaPipelineBackendAndroid::kBufferPending; -} - -void AudioDecoderAndroid::UpdateStatistics(Statistics delta) { - DCHECK(task_runner_->BelongsToCurrentThread()); - stats_.decoded_bytes += delta.decoded_bytes; -} - -void AudioDecoderAndroid::GetStatistics(Statistics* stats) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(stats); - DCHECK(task_runner_->BelongsToCurrentThread()); - *stats = stats_; - LOG(INFO) << __func__ << ": decoded_bytes=" << stats->decoded_bytes; -} - -bool AudioDecoderAndroid::SetConfig(const AudioConfig& config) { - LOG(INFO) << __func__ << ":" - << " id=" << config.id << " codec=" << config.codec - << " sample_format=" << config.sample_format - << " bytes_per_channel=" << config.bytes_per_channel - << " channel_number=" << config.channel_number - << " samples_per_second=" << config.samples_per_second - << " is_encrypted=" << config.is_encrypted(); - - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); - if (!IsValidConfig(config) || !IsValidChannelNumber(config.channel_number)) { - LOG(ERROR) << "Invalid audio config passed to SetConfig"; - return false; - } - - bool changed_config = - (config.samples_per_second != config_.samples_per_second || - config.channel_number != config_.channel_number); - - if (!rate_shifter_ || changed_config) { - CreateRateShifter(config); - } - - if (sink_ && changed_config) { - if (!ResetSinkForNewConfig(config)) { - return false; - } - } - - config_ = config; - decoder_.reset(); - CreateDecoder(); - - if (pending_buffer_complete_ && changed_config) { - pending_buffer_complete_ = false; - delegate_->OnPushBufferComplete( - MediaPipelineBackendAndroid::kBufferSuccess); - } - return true; -} - -bool AudioDecoderAndroid::ResetSinkForNewConfig(const AudioConfig& config) { - if (!sink_.Create(this, config.channel_number, config.samples_per_second, - config.audio_track_session_id, backend_->Primary(), - is_apk_audio_, config.use_hw_av_sync, backend_->DeviceId(), - backend_->ContentType())) { - return false; - } - - sink_->SetStreamVolumeMultiplier(volume_multiplier_); - pending_output_frames_ = kNoPendingOutput; - return true; -} - -void AudioDecoderAndroid::CreateDecoder() { - LOG(INFO) << __func__ << ":"; - - DCHECK(!decoder_); - DCHECK(IsValidConfig(config_)); - DCHECK(IsValidChannelNumber(config_.channel_number)); - - // No need to create a decoder if the samples are already decoded. - if (BypassDecoder()) { - LOG(INFO) << "Data is not coded. Decoder will not be used."; - return; - } - - // Create a decoder. - decoder_ = - CastAudioDecoder::Create(task_runner_, config_, kDecoderSampleFormat); - if (!decoder_) { - LOG(INFO) << __func__ << ": Decoder initialization was unsuccessful"; - delegate_->OnDecoderError(); - } -} - -void AudioDecoderAndroid::CreateRateShifter(const AudioConfig& config) { - LOG(INFO) << __func__ << ": channel_number=" << config.channel_number - << " samples_per_second=" << config.samples_per_second; - - rate_shifter_info_.clear(); - rate_shifter_info_.push_back(RateShifterInfo(1.0f)); - - rate_shifter_output_.reset(); - rate_shifter_.reset(new ::media::AudioRendererAlgorithm(&media_log_)); - bool is_encrypted = false; - ::media::ChannelLayout channel_layout = - DecoderConfigAdapter::ToMediaChannelLayout(config.channel_layout); - rate_shifter_->Initialize( - ::media::AudioParameters(::media::AudioParameters::AUDIO_PCM_LINEAR, - {channel_layout, config.channel_number}, - config.samples_per_second, - kDefaultFramesPerBuffer), - is_encrypted); -} - -bool AudioDecoderAndroid::SetVolume(float multiplier) { - LOG(INFO) << __func__ << ": multiplier=" << multiplier; - TRACE_FUNCTION_ENTRY1(multiplier); - DCHECK(task_runner_->BelongsToCurrentThread()); - volume_multiplier_ = multiplier; - if (sink_) - sink_->SetStreamVolumeMultiplier(volume_multiplier_); - return true; -} - -AudioDecoderAndroid::RenderingDelay AudioDecoderAndroid::GetRenderingDelay() { - TRACE_FUNCTION_ENTRY0(); - if (!sink_) { - return AudioDecoderAndroid::RenderingDelay(); - } - AudioDecoderAndroid::RenderingDelay delay = sink_->GetRenderingDelay(); - if (delay.timestamp_microseconds != kInvalidTimestamp) { - double usec_per_sample = 1000000.0 / config_.samples_per_second; - - // Account for data that has been queued in the rate shifters. - for (const RateShifterInfo& info : rate_shifter_info_) { - double queued_output_frames = - (info.input_frames / info.rate) - info.output_frames; - delay.delay_microseconds += queued_output_frames * usec_per_sample; - } - - // Account for data that is in the process of being pushed to the sink. - if (pending_output_frames_ != kNoPendingOutput) { - delay.delay_microseconds += pending_output_frames_ * usec_per_sample; - } - } - - DVLOG(2) << __func__ << ":" - << " delay=" << delay.delay_microseconds - << " ts=" << delay.timestamp_microseconds; - - return delay; -} - -AudioDecoderAndroid::AudioTrackTimestamp -AudioDecoderAndroid::GetAudioTrackTimestamp() { - TRACE_FUNCTION_ENTRY0(); - return (sink_ ? sink_->GetAudioTrackTimestamp() - : AudioDecoderAndroid::AudioTrackTimestamp()); -} - -int AudioDecoderAndroid::GetStartThresholdInFrames() { - TRACE_FUNCTION_ENTRY0(); - return (sink_ ? sink_->GetStartThresholdInFrames() : 0); -} - -void AudioDecoderAndroid::OnBufferDecoded( - uint64_t input_bytes, - CastAudioDecoder::Status status, - const AudioConfig& config, - scoped_refptr decoded) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(!got_eos_); - DCHECK(!pending_buffer_complete_); - DCHECK(rate_shifter_); - - if (decoded->end_of_stream()) { - DVLOG(3) << __func__ << ": EOS"; - } else { - DVLOG(3) << __func__ << ":" - << " input_bytes=" << input_bytes - << " decoded.size=" << decoded->data_size(); - } - - if (status == CastAudioDecoder::Status::kDecodeError) { - LOG(ERROR) << "Decode error"; - delegate_->OnPushBufferComplete(MediaPipelineBackendAndroid::kBufferFailed); - return; - } - if (sink_error_) { - delegate_->OnPushBufferComplete(MediaPipelineBackendAndroid::kBufferFailed); - return; - } - if (!IsValidChannelNumber(config.channel_number)) { - LOG(ERROR) << "Channel number changes to be invalid."; - delegate_->OnPushBufferComplete(MediaPipelineBackendAndroid::kBufferFailed); - return; - } - - Statistics delta; - delta.decoded_bytes = input_bytes; - UpdateStatistics(delta); - - bool changed_config = false; - if (config.samples_per_second != config_.samples_per_second) { - LOG(INFO) << "Input sample rate changed from " << config_.samples_per_second - << " to " << config.samples_per_second; - config_.samples_per_second = config.samples_per_second; - changed_config = true; - } - if (config.channel_number != config_.channel_number) { - LOG(INFO) << "Input channel count changed from " << config_.channel_number - << " to " << config.channel_number; - config_.channel_number = config.channel_number; - changed_config = true; - } - if (changed_config) { - // Config from actual stream doesn't match supposed config from the - // container. Update the sink and rate shifter. Note that for now we - // assume that this can only happen at start of stream (ie, on the first - // decoded buffer). - CreateRateShifter(config_); - if (!ResetSinkForNewConfig(config_)) { - OnSinkError(SinkError::kInternalError); - return; - } - } - - pending_buffer_complete_ = true; - if (decoded->end_of_stream()) { - got_eos_ = true; - LOG(INFO) << __func__ << ": decoded buffer marked EOS"; - } else { - int64_t input_frames = - decoded->data_size() / (config_.channel_number * sizeof(float)); - - DCHECK(!rate_shifter_info_.empty()); - - // If not AudioChannel::kAll, wipe all other channels for stereo sound. - if (backend_->AudioChannel() != AudioChannel::kAll) { - // There is an assumption hardcoded for playout_channel to be left - // or right. Adding a check here in case this changes. - DCHECK(backend_->AudioChannel() == AudioChannel::kLeft || - backend_->AudioChannel() == AudioChannel::kRight); - const int playout_channel = - backend_->AudioChannel() == AudioChannel::kLeft ? 0 : 1; - for (int c = 0; c < config_.channel_number; ++c) { - if (c != playout_channel) { - const size_t channel_size = - decoded->data_size() / config_.channel_number; - std::memcpy(decoded->writable_data() + c * channel_size, - decoded->writable_data() + playout_channel * channel_size, - channel_size); - } - } - } - - RateShifterInfo* rate_info = &rate_shifter_info_.front(); - // Bypass rate shifter if the rate is 1.0, and there are no frames queued - // in the rate shifter. - if (rate_info->rate == 1.0 && rate_shifter_->BufferedFrames() == 0 && - pending_output_frames_ == kNoPendingOutput && - rate_shifter_info_.size() == 1) { - DCHECK_EQ(rate_info->output_frames, rate_info->input_frames); - pending_output_frames_ = input_frames; - if (got_eos_) { - DCHECK(!pushed_eos_); - pushed_eos_ = true; - } - sink_->WritePcm(std::move(decoded)); - return; - } - - // Otherwise, queue data into the rate shifter, and then try to push the - // rate-shifted data. - scoped_refptr<::media::AudioBuffer> buffer = - ::media::AudioBuffer::CreateBuffer( - ::media::kSampleFormatPlanarF32, - DecoderConfigAdapter::ToMediaChannelLayout(config_.channel_layout), - config_.channel_number, config_.samples_per_second, input_frames, - pool_); - buffer->set_timestamp(base::TimeDelta()); - const int channel_data_size = input_frames * sizeof(float); - for (int c = 0; c < config_.channel_number; ++c) { - memcpy(buffer->channel_data()[c], decoded->data() + c * channel_data_size, - channel_data_size); - } - - rate_shifter_->EnqueueBuffer(buffer); - rate_shifter_info_.back().input_frames += input_frames; - } - - PushRateShifted(); - DCHECK(!rate_shifter_info_.empty()); - CheckBufferComplete(); -} - -void AudioDecoderAndroid::CheckBufferComplete() { - DVLOG(3) << __func__ - << ": pending_buffer_complete_=" << pending_buffer_complete_; - - if (!pending_buffer_complete_) { - return; - } - - bool rate_shifter_queue_full = rate_shifter_->IsQueueFull(); - DCHECK(!rate_shifter_info_.empty()); - if (rate_shifter_info_.front().rate == 1.0) { - // If the current rate is 1.0, drain any data in the rate shifter before - // calling PushBufferComplete, so that the next PushBuffer call can skip the - // rate shifter entirely. - rate_shifter_queue_full = (rate_shifter_->BufferedFrames() > 0 || - pending_output_frames_ != kNoPendingOutput); - } - - if (pushed_eos_ || !rate_shifter_queue_full) { - pending_buffer_complete_ = false; - delegate_->OnPushBufferComplete( - MediaPipelineBackendAndroid::kBufferSuccess); - } -} - -void AudioDecoderAndroid::PushRateShifted() { - DVLOG(3) << __func__ << ":" - << " pushed_eos_=" << pushed_eos_ - << " pending_output_frames_=" << pending_output_frames_ - << " got_eos_=" << got_eos_; - - DCHECK(sink_); - - if (pushed_eos_ || pending_output_frames_ != kNoPendingOutput) { - return; - } - - if (got_eos_) { - // Push some silence into the rate shifter so we can get out any remaining - // rate-shifted data. - rate_shifter_->EnqueueBuffer(::media::AudioBuffer::CreateEmptyBuffer( - DecoderConfigAdapter::ToMediaChannelLayout(config_.channel_layout), - config_.channel_number, config_.samples_per_second, - kSilenceBufferFrames, base::TimeDelta())); - } - - DCHECK(!rate_shifter_info_.empty()); - RateShifterInfo* rate_info = &rate_shifter_info_.front(); - int64_t possible_output_frames = rate_info->input_frames / rate_info->rate; - DCHECK_GE(possible_output_frames, rate_info->output_frames); - - int desired_output_frames = possible_output_frames - rate_info->output_frames; - if (desired_output_frames == 0) { - if (got_eos_) { - DCHECK(!pushed_eos_); - pending_output_frames_ = 0; - pushed_eos_ = true; - - scoped_refptr eos_buffer( - new DecoderBufferAdapter(::media::DecoderBuffer::CreateEOSBuffer())); - DVLOG(3) << __func__ << ": WritePcm(eos_buffer)"; - sink_->WritePcm(eos_buffer); - } - return; - } - // Don't push too many frames at a time. - desired_output_frames = std::min( - desired_output_frames, - config_.samples_per_second * kMaxOutputMs / kMillisecondsPerSecond); - - if (!rate_shifter_output_ || - desired_output_frames > rate_shifter_output_->frames()) { - rate_shifter_output_ = ::media::AudioBus::Create(config_.channel_number, - desired_output_frames); - } - - int out_frames = rate_shifter_->FillBuffer( - rate_shifter_output_.get(), 0, desired_output_frames, rate_info->rate); - if (out_frames <= 0) { - return; - } - - rate_info->output_frames += out_frames; - DCHECK_GE(possible_output_frames, rate_info->output_frames); - - int channel_data_size = out_frames * sizeof(float); - scoped_refptr output_buffer(new DecoderBufferAdapter( - new ::media::DecoderBuffer(channel_data_size * config_.channel_number))); - for (int c = 0; c < config_.channel_number; ++c) { - memcpy(output_buffer->writable_data() + c * channel_data_size, - rate_shifter_output_->channel(c), channel_data_size); - } - pending_output_frames_ = out_frames; - sink_->WritePcm(output_buffer); - - if (rate_shifter_info_.size() > 1 && - rate_info->output_frames == possible_output_frames) { - double remaining_input_frames = - rate_info->input_frames - (rate_info->output_frames * rate_info->rate); - rate_shifter_info_.pop_front(); - - rate_info = &rate_shifter_info_.front(); - LOG(INFO) << "New playback rate in effect: " << rate_info->rate; - rate_info->input_frames += remaining_input_frames; - DCHECK_EQ(0, rate_info->output_frames); - - // If new playback rate is 1.0, clear out 'extra' data in the rate shifter. - // When doing rate shifting, the rate shifter queue holds data after it has - // been logically played; once we switch to passthrough mode (rate == 1.0), - // that old data needs to be cleared out. - if (rate_info->rate == 1.0) { - int extra_frames = rate_shifter_->BufferedFrames() - - static_cast(rate_info->input_frames); - if (extra_frames > 0) { - // Clear out extra buffered data. - std::unique_ptr<::media::AudioBus> dropped = - ::media::AudioBus::Create(config_.channel_number, extra_frames); - int cleared_frames = - rate_shifter_->FillBuffer(dropped.get(), 0, extra_frames, 1.0f); - DCHECK_EQ(extra_frames, cleared_frames); - } - rate_info->input_frames = rate_shifter_->BufferedFrames(); - } - } -} - -bool AudioDecoderAndroid::BypassDecoder() const { - DCHECK(task_runner_->BelongsToCurrentThread()); - // The sink input requires planar float PCM data. - return (config_.codec == kCodecPCM && - config_.sample_format == kSampleFormatPlanarF32); -} - -void AudioDecoderAndroid::OnWritePcmCompletion(BufferStatus status) { - DVLOG(3) << __func__ << ": status=" << status; - - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK_EQ(MediaPipelineBackendAndroid::kBufferSuccess, status); - pending_output_frames_ = kNoPendingOutput; - - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&AudioDecoderAndroid::PushMorePcm, - weak_factory_.GetWeakPtr())); -} - -void AudioDecoderAndroid::PushMorePcm() { - DVLOG(3) << __func__ << ":"; - - PushRateShifted(); - - DCHECK(!rate_shifter_info_.empty()); - CheckBufferComplete(); - - if (pushed_eos_) { - LOG(INFO) << __func__ << ": OnEndOfStream()"; - delegate_->OnEndOfStream(); - } -} - -void AudioDecoderAndroid::OnSinkError(SinkError error) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); - if (error != SinkError::kInputIgnored) - LOG(ERROR) << "Sink error occurred."; - sink_error_ = true; - delegate_->OnDecoderError(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_decoder_android.h chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_decoder_android.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_decoder_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_decoder_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,132 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_DECODER_ANDROID_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_DECODER_ANDROID_H_ - -#include - -#include "base/containers/circular_deque.h" -#include "base/functional/bind.h" -#include "chromecast/media/api/cast_audio_decoder.h" -#include "chromecast/media/cma/backend/android/audio_sink_android.h" -#include "chromecast/media/cma/backend/android/audio_sink_manager.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "media/base/audio_buffer.h" -#include "media/base/media_util.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace media { -class AudioBus; -class AudioRendererAlgorithm; -} // namespace media - -namespace chromecast { -namespace media { -class DecoderBufferBase; -class MediaPipelineBackendAndroid; - -// TODO(ckuiper): This class is very similar to AudioDecoderAlsa -// (alsa/audio_decoder_alsa.h) and should be consolidated into one shared -// class/file. -class AudioDecoderAndroid : public MediaPipelineBackend::AudioDecoder, - public AudioSinkAndroid::Delegate { - public: - using BufferStatus = MediaPipelineBackend::BufferStatus; - - AudioDecoderAndroid(MediaPipelineBackendAndroid* backend, bool is_apk_audio); - - AudioDecoderAndroid(const AudioDecoderAndroid&) = delete; - AudioDecoderAndroid& operator=(const AudioDecoderAndroid&) = delete; - - ~AudioDecoderAndroid() override; - - void Initialize(); - bool Start(int64_t start_pts); - void Stop(); - bool Pause(); - bool Resume(); - bool SetPlaybackRate(float rate); - - int64_t current_pts() const { return current_pts_; } - - // MediaPipelineBackend::AudioDecoder implementation: - void SetDelegate(MediaPipelineBackend::Decoder::Delegate* delegate) override; - BufferStatus PushBuffer(CastDecoderBuffer* buffer) override; - void GetStatistics(Statistics* statistics) override; - bool SetConfig(const AudioConfig& config) override; - bool SetVolume(float multiplier) override; - RenderingDelay GetRenderingDelay() override; - AudioTrackTimestamp GetAudioTrackTimestamp() override; - int GetStartThresholdInFrames() override; - - private: - struct RateShifterInfo { - explicit RateShifterInfo(float playback_rate); - - double rate; - double input_frames; - int64_t output_frames; - }; - - // AudioSinkAndroid::Delegate implementation: - void OnWritePcmCompletion(BufferStatus status) override; - void OnSinkError(SinkError error) override; - - void CleanUpPcm(); - bool ResetSinkForNewConfig(const AudioConfig& config) ABSL_MUST_USE_RESULT; - void CreateDecoder(); - void CreateRateShifter(const AudioConfig& config); - void OnBufferDecoded(uint64_t input_bytes, - CastAudioDecoder::Status status, - const AudioConfig& config, - scoped_refptr decoded); - void CheckBufferComplete(); - void PushRateShifted(); - void PushMorePcm(); - void RunEos(); - bool BypassDecoder() const; - bool ShouldStartClock() const; - void UpdateStatistics(Statistics delta); - - MediaPipelineBackendAndroid* const backend_; - const bool is_apk_audio_; - const scoped_refptr task_runner_; - MediaPipelineBackend::Decoder::Delegate* delegate_; - - Statistics stats_; - - bool pending_buffer_complete_; - bool got_eos_; - bool pushed_eos_; - bool sink_error_; - - AudioConfig config_; - std::unique_ptr decoder_; - - std::unique_ptr<::media::AudioRendererAlgorithm> rate_shifter_; - ::media::NullMediaLog media_log_; - base::circular_deque rate_shifter_info_; - std::unique_ptr<::media::AudioBus> rate_shifter_output_; - - int64_t current_pts_; - - ManagedAudioSink sink_; - int64_t pending_output_frames_; - float volume_multiplier_; - - scoped_refptr<::media::AudioBufferMemoryPool> pool_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_DECODER_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_android.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/android/audio_sink_android.h" - -#include "base/logging.h" -#include "chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h" -#include "chromecast/media/cma/backend/android/audio_sink_manager.h" - -namespace chromecast { -namespace media { - -// static -int64_t AudioSinkAndroid::GetMinimumBufferedTime(const AudioConfig& config) { - return AudioSinkAndroidAudioTrackImpl::GetMinimumBufferedTime( - config.channel_number, config.samples_per_second); -} - -ManagedAudioSink::ManagedAudioSink() : sink_(nullptr) {} - -ManagedAudioSink::~ManagedAudioSink() { - Remove(); -} - -void ManagedAudioSink::Reset() { - Remove(); -} - -bool ManagedAudioSink::Create(Delegate* delegate, - int num_channels, - int samples_per_second, - int audio_track_session_id, - bool primary, - bool is_apk_audio, - bool use_hw_av_sync, - const std::string& device_id, - AudioContentType content_type) { - Remove(); - auto impl = std::make_unique( - delegate, num_channels, samples_per_second, primary, use_hw_av_sync, - device_id, content_type); - if (!impl->Initialize(audio_track_session_id, is_apk_audio)) { - LOG(ERROR) << "Failed to initialize AudioTrack sink"; - return false; - } - - sink_ = impl.release(); - AudioSinkManager::Get()->Add(sink_); - return true; -} - -void ManagedAudioSink::Remove() { - if (sink_) { - AudioSinkManager::Get()->Remove(sink_); - delete sink_; - sink_ = nullptr; - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_android.h chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,141 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_ANDROID_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_ANDROID_H_ - -#include -#include - -#include "base/memory/ref_counted.h" -#include "base/threading/thread_checker.h" -#include "chromecast/media/cma/backend/android/media_pipeline_backend_android.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -const int kDefaultSlewTimeMs = 15; - -class DecoderBufferBase; - -// Input handle to the sink. All methods (including constructor and destructor) -// must be called on the same thread. -class AudioSinkAndroid { - public: - enum class SinkError { - // This input is being ignored due to a sample rate changed. - kInputIgnored, - // An internal sink error occurred. The input is no longer usable. - kInternalError, - }; - - class Delegate { - public: - using SinkError = AudioSinkAndroid::SinkError; - - // Called when the last data passed to WritePcm() has been successfully - // added to the queue. - virtual void OnWritePcmCompletion( - MediaPipelineBackendAndroid::BufferStatus status) = 0; - - // Called when a sink error occurs. No further data should be written. - virtual void OnSinkError(SinkError error) = 0; - - protected: - virtual ~Delegate() {} - }; - - static int64_t GetMinimumBufferedTime(const AudioConfig& config); - - AudioSinkAndroid() {} - virtual ~AudioSinkAndroid() {} - - // Writes some PCM data to the sink. |data| must be in planar float format. - // Once the data has been written, the delegate's OnWritePcmCompletion() - // method will be called on the same thread that the AudioSinkAndroid was - // created on. Note that no further calls to WritePcm() should be made until - // OnWritePcmCompletion() has been called. - virtual void WritePcm(scoped_refptr data) = 0; - - // Pauses/unpauses this input. - virtual void SetPaused(bool paused) = 0; - - // Sets the stream volume multiplier for this input. If |multiplier| is - // outside the range [0.0, 1.0], it is clamped to that range. - // The stream volume is not set by the volume controller but rather by the - // Cast app as an additional volume control on top of Android's. - virtual void SetStreamVolumeMultiplier(float multiplier) = 0; - - // Sets the limiter multiplier for this input. If |multiplier| is outside the - // range [0.0, 1.0], it is clamped to that range. - // The limiter is used by the volume controller to achieve ducking. - virtual void SetLimiterVolumeMultiplier(float multiplier) = 0; - - // Returns the volume multiplier of the stream, typically the product of - // stream multiplier and limiter multiplier. - virtual float EffectiveVolume() const = 0; - - // Returns the current audio rendering delay. - virtual MediaPipelineBackendAndroid::RenderingDelay GetRenderingDelay() = 0; - - // Returns the current audio track timestamp. - virtual MediaPipelineBackendAndroid::AudioTrackTimestamp - GetAudioTrackTimestamp() = 0; - - // Returns the streaming start threshold of the current audio track. - virtual int GetStartThresholdInFrames() = 0; - - // Getters - virtual int input_samples_per_second() const = 0; - virtual bool primary() const = 0; - virtual std::string device_id() const = 0; - virtual AudioContentType content_type() const = 0; -}; - -// Implementation of "managed" AudioSinkAndroid* object that is -// automatically added to the Sink Manager when created and removed when -// destroyed. Inspired by std::unique_ptr<>. -class ManagedAudioSink { - public: - using Delegate = AudioSinkAndroid::Delegate; - - ManagedAudioSink(); - - ManagedAudioSink(const ManagedAudioSink&) = delete; - ManagedAudioSink& operator=(const ManagedAudioSink&) = delete; - - ~ManagedAudioSink(); - - // Resets the sink_ object by removing it from the manager and deleting it. - void Reset(); - - // Creates a new sink_ object of AudioSinkAndroid* instance and adds it to - // the manager. If a valid instance existed on entry it is removed from the - // manager and deleted before creating the new one. - // Returns true on success; false otherwise. - bool Create(Delegate* delegate, - int num_channels, - int samples_per_second, - int audio_track_session_id, - bool primary, - bool is_apk_audio, - bool use_hw_av_sync, - const std::string& device_id, - AudioContentType content_type) ABSL_MUST_USE_RESULT; - - AudioSinkAndroid* operator->() const { return sink_; } - operator AudioSinkAndroid*() const { return sink_; } - - private: - void Remove(); - - AudioSinkAndroid* sink_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,453 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h" - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "media/base/audio_bus.h" - -// Must come after all headers that specialize FromJniType() / ToJniType(). -#include "chromecast/media/cma/backend/android/audio_track_jni_headers/AudioSinkAudioTrackImpl_jni.h" - -#define RUN_ON_FEEDER_THREAD(callback, ...) \ - if (!feeder_task_runner_->BelongsToCurrentThread()) { \ - POST_TASK_TO_FEEDER_THREAD(&AudioSinkAndroidAudioTrackImpl::callback, \ - ##__VA_ARGS__); \ - return; \ - } - -#define POST_TASK_TO_FEEDER_THREAD(task, ...) \ - feeder_task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(task, base::Unretained(this), ##__VA_ARGS__)); - -#define RUN_ON_CALLER_THREAD(callback, ...) \ - if (!caller_task_runner_->BelongsToCurrentThread()) { \ - POST_TASK_TO_CALLER_THREAD(&AudioSinkAndroidAudioTrackImpl::callback, \ - ##__VA_ARGS__); \ - return; \ - } - -#define POST_TASK_TO_CALLER_THREAD(task, ...) \ - caller_task_runner_->PostTask( \ - FROM_HERE, \ - base::BindOnce(task, weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); - -using base::android::JavaParamRef; - -namespace chromecast { -namespace media { - -// static -int64_t AudioSinkAndroidAudioTrackImpl::GetMinimumBufferedTime( - int num_channels, - int samples_per_second) { - return Java_AudioSinkAudioTrackImpl_getMinimumBufferedTime( - base::android::AttachCurrentThread(), num_channels, samples_per_second); -} - -AudioSinkAndroidAudioTrackImpl::AudioSinkAndroidAudioTrackImpl( - AudioSinkAndroid::Delegate* delegate, - int num_channels, - int input_samples_per_second, - bool primary, - bool use_hw_av_sync, - const std::string& device_id, - AudioContentType content_type) - : delegate_(delegate), - num_channels_(num_channels), - input_samples_per_second_(input_samples_per_second), - primary_(primary), - use_hw_av_sync_(use_hw_av_sync), - device_id_(device_id), - content_type_(content_type), - stream_volume_multiplier_(1.0f), - limiter_volume_multiplier_(1.0f), - direct_pcm_buffer_address_(nullptr), - direct_rendering_delay_address_(nullptr), - feeder_thread_("AudioTrack feeder thread"), - feeder_task_runner_(nullptr), - caller_task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()), - state_(kStateUninitialized) { - LOG(INFO) << __func__ << "(" << this << "):" - << " num_channels_=" << num_channels_ - << " input_samples_per_second_=" << input_samples_per_second_ - << " primary_=" << primary_ - << " use_hw_av_sync_=" << use_hw_av_sync_ - << " device_id_=" << device_id_ - << " content_type_=" << content_type_; - DCHECK(delegate_); - DCHECK_GT(num_channels_, 0); - DCHECK_GT(input_samples_per_second_, 0); - - base::Thread::Options options; - options.thread_type = base::ThreadType::kRealtimeAudio; - feeder_thread_.StartWithOptions(std::move(options)); - feeder_task_runner_ = feeder_thread_.task_runner(); -} - -AudioSinkAndroidAudioTrackImpl::~AudioSinkAndroidAudioTrackImpl() { - LOG(INFO) << __func__ << "(" << this << "): device_id_=" << device_id_; - PreventDelegateCalls(); - FinalizeOnFeederThread(); - feeder_thread_.Stop(); - feeder_task_runner_ = nullptr; -} - -bool AudioSinkAndroidAudioTrackImpl::Initialize(int audio_track_session_id, - bool is_apk_audio) { - j_audio_sink_audiotrack_impl_ = Java_AudioSinkAudioTrackImpl_create( - base::android::AttachCurrentThread(), reinterpret_cast(this), - static_cast(content_type_), num_channels_, input_samples_per_second_, - kDirectBufferSize, audio_track_session_id, is_apk_audio, use_hw_av_sync_); - if (!j_audio_sink_audiotrack_impl_) { - return false; - } - - // Below arguments are initialized from AudioSinkAudioTrackImpl Java class by - // calling into native APIs of this class. - DCHECK(direct_pcm_buffer_address_); - DCHECK(direct_rendering_delay_address_); - - LOG(INFO) << __func__ << "(" << this << "):" - << " audio_track_session_id=" << audio_track_session_id; - return true; -} - -int AudioSinkAndroidAudioTrackImpl::input_samples_per_second() const { - return input_samples_per_second_; -} - -bool AudioSinkAndroidAudioTrackImpl::primary() const { - return primary_; -} - -std::string AudioSinkAndroidAudioTrackImpl::device_id() const { - return device_id_; -} - -AudioContentType AudioSinkAndroidAudioTrackImpl::content_type() const { - return content_type_; -} - -MediaPipelineBackendAndroid::RenderingDelay -AudioSinkAndroidAudioTrackImpl::GetRenderingDelay() { - DVLOG(3) << __func__ << "(" << this << "): " - << " delay=" << sink_rendering_delay_.delay_microseconds - << " ts=" << sink_rendering_delay_.timestamp_microseconds; - return sink_rendering_delay_; -} - -MediaPipelineBackendAndroid::AudioTrackTimestamp -AudioSinkAndroidAudioTrackImpl::GetAudioTrackTimestamp() { - // TODO(ziyangch): Add a rate limiter to avoid calling AudioTrack.getTimestamp - // too frequent. - Java_AudioSinkAudioTrackImpl_getAudioTrackTimestamp( - base::android::AttachCurrentThread(), j_audio_sink_audiotrack_impl_); - return MediaPipelineBackendAndroid::AudioTrackTimestamp( - direct_audio_track_timestamp_address_[0], - direct_audio_track_timestamp_address_[1], - direct_audio_track_timestamp_address_[2]); -} - -int AudioSinkAndroidAudioTrackImpl::GetStartThresholdInFrames() { - return Java_AudioSinkAudioTrackImpl_getStartThresholdInFrames( - base::android::AttachCurrentThread(), j_audio_sink_audiotrack_impl_); -} - -void AudioSinkAndroidAudioTrackImpl::FinalizeOnFeederThread() { - RUN_ON_FEEDER_THREAD(FinalizeOnFeederThread); - wait_for_eos_task_.Cancel(); - - if (j_audio_sink_audiotrack_impl_) { - Java_AudioSinkAudioTrackImpl_close(base::android::AttachCurrentThread(), - j_audio_sink_audiotrack_impl_); - } -} - -void AudioSinkAndroidAudioTrackImpl::PreventDelegateCalls() { - DCHECK(caller_task_runner_->BelongsToCurrentThread()); - weak_factory_.InvalidateWeakPtrs(); -} - -void AudioSinkAndroidAudioTrackImpl::CacheDirectBufferAddress( - JNIEnv* env, - const JavaParamRef& obj, - const JavaParamRef& pcm_byte_buffer, - const JavaParamRef& rendering_delay_byte_buffer, - const JavaParamRef& audio_track_timestamp_byte_buffer) { - direct_pcm_buffer_address_ = - static_cast(env->GetDirectBufferAddress(pcm_byte_buffer)); - direct_rendering_delay_address_ = static_cast( - env->GetDirectBufferAddress(rendering_delay_byte_buffer)); - direct_audio_track_timestamp_address_ = static_cast( - env->GetDirectBufferAddress(audio_track_timestamp_byte_buffer)); -} - -void AudioSinkAndroidAudioTrackImpl::WritePcm( - scoped_refptr data) { - DCHECK(caller_task_runner_->BelongsToCurrentThread()); - DCHECK(!pending_data_); - pending_data_ = std::move(data); - pending_data_bytes_already_fed_ = 0; - FeedData(); -} - -void AudioSinkAndroidAudioTrackImpl::FeedData() { - RUN_ON_FEEDER_THREAD(FeedData); - - DCHECK(pending_data_); - if (pending_data_->end_of_stream()) { - state_ = kStateGotEos; - ScheduleWaitForEosTask(); - return; - } - - if (pending_data_->data_size() == 0) { - LOG(INFO) << __func__ << "(" << this << "): empty data buffer!"; - PostPcmCallback(); - return; - } - - pending_data_bytes_after_reformat_ = ReformatData(); - DVLOG(3) << __func__ << "(" << this << "):" - << " [" << pending_data_bytes_after_reformat_ << "]" - << " @ts=" << pending_data_->timestamp(); - - int written = Java_AudioSinkAudioTrackImpl_writePcm( - base::android::AttachCurrentThread(), j_audio_sink_audiotrack_impl_, - pending_data_bytes_after_reformat_, - (pending_data_->timestamp() == INT64_MIN) - ? pending_data_->timestamp() - : pending_data_->timestamp() * - base::Time::kNanosecondsPerMicrosecond); - - if (written < 0) { - LOG(ERROR) << __func__ << "(" << this << "): Cannot write PCM via JNI!"; - SignalError(AudioSinkAndroid::SinkError::kInternalError); - return; - } - - if (state_ == kStatePaused && written < pending_data_bytes_after_reformat_) { - LOG(INFO) << "Audio Server is full while in PAUSED, " - << "will continue when entering PLAY mode."; - pending_data_bytes_already_fed_ = written; - return; - } - - if (written != pending_data_bytes_after_reformat_) { - LOG(ERROR) << __func__ << "(" << this << "): Wrote " << written - << " instead of " << pending_data_bytes_after_reformat_; - // continue anyway, better to do a best-effort than fail completely - } - - // RenderingDelay was returned through JNI via direct buffers. - sink_rendering_delay_.delay_microseconds = direct_rendering_delay_address_[0]; - sink_rendering_delay_.timestamp_microseconds = - direct_rendering_delay_address_[1]; - - TrackRawMonotonicClockDeviation(); - - PostPcmCallback(); -} - -void AudioSinkAndroidAudioTrackImpl::ScheduleWaitForEosTask() { - DCHECK(wait_for_eos_task_.IsCancelled()); - DCHECK(state_ == kStateGotEos); - DCHECK(feeder_task_runner_->BelongsToCurrentThread()); - - int64_t playout_time_left_us = - Java_AudioSinkAudioTrackImpl_prepareForShutdown( - base::android::AttachCurrentThread(), j_audio_sink_audiotrack_impl_); - LOG(INFO) << __func__ << "(" << this << "): Hit EOS, playout time left is " - << playout_time_left_us << "us"; - wait_for_eos_task_.Reset(base::BindOnce( - &AudioSinkAndroidAudioTrackImpl::OnPlayoutDone, base::Unretained(this))); - base::TimeDelta delay = base::Microseconds(playout_time_left_us); - feeder_task_runner_->PostDelayedTask(FROM_HERE, wait_for_eos_task_.callback(), - delay); -} - -void AudioSinkAndroidAudioTrackImpl::OnPlayoutDone() { - DCHECK(feeder_task_runner_->BelongsToCurrentThread()); - DCHECK(state_ == kStateGotEos); - PostPcmCallback(); -} - -int AudioSinkAndroidAudioTrackImpl::ReformatData() { - // Data is in planar float format, i.e., planar audio data for stereo is all - // left samples first, then all right -> "LLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRR"). - // AudioTrack needs interleaved format -> "LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLR"). - DCHECK(direct_pcm_buffer_address_); - DCHECK_EQ(0, static_cast(pending_data_->data_size() % sizeof(float))); - CHECK_LT(static_cast(pending_data_->data_size()), kDirectBufferSize); - int num_of_samples = pending_data_->data_size() / sizeof(float); - int num_of_frames = num_of_samples / num_channels_; - std::vector src(num_channels_); - for (int c = 0; c < num_channels_; c++) { - src[c] = reinterpret_cast(pending_data_->data()) + - c * num_of_frames; - } - if (use_hw_av_sync_) { - // Convert audio data from float to int16_t since hardware av sync audio - // track requires ENCODING_PCM_16BIT audio format. - int16_t* dst = reinterpret_cast(direct_pcm_buffer_address_); - for (int f = 0; f < num_of_frames; f++) { - for (int c = 0; c < num_channels_; c++) { - *dst++ = *src[c]++; - } - } - return static_cast(pending_data_->data_size()) / - (sizeof(float) / sizeof(int16_t)); - } else { - float* dst = reinterpret_cast(direct_pcm_buffer_address_); - for (int f = 0; f < num_of_frames; f++) { - for (int c = 0; c < num_channels_; c++) { - *dst++ = *src[c]++; - } - } - return static_cast(pending_data_->data_size()); - } -} - -void AudioSinkAndroidAudioTrackImpl::TrackRawMonotonicClockDeviation() { - timespec now = {0, 0}; - clock_gettime(CLOCK_MONOTONIC, &now); - int64_t now_usec = base::TimeDelta::FromTimeSpec(now).InMicroseconds(); - - clock_gettime(CLOCK_MONOTONIC_RAW, &now); - int64_t now_raw_usec = base::TimeDelta::FromTimeSpec(now).InMicroseconds(); - - // TODO(ckuiper): Eventually we want to use this to convert from non-RAW to - // RAW timestamps to improve accuracy. - DVLOG(3) << __func__ << "(" << this << "):" - << " now - now_raw=" << (now_usec - now_raw_usec); -} - -void AudioSinkAndroidAudioTrackImpl::FeedDataContinue() { - RUN_ON_FEEDER_THREAD(FeedDataContinue); - - DCHECK(pending_data_); - DCHECK(pending_data_bytes_already_fed_); - - int left_to_send = - pending_data_bytes_after_reformat_ - pending_data_bytes_already_fed_; - LOG(INFO) << __func__ << "(" << this << "): send remaining " << left_to_send - << "/" << pending_data_bytes_after_reformat_; - - memmove(direct_pcm_buffer_address_, - direct_pcm_buffer_address_ + pending_data_bytes_already_fed_, - left_to_send); - - int bytes_per_frame = - num_channels_ * (use_hw_av_sync_ ? sizeof(int16_t) : sizeof(float)); - int64_t fed_frames = pending_data_bytes_already_fed_ / bytes_per_frame; - int64_t timestamp_ns_new = - (pending_data_->timestamp() == INT64_MIN) - ? pending_data_->timestamp() - : pending_data_->timestamp() * - base::Time::kNanosecondsPerMicrosecond + - fed_frames * base::Time::kNanosecondsPerSecond / - input_samples_per_second_; - int written = Java_AudioSinkAudioTrackImpl_writePcm( - base::android::AttachCurrentThread(), j_audio_sink_audiotrack_impl_, - left_to_send, timestamp_ns_new); - - DCHECK(written == left_to_send); - - // RenderingDelay was returned through JNI via direct buffers. - sink_rendering_delay_.delay_microseconds = direct_rendering_delay_address_[0]; - sink_rendering_delay_.timestamp_microseconds = - direct_rendering_delay_address_[1]; - - TrackRawMonotonicClockDeviation(); - - PostPcmCallback(); -} - -void AudioSinkAndroidAudioTrackImpl::PostPcmCallback() { - RUN_ON_CALLER_THREAD(PostPcmCallback); - DCHECK(pending_data_); - pending_data_ = nullptr; - pending_data_bytes_already_fed_ = 0; - delegate_->OnWritePcmCompletion(MediaPipelineBackendAndroid::kBufferSuccess); -} - -void AudioSinkAndroidAudioTrackImpl::SignalError( - AudioSinkAndroid::SinkError error) { - DCHECK(feeder_task_runner_->BelongsToCurrentThread()); - state_ = kStateError; - PostError(error); -} - -void AudioSinkAndroidAudioTrackImpl::PostError( - AudioSinkAndroid::SinkError error) { - RUN_ON_CALLER_THREAD(PostError, error); - delegate_->OnSinkError(error); -} - -void AudioSinkAndroidAudioTrackImpl::SetPaused(bool paused) { - RUN_ON_FEEDER_THREAD(SetPaused, paused); - - if (paused) { - LOG(INFO) << __func__ << "(" << this << "): Pausing"; - state_ = kStatePaused; - Java_AudioSinkAudioTrackImpl_pause(base::android::AttachCurrentThread(), - j_audio_sink_audiotrack_impl_); - } else { - LOG(INFO) << __func__ << "(" << this << "): Unpausing"; - sink_rendering_delay_ = MediaPipelineBackendAndroid::RenderingDelay(); - state_ = kStateNormalPlayback; - Java_AudioSinkAudioTrackImpl_play(base::android::AttachCurrentThread(), - j_audio_sink_audiotrack_impl_); - if (pending_data_ && pending_data_bytes_already_fed_) { - // The last data buffer was partially fed, complete it now. - FeedDataContinue(); - } - } -} - -void AudioSinkAndroidAudioTrackImpl::UpdateVolume() { - DCHECK(feeder_task_runner_->BelongsToCurrentThread()); - Java_AudioSinkAudioTrackImpl_setVolume(base::android::AttachCurrentThread(), - j_audio_sink_audiotrack_impl_, - EffectiveVolume()); -} - -void AudioSinkAndroidAudioTrackImpl::SetStreamVolumeMultiplier( - float multiplier) { - RUN_ON_FEEDER_THREAD(SetStreamVolumeMultiplier, multiplier); - - stream_volume_multiplier_ = std::max(0.0f, multiplier); - LOG(INFO) << __func__ << "(" << this << "): device_id_=" << device_id_ - << " stream_multiplier=" << stream_volume_multiplier_ - << " effective=" << EffectiveVolume(); - UpdateVolume(); -} - -void AudioSinkAndroidAudioTrackImpl::SetLimiterVolumeMultiplier( - float multiplier) { - RUN_ON_FEEDER_THREAD(SetLimiterVolumeMultiplier, multiplier); - - limiter_volume_multiplier_ = std::clamp(multiplier, 0.0f, 1.0f); - LOG(INFO) << __func__ << "(" << this << "): device_id_=" << device_id_ - << " limiter_multiplier=" << limiter_volume_multiplier_ - << " effective=" << EffectiveVolume(); - UpdateVolume(); -} - -float AudioSinkAndroidAudioTrackImpl::EffectiveVolume() const { - return stream_volume_multiplier_ * limiter_volume_multiplier_; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,175 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_ANDROID_AUDIOTRACK_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_ANDROID_AUDIOTRACK_IMPL_H_ - -#include - -#include -#include - -#include "base/android/jni_android.h" -#include "base/cancelable_callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread.h" -#include "base/time/time.h" -#include "chromecast/media/cma/backend/android/audio_sink_android.h" -#include "chromecast/media/cma/backend/android/media_pipeline_backend_android.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -namespace media { - -class AudioSinkAndroidAudioTrackImpl : public AudioSinkAndroid { - public: - enum State { - kStateUninitialized, // No data has been queued yet. - kStateNormalPlayback, // Normal playback. - kStatePaused, // Currently paused. - kStateGotEos, // Got the end-of-stream buffer (normal playback). - kStateError, // A sink error occurred, this is unusable now. - }; - - // TODO(ckuiper): There doesn't seem to be a maximum size for the buffers - // sent through the media pipeline, so we need to add code to break up a - // buffer larger than this size and feed it in in smaller chunks. - static const int kDirectBufferSize = 512 * 1024; - - static int64_t GetMinimumBufferedTime(int num_channels, - int samples_per_second); - - AudioSinkAndroidAudioTrackImpl(AudioSinkAndroid::Delegate* delegate, - int num_channels, - int input_samples_per_second, - bool primary, - bool use_hw_av_sync, - const std::string& device_id, - AudioContentType content_type); - - AudioSinkAndroidAudioTrackImpl(const AudioSinkAndroidAudioTrackImpl&) = - delete; - AudioSinkAndroidAudioTrackImpl& operator=( - const AudioSinkAndroidAudioTrackImpl&) = delete; - - ~AudioSinkAndroidAudioTrackImpl() override; - - // Initializes the audio track. - bool Initialize(int audio_track_session_id, bool is_apk_audio); - - // Called from Java so that we can cache the addresses of the Java-managed - // byte_buffers. - void CacheDirectBufferAddress( - JNIEnv* env, - const base::android::JavaParamRef& obj, - const base::android::JavaParamRef& pcm_byte_buffer, - const base::android::JavaParamRef& rendering_delay_byte_buffer, - const base::android::JavaParamRef& - audio_track_timestamp_byte_buffer); - - // AudioSinkAndroid implementation: - void WritePcm(scoped_refptr data) override; - void SetPaused(bool paused) override; - void SetStreamVolumeMultiplier(float multiplier) override; - void SetLimiterVolumeMultiplier(float multiplier) override; - float EffectiveVolume() const override; - MediaPipelineBackendAndroid::RenderingDelay GetRenderingDelay() override; - MediaPipelineBackendAndroid::AudioTrackTimestamp GetAudioTrackTimestamp() - override; - int GetStartThresholdInFrames() override; - - // Getters - int input_samples_per_second() const override; - bool primary() const override; - std::string device_id() const override; - AudioContentType content_type() const override; - - // Prevents any further calls to the delegate (ie, called when the delegate - // is being destroyed). - void PreventDelegateCalls(); - - State state() const { return state_; } - - private: - void FinalizeOnFeederThread(); - - void FeedData(); - void FeedDataContinue(); - - void ScheduleWaitForEosTask(); - void OnPlayoutDone(); - - // Reformats audio data from planar into interleaved for AudioTrack. I.e.: - // "LLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRR" -> "LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLR". - // If using hardware av sync, also convert audio data from float to int16_t. - // Returns the data size after reformatting. - int ReformatData(); - - void TrackRawMonotonicClockDeviation(); - - void PostPcmCallback(); - - void SignalError(AudioSinkAndroid::SinkError error); - void PostError(AudioSinkAndroid::SinkError error); - - void UpdateVolume(); - - // Config parameters provided into c'tor. - Delegate* const delegate_; - const int num_channels_; - const int input_samples_per_second_; - const bool primary_; - const bool use_hw_av_sync_; - const std::string device_id_; - const AudioContentType content_type_; - - float stream_volume_multiplier_; - float limiter_volume_multiplier_; - - // Buffers shared between native and Java space to move data across the JNI. - // We use direct buffers so that the native class can have access to the - // underlying memory address. This avoids the need to copy from a jbyteArray - // to native memory. More discussion of this here: - // http://developer.android.com/training/articles/perf-jni.html Owned by - // j_audio_sink_audiotrack_impl_. - uint8_t* direct_pcm_buffer_address_; // PCM audio data native->java - // rendering delay+timestamp return value, java->native - uint64_t* direct_rendering_delay_address_; - // AudioTrack.getTimestamp return value, java->native - uint64_t* direct_audio_track_timestamp_address_; - - // Java AudioSinkAudioTrackImpl instance. - base::android::ScopedJavaGlobalRef j_audio_sink_audiotrack_impl_; - - // Thread that feeds audio data into the Java instance though JNI, - // potentially blocking. When in Play mode the Java AudioTrack blocks as it - // waits for queue space to become available for the new data. In Pause mode - // it returns immediately once all queue space has been filled up. This case - // is handled separately via FeedDataContinue(). - base::Thread feeder_thread_; - scoped_refptr feeder_task_runner_; - - base::CancelableOnceClosure wait_for_eos_task_; - - const scoped_refptr caller_task_runner_; - - State state_; - - scoped_refptr pending_data_; - int pending_data_bytes_after_reformat_; - int pending_data_bytes_already_fed_; - - MediaPipelineBackendAndroid::RenderingDelay sink_rendering_delay_; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_ANDROID_AUDIOTRACK_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_manager.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_manager.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/android/audio_sink_manager.h" - -#include "base/logging.h" -#include "base/no_destructor.h" -#include "base/ranges/algorithm.h" -#include "chromecast/media/cma/backend/android/audio_sink_android.h" - -namespace chromecast { -namespace media { - -namespace { - -class AudioSinkManagerInstance : public AudioSinkManager { - public: - AudioSinkManagerInstance() {} - - AudioSinkManagerInstance(const AudioSinkManagerInstance&) = delete; - AudioSinkManagerInstance& operator=(const AudioSinkManagerInstance&) = delete; - - ~AudioSinkManagerInstance() override {} -}; - -} // namespace - -// static -AudioSinkManager* AudioSinkManager::Get() { - static base::NoDestructor sink_manager_instance; - return sink_manager_instance.get(); -} - -AudioSinkManager::AudioSinkManager() {} -AudioSinkManager::~AudioSinkManager() {} - -void AudioSinkManager::Add(AudioSinkAndroid* sink) { - DCHECK(sink); - - LOG(INFO) << __func__ << " sink(" << sink << "): id=" << sink->device_id() - << " primary=" << sink->primary() - << " type=" << sink->content_type(); - - base::AutoLock lock(lock_); - UpdateLimiterMultiplier(sink); - sinks_.push_back(sink); -} - -void AudioSinkManager::Remove(AudioSinkAndroid* sink) { - DCHECK(sink); - - LOG(INFO) << __func__ << " sink(" << sink << "): id=" << sink->device_id() - << " type=" << sink->content_type(); - - base::AutoLock lock(lock_); - - auto it = base::ranges::find(sinks_, sink); - if (it == sinks_.end()) { - LOG(WARNING) << __func__ << ": Cannot find sink"; - return; - } - sinks_.erase(it); -} - -void AudioSinkManager::SetTypeVolumeDb(AudioContentType type, float level_db) { - LOG(INFO) << __func__ << ": level_db=" << level_db << " type=" << type; - base::AutoLock lock(lock_); - volume_info_[type].volume_db = level_db; - // Since the type volume changed we need to reflect that in the limiter - // multipliers. - UpdateAllLimiterMultipliers(type); -} - -void AudioSinkManager::SetOutputLimitDb(AudioContentType type, float limit_db) { - LOG(INFO) << __func__ << ": limit_db=" << limit_db << " type=" << type; - base::AutoLock lock(lock_); - volume_info_[type].limit_db = limit_db; - UpdateAllLimiterMultipliers(type); -} - -void AudioSinkManager::UpdateAllLimiterMultipliers(AudioContentType type) { - for (auto* sink : sinks_) { - if (sink->content_type() == type) - UpdateLimiterMultiplier(sink); - } -} - -void AudioSinkManager::UpdateLimiterMultiplier(AudioSinkAndroid* sink) { - AudioContentType type = sink->content_type(); - if (sink->primary()) { - sink->SetLimiterVolumeMultiplier(GetLimiterMultiplier(type)); - } else { - // Volume limits don't apply to effects streams. - sink->SetLimiterVolumeMultiplier(1.0f); - } -} - -float AudioSinkManager::GetLimiterMultiplier(AudioContentType type) { - // Set multiplier so the effective volume is min(level_db, limit_db). - VolumeInfo v = volume_info_[type]; - if (v.volume_db <= v.limit_db) - return 1.0f; - return std::pow(10, (v.limit_db - v.volume_db) / 20); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_manager.h chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_manager.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/audio_sink_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/audio_sink_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_MANAGER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_MANAGER_H_ - -#include -#include - -#include "base/synchronization/lock.h" -#include "chromecast/media/cma/backend/android/audio_sink_android.h" - -namespace chromecast { -namespace media { - -// Implementation of a manager for a group of audio sinks in order to control -// and configure them (currently for volume control). -class AudioSinkManager { - public: - static AudioSinkManager* Get(); - - AudioSinkManager(const AudioSinkManager&) = delete; - AudioSinkManager& operator=(const AudioSinkManager&) = delete; - - // Adds the given sink instance to the vector. - void Add(AudioSinkAndroid* sink); - - // Removes the given sink instance from the vector. - void Remove(AudioSinkAndroid* sink); - - // Sets the type volume level (in dBFS) for the given content |type|. Note - // that this volume is not actually applied to the sink, as the volume - // controller applies it directly in Android OS. Instead the value is just - // stored and used to calculate the proper limiter multiplier. - void SetTypeVolumeDb(AudioContentType type, float level_db); - - // Sets the volume limit (in dBFS) for the given content |type|. - void SetOutputLimitDb(AudioContentType type, float limit_db); - - protected: - AudioSinkManager(); - virtual ~AudioSinkManager(); - - private: - // Contains volume control information for an audio content type. - struct VolumeInfo { - float volume_db = 0.0f; - float limit_db = 1.0f; - }; - - // Updates the limiter multipliers for all sinks of the given type. - void UpdateAllLimiterMultipliers(AudioContentType type); - - // Updates the limiter multiplier for the given sink. - void UpdateLimiterMultiplier(AudioSinkAndroid* sink); - - // Returns the limiter multiplier such that: - // multiplier * volume = min(volume, limit). - float GetLimiterMultiplier(AudioContentType type); - - base::Lock lock_; - - std::map volume_info_; - - std::vector sinks_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_AUDIO_SINK_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/cast_media_android.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/cast_media_android.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/cast_media_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/cast_media_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/at_exit.h" -#include "base/logging.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/media/cma/backend/android/media_pipeline_backend_android.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/video_plane.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { -namespace { - -class DefaultVideoPlane : public VideoPlane { - public: - ~DefaultVideoPlane() override {} - - void SetGeometry(const RectF& display_rect, Transform transform) override {} -}; - -const char* GetContentTypeName(const AudioContentType type) { - switch (type) { - case AudioContentType::kMedia: - return "kMedia"; - case AudioContentType::kAlarm: - return "kAlarm"; - case AudioContentType::kCommunication: - return "kCommunication"; - default: - return "Unknown"; - } -} - -DefaultVideoPlane* g_video_plane = nullptr; - -} // namespace - -void CastMediaShlib::Initialize(const std::vector& argv) { - LOG(INFO) << __func__ << ":"; - - g_video_plane = new DefaultVideoPlane(); -} - -void CastMediaShlib::Finalize() { - LOG(INFO) << __func__; - - delete g_video_plane; - g_video_plane = nullptr; -} - -VideoPlane* CastMediaShlib::GetVideoPlane() { - return g_video_plane; -} - -MediaPipelineBackend* CastMediaShlib::CreateMediaPipelineBackend( - const MediaPipelineDeviceParams& params) { - LOG(INFO) << __func__ << ":" - << " sync_type=" << params.sync_type - << " audio_type=" << params.audio_type - << " content_type=" << GetContentTypeName(params.content_type) - << " device_id=" << params.device_id; - return new MediaPipelineBackendAndroid(params); -} - -double CastMediaShlib::GetMediaClockRate() { - NOTREACHED(); -} - -double CastMediaShlib::MediaClockRatePrecision() { - NOTREACHED(); -} - -void CastMediaShlib::MediaClockRateRange(double* minimum_rate, - double* maximum_rate) { - NOTREACHED(); -} - -bool CastMediaShlib::SetMediaClockRate(double new_rate) { - NOTREACHED(); -} - -bool CastMediaShlib::SupportsMediaClockRateChange() { - LOG(INFO) << __func__ << ":"; - return false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/media_codec_support_cast_audio.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_codec_support_cast_audio.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/media_codec_support_cast_audio.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_codec_support_cast_audio.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/strings/string_util.h" -#include "chromecast/public/media/media_capabilities_shlib.h" - -namespace chromecast { -namespace media { - -// TODO(ckuiper): This file is identical to -// alsa/media_codec_support_cast_audio.cc and should be consolidated. -bool MediaCapabilitiesShlib::IsSupportedVideoConfig(VideoCodec codec, - VideoProfile profile, - int level) { - return (codec == kCodecH264 || codec == kCodecVP8 || codec == kCodecVP9); -} - -bool MediaCapabilitiesShlib::IsSupportedAudioConfig(const AudioConfig& config) { - return config.codec == kCodecAAC || config.codec == kCodecMP3 || - config.codec == kCodecPCM || config.codec == kCodecVorbis; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/media_pipeline_backend_android.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_pipeline_backend_android.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/media_pipeline_backend_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_pipeline_backend_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,134 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/android/media_pipeline_backend_android.h" - -#include - -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/cma/backend/android/audio_decoder_android.h" -#include "chromecast/media/cma/backend/video_decoder_null.h" - -namespace chromecast { -namespace media { - -MediaPipelineBackendAndroid::MediaPipelineBackendAndroid( - const MediaPipelineDeviceParams& params) - : state_(kStateUninitialized), params_(params) { - LOG(INFO) << __func__ << ":"; -} - -MediaPipelineBackendAndroid::~MediaPipelineBackendAndroid() {} - -MediaPipelineBackendAndroid::AudioDecoder* -MediaPipelineBackendAndroid::CreateAudioDecoder() { - LOG(INFO) << __func__ << ":"; - DCHECK_EQ(kStateUninitialized, state_); - if (audio_decoder_) - return nullptr; - audio_decoder_.reset(new AudioDecoderAndroid( - this, params_.sync_type == MediaPipelineDeviceParams::kModeApkSyncPts)); - return audio_decoder_.get(); -} - -MediaPipelineBackendAndroid::VideoDecoder* -MediaPipelineBackendAndroid::CreateVideoDecoder() { - LOG(INFO) << __func__ << ":"; - DCHECK_EQ(kStateUninitialized, state_); - if (video_decoder_) - return nullptr; - video_decoder_.reset(new VideoDecoderNull()); - return video_decoder_.get(); -} - -bool MediaPipelineBackendAndroid::Initialize() { - LOG(INFO) << __func__ << ":"; - DCHECK_EQ(kStateUninitialized, state_); - if (audio_decoder_) - audio_decoder_->Initialize(); - state_ = kStateInitialized; - return true; -} - -bool MediaPipelineBackendAndroid::Start(int64_t start_pts) { - LOG(INFO) << __func__ << ": start_pts=" << start_pts; - DCHECK_EQ(kStateInitialized, state_); - if (audio_decoder_ && !audio_decoder_->Start(start_pts)) - return false; - state_ = kStatePlaying; - return true; -} - -void MediaPipelineBackendAndroid::Stop() { - LOG(INFO) << __func__ << ":"; - DCHECK(state_ == kStatePlaying || state_ == kStatePaused) - << "Invalid state " << state_; - if (audio_decoder_) - audio_decoder_->Stop(); - - state_ = kStateInitialized; -} - -bool MediaPipelineBackendAndroid::Pause() { - LOG(INFO) << __func__ << ":"; - DCHECK_EQ(kStatePlaying, state_); - if (audio_decoder_ && !audio_decoder_->Pause()) - return false; - state_ = kStatePaused; - return true; -} - -bool MediaPipelineBackendAndroid::Resume() { - LOG(INFO) << __func__ << ":"; - DCHECK_EQ(kStatePaused, state_); - if (audio_decoder_ && !audio_decoder_->Resume()) - return false; - state_ = kStatePlaying; - return true; -} - -bool MediaPipelineBackendAndroid::SetPlaybackRate(float rate) { - LOG(INFO) << __func__ << ": rate=" << rate; - if (audio_decoder_) { - return audio_decoder_->SetPlaybackRate(rate); - } - return true; -} - -int64_t MediaPipelineBackendAndroid::GetCurrentPts() { - if (audio_decoder_) { - int64_t pts = audio_decoder_->current_pts(); - DVLOG(2) << __func__ << ": pts=" << pts; - return pts; - } - LOG(INFO) << __func__ << ": pts="; - return std::numeric_limits::min(); -} - -bool MediaPipelineBackendAndroid::Primary() const { - return (params_.audio_type != - MediaPipelineDeviceParams::kAudioStreamSoundEffects); -} - -std::string MediaPipelineBackendAndroid::DeviceId() const { - return params_.device_id; -} - -AudioContentType MediaPipelineBackendAndroid::ContentType() const { - return params_.content_type; -} - -AudioChannel MediaPipelineBackendAndroid::AudioChannel() const { - return params_.audio_channel; -} - -const scoped_refptr& -MediaPipelineBackendAndroid::GetTaskRunner() const { - return static_cast(params_.task_runner)->runner(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/media_pipeline_backend_android.h chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_pipeline_backend_android.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/media_pipeline_backend_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/media_pipeline_backend_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_MEDIA_PIPELINE_BACKEND_ANDROID_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_MEDIA_PIPELINE_BACKEND_ANDROID_H_ - -#include -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -namespace media { -class AudioDecoderAndroid; -class VideoDecoderNull; - -// TODO(ckuiper): This class is very similar to MediaPipelineBackendForMixer -// (alsa/media_pipeline_backend_alsa.h) and should be consolidated into one -// shared class/file. -class MediaPipelineBackendAndroid : public MediaPipelineBackend { - public: - using RenderingDelay = AudioDecoder::RenderingDelay; - using AudioTrackTimestamp = AudioDecoder::AudioTrackTimestamp; - - explicit MediaPipelineBackendAndroid(const MediaPipelineDeviceParams& params); - - MediaPipelineBackendAndroid(const MediaPipelineBackendAndroid&) = delete; - MediaPipelineBackendAndroid& operator=(const MediaPipelineBackendAndroid&) = - delete; - - ~MediaPipelineBackendAndroid() override; - - // MediaPipelineBackend implementation: - AudioDecoder* CreateAudioDecoder() override; - VideoDecoder* CreateVideoDecoder() override; - bool Initialize() override; - bool Start(int64_t start_pts) override; - void Stop() override; - bool Pause() override; - bool Resume() override; - bool SetPlaybackRate(float rate) override; - int64_t GetCurrentPts() override; - - bool Primary() const; - std::string DeviceId() const; - AudioContentType ContentType() const; - AudioChannel AudioChannel() const; - const scoped_refptr& GetTaskRunner() const; - - private: - // State variable for DCHECKing caller correctness. - enum State { - kStateUninitialized, - kStateInitialized, - kStatePlaying, - kStatePaused, - }; - State state_; - - const MediaPipelineDeviceParams params_; - std::unique_ptr video_decoder_; - std::unique_ptr audio_decoder_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_MEDIA_PIPELINE_BACKEND_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_cache.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_cache.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/android/volume_cache.h" - -#include -#include - -#include "base/logging.h" - -namespace chromecast { -namespace media { - -VolumeCache::VolumeCache(AudioContentType type, SystemVolumeTableAccessApi* api) - : kMaxVolumeIndex(api->GetMaxVolumeIndex(type)) { - LOG(INFO) << "Build volume cache for type " << static_cast(type) << ":"; - cache_.resize(kMaxVolumeIndex + 1); - for (size_t v_idx = 0; v_idx < cache_.size(); v_idx++) { - float v_level = static_cast(v_idx) / kMaxVolumeIndex; - float dbVolume = api->VolumeToDbFS(type, v_level); - if (isinf(dbVolume)) { - // In Android volume tables, -inf started to be used for mute. Use a value - // that is effectively mute, but allows math to be performed. - dbVolume = -120.0; - } - cache_[v_idx] = dbVolume; - LOG(INFO) << " " << v_idx << "(" << v_level << ") -> " << cache_[v_idx]; - } -} - -VolumeCache::~VolumeCache() = default; - -float VolumeCache::VolumeToDbFS(float vol_level) { - if (vol_level <= 0.0f) - return cache_[0]; - if (vol_level >= 1.0f) - return cache_[kMaxVolumeIndex]; - - float vol_idx = vol_level * kMaxVolumeIndex; - // Find the nearest integers below and above vol_idx. - float vol_idx_high = std::ceil(vol_idx); - float vol_idx_low = std::floor(vol_idx); - float db_high = cache_[static_cast(vol_idx_high)]; - if (vol_idx_high == vol_idx_low) { - return db_high; - } - // We are in between two consecutive volume points, so interpolate. - // Note that vol_idx_high = vol_idx_low + 1. - float db_low = cache_[static_cast(vol_idx_low)]; - float m = (db_high - db_low) / 1.0f; - float db_interpolated = db_low + m * (vol_idx - vol_idx_low); - return db_interpolated; -} - -float VolumeCache::DbFSToVolume(float db) { - auto db_high_it = std::lower_bound(cache_.begin(), cache_.end(), db); - if (db_high_it == cache_.end()) - return 1.0f; - if (db_high_it == cache_.begin()) - return 0.0f; - - int vol_idx_high = db_high_it - cache_.begin(); - if (db == *db_high_it) - return static_cast(vol_idx_high) / kMaxVolumeIndex; - - // We are in between two consecutive volume points, so interpolate. - // Note that vol_idx_high = vol_idx_low + 1. - auto db_low_it = std::prev(db_high_it); - float m = 1.0f / (*db_high_it - *db_low_it); - float vol_idx = static_cast(vol_idx_high) - m * (*db_high_it - db); - return vol_idx / kMaxVolumeIndex; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_cache.h chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_cache.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_VOLUME_CACHE_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_VOLUME_CACHE_H_ - -#include - -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -// Wrapper class to inject an API into VolumeCache that is used to populate the -// cache. -class SystemVolumeTableAccessApi { - public: - SystemVolumeTableAccessApi() = default; - virtual ~SystemVolumeTableAccessApi() = default; - - virtual int GetMaxVolumeIndex(AudioContentType type) = 0; - virtual float VolumeToDbFS(AudioContentType type, float volume) = 0; -}; - -// Builds a cache of the system's volume table and provides access to it. -class VolumeCache { - public: - VolumeCache(AudioContentType type, SystemVolumeTableAccessApi* api); - - VolumeCache(const VolumeCache&) = delete; - VolumeCache& operator=(const VolumeCache&) = delete; - - ~VolumeCache(); - - // Returns the mapped and interpolated dBFS value for the given volume level, - // using the cached volume table. - float VolumeToDbFS(float vol_level); - - // Returns the mapped and interpolated volume value for the given dBFS value, - // using the cached volume table. - float DbFSToVolume(float db); - - private: - const int kMaxVolumeIndex; - - std::vector cache_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_VOLUME_CACHE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_cache_test.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache_test.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_cache_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_cache_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,121 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/android/volume_cache.h" - -#include - -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { -const int kMaxVolumeIndex = 10; - -const float kTestVolumeTable[kMaxVolumeIndex + 1] = { - -100.0f, -88.0f, -82.0f, -70.0f, -62.5f, -49.9f, - -40.5f, -30.0f, -28.2f, -10.0f, 0.0f}; - -} // namespace - -class VolumeCacheTest : protected SystemVolumeTableAccessApi, - public testing::Test { - protected: - VolumeCacheTest() : volume_cache_(AudioContentType::kMedia, this) {} - - ~VolumeCacheTest() override {} - - // SystemVolumeTableAccessApi implementation. - // We use kTestVolumeTable for kMedia and just return -1.0f for other types. - // That allows to test if the type is properly used in the c'tor. - int GetMaxVolumeIndex(AudioContentType type) override { - return (type == AudioContentType::kMedia) ? kMaxVolumeIndex : 2; - } - float VolumeToDbFS(AudioContentType type, float volume) override { - if (type != AudioContentType::kMedia) - return -1.0f; - - int idx_vol = static_cast(std::round(volume * kMaxVolumeIndex)); - return kTestVolumeTable[idx_vol]; - } - - VolumeCache volume_cache_; -}; - -TEST_F(VolumeCacheTest, CachedValuesMatchesOriginalTable) { - for (int i = 0; i <= kMaxVolumeIndex; i++) { - float v = static_cast(i) / kMaxVolumeIndex; - EXPECT_FLOAT_EQ(kTestVolumeTable[i], volume_cache_.VolumeToDbFS(v)); - float db = kTestVolumeTable[i]; - EXPECT_FLOAT_EQ(v, volume_cache_.DbFSToVolume(db)); - } -} - -TEST_F(VolumeCacheTest, BoundaryValues) { - EXPECT_FLOAT_EQ(kTestVolumeTable[0], volume_cache_.VolumeToDbFS(-100.0f)); - EXPECT_FLOAT_EQ(kTestVolumeTable[0], volume_cache_.VolumeToDbFS(-1.0f)); - EXPECT_FLOAT_EQ(kTestVolumeTable[0], volume_cache_.VolumeToDbFS(-0.1f)); - EXPECT_FLOAT_EQ(kTestVolumeTable[0], volume_cache_.VolumeToDbFS(0.0f)); - - EXPECT_FLOAT_EQ(kTestVolumeTable[kMaxVolumeIndex], - volume_cache_.VolumeToDbFS(1.0f)); - EXPECT_FLOAT_EQ(kTestVolumeTable[kMaxVolumeIndex], - volume_cache_.VolumeToDbFS(1.1f)); - EXPECT_FLOAT_EQ(kTestVolumeTable[kMaxVolumeIndex], - volume_cache_.VolumeToDbFS(2.0f)); - EXPECT_FLOAT_EQ(kTestVolumeTable[kMaxVolumeIndex], - volume_cache_.VolumeToDbFS(100.0f)); - - float min_db = kTestVolumeTable[0]; - EXPECT_FLOAT_EQ(0.0f, volume_cache_.DbFSToVolume(min_db - 100.0f)); - EXPECT_FLOAT_EQ(0.0f, volume_cache_.DbFSToVolume(min_db - 1.0f)); - EXPECT_FLOAT_EQ(0.0f, volume_cache_.DbFSToVolume(min_db - 0.1f)); - EXPECT_FLOAT_EQ(0.0f, volume_cache_.DbFSToVolume(min_db - 0.0f)); - - float max_db = kTestVolumeTable[kMaxVolumeIndex]; - EXPECT_FLOAT_EQ(1.0f, volume_cache_.DbFSToVolume(max_db + 0.0f)); - EXPECT_FLOAT_EQ(1.0f, volume_cache_.DbFSToVolume(max_db + 0.1f)); - EXPECT_FLOAT_EQ(1.0f, volume_cache_.DbFSToVolume(max_db + 1.0f)); - EXPECT_FLOAT_EQ(1.0f, volume_cache_.DbFSToVolume(max_db + 100.0f)); -} - -TEST_F(VolumeCacheTest, Volume2DbFSInterpolatesCorrectly) { - int i_low = 0, i_high = 1; - for (; i_high <= kMaxVolumeIndex; ++i_high, ++i_low) { - float v_low = static_cast(i_low) / kMaxVolumeIndex; - float v_high = static_cast(i_high) / kMaxVolumeIndex; - float db_low = kTestVolumeTable[i_low]; - float db_high = kTestVolumeTable[i_high]; - float m = (db_high - db_low) / (v_high - v_low); - for (float v = v_low; v <= v_high; v += 0.1f) { - float expected_db = db_low + m * (v - v_low); - EXPECT_FLOAT_EQ(expected_db, volume_cache_.VolumeToDbFS(v)); - } - } -} - -TEST_F(VolumeCacheTest, DbFSToVolumeInterpolatesCorrectly) { - int i_low = 0, i_high = 1; - for (; i_high <= kMaxVolumeIndex; ++i_high, ++i_low) { - float v_low = static_cast(i_low) / kMaxVolumeIndex; - float v_high = static_cast(i_high) / kMaxVolumeIndex; - float db_low = kTestVolumeTable[i_low]; - float db_high = kTestVolumeTable[i_high]; - float m = (v_high - v_low) / (db_high - db_low); - for (float db = db_low; db <= db_high; db += 0.1f) { - float expected_v = v_low + m * (db - db_low); - EXPECT_FLOAT_EQ(expected_v, volume_cache_.DbFSToVolume(db)); - } - } -} - -TEST_F(VolumeCacheTest, CacheHonorsAudioContentType) { - VolumeCache volume_cache(AudioContentType::kAlarm, this); - EXPECT_FLOAT_EQ(-1.0f, volume_cache.VolumeToDbFS(0.0f)); - EXPECT_FLOAT_EQ(-1.0f, volume_cache.VolumeToDbFS(1.0f)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_control_android.cc chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_control_android.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_control_android.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_control_android.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,372 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/android/volume_control_android.h" - -#include -#include -#include -#include -#include -#include - -#include "base/android/build_info.h" -#include "base/android/jni_android.h" -#include "base/files/file_util.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/message_loop/message_pump_type.h" -#include "base/no_destructor.h" -#include "chromecast/base/init_command_line_shlib.h" -#include "chromecast/chromecast_buildflags.h" - -// Must come after all headers that specialize FromJniType() / ToJniType(). -#include "chromecast/media/cma/backend/android/audio_track_jni_headers/VolumeControl_jni.h" -#include "chromecast/media/cma/backend/android/audio_track_jni_headers/VolumeMap_jni.h" - -namespace chromecast { -namespace media { - -namespace { - -bool IsSingleVolumeDevice() { - JNIEnv* env = base::android::AttachCurrentThread(); - return Java_VolumeControl_isSingleVolumeDevice(env); -} - -} // namespace - -VolumeControlAndroid& GetVolumeControl() { - static base::NoDestructor volume_control; - return *volume_control; -} - -VolumeControlAndroid::VolumeControlAndroid() - : is_single_volume_(IsSingleVolumeDevice()), - thread_("VolumeControl"), - initialize_complete_event_( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED) { - DCHECK(j_volume_control_.is_null()); - j_volume_control_.Reset(Java_VolumeControl_createVolumeControl( - base::android::AttachCurrentThread(), reinterpret_cast(this))); - - base::Thread::Options options; - options.message_pump_type = base::MessagePumpType::IO; - thread_.StartWithOptions(std::move(options)); - - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlAndroid::InitializeOnThread, - base::Unretained(this))); - initialize_complete_event_.Wait(); -} - -VolumeControlAndroid::~VolumeControlAndroid() {} - -void VolumeControlAndroid::AddVolumeObserver(VolumeObserver* observer) { - base::AutoLock lock(observer_lock_); - volume_observers_.push_back(observer); -} - -void VolumeControlAndroid::RemoveVolumeObserver(VolumeObserver* observer) { - base::AutoLock lock(observer_lock_); - volume_observers_.erase( - std::remove(volume_observers_.begin(), volume_observers_.end(), observer), - volume_observers_.end()); -} - -float VolumeControlAndroid::GetVolume(AudioContentType type) { - base::AutoLock lock(volume_lock_); - // The return level needs to be in the kMedia (MUSIC) volume table domain. - return MapIntoDifferentVolumeTableDomain(type, AudioContentType::kMedia, - volumes_[type]); -} - -void VolumeControlAndroid::SetVolume(VolumeChangeSource source, - AudioContentType type, - float level) { - if (type == AudioContentType::kOther) { - NOTREACHED() << "Can't set volume for content type kOther"; - } - - level = std::clamp(level, 0.0f, 1.0f); - // The input level value is in the kMedia (MUSIC) volume table domain. - float mapped_level = - MapIntoDifferentVolumeTableDomain(AudioContentType::kMedia, type, level); - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlAndroid::SetVolumeOnThread, - base::Unretained(this), source, type, - mapped_level, false /* from_android */)); -} - -bool VolumeControlAndroid::IsMuted(AudioContentType type) { - base::AutoLock lock(volume_lock_); - return muted_[type]; -} - -void VolumeControlAndroid::SetMuted(VolumeChangeSource source, - AudioContentType type, - bool muted) { - if (type == AudioContentType::kOther) { - NOTREACHED() << "Can't set mute state for content type kOther"; - } - - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlAndroid::SetMutedOnThread, - base::Unretained(this), source, type, muted, - false /* from_android */)); -} - -void VolumeControlAndroid::SetOutputLimit(AudioContentType type, float limit) { - if (type == AudioContentType::kOther) { - NOTREACHED() << "Can't set output limit for content type kOther"; - } - - // The input limit is in the kMedia (MUSIC) volume table domain. - limit = std::clamp(limit, 0.0f, 1.0f); - float limit_db = VolumeToDbFSCached(AudioContentType::kMedia, limit); - AudioSinkManager::Get()->SetOutputLimitDb(type, limit_db); -} - -void VolumeControlAndroid::OnVolumeChange( - JNIEnv* env, - const base::android::JavaParamRef& obj, - jint type, - jfloat level) { - thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&VolumeControlAndroid::ReportVolumeChangeOnThread, - base::Unretained(this), - static_cast(type), level)); -} - -void VolumeControlAndroid::OnMuteChange( - JNIEnv* env, - const base::android::JavaParamRef& obj, - jint type, - jboolean muted) { - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlAndroid::ReportMuteChangeOnThread, - base::Unretained(this), - static_cast(type), muted)); -} - -int VolumeControlAndroid::GetMaxVolumeIndex(AudioContentType type) { - if (base::android::BuildInfo::GetInstance()->sdk_int() < - base::android::SDK_VERSION_NOUGAT) { - return 1; - } - return Java_VolumeMap_getMaxVolumeIndex(base::android::AttachCurrentThread(), - static_cast(type)); -} - -float VolumeControlAndroid::VolumeToDbFS(AudioContentType type, float volume) { - if (base::android::BuildInfo::GetInstance()->sdk_int() < - base::android::SDK_VERSION_NOUGAT) { - return 1.0f; - } - return Java_VolumeMap_volumeToDbFs(base::android::AttachCurrentThread(), - static_cast(type), volume); -} - -void VolumeControlAndroid::InitializeOnThread() { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - - for (auto type : - {AudioContentType::kMedia, AudioContentType::kAlarm, - AudioContentType::kCommunication, AudioContentType::kOther}) { - std::unique_ptr vc(new VolumeCache(type, this)); - volume_cache_.emplace(type, std::move(vc)); - - volumes_[type] = - Java_VolumeControl_getVolume(base::android::AttachCurrentThread(), - j_volume_control_, static_cast(type)); - float volume_db = VolumeToDbFSCached(type, volumes_[type]); - AudioSinkManager::Get()->SetTypeVolumeDb(type, volume_db); - muted_[type] = - Java_VolumeControl_isMuted(base::android::AttachCurrentThread(), - j_volume_control_, static_cast(type)); - LOG(INFO) << __func__ << ": Initial values for" - << " type=" << static_cast(type) << ": " - << " volume=" << volumes_[type] << " (" << volume_db << ")" - << " mute=" << muted_[type]; - } - - // kOther is not used on Android, so we don't attempt to set it to 100% here. - - initialize_complete_event_.Signal(); -} - -void VolumeControlAndroid::SetVolumeOnThread(VolumeChangeSource source, - AudioContentType type, - float level, - bool from_android) { - // Note: |level| is in the |type| volume table domain. - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - { - base::AutoLock lock(volume_lock_); - if (level == volumes_[type]) { - return; - } - volumes_[type] = level; - } - - float level_db = VolumeToDbFSCached(type, level); - LOG(INFO) << __func__ << ": level=" << level << " (" << level_db << ")"; - // Provide the type volume to the sink manager so it can properly calculate - // the limiter multiplier. The volume is *not* applied by the sink though. - AudioSinkManager::Get()->SetTypeVolumeDb(type, level_db); - - // Set proper volume in Android OS. - if (!from_android) { - Java_VolumeControl_setVolume(base::android::AttachCurrentThread(), - j_volume_control_, static_cast(type), - level); - } - - // Report new volume level to observers. Note that the reported value needs - // to be in the kMedia (MUSIC) volume table domain. - float media_level = - MapIntoDifferentVolumeTableDomain(type, AudioContentType::kMedia, level); - { - base::AutoLock lock(observer_lock_); - for (VolumeObserver* observer : volume_observers_) { - observer->OnVolumeChange(source, type, media_level); - } - } -} - -void VolumeControlAndroid::SetMutedOnThread(VolumeChangeSource source, - AudioContentType type, - bool muted, - bool from_android) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - { - base::AutoLock lock(volume_lock_); - if (muted == muted_[type]) { - return; - } - muted_[type] = muted; - } - - if (!from_android) { - Java_VolumeControl_setMuted(base::android::AttachCurrentThread(), - j_volume_control_, static_cast(type), - muted); - } - - { - base::AutoLock lock(observer_lock_); - for (VolumeObserver* observer : volume_observers_) { - observer->OnMuteChange(source, type, muted); - } - } -} - -void VolumeControlAndroid::ReportVolumeChangeOnThread(AudioContentType type, - float level) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - SetVolumeOnThread(VolumeChangeSource::kUser, type, level, - true /* from android */); -} - -void VolumeControlAndroid::ReportMuteChangeOnThread(AudioContentType type, - bool muted) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - SetMutedOnThread(VolumeChangeSource::kUser, type, muted, - true /* from_android */); -} - -float VolumeControlAndroid::MapIntoDifferentVolumeTableDomain( - AudioContentType from_type, - AudioContentType to_type, - float level) { - if (from_type == to_type) { - return level; - } - float from_db = VolumeToDbFSCached(from_type, level); - return DbFSToVolumeCached(to_type, from_db); -} - -float VolumeControlAndroid::VolumeToDbFSCached(AudioContentType type, - float vol_level) { - return volume_cache_[type]->VolumeToDbFS(vol_level); -} - -float VolumeControlAndroid::DbFSToVolumeCached(AudioContentType type, - float db) { - return volume_cache_[type]->DbFSToVolume(db); -} - -// -// Implementation of VolumeControl as defined in public/volume_control.h -// - -// static -void VolumeControl::Initialize(const std::vector& argv) { - GetVolumeControl(); -} - -// static -void VolumeControl::Finalize() { - // Nothing to do. -} - -// static -void VolumeControl::AddVolumeObserver(VolumeObserver* observer) { - GetVolumeControl().AddVolumeObserver(observer); -} - -// static -void VolumeControl::RemoveVolumeObserver(VolumeObserver* observer) { - GetVolumeControl().RemoveVolumeObserver(observer); -} - -// static -float VolumeControl::GetVolume(AudioContentType type) { - return GetVolumeControl().GetVolume(type); -} - -// static -void VolumeControl::SetVolume(VolumeChangeSource source, - AudioContentType type, - float level) { - GetVolumeControl().SetVolume(source, type, level); -} - -// static -bool VolumeControl::IsMuted(AudioContentType type) { - return GetVolumeControl().IsMuted(type); -} - -// static -void VolumeControl::SetMuted(VolumeChangeSource source, - AudioContentType type, - bool muted) { - GetVolumeControl().SetMuted(source, type, muted); -} - -// static -void VolumeControl::SetOutputLimit(AudioContentType type, float limit) { - GetVolumeControl().SetOutputLimit(type, limit); -} - -// static -float VolumeControl::VolumeToDbFS(float volume) { - // The volume value is the kMedia (MUSIC) volume table domain. - return GetVolumeControl().VolumeToDbFSCached(AudioContentType::kMedia, - volume); -} - -// static -float VolumeControl::DbFSToVolume(float db) { - // The db value is the kMedia (MUSIC) volume table domain. - return GetVolumeControl().DbFSToVolumeCached(AudioContentType::kMedia, db); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_control_android.h chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_control_android.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/android/volume_control_android.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/android/volume_control_android.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,95 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_VOLUME_CONTROL_ANDROID_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_VOLUME_CONTROL_ANDROID_H_ - -#include -#include - -#include "base/android/jni_android.h" -#include "base/synchronization/lock.h" -#include "base/synchronization/waitable_event.h" -#include "base/threading/thread.h" -#include "chromecast/media/cma/backend/android/audio_sink_manager.h" -#include "chromecast/media/cma/backend/android/volume_cache.h" - -namespace chromecast { -namespace media { - -class VolumeControlAndroid : SystemVolumeTableAccessApi { - public: - VolumeControlAndroid(); - - VolumeControlAndroid(const VolumeControlAndroid&) = delete; - VolumeControlAndroid& operator=(const VolumeControlAndroid&) = delete; - - ~VolumeControlAndroid() override; - - void AddVolumeObserver(VolumeObserver* observer); - void RemoveVolumeObserver(VolumeObserver* observer); - float GetVolume(AudioContentType type); - void SetVolume(VolumeChangeSource source, AudioContentType type, float level); - bool IsMuted(AudioContentType type); - void SetMuted(VolumeChangeSource source, AudioContentType type, bool muted); - void SetOutputLimit(AudioContentType type, float limit); - float VolumeToDbFSCached(AudioContentType type, float volume); - float DbFSToVolumeCached(AudioContentType type, float db); - - // Called from java to signal a change volume. - void OnVolumeChange(JNIEnv* env, - const base::android::JavaParamRef& obj, - jint type, - jfloat level); - - void OnMuteChange(JNIEnv* env, - const base::android::JavaParamRef& obj, - jint type, - jboolean muted); - - // SystemVolumeTableAccessApi implementation. - int GetMaxVolumeIndex(AudioContentType type) override; - float VolumeToDbFS(AudioContentType type, float volume) override; - - private: - void InitializeOnThread(); - void SetVolumeOnThread(VolumeChangeSource source, - AudioContentType type, - float level, - bool from_android); - void SetMutedOnThread(VolumeChangeSource source, - AudioContentType type, - bool muted, - bool from_android); - void ReportVolumeChangeOnThread(AudioContentType type, float level); - void ReportMuteChangeOnThread(AudioContentType type, bool muted); - - // For the user of the VolumeControl, all volume values are in the volume - // table domain of kMedia (MUSIC). For volume types other than media, - // VolumeControl converts them internally into their proper volume table - // domains. - float MapIntoDifferentVolumeTableDomain(AudioContentType from_type, - AudioContentType to_type, - float level); - - const bool is_single_volume_; - base::android::ScopedJavaGlobalRef j_volume_control_; - - std::map> volume_cache_; - - base::Lock volume_lock_; - std::map volumes_; - std::map muted_; - - base::Lock observer_lock_; - std::vector volume_observers_; - - base::Thread thread_; - base::WaitableEvent initialize_complete_event_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_ANDROID_VOLUME_CONTROL_ANDROID_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/audio_decoder_for_mixer.cc chromium-132.0.6834.159/chromecast/media/cma/backend/audio_decoder_for_mixer.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/audio_decoder_for_mixer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/audio_decoder_for_mixer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,607 +0,0 @@ -// 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 "chromecast/media/cma/backend/audio_decoder_for_mixer.h" - -#include -#include - -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/time/time.h" -#include "base/trace_event/trace_event.h" -#include "build/build_config.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/media/base/default_monotonic_clock.h" -#include "chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/net/io_buffer_pool.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_timestamp_helper.h" -#include "media/base/channel_layout.h" -#include "media/base/decoder_buffer.h" -#include "media/base/sample_format.h" -#include "media/filters/audio_renderer_algorithm.h" - -#define TRACE_FUNCTION_ENTRY0() TRACE_EVENT0("cma", __FUNCTION__) - -#define TRACE_FUNCTION_ENTRY1(arg1) \ - TRACE_EVENT1("cma", __FUNCTION__, #arg1, arg1) - -#define TRACE_FUNCTION_ENTRY2(arg1, arg2) \ - TRACE_EVENT2("cma", __FUNCTION__, #arg1, arg1, #arg2, arg2) - -namespace chromecast { -namespace media { - -namespace { - -const int kInitialFillSizeFrames = 512; -const double kPlaybackRateEpsilon = 0.001; - -constexpr double kMinAudioClockRate = 0.99; -constexpr double kMaxAudioClockRate = 1.01; - -const int64_t kDefaultInputQueueMs = 200; -constexpr base::TimeDelta kFadeTime = base::Milliseconds(5); -const int kDefaultStartThresholdMs = 70; - -const CastAudioDecoder::OutputFormat kDecoderSampleFormat = - CastAudioDecoder::kOutputPlanarFloat; - -const int64_t kInvalidTimestamp = std::numeric_limits::min(); - -const int64_t kNoPendingOutput = -1; - -constexpr int kAudioMessageHeaderSize = - mixer_service::MixerSocket::kAudioMessageHeaderSize; - -// TODO(jameswest): Replace numeric playout channel with AudioChannel enum in -// mixer. -int ToPlayoutChannel(AudioChannel audio_channel) { - switch (audio_channel) { - case AudioChannel::kAll: - return kChannelAll; - case AudioChannel::kLeft: - return 0; - case AudioChannel::kRight: - return 1; - } - NOTREACHED(); -} - -int MaxQueuedFrames(int sample_rate) { - static int64_t queue_ms = GetSwitchValueNonNegativeInt( - switches::kMixerSourceInputQueueMs, kDefaultInputQueueMs); - - return ::media::AudioTimestampHelper::TimeToFrames( - base::Milliseconds(queue_ms), sample_rate); -} - -int StartThreshold(int sample_rate) { - static int64_t start_threshold_ms = GetSwitchValueNonNegativeInt( - switches::kMixerSourceAudioReadyThresholdMs, kDefaultStartThresholdMs); - - return ::media::AudioTimestampHelper::TimeToFrames( - base::Milliseconds(start_threshold_ms), sample_rate); -} - -} // namespace - -// static -bool MediaPipelineBackend::AudioDecoder::RequiresDecryption() { - return true; -} - -AudioDecoderForMixer::AudioDecoderForMixer( - MediaPipelineBackendForMixer* backend) - : backend_(backend), - task_runner_(backend->GetTaskRunner()), - buffer_pool_frames_(kInitialFillSizeFrames), - pending_output_frames_(kNoPendingOutput), - pool_(new ::media::AudioBufferMemoryPool()), - weak_factory_(this) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(backend_); - DCHECK(task_runner_.get()); - DCHECK(task_runner_->BelongsToCurrentThread()); -} - -AudioDecoderForMixer::~AudioDecoderForMixer() { - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); -} - -void AudioDecoderForMixer::SetDelegate( - MediaPipelineBackend::Decoder::Delegate* delegate) { - DCHECK(delegate); - delegate_ = delegate; -} - -void AudioDecoderForMixer::Initialize() { - TRACE_FUNCTION_ENTRY0(); - DCHECK(delegate_); - stats_ = Statistics(); - pending_buffer_complete_ = false; - pending_output_frames_ = kNoPendingOutput; - paused_ = false; - playback_rate_ = 1.0f; - reported_ready_for_playback_ = false; - mixer_delay_ = RenderingDelay(); - - next_buffer_delay_ = RenderingDelay(); - last_push_pts_ = kInvalidTimestamp; - last_push_playout_timestamp_ = kInvalidTimestamp; -} - -bool AudioDecoderForMixer::Start(int64_t playback_start_pts, - bool av_sync_enabled) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(IsValidConfig(input_config_)); - - // Create decoder_ if necessary. This can happen if Stop() was called, and - // SetConfig() was not called since then. - if (!decoder_) { - CreateDecoder(); - } - decoded_config_ = (decoder_ ? decoder_->GetOutputConfig() : input_config_); - CreateMixerInput(decoded_config_, av_sync_enabled); - playback_start_pts_ = playback_start_pts; - av_sync_enabled_ = av_sync_enabled; - - return true; -} - -void AudioDecoderForMixer::CreateBufferPool(const AudioConfig& config, - int frame_count) { - DCHECK_GT(frame_count, 0); - buffer_pool_frames_ = frame_count; - buffer_pool_ = base::MakeRefCounted( - frame_count * sizeof(float) * config.channel_number + - kAudioMessageHeaderSize, - std::numeric_limits::max(), true /* threadsafe */); - buffer_pool_->Preallocate(1); -} - -void AudioDecoderForMixer::CreateMixerInput(const AudioConfig& config, - bool av_sync_enabled) { - CreateBufferPool(config, buffer_pool_frames_); - DCHECK_GT(buffer_pool_frames_, 0); - - mixer_service::OutputStreamParams params; - params.set_stream_type( - backend_->Primary() - ? mixer_service::OutputStreamParams::STREAM_TYPE_DEFAULT - : mixer_service::OutputStreamParams::STREAM_TYPE_SFX); - params.set_content_type( - audio_service::ConvertContentType(backend_->ContentType())); - params.set_sample_format(audio_service::SAMPLE_FORMAT_FLOAT_P); - params.set_device_id(backend_->DeviceId()); - params.set_sample_rate(config.samples_per_second); - params.set_num_channels(config.channel_number); - params.set_channel_selection(ToPlayoutChannel(backend_->AudioChannel())); - params.set_fill_size_frames(buffer_pool_frames_); - params.set_start_threshold_frames(StartThreshold(config.samples_per_second)); - params.set_max_buffered_frames(MaxQueuedFrames(config.samples_per_second)); - params.set_fade_frames(::media::AudioTimestampHelper::TimeToFrames( - kFadeTime, config.samples_per_second)); - params.set_use_start_timestamp(av_sync_enabled); - params.set_enable_audio_clock_simulation(av_sync_enabled); - - mixer_input_ = - std::make_unique(this, params); - mixer_input_->SetVolumeMultiplier(volume_multiplier_); - mixer_input_->SetAudioClockRate(av_sync_clock_rate_); - mixer_input_->SetPlaybackRate(playback_rate_); - mixer_input_->Connect(); -} - -void AudioDecoderForMixer::StartPlaybackAt(int64_t playback_start_timestamp) { - LOG(INFO) << __func__ - << " playback_start_timestamp_=" << playback_start_timestamp; - mixer_input_->SetStartTimestamp(playback_start_timestamp, - playback_start_pts_); -} - -void AudioDecoderForMixer::RestartPlaybackAt(int64_t pts, int64_t timestamp) { - LOG(INFO) << __func__ << " pts=" << pts << " timestamp=" << timestamp; - - next_buffer_delay_ = RenderingDelay(); - last_push_playout_timestamp_ = kInvalidTimestamp; - mixer_input_->SetStartTimestamp(timestamp, pts); -} - -AudioDecoderForMixer::RenderingDelay -AudioDecoderForMixer::GetMixerRenderingDelay() { - return mixer_delay_; -} - -void AudioDecoderForMixer::Stop() { - TRACE_FUNCTION_ENTRY0(); - decoder_.reset(); - mixer_input_.reset(); - weak_factory_.InvalidateWeakPtrs(); - - Initialize(); -} - -bool AudioDecoderForMixer::Pause() { - TRACE_FUNCTION_ENTRY0(); - DCHECK(mixer_input_); - paused_ = true; - mixer_input_->Pause(); - return true; -} - -bool AudioDecoderForMixer::Resume() { - TRACE_FUNCTION_ENTRY0(); - DCHECK(mixer_input_); - mixer_input_->Resume(); - next_buffer_delay_ = RenderingDelay(); - last_push_playout_timestamp_ = kInvalidTimestamp; - paused_ = false; - return true; -} - -float AudioDecoderForMixer::SetPlaybackRate(float rate) { - if (std::abs(rate - 1.0) < kPlaybackRateEpsilon) { - // AudioRendererAlgorithm treats values close to 1 as exactly 1. - rate = 1.0f; - } - LOG(INFO) << "SetPlaybackRate to " << rate; - if (rate <= 0) { - LOG(ERROR) << "Invalid playback rate " << rate; - rate = 1.0f; - } - - playback_rate_ = rate; - mixer_input_->SetPlaybackRate(rate); - backend_->NewAudioPlaybackRateInEffect(rate); - - return rate; -} - -double AudioDecoderForMixer::SetAvSyncPlaybackRate(double rate) { - av_sync_clock_rate_ = - std::max(kMinAudioClockRate, std::min(rate, kMaxAudioClockRate)); - if (mixer_input_) - mixer_input_->SetAudioClockRate(av_sync_clock_rate_); - return av_sync_clock_rate_; -} - -bool AudioDecoderForMixer::GetTimestampedPts(int64_t* timestamp, - int64_t* pts) const { - if (paused_ || last_push_playout_timestamp_ == kInvalidTimestamp || - last_push_pts_ == kInvalidTimestamp) { - return false; - } - - // Note: timestamp may be slightly in the future. - *timestamp = last_push_playout_timestamp_; - *pts = last_push_pts_; - return true; -} - -int64_t AudioDecoderForMixer::GetCurrentPts() const { - return last_push_pts_; -} - -AudioDecoderForMixer::BufferStatus AudioDecoderForMixer::PushBuffer( - CastDecoderBuffer* buffer) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(buffer); - DCHECK(!mixer_error_); - DCHECK(!pending_buffer_complete_); - DCHECK(mixer_input_); - - uint64_t input_bytes = buffer->end_of_stream() ? 0 : buffer->data_size(); - scoped_refptr buffer_base( - static_cast(buffer)); - - // If the buffer is already decoded, do not attempt to decode. Call - // OnBufferDecoded asynchronously on the main thread. - if (BypassDecoder()) { - DCHECK(!decoder_); - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&AudioDecoderForMixer::OnBufferDecoded, - weak_factory_.GetWeakPtr(), input_bytes, - false /* has_config */, - CastAudioDecoder::Status::kDecodeOk, - AudioConfig(), buffer_base)); - return MediaPipelineBackend::kBufferPending; - } - - if (!decoder_) { - return MediaPipelineBackend::kBufferFailed; - } - - // Decode the buffer. - decoder_->Decode(std::move(buffer_base), - base::BindOnce(&AudioDecoderForMixer::OnBufferDecoded, - base::Unretained(this), input_bytes, - true /* has_config */)); - return MediaPipelineBackend::kBufferPending; -} - -void AudioDecoderForMixer::UpdateStatistics(Statistics delta) { - DCHECK(task_runner_->BelongsToCurrentThread()); - stats_.decoded_bytes += delta.decoded_bytes; -} - -void AudioDecoderForMixer::GetStatistics(Statistics* stats) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(stats); - DCHECK(task_runner_->BelongsToCurrentThread()); - *stats = stats_; -} - -bool AudioDecoderForMixer::SetConfig(const AudioConfig& config) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); - if (!IsValidConfig(config)) { - LOG(ERROR) << "Invalid audio config passed to SetConfig"; - return false; - } - - input_config_ = config; - decoder_.reset(); - CreateDecoder(); - - auto decoded_config = - (decoder_ ? decoder_->GetOutputConfig() : input_config_); - bool changed_config = - (decoded_config.samples_per_second != - decoded_config_.samples_per_second || - decoded_config.channel_number != decoded_config_.channel_number); - decoded_config_ = decoded_config; - if (mixer_input_ && changed_config) { - ResetMixerInputForNewConfig(decoded_config); - } - - if (pending_buffer_complete_ && changed_config) { - pending_buffer_complete_ = false; - delegate_->OnPushBufferComplete(MediaPipelineBackend::kBufferSuccess); - } - return true; -} - -void AudioDecoderForMixer::ResetMixerInputForNewConfig( - const AudioConfig& config) { - // Destroy the old input first to ensure that the mixer output sample rate - // is updated. - mixer_input_.reset(); - - pending_output_frames_ = kNoPendingOutput; - next_buffer_delay_ = AudioDecoderForMixer::RenderingDelay(); - int64_t last_timestamp = last_push_playout_timestamp_; - last_push_playout_timestamp_ = kInvalidTimestamp; - - CreateMixerInput(config, av_sync_enabled_); - if (av_sync_enabled_) { - if (last_timestamp != kInvalidTimestamp && - last_push_pts_ != kInvalidTimestamp) { - mixer_input_->SetStartTimestamp(last_timestamp, last_push_pts_); - } else { - // Pause + resume starts playback immediately. - mixer_input_->Pause(); - mixer_input_->Resume(); - } - } -} - -void AudioDecoderForMixer::CreateDecoder() { - DCHECK(!decoder_); - DCHECK(IsValidConfig(input_config_)); - - // No need to create a decoder if the samples are already decoded. - if (BypassDecoder()) { - LOG(INFO) << "Data is not coded. Decoder will not be used."; - return; - } - - // Create a decoder. - decoder_ = CastAudioDecoder::Create(task_runner_, input_config_, - kDecoderSampleFormat); - if (!decoder_) { - LOG(ERROR) << "Failed to create audio decoder"; - delegate_->OnDecoderError(); - } -} - -bool AudioDecoderForMixer::SetVolume(float multiplier) { - TRACE_FUNCTION_ENTRY1(multiplier); - DCHECK(task_runner_->BelongsToCurrentThread()); - volume_multiplier_ = multiplier; - if (mixer_input_) - mixer_input_->SetVolumeMultiplier(volume_multiplier_); - return true; -} - -AudioDecoderForMixer::RenderingDelay AudioDecoderForMixer::GetRenderingDelay() { - TRACE_FUNCTION_ENTRY0(); - if (paused_) { - return RenderingDelay(); - } - - AudioDecoderForMixer::RenderingDelay delay = next_buffer_delay_; - if (delay.timestamp_microseconds != INT64_MIN) { - double usec_per_sample = 1000000.0 / decoded_config_.samples_per_second; - double queued_output_frames = 0.0; - - // Account for data that is in the process of being pushed to the mixer. - if (pending_output_frames_ != kNoPendingOutput) { - queued_output_frames += pending_output_frames_; - } - delay.delay_microseconds += queued_output_frames * usec_per_sample; - } - - return delay; -} - -AudioDecoderForMixer::AudioTrackTimestamp -AudioDecoderForMixer::GetAudioTrackTimestamp() { - return AudioTrackTimestamp(); -} - -int AudioDecoderForMixer::GetStartThresholdInFrames() { - return 0; -} - -void AudioDecoderForMixer::OnBufferDecoded( - uint64_t input_bytes, - bool has_config, - CastAudioDecoder::Status status, - const AudioConfig& config, - scoped_refptr decoded) { - TRACE_FUNCTION_ENTRY0(); - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(!pending_buffer_complete_); - - if (!mixer_input_) { - LOG(DFATAL) << "Buffer pushed before Start() or after Stop()"; - return; - } - if (status == CastAudioDecoder::Status::kDecodeError) { - LOG(ERROR) << "Decode error"; - delegate_->OnPushBufferComplete(MediaPipelineBackend::kBufferFailed); - return; - } - if (mixer_error_) { - delegate_->OnPushBufferComplete(MediaPipelineBackend::kBufferFailed); - return; - } - - Statistics delta; - delta.decoded_bytes = input_bytes; - UpdateStatistics(delta); - - if (has_config) { - bool changed_config = false; - if (config.samples_per_second != decoded_config_.samples_per_second) { - LOG(INFO) << "Input sample rate changed from " - << decoded_config_.samples_per_second << " to " - << config.samples_per_second; - decoded_config_.samples_per_second = config.samples_per_second; - changed_config = true; - } - if (config.channel_number != decoded_config_.channel_number) { - LOG(INFO) << "Input channel count changed from " - << decoded_config_.channel_number << " to " - << config.channel_number; - decoded_config_.channel_number = config.channel_number; - changed_config = true; - } - if (changed_config) { - // Config from actual stream doesn't match supposed config from the - // container. Update the mixer. - ResetMixerInputForNewConfig(decoded_config_); - } - } - - if (!decoded->end_of_stream()) { - pending_output_frames_ = - decoded->data_size() / (decoded_config_.channel_number * sizeof(float)); - last_push_pts_ = decoded->timestamp(); - last_push_playout_timestamp_ = - (next_buffer_delay_.timestamp_microseconds == kInvalidTimestamp - ? kInvalidTimestamp - : next_buffer_delay_.timestamp_microseconds + - next_buffer_delay_.delay_microseconds); - } - WritePcm(std::move(decoded)); -} - -void AudioDecoderForMixer::CheckBufferComplete() { - if (!pending_buffer_complete_) { - return; - } - - pending_buffer_complete_ = false; - delegate_->OnPushBufferComplete(MediaPipelineBackend::kBufferSuccess); -} - -bool AudioDecoderForMixer::BypassDecoder() const { - DCHECK(task_runner_->BelongsToCurrentThread()); - // The mixer input requires planar float PCM data. - return (input_config_.codec == kCodecPCM && - input_config_.sample_format == kSampleFormatPlanarF32); -} - -void AudioDecoderForMixer::WritePcm(scoped_refptr buffer) { - DCHECK(mixer_input_); - DCHECK(buffer_pool_); - DCHECK(!pending_buffer_complete_); - - if (buffer->end_of_stream()) { - pending_buffer_complete_ = true; - mixer_input_->SendAudioBuffer(buffer_pool_->GetBuffer(), 0, 0); - return; - } - - const int frame_size = sizeof(float) * decoded_config_.channel_number; - const int original_frame_count = buffer->data_size() / frame_size; - if (original_frame_count == 0) { - // Don't send empty buffers since it is interpreted as EOS. - delegate_->OnPushBufferComplete(MediaPipelineBackend::kBufferSuccess); - return; - } - - const int frame_count = buffer->data_size() / frame_size; - DCHECK_GT(frame_count, 0); - - if (frame_count > buffer_pool_frames_) { - CreateBufferPool(decoded_config_, frame_count * 2); - } - - auto io_buffer = buffer_pool_->GetBuffer(); - memcpy(io_buffer->data() + kAudioMessageHeaderSize, buffer->data(), - buffer->data_size()); - - pending_buffer_complete_ = true; - mixer_input_->SendAudioBuffer(std::move(io_buffer), frame_count, - buffer->timestamp()); -} - -void AudioDecoderForMixer::FillNextBuffer(void* buffer, - int frames, - int64_t delay_timestamp, - int64_t delay) { - DCHECK(task_runner_->BelongsToCurrentThread()); - pending_output_frames_ = kNoPendingOutput; - next_buffer_delay_ = RenderingDelay(delay, delay_timestamp); - CheckBufferComplete(); -} - -void AudioDecoderForMixer::OnAudioReadyForPlayback(int64_t mixer_delay) { - DCHECK(task_runner_->BelongsToCurrentThread()); - mixer_delay_ = RenderingDelay(mixer_delay, MonotonicClockNow()); - if (reported_ready_for_playback_) { - return; - } - reported_ready_for_playback_ = true; - backend_->OnAudioReadyForPlayback(); -} - -void AudioDecoderForMixer::OnEosPlayed() { - DCHECK(task_runner_->BelongsToCurrentThread()); - CheckBufferComplete(); - delegate_->OnEndOfStream(); -} - -void AudioDecoderForMixer::OnMixerError() { - DCHECK(task_runner_->BelongsToCurrentThread()); - mixer_error_ = true; - delegate_->OnDecoderError(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/audio_decoder_for_mixer.h chromium-132.0.6834.159/chromecast/media/cma/backend/audio_decoder_for_mixer.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/audio_decoder_for_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/audio_decoder_for_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,141 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_DECODER_FOR_MIXER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_DECODER_FOR_MIXER_H_ - -#include -#include - -#include "base/functional/bind.h" -#include "chromecast/media/api/cast_audio_decoder.h" -#include "chromecast/media/audio/mixer_service/output_stream_connection.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "media/base/audio_buffer.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -class IOBufferPool; - -namespace media { -class DecoderBufferBase; -class MediaPipelineBackendForMixer; - -// AudioDecoder implementation that streams decoded stream to the StreamMixer. -class AudioDecoderForMixer - : public MediaPipelineBackend::AudioDecoder, - public mixer_service::OutputStreamConnection::Delegate { - public: - using BufferStatus = MediaPipelineBackend::BufferStatus; - - explicit AudioDecoderForMixer(MediaPipelineBackendForMixer* backend); - - AudioDecoderForMixer(const AudioDecoderForMixer&) = delete; - AudioDecoderForMixer& operator=(const AudioDecoderForMixer&) = delete; - - ~AudioDecoderForMixer() override; - - virtual void Initialize(); - virtual bool Start(int64_t pts, bool av_sync_enabled); - void StartPlaybackAt(int64_t timestamp); - virtual void Stop(); - virtual bool Pause(); - virtual bool Resume(); - virtual float SetPlaybackRate(float rate); - virtual bool GetTimestampedPts(int64_t* timestamp, int64_t* pts) const; - virtual int64_t GetCurrentPts() const; - - // MediaPipelineBackend::AudioDecoder implementation: - void SetDelegate(MediaPipelineBackend::Decoder::Delegate* delegate) override; - BufferStatus PushBuffer(CastDecoderBuffer* buffer) override; - void GetStatistics(Statistics* statistics) override; - bool SetConfig(const AudioConfig& config) override; - bool SetVolume(float multiplier) override; - RenderingDelay GetRenderingDelay() override; - AudioTrackTimestamp GetAudioTrackTimestamp() override; - int GetStartThresholdInFrames() override; - - // This allows for very small changes in the rate of audio playback that are - // (supposedly) imperceptible. - double SetAvSyncPlaybackRate(double rate); - void RestartPlaybackAt(int64_t pts, int64_t timestamp); - - RenderingDelay GetMixerRenderingDelay(); - - private: - friend class MockAudioDecoderForMixer; - friend class AvSyncTest; - - // mixer_service::OutputStreamConnection::Delegate implementation: - void FillNextBuffer(void* buffer, - int frames, - int64_t delay_timestamp, - int64_t delay) override; - void OnAudioReadyForPlayback(int64_t mixer_delay) override; - void OnEosPlayed() override; - void OnMixerError() override; - - void CreateBufferPool(const AudioConfig& config, int frame_count); - void CreateMixerInput(const AudioConfig& config, bool av_sync_enabled); - void CleanUpPcm(); - void ResetMixerInputForNewConfig(const AudioConfig& config); - void CreateDecoder(); - - void OnBufferDecoded(uint64_t input_bytes, - bool has_config, - CastAudioDecoder::Status status, - const AudioConfig& config, - scoped_refptr decoded); - void CheckBufferComplete(); - void WritePcm(scoped_refptr buffer); - bool BypassDecoder() const; - void UpdateStatistics(Statistics delta); - - MediaPipelineBackendForMixer* const backend_; - const scoped_refptr task_runner_; - MediaPipelineBackend::Decoder::Delegate* delegate_ = nullptr; - - Statistics stats_; - - int buffer_pool_frames_ = 0; - bool pending_buffer_complete_ = false; - bool mixer_error_ = false; - bool paused_ = false; - float playback_rate_ = 1.0f; - bool reported_ready_for_playback_ = false; - RenderingDelay mixer_delay_; - - AudioConfig input_config_; - AudioConfig decoded_config_; - std::unique_ptr decoder_; - - double av_sync_clock_rate_ = 1.0; - - std::unique_ptr mixer_input_; - - RenderingDelay next_buffer_delay_; - int64_t pending_output_frames_ = -1; - float volume_multiplier_ = 1.0f; - - int64_t last_push_pts_ = INT64_MIN; - int64_t last_push_playout_timestamp_ = INT64_MIN; - - scoped_refptr<::media::AudioBufferMemoryPool> pool_; - scoped_refptr buffer_pool_; - - int64_t playback_start_pts_ = 0; - bool av_sync_enabled_ = false; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_DECODER_FOR_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/audio_video_pipeline_device_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/audio_video_pipeline_device_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/audio_video_pipeline_device_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/audio_video_pipeline_device_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,1259 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include -#include -#include - -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/files/memory_mapped_file.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" -#include "base/path_service.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "chromecast/base/task_runner_impl.h" -#if defined(ENABLE_VIDEO_WITH_MIXED_AUDIO) -#include "chromecast/media/cma/backend/audio_decoder_for_mixer.h" // nogncheck -#include "chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h" // nogncheck -#include "chromecast/media/cma/backend/video_decoder_for_mixer.h" // nogncheck -#endif -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/media/cma/test/frame_segmenter_for_test.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_capabilities_shlib.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/audio_device_description.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/audio_timestamp_helper.h" -#include "media/base/decoder_buffer.h" -#include "media/base/encryption_scheme.h" -#include "media/base/video_decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -class AudioVideoPipelineDeviceTest; - -namespace { - -const base::TimeDelta kMonitorLoopDelay = base::Milliseconds(20); -// Call Start() with an initial PTS of 0.5 seconds, to test the behaviour if -// we push buffers with a PTS before the start PTS. In this case the backend -// should report the PTS as no later than the last pushed buffers. -const int64_t kStartPts = 500 * 1000; - -// Amount that PTS is allowed to progress past the time that Pause() was called. -const int kPausePtsSlackMs = 75; -// Number of effects streams to open simultaneously when also playing a -// non-effects stream. -const int kNumEffectsStreams = 1; - -void IgnoreEos() {} - -AudioConfig DefaultAudioConfig() { - AudioConfig default_config; - default_config.codec = kCodecPCM; - default_config.channel_layout = ChannelLayout::STEREO; - default_config.sample_format = kSampleFormatS16; - default_config.channel_number = 2; - default_config.bytes_per_channel = 2; - default_config.samples_per_second = 48000; - return default_config; -} - -VideoConfig DefaultVideoConfig() { - VideoConfig default_config; - default_config.codec = kCodecH264; - default_config.profile = kH264Main; - default_config.additional_config = nullptr; - default_config.encryption_scheme = EncryptionScheme::kUnencrypted; - return default_config; -} - -base::FilePath GetTestDataFilePath(const std::string& name) { - base::FilePath file_path; - CHECK(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &file_path)); - - file_path = file_path.Append(FILE_PATH_LITERAL("media")) - .Append(FILE_PATH_LITERAL("test")) - .Append(FILE_PATH_LITERAL("data")) - .AppendASCII(name); - return file_path; -} - -class BufferFeeder : public MediaPipelineBackend::Decoder::Delegate { - public: - explicit BufferFeeder(base::OnceClosure eos_cb); - - BufferFeeder(const BufferFeeder&) = delete; - BufferFeeder& operator=(const BufferFeeder&) = delete; - - ~BufferFeeder() override {} - - static std::unique_ptr LoadAudio(MediaPipelineBackend* backend, - const std::string& filename, - base::OnceClosure eos_cb); - static std::unique_ptr LoadVideo(MediaPipelineBackend* backend, - const std::string& filename, - bool raw_h264, - base::OnceClosure eos_cb); - - bool eos() const { return eos_; } - MediaPipelineBackend::Decoder* decoder() const { return decoder_; } - int64_t last_pushed_pts() const { return last_pushed_pts_; } - - void SetAudioConfig(const AudioConfig& config) { audio_config_ = config; } - void SetVideoConfig(const VideoConfig& config) { video_config_ = config; } - - void FeedContinuousPcm(); - void PauseBeforeEos(); - void Initialize(MediaPipelineBackend* backend, - MediaPipelineBackend::Decoder* decoder, - const BufferList& buffers); - void Start(); - void Stop(); - - void ScheduleConfigTest(); - - void TestAudioConfigs(); - void TestAudioVolume(); - void TestVideoConfigs(); - - // MediaPipelineBackend::Decoder::Delegate implementation: - void OnPushBufferComplete(MediaPipelineBackend::BufferStatus status) override; - void OnEndOfStream() override; - void OnDecoderError() override; - void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override; - void OnVideoResolutionChanged(const Size& size) override; - - private: - void FeedBuffer(); - void FeedPcm(); - void TestConfigs(); - - base::OnceClosure eos_cb_; - bool within_push_buffer_call_; - bool expecting_buffer_complete_; - bool feeding_completed_; - bool eos_; - bool pause_before_eos_; - bool test_config_after_next_push_; - bool feed_continuous_pcm_; - MediaPipelineBackend* backend_; - MediaPipelineBackend::Decoder* decoder_; - BufferList buffers_; - BufferList buffers_copy_; - scoped_refptr pending_buffer_; - base::ThreadChecker thread_checker_; - AudioConfig audio_config_; - VideoConfig video_config_; - int64_t last_pushed_pts_; - std::unique_ptr<::media::AudioTimestampHelper> timestamp_helper_; -}; - -} // namespace - -class AudioVideoPipelineDeviceTest : public testing::Test { - public: - struct PauseInfo { - PauseInfo() {} - PauseInfo(base::TimeDelta d, base::TimeDelta l) : delay(d), length(l) {} - ~PauseInfo() {} - - base::TimeDelta delay; - base::TimeDelta length; - }; - - AudioVideoPipelineDeviceTest(); - - AudioVideoPipelineDeviceTest(const AudioVideoPipelineDeviceTest&) = delete; - AudioVideoPipelineDeviceTest& operator=(const AudioVideoPipelineDeviceTest&) = - delete; - - ~AudioVideoPipelineDeviceTest() override; - - MediaPipelineBackend* backend() const { return backend_.get(); } - void set_sync_type(MediaPipelineDeviceParams::MediaSyncType sync_type) { - sync_type_ = sync_type; - } - void set_audio_type(MediaPipelineDeviceParams::AudioStreamType audio_type) { - audio_type_ = audio_type; - } - - void SetUp() override { - CastMediaShlib::Initialize(base::CommandLine::ForCurrentProcess()->argv()); - VolumeControl::Initialize(base::CommandLine::ForCurrentProcess()->argv()); - } - - void TearDown() override { - // Pipeline must be destroyed before finalizing media shlib. - backend_.reset(); - effects_backends_.clear(); - VolumeControl::Finalize(); - CastMediaShlib::Finalize(); - } - - void ConfigureForFile(const std::string& filename); - void ConfigureForAudioOnly(const std::string& filename); - void ConfigureForVideoOnly(const std::string& filename, bool raw_h264); - - // Pattern loops, waiting >= pattern[i].delay against media clock between - // pauses, then pausing for >= pattern[i].length against MessageLoop - // A pause with delay <0 signals to stop sequence and do not loop - void SetPausePattern(const std::vector pattern); - - // Adds a pause to the end of pause pattern - void AddPause(base::TimeDelta delay, base::TimeDelta length); - void PauseBeforeEos(); - void AddEffectsStreams(); - - void Initialize(); - void Start(); - void RunUntilIdle(); - void OnEndOfStream(); - - void SetAudioFeeder(std::unique_ptr audio_feeder) { - audio_feeder_ = std::move(audio_feeder); - } - void SetVideoFeeder(std::unique_ptr video_feeder) { - video_feeder_ = std::move(video_feeder); - } - - void RunStoppedChecks(); - void RunPlaybackChecks(); - void TestBackendStates(); - void StartImmediateEosTest(); - void EndImmediateEosTest(); - - private: - void MonitorLoop(); - - void OnPauseCompleted(); - - base::test::TaskEnvironment task_environment_; - MediaPipelineDeviceParams::MediaSyncType sync_type_; - MediaPipelineDeviceParams::AudioStreamType audio_type_; - std::unique_ptr task_runner_; - std::unique_ptr backend_; - std::vector> effects_backends_; - std::vector> effects_feeders_; - std::unique_ptr audio_feeder_; - std::unique_ptr video_feeder_; - bool stopped_; - bool ran_playing_playback_checks_; - bool backwards_pts_change_; - int64_t last_pts_; - - base::RunLoop loop_{base::RunLoop::Type::kNestableTasksAllowed}; - - // Current media time. - base::TimeDelta pause_time_; - - // Pause settings - std::vector pause_pattern_; - size_t pause_pattern_idx_; -}; - -namespace { - -BufferFeeder::BufferFeeder(base::OnceClosure eos_cb) - : eos_cb_(std::move(eos_cb)), - within_push_buffer_call_(false), - expecting_buffer_complete_(false), - feeding_completed_(false), - eos_(false), - pause_before_eos_(false), - test_config_after_next_push_(false), - feed_continuous_pcm_(false), - backend_(nullptr) { - CHECK(!eos_cb_.is_null()); -} - -void BufferFeeder::FeedContinuousPcm() { - feed_continuous_pcm_ = true; -} - -void BufferFeeder::PauseBeforeEos() { - pause_before_eos_ = true; -} - -void BufferFeeder::Initialize(MediaPipelineBackend* backend, - MediaPipelineBackend::Decoder* decoder, - const BufferList& buffers) { - CHECK(backend); - CHECK(decoder); - backend_ = backend; - decoder_ = decoder; - decoder_->SetDelegate(this); - buffers_ = buffers; - buffers_.push_back(scoped_refptr( - new DecoderBufferAdapter(::media::DecoderBuffer::CreateEOSBuffer()))); -} - -void BufferFeeder::Start() { - if (feed_continuous_pcm_) { - timestamp_helper_.reset( - new ::media::AudioTimestampHelper(audio_config_.samples_per_second)); - timestamp_helper_->SetBaseTimestamp(base::TimeDelta()); - } - last_pushed_pts_ = std::numeric_limits::min(); - buffers_copy_ = buffers_; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&BufferFeeder::FeedBuffer, base::Unretained(this))); -} - -void BufferFeeder::Stop() { - feeding_completed_ = true; -} - -void BufferFeeder::ScheduleConfigTest() { -#if defined(ENABLE_VIDEO_WITH_MIXED_AUDIO) - // On mixer backends, the config test causes the mixer to remove/add the - // mixer input, which causes it to return invalid PTS to AV sync. Disable for - // now. - // TODO(almasrymina): re-enable this. b/110961816. - return; -#else - if (expecting_buffer_complete_) { - test_config_after_next_push_ = true; - } else { - TestConfigs(); - } -#endif -} - -void BufferFeeder::FeedBuffer() { - CHECK(decoder_); - if (feeding_completed_) - return; - if (feed_continuous_pcm_) { - FeedPcm(); - return; - } - // Possibly feed one buffer. - CHECK(!buffers_.empty()); - - pending_buffer_ = buffers_.front(); - if (pending_buffer_->end_of_stream()) { - if (pause_before_eos_) - ASSERT_TRUE(backend_->Pause()); - } else { - last_pushed_pts_ = pending_buffer_->timestamp(); - } - expecting_buffer_complete_ = true; - within_push_buffer_call_ = true; - BufferStatus status = decoder_->PushBuffer(pending_buffer_.get()); - within_push_buffer_call_ = false; - EXPECT_NE(status, MediaPipelineBackend::kBufferFailed); - buffers_.pop_front(); - - if (pending_buffer_->end_of_stream() && pause_before_eos_) - ASSERT_TRUE(backend_->Resume()); - - // Feeding is done, just wait for the end of stream callback. - if (pending_buffer_->end_of_stream() || buffers_.empty()) { - if (buffers_.empty() && !pending_buffer_->end_of_stream()) - LOG(WARNING) << "Stream emptied without feeding EOS frame"; - if (!buffers_.empty()) - LOG(WARNING) << "Stream has more buffers after EOS frame"; - - feeding_completed_ = true; - } - - if (status == MediaPipelineBackend::kBufferPending) - return; - - OnPushBufferComplete(MediaPipelineBackend::kBufferSuccess); -} - -void BufferFeeder::FeedPcm() { - const int num_frames = 512; - scoped_refptr<::media::DecoderBuffer> silence_buffer( - new ::media::DecoderBuffer(num_frames * audio_config_.channel_number * - audio_config_.bytes_per_channel)); - memset(silence_buffer->writable_data(), 0, silence_buffer->size()); - pending_buffer_ = new media::DecoderBufferAdapter(silence_buffer); - pending_buffer_->set_timestamp(timestamp_helper_->GetTimestamp()); - timestamp_helper_->AddFrames(num_frames); - - expecting_buffer_complete_ = true; - within_push_buffer_call_ = true; - BufferStatus status = decoder_->PushBuffer(pending_buffer_.get()); - within_push_buffer_call_ = false; - ASSERT_NE(status, MediaPipelineBackend::kBufferFailed); - if (status == MediaPipelineBackend::kBufferPending) - return; - OnPushBufferComplete(MediaPipelineBackend::kBufferSuccess); -} - -void BufferFeeder::OnEndOfStream() { - DCHECK(thread_checker_.CalledOnValidThread()); - EXPECT_FALSE(expecting_buffer_complete_) - << "Got OnEndOfStream() before the EOS buffer completed"; - eos_ = true; - std::move(eos_cb_).Run(); -} - -void BufferFeeder::OnPushBufferComplete(BufferStatus status) { - DCHECK(thread_checker_.CalledOnValidThread()); - pending_buffer_ = nullptr; - EXPECT_FALSE(within_push_buffer_call_) - << "OnPushBufferComplete() called during a call to PushBuffer()"; - EXPECT_TRUE(expecting_buffer_complete_) - << "OnPushBufferComplete() called unexpectedly"; - expecting_buffer_complete_ = false; - if (!feed_continuous_pcm_ || !feeding_completed_) { - ASSERT_NE(status, MediaPipelineBackend::kBufferFailed); - } - EXPECT_FALSE(eos_) << "Got OnPushBufferComplete() after OnEndOfStream()"; - - if (test_config_after_next_push_) { - test_config_after_next_push_ = false; - TestConfigs(); - } - - if (feeding_completed_) - return; - - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&BufferFeeder::FeedBuffer, base::Unretained(this))); -} - -void BufferFeeder::OnDecoderError() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (feed_continuous_pcm_) { - feeding_completed_ = true; - } else { - ASSERT_TRUE(false); - } -} - -void BufferFeeder::OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) { - DCHECK(thread_checker_.CalledOnValidThread()); - ASSERT_TRUE(false); -} - -void BufferFeeder::OnVideoResolutionChanged(const Size& size) { - DCHECK(thread_checker_.CalledOnValidThread()); -} - -void BufferFeeder::TestConfigs() { - if (IsValidConfig(audio_config_)) - TestAudioConfigs(); - if (IsValidConfig(video_config_)) - TestVideoConfigs(); -} - -void BufferFeeder::TestAudioConfigs() { - MediaPipelineBackend::AudioDecoder* audio_decoder = - static_cast(decoder_); - AudioConfig config; - // First, make sure that kAudioCodecUnknown is not accepted. - config.codec = kAudioCodecUnknown; - config.channel_layout = ChannelLayout::STEREO; - config.sample_format = kSampleFormatS16; - config.channel_number = 2; - config.bytes_per_channel = 2; - config.samples_per_second = 48000; - // Set invalid config first, to test that the decoder still accepts valid - // config after an invalid config. - audio_decoder->SetConfig(config); - - // Next, test required sample formats. - config.codec = kCodecPCM; - EXPECT_TRUE(audio_decoder->SetConfig(config)) - << "Audio decoder does not accept kCodecPCM"; - - config.sample_format = kSampleFormatPlanarF32; - config.bytes_per_channel = 4; - EXPECT_TRUE(audio_decoder->SetConfig(config)) - << "Audio decoder does not accept kCodecPCM with " - << "planar float (required for multiroom audio)"; - - config.codec = kCodecAAC; - // TODO(kmackay) Determine required sample formats/channel numbers. - config.sample_format = kSampleFormatS16; - config.bytes_per_channel = 2; - config.codec = kCodecPCM; - EXPECT_TRUE(audio_decoder->SetConfig(config)) - << "Audio decoder does not accept kCodecPCM"; - config.codec = kCodecPCM_S16BE; - EXPECT_TRUE(audio_decoder->SetConfig(config)) - << "Audio decoder does not accept kCodecPCM_S16BE"; - config.codec = kCodecAAC; - EXPECT_TRUE(audio_decoder->SetConfig(config)) - << "Audio decoder does not accept kCodecAAC"; - config.codec = kCodecMP3; - EXPECT_TRUE(audio_decoder->SetConfig(config)) - << "Audio decoder does not accept kCodecMP3"; - - // Test supported sample rates. - const int kRequiredSampleRates[] = {8000, 11025, 12000, 16000, 22050, - 24000, 32000, 44100, 48000}; - const int kHiResSampleRates[] = {64000, 88200, 96000}; - config.codec = kCodecPCM; - for (int rate : kRequiredSampleRates) { - config.samples_per_second = rate; - EXPECT_TRUE(audio_decoder->SetConfig(config)) - << "Audio decoder does not accept sample rate " << rate; - } - for (int rate : kHiResSampleRates) { - config.samples_per_second = rate; - if (!audio_decoder->SetConfig(config)) - LOG(INFO) << "Audio decoder does not accept hi-res sample rate " << rate; - } - EXPECT_TRUE(audio_decoder->SetConfig(audio_config_)); -} - -void BufferFeeder::TestAudioVolume() { - MediaPipelineBackend::AudioDecoder* audio_decoder = - static_cast(decoder_); - EXPECT_TRUE(audio_decoder->SetVolume(1.0)) - << "Failed to set audio volume to 1.0"; - EXPECT_TRUE(audio_decoder->SetVolume(0.0)) - << "Failed to set audio volume to 0.0"; - EXPECT_TRUE(audio_decoder->SetVolume(0.2)) - << "Failed to set audio volume to 0.2"; -} - -void BufferFeeder::TestVideoConfigs() { - MediaPipelineBackend::VideoDecoder* video_decoder = - static_cast(decoder_); - // Set invalid config first, to test that the decoder still accepts valid - // config after an invalid config. - VideoConfig config; - config.codec = kVideoCodecUnknown; - video_decoder->SetConfig(config); - - EXPECT_TRUE(video_decoder->SetConfig(video_config_)); -} - -// static -std::unique_ptr BufferFeeder::LoadAudio( - MediaPipelineBackend* backend, - const std::string& filename, - base::OnceClosure eos_cb) { - CHECK(backend); - base::FilePath file_path = GetTestDataFilePath(filename); - DemuxResult demux_result = FFmpegDemuxForTest(file_path, true /* audio */); - - MediaPipelineBackend::AudioDecoder* decoder = backend->CreateAudioDecoder(); - CHECK(decoder); - AudioConfig config = DecoderConfigAdapter::ToCastAudioConfig( - kPrimary, demux_result.audio_config); - bool success = decoder->SetConfig(config); - CHECK(success); - - LOG(INFO) << "Got " << demux_result.frames.size() << " audio input frames"; - std::unique_ptr feeder(new BufferFeeder(std::move(eos_cb))); - feeder->audio_config_ = config; - feeder->Initialize(backend, decoder, demux_result.frames); - return feeder; -} - -// static -std::unique_ptr BufferFeeder::LoadVideo( - MediaPipelineBackend* backend, - const std::string& filename, - bool raw_h264, - base::OnceClosure eos_cb) { - CHECK(backend); - - VideoConfig video_config; - BufferList buffers; - if (raw_h264) { - base::FilePath file_path = GetTestDataFilePath(filename); - base::MemoryMappedFile video_stream; - CHECK(video_stream.Initialize(file_path)) - << "Couldn't open stream file: " << file_path.MaybeAsASCII(); - buffers = H264SegmenterForTest(video_stream.data(), video_stream.length()); - - // TODO(erickung): Either pull data from stream or make caller specify value - video_config.codec = kCodecH264; - video_config.profile = kH264Main; - video_config.additional_config = nullptr; - video_config.encryption_scheme = EncryptionScheme::kUnencrypted; - } else { - base::FilePath file_path = GetTestDataFilePath(filename); - DemuxResult demux_result = FFmpegDemuxForTest(file_path, false /* audio */); - buffers = demux_result.frames; - video_config = DecoderConfigAdapter::ToCastVideoConfig( - kPrimary, demux_result.video_config); - } - - MediaPipelineBackend::VideoDecoder* decoder = backend->CreateVideoDecoder(); - CHECK(decoder); - - bool success = decoder->SetConfig(video_config); - CHECK(success); - - LOG(INFO) << "Got " << buffers.size() << " video input frames"; - std::unique_ptr feeder(new BufferFeeder(std::move(eos_cb))); - feeder->video_config_ = video_config; - feeder->Initialize(backend, decoder, buffers); - return feeder; -} - -} // namespace - -AudioVideoPipelineDeviceTest::AudioVideoPipelineDeviceTest() - : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), - sync_type_(MediaPipelineDeviceParams::kModeSyncPts), - audio_type_(MediaPipelineDeviceParams::kAudioStreamNormal), - stopped_(false), - ran_playing_playback_checks_(false), - backwards_pts_change_(false), - pause_pattern_() {} - -AudioVideoPipelineDeviceTest::~AudioVideoPipelineDeviceTest() {} - -void AudioVideoPipelineDeviceTest::Initialize() { -#if defined(ENABLE_VIDEO_WITH_MIXED_AUDIO) - VideoDecoderForMixer::InitializeGraphicsForTesting(); -#endif - - // Create the media device. - task_runner_.reset(new TaskRunnerImpl()); - MediaPipelineDeviceParams params( - sync_type_, audio_type_, task_runner_.get(), AudioContentType::kMedia, - ::media::AudioDeviceDescription::kDefaultDeviceId); - backend_.reset(CastMediaShlib::CreateMediaPipelineBackend(params)); - CHECK(backend_); -} - -void AudioVideoPipelineDeviceTest::AddPause(base::TimeDelta delay, - base::TimeDelta length) { - DCHECK_EQ(MediaPipelineDeviceParams::kModeSyncPts, sync_type_); - pause_pattern_.push_back(PauseInfo(delay, length)); -} - -void AudioVideoPipelineDeviceTest::PauseBeforeEos() { - if (audio_feeder_) - audio_feeder_->PauseBeforeEos(); - if (video_feeder_) - video_feeder_->PauseBeforeEos(); -} - -void AudioVideoPipelineDeviceTest::AddEffectsStreams() { - for (int i = 0; i < kNumEffectsStreams; ++i) { - MediaPipelineDeviceParams params( - MediaPipelineDeviceParams::kModeIgnorePts, - MediaPipelineDeviceParams::kAudioStreamSoundEffects, task_runner_.get(), - AudioContentType::kMedia, - ::media::AudioDeviceDescription::kDefaultDeviceId); - MediaPipelineBackend* effects_backend = - CastMediaShlib::CreateMediaPipelineBackend(params); - CHECK(effects_backend); - effects_backends_.push_back(base::WrapUnique(effects_backend)); - - MediaPipelineBackend::AudioDecoder* audio_decoder = - effects_backend->CreateAudioDecoder(); - audio_decoder->SetConfig(DefaultAudioConfig()); - - std::unique_ptr feeder( - new BufferFeeder(base::BindOnce(&IgnoreEos))); - feeder->FeedContinuousPcm(); - feeder->Initialize(effects_backend, audio_decoder, BufferList()); - feeder->SetAudioConfig(DefaultAudioConfig()); - effects_feeders_.push_back(std::move(feeder)); - ASSERT_TRUE(effects_backend->Initialize()); - } -} - -void AudioVideoPipelineDeviceTest::SetPausePattern( - const std::vector pattern) { - DCHECK_EQ(MediaPipelineDeviceParams::kModeSyncPts, sync_type_); - pause_pattern_ = pattern; -} - -void AudioVideoPipelineDeviceTest::ConfigureForAudioOnly( - const std::string& filename) { - Initialize(); - audio_feeder_ = BufferFeeder::LoadAudio( - backend_.get(), filename, - base::BindOnce(&AudioVideoPipelineDeviceTest::OnEndOfStream, - base::Unretained(this))); - ASSERT_TRUE(backend_->Initialize()); -} - -void AudioVideoPipelineDeviceTest::ConfigureForVideoOnly( - const std::string& filename, - bool raw_h264) { - Initialize(); - video_feeder_ = BufferFeeder::LoadVideo( - backend_.get(), filename, raw_h264, - base::BindOnce(&AudioVideoPipelineDeviceTest::OnEndOfStream, - base::Unretained(this))); - ASSERT_TRUE(backend_->Initialize()); -} - -void AudioVideoPipelineDeviceTest::ConfigureForFile( - const std::string& filename) { - Initialize(); - base::OnceClosure eos_video_cb = base::BindOnce( - &AudioVideoPipelineDeviceTest::OnEndOfStream, base::Unretained(this)); - base::OnceClosure eos_audio_cb = base::BindOnce( - &AudioVideoPipelineDeviceTest::OnEndOfStream, base::Unretained(this)); - - video_feeder_ = BufferFeeder::LoadVideo( - backend_.get(), filename, false /* raw_h264 */, std::move(eos_video_cb)); - audio_feeder_ = BufferFeeder::LoadAudio(backend_.get(), filename, - std::move(eos_audio_cb)); - ASSERT_TRUE(backend_->Initialize()); -} - -void AudioVideoPipelineDeviceTest::RunUntilIdle() { - loop_.RunUntilIdle(); -} - -void AudioVideoPipelineDeviceTest::Start() { - pause_time_ = base::TimeDelta(); - pause_pattern_idx_ = 0; - stopped_ = false; - ran_playing_playback_checks_ = false; - last_pts_ = std::numeric_limits::min(); - - if (audio_feeder_) - audio_feeder_->Start(); - if (video_feeder_) - video_feeder_->Start(); - - for (auto& feeder : effects_feeders_) - feeder->Start(); - for (auto& backend : effects_backends_) - backend->Start(kStartPts); - - RunStoppedChecks(); - - backend_->Start(kStartPts); - // The buffering logic in the media pipeline always starts playback in a - // paused state. For AV sync reasons, the AV sync media backend now depends on - // this behavior and doesn't start playback without it, so it needs to be - // added to the test. - backend_->Pause(); - backend_->Resume(); - int64_t current_pts = backend()->GetCurrentPts(); - EXPECT_TRUE(current_pts == kStartPts || - current_pts == std::numeric_limits::min()); - last_pts_ = current_pts; - - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&AudioVideoPipelineDeviceTest::MonitorLoop, - base::Unretained(this))); - - loop_.Run(); -} - -void AudioVideoPipelineDeviceTest::RunStoppedChecks() { - if (audio_feeder_) { - audio_feeder_->ScheduleConfigTest(); - audio_feeder_->TestAudioVolume(); - } - if (video_feeder_) - video_feeder_->ScheduleConfigTest(); -} - -void AudioVideoPipelineDeviceTest::RunPlaybackChecks() { - if (sync_type_ != MediaPipelineDeviceParams::kModeSyncPts) - return; - RunStoppedChecks(); - - EXPECT_TRUE(backend_->SetPlaybackRate(1.0f)); - if (!backend_->SetPlaybackRate(0.1f)) - LOG(INFO) << "Playback rate 0.1 not supported"; - if (!backend_->SetPlaybackRate(0.5f)) - LOG(INFO) << "Playback rate 0.5 not supported"; - if (!backend_->SetPlaybackRate(1.5f)) - LOG(INFO) << "Playback rate 1.5 not supported"; - EXPECT_TRUE(backend_->SetPlaybackRate(1.0f)); -} - -void AudioVideoPipelineDeviceTest::OnEndOfStream() { - if ((!audio_feeder_ || audio_feeder_->eos()) && - (!video_feeder_ || video_feeder_->eos())) { - RunPlaybackChecks(); - backend_->Stop(); - stopped_ = true; - RunStoppedChecks(); - - for (auto& feeder : effects_feeders_) - feeder->Stop(); - - loop_.QuitWhenIdle(); - } -} - -void AudioVideoPipelineDeviceTest::MonitorLoop() { - // Backend is stopped, no need to monitor the loop any more. - if (stopped_ || !backend_) - return; - - // Run checks while playing (once). - if (!ran_playing_playback_checks_) { - RunPlaybackChecks(); - ran_playing_playback_checks_ = true; - } - - int64_t pts = backend_->GetCurrentPts(); - base::TimeDelta media_time = base::Microseconds(pts); - if (sync_type_ == MediaPipelineDeviceParams::kModeSyncPts) { - // Check that the current PTS is no more than 100ms past the last pushed - // PTS. - if (audio_feeder_ && audio_feeder_->last_pushed_pts() != - std::numeric_limits::min()) { - EXPECT_LE(pts, std::max(kStartPts, - audio_feeder_->last_pushed_pts() + 100 * 1000)); - } - if (video_feeder_ && video_feeder_->last_pushed_pts() != - std::numeric_limits::min()) { - EXPECT_LE(pts, std::max(kStartPts, - video_feeder_->last_pushed_pts() + 100 * 1000)); - } - // PTS is allowed to move backwards once to allow for updates when the first - // buffers are pushed. - if (!backwards_pts_change_) { - if (pts < last_pts_) - backwards_pts_change_ = true; - } else { - EXPECT_GE(pts, last_pts_); - } - last_pts_ = pts; - } - -#if defined(ENABLE_VIDEO_WITH_MIXED_AUDIO) - // Do AV sync checks. - MediaPipelineBackendForMixer* backend_for_mixer = - static_cast(backend_.get()); - DCHECK(backend_for_mixer); - - int64_t playback_start_time = - backend_for_mixer->GetPlaybackStartTimeForTesting(); - - // The playback start time will be INT64_MIN until the audio and video are - // ready for playback, so just defer all the AV sync checks till then. - if (playback_start_time == INT64_MIN) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&AudioVideoPipelineDeviceTest::MonitorLoop, - base::Unretained(this)), - kMonitorLoopDelay); - return; - } - - int64_t playback_start_pts = - backend_for_mixer->GetPlaybackStartPtsForTesting(); - - if (backend_for_mixer->audio_decoder() && - backend_for_mixer->video_decoder() && - backend_for_mixer->MonotonicClockNow() > playback_start_time + 50000) { - int64_t vpts = 0; - int64_t vpts_timestamp = 0; - EXPECT_TRUE(backend_for_mixer->video_decoder()->GetCurrentPts( - &vpts_timestamp, &vpts)) - << "Getting VPTS failed at current time=" - << backend_for_mixer->MonotonicClockNow() - << " playback should have started at=" << playback_start_time; - - // Check video started at the correct time. - EXPECT_LT(abs((vpts_timestamp - vpts) - - (playback_start_time - playback_start_pts)), - 16000); - - // Check AV sync. - int64_t apts = 0; - int64_t apts_timestamp = 0; - if (backend_for_mixer->audio_decoder()->GetTimestampedPts(&apts_timestamp, - &apts)) { - int64_t av_sync_difference = - (apts - apts_timestamp) - (vpts - vpts_timestamp); - - EXPECT_LT(abs(av_sync_difference), 16000); - } - } -#endif - - if (!pause_pattern_.empty() && pause_pattern_idx_ < pause_pattern_.size() && - pause_pattern_[pause_pattern_idx_].delay >= base::TimeDelta() && - media_time >= pause_time_ + pause_pattern_[pause_pattern_idx_].delay) { - // Do Pause - backend_->Pause(); - pause_time_ = base::Microseconds(backend_->GetCurrentPts()); - RunPlaybackChecks(); - - LOG(INFO) << "Pausing at " << pause_time_.InMilliseconds() << "ms for " - << pause_pattern_[pause_pattern_idx_].length.InMilliseconds() - << "ms"; - - // Wait for pause finish - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&AudioVideoPipelineDeviceTest::OnPauseCompleted, - base::Unretained(this)), - pause_pattern_[pause_pattern_idx_].length); - return; - } - - // Check state again in a little while - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&AudioVideoPipelineDeviceTest::MonitorLoop, - base::Unretained(this)), - kMonitorLoopDelay); -} - -void AudioVideoPipelineDeviceTest::OnPauseCompleted() { - // Make sure the media time didn't move during that time. - base::TimeDelta media_time = base::Microseconds(backend_->GetCurrentPts()); - - // Make sure that the PTS did not advance too much while paused. - EXPECT_LT(media_time, pause_time_ + base::Milliseconds(kPausePtsSlackMs)); - -#if defined(ENABLE_VIDEO_WITH_MIXED_AUDIO) - // Do AV sync checks. - MediaPipelineBackendForMixer* backend_for_mixer = - static_cast(backend_.get()); - DCHECK(backend_for_mixer); - - int64_t playback_start_time = - backend_for_mixer->GetPlaybackStartTimeForTesting(); - - if (backend_for_mixer->audio_decoder() && - backend_for_mixer->video_decoder() && - backend_for_mixer->MonotonicClockNow() > playback_start_time + 50000) { - // Check the audio time. - base::TimeDelta audio_time = - base::Microseconds(backend_for_mixer->audio_decoder()->GetCurrentPts()); - EXPECT_LT(audio_time, pause_time_ + base::Milliseconds(kPausePtsSlackMs)); - - // Check the video time. - int64_t timestamp = 0; - int64_t pts = 0; - EXPECT_TRUE( - backend_for_mixer->video_decoder()->GetCurrentPts(×tamp, &pts)) - << "Getting VPTS failed at current time=" - << backend_for_mixer->MonotonicClockNow() - << " playback should have started at=" << playback_start_time; - - base::TimeDelta video_time = base::Microseconds(pts); - - EXPECT_LT(video_time, pause_time_ + base::Milliseconds(kPausePtsSlackMs)); - } -#endif - - pause_time_ = media_time; - ++pause_pattern_idx_; - - LOG(INFO) << "Pause complete, restarting media clock"; - RunPlaybackChecks(); - - // Resume playback and frame feeding. - backend_->Resume(); - RunPlaybackChecks(); - - MonitorLoop(); -} - -void AudioVideoPipelineDeviceTest::TestBackendStates() { - ASSERT_TRUE(backend()->Initialize()); - RunUntilIdle(); - - RunStoppedChecks(); - RunUntilIdle(); - - const int64_t start_pts = 222; - ASSERT_TRUE(backend()->Start(start_pts)); - RunUntilIdle(); - RunPlaybackChecks(); - - ASSERT_TRUE(backend()->Pause()); - RunUntilIdle(); - RunPlaybackChecks(); - - ASSERT_TRUE(backend()->Resume()); - RunUntilIdle(); - RunPlaybackChecks(); - - backend()->Stop(); - RunUntilIdle(); - - RunStoppedChecks(); - RunUntilIdle(); -} - -void AudioVideoPipelineDeviceTest::StartImmediateEosTest() { - RunStoppedChecks(); - - ASSERT_TRUE(backend()->Initialize()); - RunUntilIdle(); -} - -void AudioVideoPipelineDeviceTest::EndImmediateEosTest() { - RunPlaybackChecks(); - - ASSERT_TRUE(backend_->Pause()); - RunUntilIdle(); - - RunPlaybackChecks(); - - backend_->Stop(); - RunUntilIdle(); - - RunStoppedChecks(); -} - -TEST_F(AudioVideoPipelineDeviceTest, PcmPlayback) { - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForAudioOnly("bear_pcm.wav"); - PauseBeforeEos(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, Mp3Playback) { - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForAudioOnly("sfx.mp3"); - PauseBeforeEos(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, AacPlayback) { - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForAudioOnly("sfx.m4a"); - PauseBeforeEos(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, VorbisPlayback) { - set_sync_type(MediaPipelineDeviceParams::kModeIgnorePts); - ConfigureForAudioOnly("sfx.ogg"); - Start(); -} - -// TODO(kmackay) FFmpegDemuxForTest can't handle AC3 or EAC3. - -TEST_F(AudioVideoPipelineDeviceTest, H264Playback) { - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForVideoOnly("bear.h264", true /* raw_h264 */); - PauseBeforeEos(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, WebmPlaybackWithPause) { - if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, - kVideoProfileUnknown, 1)) - return; - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - // Setup to pause for 100ms every 500ms - AddPause(base::Milliseconds(500), base::Milliseconds(100)); - - ConfigureForVideoOnly("bear-640x360.webm", false /* raw_h264 */); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, Vp8Playback) { - if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, - kVideoProfileUnknown, 1)) - return; - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForVideoOnly("bear-vp8a.webm", false /* raw_h264 */); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, WebmPlayback) { - if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, - kVideoProfileUnknown, 1)) - return; - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForFile("bear-640x360.webm"); - PauseBeforeEos(); - Start(); -} - -// TODO(kmackay) FFmpegDemuxForTest can't handle HEVC or VP9. - -TEST_F(AudioVideoPipelineDeviceTest, AudioBackendStates) { - Initialize(); - MediaPipelineBackend::AudioDecoder* audio_decoder = - backend()->CreateAudioDecoder(); - - // Test setting config before Initialize(). - std::unique_ptr feeder( - new BufferFeeder(base::BindOnce(&IgnoreEos))); - feeder->Initialize(backend(), audio_decoder, BufferList()); - feeder->SetAudioConfig(DefaultAudioConfig()); - feeder->TestAudioConfigs(); - - SetAudioFeeder(std::move(feeder)); - TestBackendStates(); -} - -TEST_F(AudioVideoPipelineDeviceTest, AudioEffectsBackendStates) { - set_audio_type(MediaPipelineDeviceParams::kAudioStreamSoundEffects); - set_sync_type(MediaPipelineDeviceParams::kModeIgnorePts); - Initialize(); - MediaPipelineBackend::AudioDecoder* audio_decoder = - backend()->CreateAudioDecoder(); - - std::unique_ptr feeder( - new BufferFeeder(base::BindOnce(&IgnoreEos))); - feeder->Initialize(backend(), audio_decoder, BufferList()); - feeder->SetAudioConfig(DefaultAudioConfig()); - ASSERT_TRUE(audio_decoder->SetConfig(DefaultAudioConfig())); - - SetAudioFeeder(std::move(feeder)); - TestBackendStates(); -} - -TEST_F(AudioVideoPipelineDeviceTest, VideoBackendStates) { - Initialize(); - MediaPipelineBackend::VideoDecoder* video_decoder = - backend()->CreateVideoDecoder(); - - // Test setting config before Initialize(). - std::unique_ptr feeder( - new BufferFeeder(base::BindOnce(&IgnoreEos))); - feeder->Initialize(backend(), video_decoder, BufferList()); - feeder->SetVideoConfig(DefaultVideoConfig()); - feeder->TestVideoConfigs(); - - SetVideoFeeder(std::move(feeder)); - TestBackendStates(); -} - -TEST_F(AudioVideoPipelineDeviceTest, AudioImmediateEos) { - Initialize(); - MediaPipelineBackend::AudioDecoder* audio_decoder = - backend()->CreateAudioDecoder(); - - std::unique_ptr feeder(new BufferFeeder( - base::BindOnce(&AudioVideoPipelineDeviceTest::EndImmediateEosTest, - base::Unretained(this)))); - feeder->Initialize(backend(), audio_decoder, BufferList()); - feeder->SetAudioConfig(DefaultAudioConfig()); - SetAudioFeeder(std::move(feeder)); - - ASSERT_TRUE(audio_decoder->SetConfig(DefaultAudioConfig())); - StartImmediateEosTest(); -} - -TEST_F(AudioVideoPipelineDeviceTest, VideoImmediateEos) { - Initialize(); - MediaPipelineBackend::VideoDecoder* video_decoder = - backend()->CreateVideoDecoder(); - std::unique_ptr video_feeder(new BufferFeeder( - base::BindOnce(&AudioVideoPipelineDeviceTest::EndImmediateEosTest, - base::Unretained(this)))); - video_feeder->Initialize(backend(), video_decoder, BufferList()); - video_feeder->SetVideoConfig(DefaultVideoConfig()); - SetVideoFeeder(std::move(video_feeder)); - - MediaPipelineBackend::AudioDecoder* audio_decoder = - backend()->CreateAudioDecoder(); - std::unique_ptr audio_feeder( - new BufferFeeder(base::BindOnce(&IgnoreEos))); - audio_feeder->Initialize(backend(), audio_decoder, BufferList()); - audio_feeder->SetAudioConfig(DefaultAudioConfig()); - SetAudioFeeder(std::move(audio_feeder)); - - ASSERT_TRUE(audio_decoder->SetConfig(DefaultAudioConfig())); - ASSERT_TRUE(video_decoder->SetConfig(DefaultVideoConfig())); - StartImmediateEosTest(); -} - -TEST_F(AudioVideoPipelineDeviceTest, Mp3Playback_WithEffectsStreams) { - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForAudioOnly("sfx.mp3"); - PauseBeforeEos(); - AddEffectsStreams(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, AacPlayback_WithEffectsStreams) { - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForAudioOnly("sfx.m4a"); - PauseBeforeEos(); - AddEffectsStreams(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, VorbisPlayback_WithEffectsStreams) { - set_sync_type(MediaPipelineDeviceParams::kModeIgnorePts); - ConfigureForAudioOnly("sfx.ogg"); - AddEffectsStreams(); - Start(); -} - -// TODO(kmackay) FFmpegDemuxForTest can't handle AC3 or EAC3. - -TEST_F(AudioVideoPipelineDeviceTest, H264Playback_WithEffectsStreams) { - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForVideoOnly("bear.h264", true /* raw_h264 */); - PauseBeforeEos(); - AddEffectsStreams(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, WebmPlaybackWithPause_WithEffectsStreams) { - if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, - kVideoProfileUnknown, 1)) - return; - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - // Setup to pause for 100ms every 500ms - AddPause(base::Milliseconds(500), base::Milliseconds(100)); - - ConfigureForVideoOnly("bear-640x360.webm", false /* raw_h264 */); - AddEffectsStreams(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, Vp8Playback_WithEffectsStreams) { - if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, - kVideoProfileUnknown, 1)) - return; - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForVideoOnly("bear-vp8a.webm", false /* raw_h264 */); - AddEffectsStreams(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, WebmPlayback_WithEffectsStreams) { - if (!MediaCapabilitiesShlib::IsSupportedVideoConfig(kCodecVP8, - kVideoProfileUnknown, 1)) - return; - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForFile("bear-640x360.webm"); - PauseBeforeEos(); - AddEffectsStreams(); - Start(); -} - -TEST_F(AudioVideoPipelineDeviceTest, Mp4Playback) { - set_sync_type(MediaPipelineDeviceParams::kModeSyncPts); - ConfigureForFile("bear.mp4"); - Start(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/av_sync.h chromium-132.0.6834.159/chromecast/media/cma/backend/av_sync.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/av_sync.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/av_sync.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_AV_SYNC_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_AV_SYNC_H_ - -#include -#include - -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -namespace media { - -class MediaPipelineBackendForMixer; - -// Interface to an AV sync module. This AV sync treats the video as master and -// syncs the audio to it. -// -// Whatever the owner of this component is, it should include and depend on -// this interface rather the implementation header file. It should be possible -// for someone in the future to provide their own implementation of this class -// by linking in their AvSync::Create method statically defined below. -class AvSync { - public: - static std::unique_ptr Create(MediaPipelineBackendForMixer* backend); - - virtual ~AvSync() = default; - - // Notify that the audio and video playback will start at |timestamp|, from - // |pts|. |timestamp| is an absolute timestamp on CLOCK_MONOTONIC or - // CLOCK_MONOTONIC_RAW. |pts| is the PTS that the media playback will start - // at. AvSync will typically start upkeeping AV sync after this is called. - virtual void NotifyStart(int64_t timestamp, int64_t pts) = 0; - - // Notify that the playback has been stopped. AvSync will typically stop - // upkeeping AV sync after this call. - virtual void NotifyStop() = 0; - - // Notify that the playback has been paused. AvSync will typically stop - // upkeeping AV sync until the playback is resumed again. - virtual void NotifyPause() = 0; - - // Notify that the playback has been resumed. AvSync will typically - // start upkeeping AV sync again after this is called. - virtual void NotifyResume() = 0; - - // Notify that the video playback rate has been changed to |rate|. AvSync will - // typically match the audio playback rate to |rate|. - virtual void NotifyPlaybackRateChange(float rate) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_AV_SYNC_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/av_sync_dummy.cc chromium-132.0.6834.159/chromecast/media/cma/backend/av_sync_dummy.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/av_sync_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/av_sync_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/av_sync.h" - -namespace chromecast { -namespace media { - -std::unique_ptr AvSync::Create( - MediaPipelineBackendForMixer* const backend) { - return nullptr; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/cast_audio_json.cc chromium-132.0.6834.159/chromecast/media/cma/backend/cast_audio_json.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/cast_audio_json.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/cast_audio_json.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,111 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/cast_audio_json.h" - -#include -#include - -#include "base/files/file_util.h" -#include "base/functional/bind.h" -#include "base/json/json_reader.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/task_traits.h" -#include "base/task/thread_pool.h" -#include "base/task/thread_pool/thread_pool_instance.h" -#include "build/build_config.h" - -namespace chromecast { -namespace media { - -namespace { - -void ReadFileRunCallback(CastAudioJsonProvider::TuningChangedCallback callback, - const base::FilePath& path, - bool error) { - DCHECK(callback); - - std::string contents; - base::ReadFileToString(path, &contents); - std::optional value = base::JSONReader::Read(contents); - if (value && value->is_dict()) { - callback.Run(std::move(*value).TakeDict()); - return; - } - LOG(ERROR) << "Unable to parse JSON in " << path; -} - -} // namespace - -#if BUILDFLAG(IS_FUCHSIA) -const char kCastAudioJsonFilePath[] = "/system/data/cast_audio.json"; -#else -const char kCastAudioJsonFilePath[] = "/etc/cast_audio.json"; -#endif -const char kCastAudioJsonFileName[] = "cast_audio.json"; - -// static -base::FilePath CastAudioJson::GetFilePath() { - base::FilePath tuning_path = CastAudioJson::GetFilePathForTuning(); - if (base::PathExists(tuning_path)) { - return tuning_path; - } - - return CastAudioJson::GetReadOnlyFilePath(); -} - -// static -base::FilePath CastAudioJson::GetReadOnlyFilePath() { - return base::FilePath(kCastAudioJsonFilePath); -} - -// static -base::FilePath CastAudioJson::GetFilePathForTuning() { - return base::GetHomeDir().Append(kCastAudioJsonFileName); -} - -CastAudioJsonProviderImpl::CastAudioJsonProviderImpl() { - if (base::ThreadPoolInstance::Get()) { - cast_audio_watcher_ = base::SequenceBound( - base::ThreadPool::CreateSequencedTaskRunner( - {base::MayBlock(), base::TaskPriority::LOWEST})); - } -} - -CastAudioJsonProviderImpl::~CastAudioJsonProviderImpl() = default; - -std::optional -CastAudioJsonProviderImpl::GetCastAudioConfig() { - std::string contents; - base::ReadFileToString(CastAudioJson::GetFilePath(), &contents); - std::optional value = base::JSONReader::Read(contents); - if (!value || value->is_dict()) { - return std::nullopt; - } - - return std::move(*value).TakeDict(); -} - -void CastAudioJsonProviderImpl::SetTuningChangedCallback( - TuningChangedCallback callback) { - if (cast_audio_watcher_) { - cast_audio_watcher_.AsyncCall(&FileWatcher::SetTuningChangedCallback) - .WithArgs(std::move(callback)); - } -} - -CastAudioJsonProviderImpl::FileWatcher::FileWatcher() = default; -CastAudioJsonProviderImpl::FileWatcher::~FileWatcher() = default; - -void CastAudioJsonProviderImpl::FileWatcher::SetTuningChangedCallback( - TuningChangedCallback callback) { - watcher_.Watch( - CastAudioJson::GetFilePathForTuning(), - base::FilePathWatcher::Type::kNonRecursive, - base::BindRepeating(&ReadFileRunCallback, std::move(callback))); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/cast_audio_json.h chromium-132.0.6834.159/chromecast/media/cma/backend/cast_audio_json.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/cast_audio_json.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/cast_audio_json.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_CAST_AUDIO_JSON_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_CAST_AUDIO_JSON_H_ - -#include - -#include "base/files/file_path.h" -#include "base/files/file_path_watcher.h" -#include "base/functional/callback.h" -#include "base/memory/scoped_refptr.h" -#include "base/threading/sequence_bound.h" -#include "base/values.h" - -namespace chromecast { -namespace media { - -class CastAudioJson { - public: - // Returns GetFilePathForTuning() if a file exists at that path, otherwise - // returns GetReadOnlyFilePath(). - static base::FilePath GetFilePath(); - static base::FilePath GetReadOnlyFilePath(); - static base::FilePath GetFilePathForTuning(); -}; - -// Provides an interface for reading CastAudioJson and registering for file -// updates. -class CastAudioJsonProvider { - public: - using TuningChangedCallback = - base::RepeatingCallback contents)>; - - virtual ~CastAudioJsonProvider() = default; - - // Returns the contents of cast_audio.json. - // If a file exists at CastAudioJson::GetFilePathForTuning() and is valid - // JSON, its contents will be returned. Otherwise, the contents of the file - // at CastAudioJson::GetReadOnlyFilePath() will be returned. - // This function will run on the thread on which it is called, and may - // perform blocking I/O. - virtual std::optional GetCastAudioConfig() = 0; - - // |callback| will be called when a new cast_audio config is available. - // |callback| will always be called from the same thread, but not necessarily - // the same thread on which |SetTuningChangedCallback| is called. - virtual void SetTuningChangedCallback(TuningChangedCallback callback) = 0; -}; - -class CastAudioJsonProviderImpl : public CastAudioJsonProvider { - public: - CastAudioJsonProviderImpl(); - - CastAudioJsonProviderImpl(const CastAudioJsonProviderImpl&) = delete; - CastAudioJsonProviderImpl& operator=(const CastAudioJsonProviderImpl&) = - delete; - - ~CastAudioJsonProviderImpl() override; - - private: - class FileWatcher { - public: - FileWatcher(); - ~FileWatcher(); - - void SetTuningChangedCallback(TuningChangedCallback callback); - - private: - base::FilePathWatcher watcher_; - }; - - // CastAudioJsonProvider implementation: - std::optional GetCastAudioConfig() override; - void SetTuningChangedCallback(TuningChangedCallback callback) override; - - base::SequenceBound cast_audio_watcher_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_CAST_AUDIO_JSON_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/cast_media_dummy.cc chromium-132.0.6834.159/chromecast/media/cma/backend/cast_media_dummy.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/cast_media_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/cast_media_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// 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 "chromecast/media/cma/backend/audio_buildflags.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/media_capabilities_shlib.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -void CastMediaShlib::Initialize(const std::vector& argv) {} - -void CastMediaShlib::Finalize() {} - -VideoPlane* CastMediaShlib::GetVideoPlane() { - return nullptr; -} - -MediaPipelineBackend* CastMediaShlib::CreateMediaPipelineBackend( - const MediaPipelineDeviceParams& params) { - return nullptr; -} - -double CastMediaShlib::GetMediaClockRate() { - return 0.0; -} - -double CastMediaShlib::MediaClockRatePrecision() { - return 0.0; -} - -void CastMediaShlib::MediaClockRateRange(double* minimum_rate, - double* maximum_rate) {} - -bool CastMediaShlib::SetMediaClockRate(double new_rate) { - return false; -} - -bool CastMediaShlib::SupportsMediaClockRateChange() { - return false; -} - -bool MediaCapabilitiesShlib::IsSupportedVideoConfig(VideoCodec codec, - VideoProfile profile, - int level) { - return (codec == kCodecH264 || codec == kCodecVP8); -} - -bool MediaCapabilitiesShlib::IsSupportedAudioConfig(const AudioConfig& config) { - return config.codec == kCodecAAC || config.codec == kCodecMP3 || - config.codec == kCodecPCM || config.codec == kCodecVorbis; -} - -#if BUILDFLAG(VOLUME_CONTROL_IN_MEDIA_SHLIB) - -void VolumeControl::Initialize(const std::vector& argv) {} -void VolumeControl::Finalize() {} -void VolumeControl::AddVolumeObserver(VolumeObserver* observer) {} -void VolumeControl::RemoveVolumeObserver(VolumeObserver* observer) {} - -float VolumeControl::GetVolume(AudioContentType type) { - return 0.0f; -} - -void VolumeControl::SetVolume(VolumeChangeSource source, - AudioContentType type, - float level) {} - -bool VolumeControl::IsMuted(AudioContentType type) { - return false; -} - -void VolumeControl::SetMuted(VolumeChangeSource source, - AudioContentType type, - bool muted) {} - -void VolumeControl::SetOutputLimit(AudioContentType type, float limit) {} - -float VolumeControl::VolumeToDbFS(float volume) { - return 0.0f; -} - -float VolumeControl::DbFSToVolume(float db) { - return 0.0f; -} - -void VolumeControl::SetPowerSaveMode(bool power_save_on) {} - -#endif // BUILDFLAG(VOLUME_CONTROL_IN_MEDIA_SHLIB) - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/cma_backend_factory_impl.cc chromium-132.0.6834.159/chromecast/media/cma/backend/cma_backend_factory_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/cma_backend_factory_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/cma_backend_factory_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/cma_backend_factory_impl.h" - -#include "base/task/sequenced_task_runner.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/common/media_pipeline_backend_manager.h" -#if BUILDFLAG(ENABLE_CHROMIUM_RUNTIME_CAST_RENDERER) -#include "chromecast/media/cma/backend/proxy/cma_backend_proxy.h" // nogncheck -#endif // BUILDFLAG(ENABLE_CHROMIUM_RUNTIME_CAST_RENDERER) -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { - -CmaBackendFactoryImpl::CmaBackendFactoryImpl( - MediaPipelineBackendManager* media_pipeline_backend_manager) - : media_pipeline_backend_manager_(media_pipeline_backend_manager) { - DCHECK(media_pipeline_backend_manager_); -} - -CmaBackendFactoryImpl::~CmaBackendFactoryImpl() = default; - -std::unique_ptr CmaBackendFactoryImpl::CreateBackend( - const MediaPipelineDeviceParams& params) { - std::unique_ptr backend = - media_pipeline_backend_manager_->CreateBackend(params); - -#if BUILDFLAG(ENABLE_CHROMIUM_RUNTIME_CAST_RENDERER) - backend = std::make_unique(params, std::move(backend)); -#endif // BUILDFLAG(ENABLE_CHROMIUM_RUNTIME_CAST_RENDERER) - - return backend; -} - -scoped_refptr -CmaBackendFactoryImpl::GetMediaTaskRunner() { - return media_pipeline_backend_manager_->GetMediaTaskRunner(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/cma_backend_factory_impl.h chromium-132.0.6834.159/chromecast/media/cma/backend/cma_backend_factory_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/cma_backend_factory_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/cma_backend_factory_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_CMA_BACKEND_FACTORY_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_CMA_BACKEND_FACTORY_IMPL_H_ - -#include - -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/api/cma_backend_factory.h" - -namespace chromecast { -namespace media { - -class CmaBackend; -class MediaPipelineBackendManager; -struct MediaPipelineDeviceParams; - -// Creates CmaBackends using a given MediaPipelineBackendManager. -class CmaBackendFactoryImpl : public CmaBackendFactory { - public: - // TODO(slan): Use a static Create method once all of the constructor - // dependencies are removed from the internal implemenation. - explicit CmaBackendFactoryImpl( - MediaPipelineBackendManager* media_pipeline_backend_manager); - - CmaBackendFactoryImpl(const CmaBackendFactoryImpl&) = delete; - CmaBackendFactoryImpl& operator=(const CmaBackendFactoryImpl&) = delete; - - ~CmaBackendFactoryImpl() override; - - std::unique_ptr CreateBackend( - const MediaPipelineDeviceParams& params) override; - - scoped_refptr GetMediaTaskRunner() override; - - protected: - MediaPipelineBackendManager* media_pipeline_backend_manager() { - return media_pipeline_backend_manager_; - } - - private: - media::MediaPipelineBackendManager* const media_pipeline_backend_manager_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_CMA_BACKEND_FACTORY_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/cplay/cplay.cc chromium-132.0.6834.159/chromecast/media/cma/backend/cplay/cplay.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/cplay/cplay.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/cplay/cplay.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,384 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// A standalone utility for processing audio files through the cast -// MixerPipeline. This can be used to pre-process files for offline testing. - -#include - -#include -#include -#include -#include -#include - -#include "base/containers/span.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/no_destructor.h" -#include "base/task/thread_pool/thread_pool_instance.h" -#include "chromecast/media/audio/wav_header.h" -#include "chromecast/media/cma/backend/cast_audio_json.h" -#include "chromecast/media/cma/backend/mixer/mixer_input.h" -#include "chromecast/media/cma/backend/mixer/mixer_pipeline.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h" -#include "chromecast/media/cma/backend/volume_map.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "media/audio/wav_audio_handler.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_sample_types.h" - -namespace chromecast { -namespace media { - -// Need an implementation of DbFSToVolume, but volume_control.cc pulls in too -// too many dependencies. -VolumeMap& GetVolumeMap() { - static base::NoDestructor volume_map; - return *volume_map; -} - -namespace { - -const int kReadSize = 1024; -const WavHeader::AudioFormat kDefaultAudioFormat = - WavHeader::AudioFormat::kFloat32; - -void PrintHelp(const std::string& command) { - LOG(INFO) << "Usage: " << command; - LOG(INFO) << " -i input .wav file"; - LOG(INFO) << " -o output .wav file"; - LOG(INFO) << " -r output samples per second"; - LOG(INFO) << " -s saturate output"; - LOG(INFO) << " [-c cast_audio.json path]"; - LOG(INFO) << " [-v cast volume as fraction of 1 (0.0-1.0)]"; - LOG(INFO) << " [-d max duration (s)]"; -} - -struct Parameters { - double cast_volume = 1.0; - double duration_s = std::numeric_limits::infinity(); - int output_samples_per_second = -1; - bool saturate_output = false; - std::string device_id = "default"; - base::FilePath input_file_path; - base::FilePath output_file_path; - base::FilePath cast_audio_json_path; -}; - -std::string ReadInputFile(const Parameters& params) { - if (!base::PathExists(params.input_file_path)) { - NOTREACHED() << "File " << params.input_file_path << " does not exist."; - } - std::string wav_data; - if (!base::ReadFileToString(params.input_file_path, &wav_data)) { - NOTREACHED() << "Unable to open wav file, " << params.input_file_path; - } - return wav_data; -} - -// MixerInput::Source that reads from a .wav file. -class WavMixerInputSource : public MixerInput::Source { - public: - WavMixerInputSource(const Parameters& params) - : wav_data_(ReadInputFile(params)), - input_handler_(::media::WavAudioHandler::Create(wav_data_)), - device_id_(params.device_id), - bytes_per_frame_(input_handler_->num_channels() * - input_handler_->bits_per_sample() / 8) { - DCHECK(input_handler_); - LOG(INFO) << "Loaded " << params.input_file_path << ":"; - LOG(INFO) << " Channels: " << input_handler_->num_channels() - << " Bit Depth: " << input_handler_->bits_per_sample() - << " Duration: " << input_handler_->GetDuration().InSecondsF() - << "s."; - } - - WavMixerInputSource(const WavMixerInputSource&) = delete; - WavMixerInputSource& operator=(const WavMixerInputSource&) = delete; - - ~WavMixerInputSource() override = default; - - bool AtEnd() { return input_handler_->AtEnd(cursor_); } - - // MixerInput::Source implementation: - size_t num_channels() const override { - return input_handler_->num_channels(); - } - ::media::ChannelLayout channel_layout() const override { - return ::media::GuessChannelLayout(num_channels()); - } - int sample_rate() const override { return input_handler_->sample_rate(); } - bool primary() override { return true; } - bool active() override { return true; } - const std::string& device_id() override { return device_id_; } - AudioContentType content_type() override { return AudioContentType::kMedia; } - AudioContentType focus_type() override { return AudioContentType::kMedia; } - int desired_read_size() override { return kReadSize; } - int playout_channel() override { return -1; } - bool require_clock_rate_simulation() const override { return false; } - - void InitializeAudioPlayback( - int read_size, - MixerInput::RenderingDelay initial_rendering_delay) override {} - - int FillAudioPlaybackFrames(int num_frames, - MixerInput::RenderingDelay rendering_delay, - ::media::AudioBus* buffer) override { - CHECK(buffer); - size_t bytes_written; - CHECK_LE(num_frames, buffer->frames()); - if (num_frames < buffer->frames()) { - std::vector channel_data; - for (int i = 0; i < buffer->channels(); ++i) { - channel_data.push_back(buffer->channel(i)); - } - std::unique_ptr<::media::AudioBus> buffer_wrapper = - ::media::AudioBus::WrapVector(num_frames, channel_data); - CHECK(input_handler_->CopyTo(buffer_wrapper.get(), cursor_, &bytes_written)); - } else { - CHECK(input_handler_->CopyTo(buffer, cursor_, &bytes_written)); - } - cursor_ += bytes_written; - return bytes_written / bytes_per_frame_; - } - - void OnAudioPlaybackError(MixerError error) override {} - void FinalizeAudioPlayback() override {} - - private: - const std::string wav_data_; - std::unique_ptr<::media::WavAudioHandler> input_handler_; - size_t cursor_ = 0; - const std::string device_id_; - const size_t bytes_per_frame_; -}; - -// OutputHandler interface to allow switching between alsa and file output. -// TODO(bshaya): Add option to play directly to an output device! -class OutputHandler { - public: - virtual ~OutputHandler() = default; - virtual void WriteData(float* data, int num_frames, bool saturate_output) = 0; -}; - -class WavOutputHandler : public OutputHandler { - public: - WavOutputHandler(const base::FilePath& path, - int num_channels, - int sample_rate) - : wav_file_(path, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE), - num_channels_(num_channels) { - header_.SetAudioFormat(kDefaultAudioFormat); - header_.SetNumChannels(num_channels); - header_.SetSampleRate(sample_rate); - - // Write wav file header to fill space. We'll need to go back and fill in - // the size later. - wav_file_.WriteAtCurrentPos(base::byte_span_from_ref(header_)); - } - - WavOutputHandler(const WavOutputHandler&) = delete; - WavOutputHandler& operator=(const WavOutputHandler&) = delete; - - ~WavOutputHandler() override { - // Update size and re-write header. We only really need to overwrite 8 bytes - // but it is easy and cheap to overwrite the whole header. - int size = wav_file_.GetLength(); - int data_size = size - sizeof(header_); - header_.SetDataSize(data_size); - wav_file_.Write(0 /* offset */, reinterpret_cast(&header_), - sizeof(header_)); - } - - void WriteData(float* data, int num_frames, bool saturate_output) override { - std::vector clipped_data(num_frames * num_channels_); - std::memcpy(clipped_data.data(), data, - clipped_data.size() * sizeof(clipped_data[0])); - if (saturate_output) { - for (size_t i = 0; i < clipped_data.size(); ++i) { - clipped_data[i] = std::clamp(clipped_data[i], -1.0f, 1.0f); - } - } - wav_file_.WriteAtCurrentPos(base::as_byte_span(clipped_data)); - } - - private: - WavHeader header_; - base::File wav_file_; - const int num_channels_; -}; - -class AudioMetrics { - public: - AudioMetrics(int num_channels) : num_channels_(num_channels) {} - - AudioMetrics(const AudioMetrics&) = delete; - AudioMetrics& operator=(const AudioMetrics&) = delete; - - ~AudioMetrics() = default; - - void ProcessFrames(float* data, int num_frames) { - for (int i = 0; i < num_frames * num_channels_; ++i) { - squared_sum_ += std::pow(data[i], 2); - if (std::fabs(data[i]) > 1.0) { - ++clipped_samples_; - largest_sample_ = std::max(largest_sample_, std::fabs(data[i])); - } - } - total_samples_ += num_frames * num_channels_; - } - - void PrintReport() { - LOG(INFO) << "RMS magnitude: " - << 20 * log10(std::sqrt(squared_sum_ / total_samples_)) << "dB"; - if (clipped_samples_ == 0) { - return; - } - LOG(WARNING) << "Detected " << clipped_samples_ << " clipped samples (" - << 100.0 * clipped_samples_ / total_samples_ << "%)."; - LOG(WARNING) << "Largest sample: " << largest_sample_; - } - - private: - const int num_channels_; - int clipped_samples_ = 0; - int total_samples_ = 0; - float largest_sample_ = 0.0f; - double squared_sum_ = 0.0; -}; - -Parameters ReadArgs(int argc, char* argv[]) { - Parameters params; - params.cast_audio_json_path = CastAudioJson::GetFilePath(); - int opt; - while ((opt = getopt(argc, argv, "i:o:c:v:d:r:s")) != -1) { - switch (opt) { - case 'i': - params.input_file_path = base::FilePath(optarg); - break; - case 'o': - params.output_file_path = base::FilePath(optarg); - break; - case 'c': - params.cast_audio_json_path = base::FilePath(optarg); - break; - case 'v': - params.cast_volume = strtod(optarg, nullptr); - CHECK_LE(params.cast_volume, 1.0); - CHECK_GE(params.cast_volume, 0.0); - break; - case 'd': - params.duration_s = strtod(optarg, nullptr); - break; - case 'r': - params.output_samples_per_second = strtod(optarg, nullptr); - break; - case 's': - params.saturate_output = true; - break; - default: - PrintHelp(argv[0]); - exit(1); - } - } - if (params.input_file_path.empty()) { - PrintHelp(argv[0]); - exit(1); - } - if (params.output_file_path.empty()) { - PrintHelp(argv[0]); - exit(1); - } - return params; -} - -// Real main() inside namespace. -int CplayMain(int argc, char* argv[]) { - Parameters params = ReadArgs(argc, argv); - - // Comply with CastAudioJsonProviderImpl. - base::ThreadPoolInstance::CreateAndStartWithDefaultParams( - "cplay_thread_pool"); - - // Read input file. - WavMixerInputSource input_source(params); - if (params.output_samples_per_second <= 0) { - params.output_samples_per_second = input_source.sample_rate(); - } - if (params.output_samples_per_second != input_source.sample_rate()) { - LOG(INFO) << "Resampling from " << input_source.sample_rate() << " to " - << params.output_samples_per_second; - } else { - LOG(INFO) << "Sample rate: " << params.output_samples_per_second; - } - - // Build Processing Pipeline. - PostProcessingPipelineParser parser(params.cast_audio_json_path); - auto factory = std::make_unique(); - auto pipeline = MixerPipeline::CreateMixerPipeline( - &parser, factory.get(), input_source.num_channels()); - CHECK(pipeline); - pipeline->Initialize(params.output_samples_per_second, kReadSize); - LOG(INFO) << "Initialized Cast Audio Pipeline at " - << params.output_samples_per_second << " samples per second"; - - // Add |input_source| to |pipeline| - FilterGroup* input_group = pipeline->GetInputGroup(params.device_id); - CHECK(input_group); - MixerInput mixer_input(&input_source, input_group); - mixer_input.Initialize(); - - // Set volume. - std::string contents; - base::ReadFileToString(params.cast_audio_json_path, &contents); - std::optional parsed_json = base::JSONReader::Read(contents); - if (parsed_json && parsed_json->is_dict()) { - GetVolumeMap().LoadVolumeMap(std::move(*parsed_json).TakeDict()); - } else { - GetVolumeMap().LoadVolumeMap(std::nullopt); - } - float volume_dbfs = GetVolumeMap().VolumeToDbFS(params.cast_volume); - float volume_multiplier = std::pow(10.0, volume_dbfs / 20.0); - mixer_input.SetVolumeMultiplier(1.0); - mixer_input.SetContentTypeVolume(volume_multiplier); - LOG(INFO) << "Volume set to level " << params.cast_volume << " | " - << volume_dbfs << "dBFS | multiplier=" << volume_multiplier; - - // Prepare output. - std::unique_ptr output_handler_ = - std::make_unique(params.output_file_path, - pipeline->GetOutputChannelCount(), - params.output_samples_per_second); - AudioMetrics audio_metrics(pipeline->GetOutputChannelCount()); - - // Play! - int frames_written = 0; - while (!input_source.AtEnd() && - frames_written / params.output_samples_per_second < - params.duration_s) { - pipeline->MixAndFilter(kReadSize, MixerInput::RenderingDelay()); - audio_metrics.ProcessFrames(pipeline->GetOutput(), kReadSize); - output_handler_->WriteData(pipeline->GetOutput(), kReadSize, - params.saturate_output); - frames_written += kReadSize; - } - - audio_metrics.PrintReport(); - base::ThreadPoolInstance::Get()->Shutdown(); - return 0; -} - -} // namespace -} // namespace media -} // namespace chromecast - -int main(int argc, char* argv[]) { - return chromecast::media::CplayMain(argc, argv); -} diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/audio_decoder_desktop.cc chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/audio_decoder_desktop.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/audio_decoder_desktop.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/audio_decoder_desktop.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -// 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 "chromecast/media/cma/backend/desktop/audio_decoder_desktop.h" - -#include "chromecast/media/cma/backend/desktop/media_sink_desktop.h" - -namespace chromecast { -namespace media { - -AudioDecoderDesktop::AudioDecoderDesktop() : delegate_(nullptr) {} - -AudioDecoderDesktop::~AudioDecoderDesktop() {} - -void AudioDecoderDesktop::Start(base::TimeDelta start_pts) { - DCHECK(!sink_); - sink_ = std::make_unique(delegate_, start_pts); -} - -void AudioDecoderDesktop::Stop() { - DCHECK(sink_); - sink_.reset(); -} - -void AudioDecoderDesktop::SetPlaybackRate(float rate) { - DCHECK(sink_); - sink_->SetPlaybackRate(rate); -} - -base::TimeDelta AudioDecoderDesktop::GetCurrentPts() { - DCHECK(sink_); - return sink_->GetCurrentPts(); -} - -void AudioDecoderDesktop::SetDelegate(Delegate* delegate) { - DCHECK(!sink_); - delegate_ = delegate; -} - -MediaPipelineBackend::BufferStatus AudioDecoderDesktop::PushBuffer( - CastDecoderBuffer* buffer) { - DCHECK(sink_); - return sink_->PushBuffer(buffer); -} - -void AudioDecoderDesktop::GetStatistics(Statistics* statistics) {} - -bool AudioDecoderDesktop::SetConfig(const AudioConfig& config) { - return true; -} - -bool AudioDecoderDesktop::SetVolume(float multiplier) { - return true; -} - -AudioDecoderDesktop::RenderingDelay AudioDecoderDesktop::GetRenderingDelay() { - return RenderingDelay(); -} - -AudioDecoderDesktop::AudioTrackTimestamp AudioDecoderDesktop::GetAudioTrackTimestamp() { - return AudioTrackTimestamp(); -} - -int AudioDecoderDesktop::GetStartThresholdInFrames() { - return 0; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/audio_decoder_desktop.h chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/audio_decoder_desktop.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/audio_decoder_desktop.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/audio_decoder_desktop.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_AUDIO_DECODER_DESKTOP_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_AUDIO_DECODER_DESKTOP_H_ - -#include - -#include "base/time/time.h" -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -namespace media { - -class MediaSinkDesktop; - -class AudioDecoderDesktop : public MediaPipelineBackend::AudioDecoder { - public: - AudioDecoderDesktop(); - - AudioDecoderDesktop(const AudioDecoderDesktop&) = delete; - AudioDecoderDesktop& operator=(const AudioDecoderDesktop&) = delete; - - ~AudioDecoderDesktop() override; - - void Start(base::TimeDelta start_pts); - void Stop(); - void SetPlaybackRate(float rate); - base::TimeDelta GetCurrentPts(); - - // MediaPipelineBackend::AudioDecoder implementation: - void SetDelegate(Delegate* delegate) override; - MediaPipelineBackend::BufferStatus PushBuffer( - CastDecoderBuffer* buffer) override; - void GetStatistics(Statistics* statistics) override; - bool SetConfig(const AudioConfig& config) override; - bool SetVolume(float multiplier) override; - RenderingDelay GetRenderingDelay() override; - AudioTrackTimestamp GetAudioTrackTimestamp() override; - int GetStartThresholdInFrames() override; - - private: - Delegate* delegate_; - std::unique_ptr sink_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_AUDIO_DECODER_DESKTOP_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/cast_media_desktop.cc chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/cast_media_desktop.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/cast_media_desktop.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/cast_media_desktop.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -// 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 - -#if defined(ENABLE_VIDEO_WITH_MIXED_AUDIO) -#include "chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h" // nogncheck -#else -#include "chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.h" -#endif -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/media/media_capabilities_shlib.h" -#include "chromecast/public/video_plane.h" - -namespace chromecast { -namespace media { -namespace { - -class DesktopVideoPlane : public VideoPlane { - public: - ~DesktopVideoPlane() override {} - - void SetGeometry(const RectF& display_rect, Transform transform) override {} -}; - -DesktopVideoPlane* g_video_plane = nullptr; - -} // namespace - -void CastMediaShlib::Initialize(const std::vector& argv) { - g_video_plane = new DesktopVideoPlane(); -} - -void CastMediaShlib::Finalize() { - delete g_video_plane; - g_video_plane = nullptr; -} - -VideoPlane* CastMediaShlib::GetVideoPlane() { - return g_video_plane; -} - -MediaPipelineBackend* CastMediaShlib::CreateMediaPipelineBackend( - const MediaPipelineDeviceParams& params) { -#if defined(ENABLE_VIDEO_WITH_MIXED_AUDIO) - return new MediaPipelineBackendForMixer(params); -#else - return new MediaPipelineBackendDesktop(); -#endif -} - -double CastMediaShlib::GetMediaClockRate() { - return 0.0; -} - -double CastMediaShlib::MediaClockRatePrecision() { - return 0.0; -} - -void CastMediaShlib::MediaClockRateRange(double* minimum_rate, - double* maximum_rate) { - *minimum_rate = 0.0; - *maximum_rate = 1.0; -} - -bool CastMediaShlib::SetMediaClockRate(double new_rate) { - return false; -} - -bool CastMediaShlib::SupportsMediaClockRateChange() { - return false; -} - -bool MediaCapabilitiesShlib::IsSupportedVideoConfig(VideoCodec codec, - VideoProfile profile, - int level) { - return (codec == kCodecH264 || codec == kCodecVP8); -} - -bool MediaCapabilitiesShlib::IsSupportedAudioConfig(const AudioConfig& config) { - return config.codec == kCodecAAC || config.codec == kCodecMP3 || - config.codec == kCodecPCM || config.codec == kCodecVorbis; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/desktop_system_volume_control.cc chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/desktop_system_volume_control.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/desktop_system_volume_control.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/desktop_system_volume_control.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// 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 - -#include "base/notreached.h" -#include "chromecast/media/cma/backend/system_volume_control.h" - -namespace chromecast { -namespace media { - -class DesktopSystemVolumeControl : public SystemVolumeControl { - public: - explicit DesktopSystemVolumeControl(Delegate* delegate) - : delegate_(delegate) {} - ~DesktopSystemVolumeControl() override = default; - - // SystemVolumeControl interface. - // Consider 'level' and 'volume' equivalent for simplicity. - float GetRoundtripVolume(float volume) override { return volume; } - float DbToVolumeLevel(float db_volume) override { - NOTIMPLEMENTED(); - return 0.0f; - } - float VolumeLevelToDb(float level) override { - NOTIMPLEMENTED(); - return 0.0f; - } - float GetVolume() override { return volume_; } - void SetVolume(float level) override { - if (level != volume_) { - volume_ = level; - delegate_->OnSystemVolumeOrMuteChange(volume_, muted_); - } - } - bool IsMuted() override { return muted_; } - void SetMuted(bool muted) override { - if (muted != muted_) { - muted_ = muted; - delegate_->OnSystemVolumeOrMuteChange(volume_, muted_); - } - } - void SetPowerSave(bool power_save_on) override {} - void SetLimit(float limit) override {} - - private: - Delegate* delegate_; - float volume_ = 0.0f; - bool muted_ = false; -}; - -// static -std::unique_ptr SystemVolumeControl::Create( - Delegate* delegate) { - return std::make_unique(delegate); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.cc chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,119 +0,0 @@ -// 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 "chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.h" - -#include "base/check_op.h" -#include "base/time/time.h" -#include "chromecast/media/cma/backend/desktop/audio_decoder_desktop.h" -#include "chromecast/media/cma/backend/desktop/video_decoder_desktop.h" -#include "media/base/timestamp_constants.h" - -namespace chromecast { -namespace media { - -MediaPipelineBackendDesktop::MediaPipelineBackendDesktop() - : state_(kStateUninitialized), rate_(1.0f) {} - -MediaPipelineBackendDesktop::~MediaPipelineBackendDesktop() {} - -MediaPipelineBackend::AudioDecoder* -MediaPipelineBackendDesktop::CreateAudioDecoder() { - DCHECK_EQ(kStateUninitialized, state_); - DCHECK(!audio_decoder_); - audio_decoder_ = std::make_unique(); - return audio_decoder_.get(); -} - -MediaPipelineBackend::VideoDecoder* -MediaPipelineBackendDesktop::CreateVideoDecoder() { - DCHECK_EQ(kStateUninitialized, state_); - DCHECK(!video_decoder_); - video_decoder_ = std::make_unique(); - return video_decoder_.get(); -} - -bool MediaPipelineBackendDesktop::Initialize() { - DCHECK_EQ(kStateUninitialized, state_); - state_ = kStateInitialized; - return true; -} - -bool MediaPipelineBackendDesktop::Start(int64_t start_pts) { - DCHECK_EQ(kStateInitialized, state_); - if (!audio_decoder_ && !video_decoder_) - return false; - - if (audio_decoder_) { - audio_decoder_->Start(base::Microseconds(start_pts)); - audio_decoder_->SetPlaybackRate(rate_); - } - if (video_decoder_) { - video_decoder_->Start(base::Microseconds(start_pts)); - video_decoder_->SetPlaybackRate(rate_); - } - state_ = kStatePlaying; - return true; -} - -void MediaPipelineBackendDesktop::Stop() { - DCHECK(state_ == kStatePlaying || state_ == kStatePaused); - if (audio_decoder_) - audio_decoder_->Stop(); - if (video_decoder_) - video_decoder_->Stop(); - state_ = kStateInitialized; -} - -bool MediaPipelineBackendDesktop::Pause() { - DCHECK_EQ(kStatePlaying, state_); - if (audio_decoder_) - audio_decoder_->SetPlaybackRate(0.0f); - if (video_decoder_) - video_decoder_->SetPlaybackRate(0.0f); - state_ = kStatePaused; - return true; -} - -bool MediaPipelineBackendDesktop::Resume() { - DCHECK_EQ(kStatePaused, state_); - if (audio_decoder_) - audio_decoder_->SetPlaybackRate(rate_); - if (video_decoder_) - video_decoder_->SetPlaybackRate(rate_); - state_ = kStatePlaying; - return true; -} - -int64_t MediaPipelineBackendDesktop::GetCurrentPts() { - base::TimeDelta current_pts = ::media::kNoTimestamp; - - if (audio_decoder_ && video_decoder_) { - current_pts = std::min(audio_decoder_->GetCurrentPts(), - video_decoder_->GetCurrentPts()); - } else if (audio_decoder_) { - current_pts = audio_decoder_->GetCurrentPts(); - } else if (video_decoder_) { - current_pts = video_decoder_->GetCurrentPts(); - } - - return current_pts.InMicroseconds(); -} - -bool MediaPipelineBackendDesktop::SetPlaybackRate(float rate) { - DCHECK_GT(rate, 0.0f); - rate_ = rate; - - if (state_ == kStatePlaying) { - if (audio_decoder_) - audio_decoder_->SetPlaybackRate(rate_); - if (video_decoder_) - video_decoder_->SetPlaybackRate(rate_); - } - - return true; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.h chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_pipeline_backend_desktop.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MEDIA_PIPELINE_BACKEND_DESKTOP_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MEDIA_PIPELINE_BACKEND_DESKTOP_H_ - -#include - -#include - -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -namespace media { -class AudioDecoderDesktop; -class VideoDecoderDesktop; - -// Factory that instantiates desktop (stub) media pipeline device elements. -class MediaPipelineBackendDesktop : public MediaPipelineBackend { - public: - MediaPipelineBackendDesktop(); - - MediaPipelineBackendDesktop(const MediaPipelineBackendDesktop&) = delete; - MediaPipelineBackendDesktop& operator=(const MediaPipelineBackendDesktop&) = - delete; - - ~MediaPipelineBackendDesktop() override; - - const AudioDecoderDesktop* audio_decoder() const { - return audio_decoder_.get(); - } - const VideoDecoderDesktop* video_decoder() const { - return video_decoder_.get(); - } - - // MediaPipelineBackend implementation: - AudioDecoder* CreateAudioDecoder() override; - VideoDecoder* CreateVideoDecoder() override; - bool Initialize() override; - bool Start(int64_t start_pts) override; - void Stop() override; - bool Pause() override; - bool Resume() override; - int64_t GetCurrentPts() override; - bool SetPlaybackRate(float rate) override; - - private: - enum State { - kStateUninitialized, - kStateInitialized, - kStatePlaying, - kStatePaused, - }; - State state_; - float rate_; - std::unique_ptr audio_decoder_; - std::unique_ptr video_decoder_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MEDIA_PIPELINE_BACKEND_DESKTOP_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/media_sink_desktop.cc chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_sink_desktop.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/media_sink_desktop.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_sink_desktop.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/desktop/media_sink_desktop.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "media/base/timestamp_constants.h" - -namespace chromecast { -namespace media { - -MediaSinkDesktop::MediaSinkDesktop( - MediaPipelineBackend::Decoder::Delegate* delegate, - base::TimeDelta start_pts) - : delegate_(delegate), - time_interpolator_(&tick_clock_), - playback_rate_(1.0f), - last_frame_pts_(start_pts), - received_eos_(false) { - DCHECK(delegate_); - time_interpolator_.SetPlaybackRate(playback_rate_); - time_interpolator_.SetBounds(start_pts, start_pts, tick_clock_.NowTicks()); - time_interpolator_.StartInterpolating(); -} - -MediaSinkDesktop::~MediaSinkDesktop() {} - -void MediaSinkDesktop::SetPlaybackRate(float rate) { - DCHECK_GE(rate, 0.0f); - playback_rate_ = rate; - time_interpolator_.SetPlaybackRate(playback_rate_); - - // Changing the playback rate affects the delay after which EOS callback - // should run. Reschedule the task according to the new delay. - if (received_eos_) { - eos_task_.Cancel(); - ScheduleEndOfStreamTask(); - } -} - -base::TimeDelta MediaSinkDesktop::GetCurrentPts() { - return time_interpolator_.GetInterpolatedTime(); -} - -MediaPipelineBackend::BufferStatus MediaSinkDesktop::PushBuffer( - CastDecoderBuffer* buffer) { - if (buffer->end_of_stream()) { - received_eos_ = true; - ScheduleEndOfStreamTask(); - return MediaPipelineBackend::kBufferSuccess; - } - - // This is wrong on several levels. - // 1. The correct PTS should be buffer->timestamp() + buffer->duration(). - // But CastDecoderBuffer does not expose duration unlike - // ::media::DecoderBuffer. - // 2. The PTS reported by GetCurrentPts should not move backwards. - // It should be clamped in the range [start_pts, last_frame_pts_]. - // But doing so makes several AudioVideoPipelineDeviceTest cases fail. - // Those tests are wrong should be fixed. - // TODO(alokp): Fix these issues when the next version of CMA backend is - // scheduled to roll out. crbug.com/678394 - auto timestamp = base::Microseconds(buffer->timestamp()); - if (timestamp != ::media::kNoTimestamp) { - last_frame_pts_ = timestamp; - time_interpolator_.SetUpperBound(last_frame_pts_); - } - return MediaPipelineBackend::kBufferSuccess; -} - -void MediaSinkDesktop::ScheduleEndOfStreamTask() { - DCHECK(received_eos_); - DCHECK(eos_task_.IsCancelled()); - - // Do not schedule if playback is paused. - if (playback_rate_ == 0.0f) - return; - - eos_task_.Reset( - base::BindOnce(&MediaPipelineBackend::Decoder::Delegate::OnEndOfStream, - base::Unretained(delegate_))); - base::TimeDelta delay = (last_frame_pts_ - GetCurrentPts()) / playback_rate_; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, eos_task_.callback(), delay); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/media_sink_desktop.h chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_sink_desktop.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/media_sink_desktop.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/media_sink_desktop.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MEDIA_SINK_DESKTOP_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MEDIA_SINK_DESKTOP_H_ - -#include "base/cancelable_callback.h" -#include "base/time/default_tick_clock.h" -#include "base/time/time.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "media/base/time_delta_interpolator.h" - -namespace chromecast { -namespace media { - -class MediaSinkDesktop { - public: - MediaSinkDesktop(MediaPipelineBackend::Decoder::Delegate* delegate, - base::TimeDelta start_pts); - - MediaSinkDesktop(const MediaSinkDesktop&) = delete; - MediaSinkDesktop& operator=(const MediaSinkDesktop&) = delete; - - ~MediaSinkDesktop(); - - void SetPlaybackRate(float rate); - base::TimeDelta GetCurrentPts(); - MediaPipelineBackend::BufferStatus PushBuffer(CastDecoderBuffer* buffer); - - private: - void ScheduleEndOfStreamTask(); - - MediaPipelineBackend::Decoder::Delegate* delegate_; - base::DefaultTickClock tick_clock_; - ::media::TimeDeltaInterpolator time_interpolator_; - float playback_rate_; - base::TimeDelta last_frame_pts_; - bool received_eos_; - base::CancelableOnceClosure eos_task_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MEDIA_SINK_DESKTOP_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.cc chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// 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 "chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.h" - -#include - -#include "base/threading/platform_thread.h" -#include "base/time/time.h" -#include "media/base/audio_timestamp_helper.h" - -namespace chromecast { -namespace media { - -constexpr base::TimeDelta kTargetWritePeriod = base::Milliseconds(20); - -bool MixerOutputStreamDesktop::Start(int requested_sample_rate, int channels) { - sample_rate_ = requested_sample_rate; - channels_ = channels; - target_packet_size_ = ::media::AudioTimestampHelper::TimeToFrames( - kTargetWritePeriod, sample_rate_); - return true; -} - -int MixerOutputStreamDesktop::GetNumChannels() { - return channels_; -} - -int MixerOutputStreamDesktop::GetSampleRate() { - return sample_rate_; -} - -MediaPipelineBackend::AudioDecoder::RenderingDelay -MixerOutputStreamDesktop::GetRenderingDelay() { - return MediaPipelineBackend::AudioDecoder::RenderingDelay(); -} - -int MixerOutputStreamDesktop::OptimalWriteFramesCount() { - return target_packet_size_; -} - -bool MixerOutputStreamDesktop::Write(const float* data, - int data_size, - bool* out_playback_interrupted) { - int frames = data_size / channels_; - auto frames_duration = - ::media::AudioTimestampHelper::FramesToTime(frames, sample_rate_); - base::PlatformThread::Sleep(frames_duration); - - return true; -} - -void MixerOutputStreamDesktop::Stop() {} - -// static -std::unique_ptr MixerOutputStream::Create() { - return std::make_unique(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.h chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/mixer_output_stream_desktop.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MIXER_OUTPUT_STREAM_DESKTOP_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MIXER_OUTPUT_STREAM_DESKTOP_H_ - -#include "chromecast/public/media/mixer_output_stream.h" - -namespace chromecast { -namespace media { - -// MixerOutputStream implementation for Desktop. -class MixerOutputStreamDesktop : public MixerOutputStream { - public: - MixerOutputStreamDesktop() = default; - ~MixerOutputStreamDesktop() override = default; - MixerOutputStreamDesktop(const MixerOutputStreamDesktop&) = delete; - - // MixerOutputStream implementation: - bool Start(int requested_sample_rate, int channels) override; - int GetNumChannels() override; - int GetSampleRate() override; - MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelay() - override; - int OptimalWriteFramesCount() override; - bool Write(const float* data, - int data_size, - bool* out_playback_interrupted) override; - void Stop() override; - - private: - int sample_rate_ = 0; - int channels_ = 0; - - // Value returned by OptimalWriteFramesCount(). - int target_packet_size_ = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_MIXER_OUTPUT_STREAM_DESKTOP_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/video_decoder_desktop.cc chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/video_decoder_desktop.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/video_decoder_desktop.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/video_decoder_desktop.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// 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 "chromecast/media/cma/backend/desktop/video_decoder_desktop.h" - -#include "chromecast/media/cma/backend/desktop/media_sink_desktop.h" - -namespace chromecast { -namespace media { - -VideoDecoderDesktop::VideoDecoderDesktop() {} - -VideoDecoderDesktop::~VideoDecoderDesktop() {} - -void VideoDecoderDesktop::Start(base::TimeDelta start_pts) { - DCHECK(!sink_); - sink_ = std::make_unique(delegate_, start_pts); -} - -void VideoDecoderDesktop::Stop() { - DCHECK(sink_); - sink_.reset(); -} - -void VideoDecoderDesktop::SetPlaybackRate(float rate) { - DCHECK(sink_); - sink_->SetPlaybackRate(rate); -} - -base::TimeDelta VideoDecoderDesktop::GetCurrentPts() { - DCHECK(sink_); - return sink_->GetCurrentPts(); -} - -void VideoDecoderDesktop::SetDelegate(Delegate* delegate) { - DCHECK(!sink_); - delegate_ = delegate; -} - -MediaPipelineBackend::BufferStatus VideoDecoderDesktop::PushBuffer( - CastDecoderBuffer* buffer) { - DCHECK(sink_); - return sink_->PushBuffer(buffer); -} - -void VideoDecoderDesktop::GetStatistics(Statistics* statistics) {} - -bool VideoDecoderDesktop::SetConfig(const VideoConfig& config) { - return true; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/video_decoder_desktop.h chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/video_decoder_desktop.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/video_decoder_desktop.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/video_decoder_desktop.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_VIDEO_DECODER_DESKTOP_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_VIDEO_DECODER_DESKTOP_H_ - -#include - -#include "base/time/time.h" -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -namespace media { - -class MediaSinkDesktop; - -class VideoDecoderDesktop : public MediaPipelineBackend::VideoDecoder { - public: - VideoDecoderDesktop(); - - VideoDecoderDesktop(const VideoDecoderDesktop&) = delete; - VideoDecoderDesktop& operator=(const VideoDecoderDesktop&) = delete; - - ~VideoDecoderDesktop() override; - - void Start(base::TimeDelta start_pts); - void Stop(); - void SetPlaybackRate(float rate); - base::TimeDelta GetCurrentPts(); - - // MediaPipelineBackend::VideoDecoder implementation: - void SetDelegate(Delegate* delegate) override; - MediaPipelineBackend::BufferStatus PushBuffer( - CastDecoderBuffer* buffer) override; - void GetStatistics(Statistics* statistics) override; - bool SetConfig(const VideoConfig& config) override; - - private: - Delegate* delegate_; - std::unique_ptr sink_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_DESKTOP_VIDEO_DECODER_DESKTOP_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/volume_control_desktop.cc chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/volume_control_desktop.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/desktop/volume_control_desktop.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/desktop/volume_control_desktop.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,217 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/public/volume_control.h" - -#include -#include -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/message_loop/message_pump_type.h" -#include "base/no_destructor.h" -#include "base/notreached.h" -#include "base/synchronization/lock.h" -#include "base/threading/thread.h" - -namespace chromecast { -namespace media { - -namespace { - -const float kMinVolumeDbfs = -60.0f; -const float kMaxVolumeDbfs = 0.0f; - -class VolumeControlInternal { - public: - VolumeControlInternal() : thread_("VolumeControl") { - for (auto type : - {AudioContentType::kMedia, AudioContentType::kAlarm, - AudioContentType::kCommunication, AudioContentType::kOther}) { - volumes_[type] = 1.0f; - muted_[type] = false; - } - - base::Thread::Options options; - options.message_pump_type = base::MessagePumpType::IO; - thread_.StartWithOptions(std::move(options)); - } - - VolumeControlInternal(const VolumeControlInternal&) = delete; - VolumeControlInternal& operator=(const VolumeControlInternal&) = delete; - - ~VolumeControlInternal() = default; - - void AddVolumeObserver(VolumeObserver* observer) { - base::AutoLock lock(observer_lock_); - volume_observers_.push_back(observer); - } - - void RemoveVolumeObserver(VolumeObserver* observer) { - base::AutoLock lock(observer_lock_); - volume_observers_.erase(std::remove(volume_observers_.begin(), - volume_observers_.end(), observer), - volume_observers_.end()); - } - - float GetVolume(AudioContentType type) { - base::AutoLock lock(volume_lock_); - return volumes_[type]; - } - - void SetVolume(media::VolumeChangeSource source, - AudioContentType type, - float level) { - if (type == AudioContentType::kOther) { - NOTREACHED() << "Can't set volume for content type kOther"; - } - - level = std::clamp(level, 0.0f, 1.0f); - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlInternal::SetVolumeOnThread, - base::Unretained(this), source, type, level)); - } - - bool IsMuted(AudioContentType type) { - base::AutoLock lock(volume_lock_); - return muted_[type]; - } - - void SetMuted(media::VolumeChangeSource source, - AudioContentType type, - bool muted) { - if (type == AudioContentType::kOther) { - NOTREACHED() << "Can't set mute state for content type kOther"; - } - - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlInternal::SetMutedOnThread, - base::Unretained(this), source, type, muted)); - } - - private: - void SetVolumeOnThread(media::VolumeChangeSource source, - AudioContentType type, - float level) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - DCHECK(type != AudioContentType::kOther); - - { - base::AutoLock lock(volume_lock_); - if (level == volumes_[type]) { - return; - } - volumes_[type] = level; - } - - { - base::AutoLock lock(observer_lock_); - for (VolumeObserver* observer : volume_observers_) { - observer->OnVolumeChange(source, type, level); - } - } - } - - void SetMutedOnThread(media::VolumeChangeSource source, - AudioContentType type, - bool muted) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - DCHECK(type != AudioContentType::kOther); - - { - base::AutoLock lock(volume_lock_); - if (muted == muted_[type]) { - return; - } - muted_[type] = muted; - } - - { - base::AutoLock lock(observer_lock_); - for (VolumeObserver* observer : volume_observers_) { - observer->OnMuteChange(source, type, muted); - } - } - } - - base::Lock volume_lock_; - std::map volumes_; - std::map muted_; - - base::Lock observer_lock_; - std::vector volume_observers_; - - base::Thread thread_; -}; - -VolumeControlInternal& GetVolumeControl() { - static base::NoDestructor g_volume_control; - return *g_volume_control; -} - -} // namespace - -// static -void VolumeControl::Initialize(const std::vector& argv) { - GetVolumeControl(); -} - -// static -void VolumeControl::Finalize() {} - -// static -void VolumeControl::AddVolumeObserver(VolumeObserver* observer) { - GetVolumeControl().AddVolumeObserver(observer); -} - -// static -void VolumeControl::RemoveVolumeObserver(VolumeObserver* observer) { - GetVolumeControl().RemoveVolumeObserver(observer); -} - -// static -float VolumeControl::GetVolume(AudioContentType type) { - return GetVolumeControl().GetVolume(type); -} - -// static -void VolumeControl::SetVolume(media::VolumeChangeSource source, - AudioContentType type, - float level) { - GetVolumeControl().SetVolume(source, type, level); -} - -// static -bool VolumeControl::IsMuted(AudioContentType type) { - return GetVolumeControl().IsMuted(type); -} - -// static -void VolumeControl::SetMuted(media::VolumeChangeSource source, - AudioContentType type, - bool muted) { - GetVolumeControl().SetMuted(source, type, muted); -} - -// static -void VolumeControl::SetOutputLimit(AudioContentType type, float limit) {} - -// static -float VolumeControl::VolumeToDbFS(float volume) { - volume = std::clamp(volume, 0.0f, 1.0f); - return kMinVolumeDbfs + volume * (kMaxVolumeDbfs - kMinVolumeDbfs); -} - -// static -float VolumeControl::DbFSToVolume(float db) { - db = std::clamp(db, kMinVolumeDbfs, kMaxVolumeDbfs); - return (db - kMinVolumeDbfs) / (kMaxVolumeDbfs - kMinVolumeDbfs); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/media_codec_support_cast_audio.cc chromium-132.0.6834.159/chromecast/media/cma/backend/media_codec_support_cast_audio.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/media_codec_support_cast_audio.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/media_codec_support_cast_audio.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// 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 "base/strings/string_util.h" -#include "chromecast/public/media/media_capabilities_shlib.h" - -namespace chromecast { -namespace media { - -bool MediaCapabilitiesShlib::IsSupportedVideoConfig(VideoCodec codec, - VideoProfile profile, - int level) { - return (codec == kCodecH264 || codec == kCodecVP8 || codec == kCodecVP9); -} - -bool MediaCapabilitiesShlib::IsSupportedAudioConfig(const AudioConfig& config) { - return config.codec == kCodecAAC || config.codec == kCodecMP3 || - config.codec == kCodecPCM || config.codec == kCodecVorbis; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.cc chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,317 +0,0 @@ -// 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 "chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h" - -#include - -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/base/default_monotonic_clock.h" -#include "chromecast/media/cma/backend/audio_decoder_for_mixer.h" -#include "chromecast/media/cma/backend/av_sync.h" -#include "chromecast/media/cma/backend/video_decoder_for_mixer.h" - -namespace { - -// Delay video playback to achieve AV sync when video starts. -// This value is based on experimental calculation. -int64_t kSyncedPlaybackStartDelayUs = 20000; - -} // namespace - -namespace chromecast { -namespace media { - -MediaPipelineBackendForMixer::MediaPipelineBackendForMixer( - const MediaPipelineDeviceParams& params) - : state_(kStateUninitialized), params_(params), weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); -} - -MediaPipelineBackendForMixer::~MediaPipelineBackendForMixer() { - DCHECK(GetTaskRunner()->RunsTasksInCurrentSequence()); -} - -MediaPipelineBackendForMixer::AudioDecoder* -MediaPipelineBackendForMixer::CreateAudioDecoder() { - DCHECK_EQ(kStateUninitialized, state_); - if (audio_decoder_) - return nullptr; - audio_decoder_ = std::make_unique(this); - if (video_decoder_ && !av_sync_ && !IsIgnorePtsMode()) { - av_sync_ = AvSync::Create(this); - } - return audio_decoder_.get(); -} - -MediaPipelineBackendForMixer::VideoDecoder* -MediaPipelineBackendForMixer::CreateVideoDecoder() { - DCHECK_EQ(kStateUninitialized, state_); - if (video_decoder_) - return nullptr; - video_decoder_ = VideoDecoderForMixer::Create(params_); - video_decoder_->SetObserver(this); - DCHECK(video_decoder_.get()); - if (audio_decoder_ && !av_sync_ && !IsIgnorePtsMode()) { - av_sync_ = AvSync::Create(this); - } - return video_decoder_.get(); -} - -bool MediaPipelineBackendForMixer::Initialize() { - DCHECK_EQ(kStateUninitialized, state_); - if (audio_decoder_) - audio_decoder_->Initialize(); - if (video_decoder_ && !video_decoder_->Initialize()) { - return false; - } - state_ = kStateInitialized; - return true; -} - -bool MediaPipelineBackendForMixer::Start(int64_t start_pts) { - DCHECK_EQ(kStateInitialized, state_); - - video_ready_to_play_ = !video_decoder_; - audio_ready_to_play_ = !audio_decoder_; - - start_playback_timestamp_us_ = INT64_MIN; - start_playback_pts_us_ = start_pts; - - int64_t effective_start_pts = - (IsIgnorePtsMode() ? INT64_MIN : start_playback_pts_us_); - if (audio_decoder_ && !audio_decoder_->Start(effective_start_pts, - static_cast(av_sync_))) { - return false; - } - - if (video_decoder_ && !video_decoder_->Start(start_playback_pts_us_, true)) - return false; - - state_ = kStatePlaying; - playback_started_ = !av_sync_; - starting_playback_rate_ = 1.0; - - return true; -} - -void MediaPipelineBackendForMixer::Stop() { - DCHECK(state_ == kStatePlaying || state_ == kStatePaused) - << "Invalid state " << state_; - if (audio_decoder_) - audio_decoder_->Stop(); - if (video_decoder_) - video_decoder_->Stop(); - if (av_sync_) { - av_sync_->NotifyStop(); - } - - state_ = kStateInitialized; -} - -bool MediaPipelineBackendForMixer::Pause() { - DCHECK_EQ(kStatePlaying, state_); - if (!playback_started_) { - state_ = kStatePaused; - LOG(INFO) << "Pause received while playback has not started yet."; - return true; - } - - if (audio_decoder_ && !audio_decoder_->Pause()) { - return false; - } - if (video_decoder_ && !video_decoder_->Pause()) { - return false; - } - if (av_sync_) { - av_sync_->NotifyPause(); - } - - state_ = kStatePaused; - return true; -} - -bool MediaPipelineBackendForMixer::Resume() { - DCHECK_EQ(kStatePaused, state_); - - if (!playback_started_) { - LOG(INFO) << "Resume received while playback has not started yet."; - state_ = kStatePlaying; - TryStartPlayback(); - return true; - } - - if (av_sync_) { - av_sync_->NotifyResume(); - } - if (audio_decoder_ && !audio_decoder_->Resume()) - return false; - if (video_decoder_ && !video_decoder_->Resume()) - return false; - - state_ = kStatePlaying; - return true; -} - -bool MediaPipelineBackendForMixer::SetPlaybackRate(float rate) { - if (!playback_started_) { - LOG(INFO) << "Got playback rate change before playback has started."; - - // Some vendor VideoDecoderForMixer implementations may not properly handle - // the rate change before playback has started. It needs to be moved to - // after we start playback - starting_playback_rate_ = rate; - } else { - LOG(INFO) << __func__ << " rate=" << rate; - - // If av_sync_ is available, only change the audio rate of playback. This - // will notify us of when the audio playback rate change goes into effect, - // and then we'll change the video rate of playback. - if (av_sync_) { - DCHECK(audio_decoder_); - audio_decoder_->SetPlaybackRate(rate); - return true; - } - - if (audio_decoder_) { - rate = audio_decoder_->SetPlaybackRate(rate); - } - if (video_decoder_ && !video_decoder_->SetPlaybackRate(rate)) - return false; - } - - return true; -} - -int64_t MediaPipelineBackendForMixer::GetCurrentPts() { - int64_t timestamp = 0; - int64_t pts = 0; - int64_t video_pts = INT64_MIN; - int64_t audio_pts = INT64_MIN; - - // Decoders will do funky things if you ask them what the PTS is before - // playback has started, so deal with that here. - if (!playback_started_ || - start_playback_timestamp_us_ > MonotonicClockNow()) { - return INT64_MIN; - } - - if (video_decoder_ && video_decoder_->GetCurrentPts(×tamp, &pts)) - video_pts = pts; - if (audio_decoder_) - audio_pts = audio_decoder_->GetCurrentPts(); - return std::max(audio_pts, video_pts); -} - -bool MediaPipelineBackendForMixer::Primary() const { - return (params_.audio_type != - MediaPipelineDeviceParams::kAudioStreamSoundEffects); -} - -std::string MediaPipelineBackendForMixer::DeviceId() const { - return params_.device_id; -} - -AudioContentType MediaPipelineBackendForMixer::ContentType() const { - return params_.content_type; -} - -AudioChannel MediaPipelineBackendForMixer::AudioChannel() const { - return params_.audio_channel; -} - -const scoped_refptr& -MediaPipelineBackendForMixer::GetTaskRunner() const { - return static_cast(params_.task_runner)->runner(); -} - -int64_t MediaPipelineBackendForMixer::MonotonicClockNow() const { - return media::MonotonicClockNow(); -} - -bool MediaPipelineBackendForMixer::IsIgnorePtsMode() const { - return params_.sync_type == - MediaPipelineDeviceParams::MediaSyncType::kModeIgnorePts || - params_.sync_type == - MediaPipelineDeviceParams::MediaSyncType::kModeIgnorePtsAndVSync; -} - -void MediaPipelineBackendForMixer::VideoReadyToPlay() { - GetTaskRunner()->PostTask( - FROM_HERE, - base::BindOnce(&MediaPipelineBackendForMixer::OnVideoReadyToPlay, - weak_this_)); -} - -void MediaPipelineBackendForMixer::OnVideoReadyToPlay() { - DCHECK(GetTaskRunner()->RunsTasksInCurrentSequence()); - DCHECK(!video_ready_to_play_); - DCHECK(video_decoder_); - - LOG(INFO) << "Video ready to play"; - video_ready_to_play_ = true; - - if (av_sync_) { - TryStartPlayback(); - } else if (!IsIgnorePtsMode()) { - start_playback_timestamp_us_ = MonotonicClockNow(); - LOG(INFO) << "Starting playback at=" << start_playback_timestamp_us_; - - video_decoder_->SetPts(start_playback_timestamp_us_, - start_playback_pts_us_); - } -} - -void MediaPipelineBackendForMixer::OnAudioReadyForPlayback() { - DCHECK(!audio_ready_to_play_); - - LOG(INFO) << "Audio ready to play"; - audio_ready_to_play_ = true; - - if (av_sync_) { - TryStartPlayback(); - } -} - -void MediaPipelineBackendForMixer::TryStartPlayback() { - DCHECK(av_sync_); - DCHECK(!IsIgnorePtsMode()); - DCHECK(video_decoder_); - DCHECK(audio_decoder_); - DCHECK(!playback_started_); - - if (!audio_ready_to_play_ || !video_ready_to_play_ || - state_ != kStatePlaying) { - return; - } - - start_playback_timestamp_us_ = - MonotonicClockNow() + kSyncedPlaybackStartDelayUs + - audio_decoder_->GetMixerRenderingDelay().delay_microseconds; - LOG(INFO) << "Starting playback at=" << start_playback_timestamp_us_; - - video_decoder_->SetPts(start_playback_timestamp_us_, start_playback_pts_us_); - audio_decoder_->StartPlaybackAt(start_playback_timestamp_us_); - av_sync_->NotifyStart(start_playback_timestamp_us_, start_playback_pts_us_); - - playback_started_ = true; - if (starting_playback_rate_ != 1.0) { - SetPlaybackRate(starting_playback_rate_); - } -} - -void MediaPipelineBackendForMixer::NewAudioPlaybackRateInEffect(float rate) { - if (av_sync_) { - av_sync_->NotifyPlaybackRateChange(rate); - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_FOR_MIXER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_FOR_MIXER_H_ - -#include -#include - -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/media/cma/backend/video_decoder_for_mixer.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -namespace media { - -class AvSync; -class AudioDecoderForMixer; -class VideoDecoderForMixer; - -// CMA Backend implementation for audio devices. -class MediaPipelineBackendForMixer : public MediaPipelineBackend, - public VideoDecoderForMixer::Observer { - public: - explicit MediaPipelineBackendForMixer( - const MediaPipelineDeviceParams& params); - - MediaPipelineBackendForMixer(const MediaPipelineBackendForMixer&) = delete; - MediaPipelineBackendForMixer& operator=(const MediaPipelineBackendForMixer&) = - delete; - - ~MediaPipelineBackendForMixer() override; - - // MediaPipelineBackend implementation: - AudioDecoder* CreateAudioDecoder() override; - VideoDecoder* CreateVideoDecoder() override; - bool Initialize() override; - bool Start(int64_t start_pts) override; - void Stop() override; - bool Pause() override; - bool Resume() override; - bool SetPlaybackRate(float rate) override; - int64_t GetCurrentPts() override; - - // VideoDecoderForMixer::Observer implementation: - void VideoReadyToPlay() override; - - bool Primary() const; - std::string DeviceId() const; - AudioContentType ContentType() const; - AudioChannel AudioChannel() const; - const scoped_refptr& GetTaskRunner() const; - VideoDecoderForMixer* video_decoder() const { return video_decoder_.get(); } - AudioDecoderForMixer* audio_decoder() const { return audio_decoder_.get(); } - void OnAudioReadyForPlayback(); - void NewAudioPlaybackRateInEffect(float rate); - - // Gets current time on the same clock as the rendering delay timestamp. - virtual int64_t MonotonicClockNow() const; - - int64_t GetPlaybackStartTimeForTesting() const { - return start_playback_timestamp_us_; - } - int64_t GetPlaybackStartPtsForTesting() const { - return start_playback_pts_us_; - } - - protected: - std::unique_ptr video_decoder_; - std::unique_ptr audio_decoder_; - - private: - // State variable for DCHECKing caller correctness. - enum State { - kStateUninitialized, - kStateInitialized, - kStatePlaying, - kStatePaused, - }; - State state_; - - void OnVideoReadyToPlay(); - bool IsIgnorePtsMode() const; - void TryStartPlayback(); - - const MediaPipelineDeviceParams params_; - - std::unique_ptr av_sync_; - int64_t start_playback_timestamp_us_ = INT64_MIN; - int64_t start_playback_pts_us_ = INT64_MIN; - - // The media pipeline doesn't start playback until these 3 conditions are - // met. - bool audio_ready_to_play_ = false; - bool video_ready_to_play_ = false; - bool playback_started_ = false; - float starting_playback_rate_ = 1.0; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_FOR_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/media_pipeline_backend_manager_mixer.cc chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_manager_mixer.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/media_pipeline_backend_manager_mixer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_manager_mixer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/media_pipeline_backend_manager.h" - -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "chromecast/media/audio/mixer_service/control_connection.h" - -namespace chromecast { -namespace media { - -void MediaPipelineBackendManager::CreateMixerConnection() { - struct RealMixerConnection : public MixerConnection { - RealMixerConnection() { connection.Connect(); } - - ~RealMixerConnection() override = default; - - mixer_service::ControlConnection connection; - }; - - DCHECK(media_task_runner_->BelongsToCurrentThread()); - auto mixer = std::make_unique(); - mixer->connection.SetStreamCountCallback(base::BindRepeating( - &MediaPipelineBackendManager::OnMixerStreamCountChange, - base::Unretained(this))); - mixer_connection_ = std::move(mixer); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/media_pipeline_backend_manager_no_mixer.cc chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_manager_no_mixer.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/media_pipeline_backend_manager_no_mixer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/media_pipeline_backend_manager_no_mixer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/media_pipeline_backend_manager.h" - -namespace chromecast { -namespace media { - -void MediaPipelineBackendManager::CreateMixerConnection() {} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/audio_output_redirector.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/audio_output_redirector.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,477 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/audio_output_redirector.h" - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/strings/pattern.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/audio/audio_fader.h" -#include "chromecast/media/audio/audio_log.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/media/cma/backend/mixer/audio_output_redirector_input.h" -#include "chromecast/media/cma/backend/mixer/channel_layout.h" -#include "chromecast/media/cma/backend/mixer/mixer_input.h" -#include "chromecast/media/cma/backend/mixer/stream_mixer.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "media/base/audio_bus.h" -#include "media/base/channel_layout.h" -#include "media/base/channel_mixer.h" - -namespace chromecast { -namespace media { - -namespace { - -using Patterns = std::vector>; - -constexpr int kDefaultBufferSize = 2048; -constexpr int kMaxChannels = 32; - -constexpr int kAudioMessageHeaderSize = - mixer_service::MixerSocket::kAudioMessageHeaderSize; - -::media::ChannelLayout GetMediaChannelLayout( - chromecast::media::ChannelLayout layout, - int num_channels) { - if (layout == media::ChannelLayout::UNSUPPORTED) { - return mixer::GuessChannelLayout(num_channels); - } - return DecoderConfigAdapter::ToMediaChannelLayout(layout); -} - -enum MessageTypes : int { - kStreamConfig = 1, -}; - -} // namespace - -class AudioOutputRedirector::RedirectionConnection - : public mixer_service::MixerSocket::Delegate { - public: - explicit RedirectionConnection( - std::unique_ptr socket, - scoped_refptr mixer_task_runner, - base::WeakPtr redirector) - : socket_(std::move(socket)), - mixer_task_runner_(std::move(mixer_task_runner)), - redirector_(std::move(redirector)) { - DCHECK(socket_); - DCHECK(mixer_task_runner_); - - socket_->SetDelegate(this); - } - - RedirectionConnection(const RedirectionConnection&) = delete; - RedirectionConnection& operator=(const RedirectionConnection&) = delete; - - ~RedirectionConnection() override = default; - - void SetStreamConfig(SampleFormat sample_format, - int sample_rate, - int num_channels, - int data_size) { - mixer_service::Generic message; - mixer_service::StreamConfig* config = message.mutable_stream_config(); - config->set_sample_format( - audio_service::ConvertSampleFormat(sample_format)); - config->set_sample_rate(sample_rate); - config->set_num_channels(num_channels); - config->set_data_size(data_size); - socket_->SendProto(kStreamConfig, message); - - sent_stream_config_ = true; - } - - void SendAudio(scoped_refptr audio_buffer, - int data_size_bytes, - int64_t timestamp) { - if (error_) { - return; - } - DCHECK(sent_stream_config_); - socket_->SendAudioBuffer(std::move(audio_buffer), data_size_bytes, - timestamp); - } - - // mixer_service::MixerSocket::Delegate implementation: - bool HandleMetadata(const mixer_service::Generic& message) override { - if (!message.has_redirected_stream_patterns()) { - return true; - } - - Patterns new_patterns; - for (const auto& p : message.redirected_stream_patterns().patterns()) { - new_patterns.emplace_back( - audio_service::ConvertContentType(p.content_type()), - p.device_id_pattern()); - } - mixer_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&AudioOutputRedirector::UpdatePatterns, - redirector_, std::move(new_patterns))); - return true; - } - - private: - bool HandleAudioData(char* data, size_t size, int64_t timestamp) override { - return true; - } - - void OnConnectionError() override { - if (error_) { - return; - } - error_ = true; - mixer_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&AudioOutputRedirector::OnConnectionError, redirector_)); - } - - const std::unique_ptr socket_; - const scoped_refptr mixer_task_runner_; - const base::WeakPtr redirector_; - - bool error_ = false; - bool sent_stream_config_ = false; -}; - -class AudioOutputRedirector::InputImpl : public AudioOutputRedirectorInput { - public: - using RenderingDelay = MediaPipelineBackend::AudioDecoder::RenderingDelay; - - InputImpl(AudioOutputRedirector* output_redirector, MixerInput* mixer_input); - - InputImpl(const InputImpl&) = delete; - InputImpl& operator=(const InputImpl&) = delete; - - ~InputImpl() override; - - // AudioOutputRedirectorInput implementation: - int Order() override { return output_redirector_->order(); } - int64_t GetDelayMicroseconds() override { - return output_redirector_->extra_delay_microseconds(); - } - void Redirect(::media::AudioBus* const buffer, - int num_frames, - RenderingDelay rendering_delay, - bool redirected) override; - - private: - AudioOutputRedirector* const output_redirector_; - MixerInput* const mixer_input_; - const ::media::ChannelLayout output_channel_layout_; - const int num_output_channels_; - - bool previous_ended_in_silence_; - - std::unique_ptr<::media::ChannelMixer> channel_mixer_; - std::unique_ptr<::media::AudioBus> temp_buffer_; -}; - -AudioOutputRedirector::InputImpl::InputImpl( - AudioOutputRedirector* output_redirector, - MixerInput* mixer_input) - : output_redirector_(output_redirector), - mixer_input_(mixer_input), - output_channel_layout_(output_redirector_->output_channel_layout()), - num_output_channels_(output_redirector_->num_output_channels()), - previous_ended_in_silence_(true) { - DCHECK_LE(num_output_channels_, kMaxChannels); - DCHECK(output_redirector_); - DCHECK(mixer_input_); - - if (mixer_input_->num_channels() != num_output_channels_) { - AUDIO_LOG(INFO) << "Remixing channels for " << mixer_input_->source() - << " from " << mixer_input_->num_channels() << " to " - << num_output_channels_; - channel_mixer_ = std::make_unique<::media::ChannelMixer>( - mixer::CreateAudioParametersForChannelMixer( - mixer_input_->channel_layout(), mixer_input_->num_channels()), - mixer::CreateAudioParametersForChannelMixer(output_channel_layout_, - num_output_channels_)); - } - - temp_buffer_ = - ::media::AudioBus::Create(num_output_channels_, kDefaultBufferSize); - temp_buffer_->Zero(); - - mixer_input_->AddAudioOutputRedirector(this); -} - -AudioOutputRedirector::InputImpl::~InputImpl() { - mixer_input_->RemoveAudioOutputRedirector(this); -} - -void AudioOutputRedirector::InputImpl::Redirect(::media::AudioBus* const buffer, - int num_frames, - RenderingDelay rendering_delay, - bool redirected) { - if (num_frames == 0) { - return; - } - - if (previous_ended_in_silence_ && redirected) { - // Previous buffer ended in silence, and the current buffer was redirected - // by a previous output splitter, so maintain silence. - return; - } - if (!previous_ended_in_silence_ && !redirected && !channel_mixer_) { - // No fading or channel mixing required, just mix directly. - output_redirector_->MixInput(mixer_input_, buffer, num_frames, - rendering_delay); - return; - } - - if (temp_buffer_->frames() < num_frames) { - temp_buffer_ = ::media::AudioBus::Create( - num_output_channels_, std::max(num_frames, kDefaultBufferSize)); - } - - if (channel_mixer_) { - channel_mixer_->TransformPartial(buffer, num_frames, temp_buffer_.get()); - } else { - buffer->CopyPartialFramesTo(0, num_frames, 0, temp_buffer_.get()); - } - - float* channels[kMaxChannels]; - for (int c = 0; c < num_output_channels_; ++c) { - channels[c] = temp_buffer_->channel(c); - } - if (previous_ended_in_silence_) { - if (!redirected) { - // Smoothly fade in from previous silence. - AudioFader::FadeInHelper(channels, num_output_channels_, num_frames, - num_frames, num_frames); - } - } else if (redirected) { - // Smoothly fade out to silence, since output is now being redirected by a - // previous output splitter. - AudioFader::FadeOutHelper(channels, num_output_channels_, num_frames, - num_frames, num_frames); - } - previous_ended_in_silence_ = redirected; - - output_redirector_->MixInput(mixer_input_, temp_buffer_.get(), num_frames, - rendering_delay); -} - -// static -AudioOutputRedirector::Config AudioOutputRedirector::ParseConfig( - const mixer_service::Generic& message) { - Config config; - DCHECK(message.has_redirection_request()); - const mixer_service::RedirectionRequest& request = - message.redirection_request(); - if (request.has_num_channels()) { - config.num_output_channels = request.num_channels(); - } - if (request.has_channel_layout() && - request.channel_layout() != audio_service::CHANNEL_LAYOUT_BITSTREAM) { - config.output_channel_layout = - audio_service::ConvertChannelLayout(request.channel_layout()); - } else { - config.output_channel_layout = media::ChannelLayout::UNSUPPORTED; - } - if (request.has_order()) { - config.order = request.order(); - } - if (request.has_apply_volume()) { - config.apply_volume = request.apply_volume(); - } - if (request.has_extra_delay_microseconds()) { - config.extra_delay_microseconds = request.extra_delay_microseconds(); - } - return config; -} - -AudioOutputRedirector::AudioOutputRedirector( - StreamMixer* mixer, - std::unique_ptr socket, - const mixer_service::Generic& message) - : mixer_(mixer), - config_(ParseConfig(message)), - output_channel_layout_( - GetMediaChannelLayout(config_.output_channel_layout, - config_.num_output_channels)), - io_task_runner_(base::SequencedTaskRunner::GetCurrentDefault()), - buffer_pool_( - base::MakeRefCounted(kDefaultBufferSize, - std::numeric_limits::max(), - true /* threadsafe */)), - weak_factory_(this) { - DCHECK_GT(config_.num_output_channels, 0); - - output_ = std::make_unique( - std::move(socket), mixer_->task_runner(), weak_factory_.GetWeakPtr()); - output_->HandleMetadata(message); -} - -AudioOutputRedirector::~AudioOutputRedirector() { - io_task_runner_->DeleteSoon(FROM_HERE, std::move(output_)); -} - -void AudioOutputRedirector::AddInput(MixerInput* mixer_input) { - if (ApplyToInput(mixer_input)) { - DCHECK_EQ(mixer_input->output_samples_per_second(), sample_rate_); - inputs_[mixer_input] = std::make_unique(this, mixer_input); - } else { - non_redirected_inputs_.insert(mixer_input); - } -} - -void AudioOutputRedirector::RemoveInput(MixerInput* mixer_input) { - inputs_.erase(mixer_input); - non_redirected_inputs_.erase(mixer_input); -} - -bool AudioOutputRedirector::ApplyToInput(MixerInput* mixer_input) { - if (!mixer_input->primary()) { - return false; - } - - for (const auto& pattern : patterns_) { - if (mixer_input->content_type() == pattern.first && - base::MatchPattern(mixer_input->device_id(), pattern.second)) { - return true; - } - } - - return false; -} - -void AudioOutputRedirector::UpdatePatterns( - std::vector> patterns) { - patterns_ = std::move(patterns); - // Remove streams that no longer match. - for (auto it = inputs_.begin(); it != inputs_.end();) { - MixerInput* mixer_input = it->first; - if (!ApplyToInput(mixer_input)) { - non_redirected_inputs_.insert(mixer_input); - it = inputs_.erase(it); - } else { - ++it; - } - } - - // Add streams that previously didn't match. - for (auto it = non_redirected_inputs_.begin(); - it != non_redirected_inputs_.end();) { - MixerInput* mixer_input = *it; - if (ApplyToInput(mixer_input)) { - inputs_[mixer_input] = std::make_unique(this, mixer_input); - it = non_redirected_inputs_.erase(it); - } else { - ++it; - } - } -} - -void AudioOutputRedirector::OnConnectionError() { - mixer_->RemoveAudioOutputRedirector(this); -} - -void AudioOutputRedirector::SetSampleRate(int output_samples_per_second) { - sample_rate_ = output_samples_per_second; - - io_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&RedirectionConnection::SetStreamConfig, - base::Unretained(output_.get()), kSampleFormatPlanarF32, - sample_rate_, config_.num_output_channels, - buffer_pool_->buffer_size() - kAudioMessageHeaderSize)); -} - -void AudioOutputRedirector::PrepareNextBuffer(int num_frames) { - size_t required_size_bytes = - kAudioMessageHeaderSize + - num_frames * config_.num_output_channels * sizeof(float); - if (buffer_pool_->buffer_size() < required_size_bytes) { - buffer_pool_ = base::MakeRefCounted( - required_size_bytes, std::numeric_limits::max(), - true /* threadsafe */); - io_task_runner_->PostTask( - FROM_HERE, - base::BindOnce( - &RedirectionConnection::SetStreamConfig, - base::Unretained(output_.get()), kSampleFormatPlanarF32, - sample_rate_, config_.num_output_channels, - num_frames * config_.num_output_channels * sizeof(float))); - } - - current_mix_buffer_ = buffer_pool_->GetBuffer(); - current_mix_data_ = reinterpret_cast(current_mix_buffer_->data() + - kAudioMessageHeaderSize); - std::fill_n(current_mix_data_, num_frames * config_.num_output_channels, - 0.0f); - next_output_timestamp_ = INT64_MIN; - next_num_frames_ = num_frames; - input_count_ = 0; -} - -void AudioOutputRedirector::MixInput(MixerInput* mixer_input, - ::media::AudioBus* data, - int num_frames, - RenderingDelay rendering_delay) { - DCHECK(current_mix_data_); - DCHECK_GE(next_num_frames_, num_frames); - DCHECK_EQ(config_.num_output_channels, data->channels()); - - if (rendering_delay.timestamp_microseconds != INT64_MIN) { - int64_t output_timestamp = rendering_delay.timestamp_microseconds + - rendering_delay.delay_microseconds + - extra_delay_microseconds(); - if (next_output_timestamp_ == INT64_MIN || - output_timestamp < next_output_timestamp_) { - next_output_timestamp_ = output_timestamp; - } - } - - if (num_frames <= 0) { - return; - } - - ++input_count_; - for (int c = 0; c < config_.num_output_channels; ++c) { - float* dest_channel = current_mix_data_ + c * next_num_frames_; - if (config_.apply_volume) { - mixer_input->VolumeScaleAccumulate(data->channel(c), num_frames, - dest_channel, c); - } else { - const float* temp_channel = data->channel(c); - for (int i = 0; i < num_frames; ++i) { - dest_channel[i] += temp_channel[i]; - } - } - } -} - -void AudioOutputRedirector::FinishBuffer() { - if (input_count_ == 0) { - return; - } - - // Hard limit to [1.0, -1.0]. - for (int s = 0; s < config_.num_output_channels * next_num_frames_; ++s) { - current_mix_data_[s] = std::clamp(current_mix_data_[s], -1.0f, 1.0f); - } - - io_task_runner_->PostTask( - FROM_HERE, - base::BindOnce( - &RedirectionConnection::SendAudio, base::Unretained(output_.get()), - std::move(current_mix_buffer_), - config_.num_output_channels * next_num_frames_ * sizeof(float), - next_output_timestamp_)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/audio_output_redirector.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/audio_output_redirector.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,145 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_AUDIO_OUTPUT_REDIRECTOR_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_AUDIO_OUTPUT_REDIRECTOR_H_ - -#include -#include -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/containers/flat_set.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/media/audio/mixer_service/redirected_audio_connection.h" -#include "chromecast/net/io_buffer_pool.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/volume_control.h" -#include "media/base/channel_layout.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace media { -class AudioBus; -} // namespace media - -namespace chromecast { -namespace media { -class MixerInput; -class StreamMixer; - -namespace mixer_service { -class Generic; -class MixerSocket; -} // namespace mixer_service - -// The AudioOutputRedirector class determines which MixerInputs match the config -// conditions, and adds an AudioOutputRedirectorInput to each one. -// When the mixer is writing output, it tells each AudioOutputRedirector to -// create a new buffer (by calling PrepareNextBuffer()). As audio is pulled from -// each MixerInput, the resulting audio is passed through any added -// AudioOutputRedirectorInputs and is mixed into the redirected buffer by the -// AudioOutputRedirector (with appropriate fading to avoid pops/clicks, and -// volume applied if desired). Once all MixerInputs have been processed, the -// mixer will call FinishBuffer() on each AudioOutputRedirector; the -// redirected buffer is then sent to the RedirectedAudioOutput associated -// with each redirector. -// Created on the IO thread, but otherwise runs on the mixer thread. -class AudioOutputRedirector { - public: - using RenderingDelay = MediaPipelineBackend::AudioDecoder::RenderingDelay; - - AudioOutputRedirector(StreamMixer* mixer, - std::unique_ptr socket, - const mixer_service::Generic& message); - - AudioOutputRedirector(const AudioOutputRedirector&) = delete; - AudioOutputRedirector& operator=(const AudioOutputRedirector&) = delete; - - ~AudioOutputRedirector(); - - int order() const { return config_.order; } - int num_output_channels() const { return config_.num_output_channels; } - ::media::ChannelLayout output_channel_layout() const { - return output_channel_layout_; - } - - int64_t extra_delay_microseconds() const { - return config_.extra_delay_microseconds; - } - - // Adds/removes mixer inputs. The mixer adds/removes all mixer inputs from - // the AudioOutputRedirector; this class does the work to determine which - // inputs match the desired conditions. - void AddInput(MixerInput* mixer_input); - void RemoveInput(MixerInput* mixer_input); - - // Sets the sample rate for subsequent audio from inputs. - void SetSampleRate(int output_samples_per_second); - - // Called by the mixer when it is preparing to write another buffer of - // |num_frames| frames. - void PrepareNextBuffer(int num_frames); - - // Mixes audio into the redirected output buffer. Called by the - // AudioOutputRedirectorInput implementation to mix in audio from each - // matching MixerInput. - void MixInput(MixerInput* mixer_input, - ::media::AudioBus* data, - int num_frames, - RenderingDelay rendering_delay); - - // Called by the mixer once all MixerInputs have been processed; passes the - // redirected audio buffer to the output plugin. - void FinishBuffer(); - - private: - class InputImpl; - class RedirectionConnection; - - using Config = mixer_service::RedirectedAudioConnection::Config; - - static Config ParseConfig(const mixer_service::Generic& message); - - // Updates the set of patterns used to determine which inputs should be - // redirected by this AudioOutputRedirector. Any inputs which no longer match - // will stop being redirected. - void UpdatePatterns( - std::vector> patterns); - void OnConnectionError(); - - bool ApplyToInput(MixerInput* mixer_input); - - StreamMixer* const mixer_; - const Config config_; - const ::media::ChannelLayout output_channel_layout_; - std::unique_ptr output_; - scoped_refptr io_task_runner_; - - int sample_rate_ = 0; - - std::vector> patterns_; - - int next_num_frames_ = 0; - int64_t next_output_timestamp_ = INT64_MIN; - int input_count_ = 0; - - scoped_refptr buffer_pool_; - scoped_refptr<::net::IOBuffer> current_mix_buffer_; - float* current_mix_data_ = nullptr; - - base::flat_map> inputs_; - base::flat_set non_redirected_inputs_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_AUDIO_OUTPUT_REDIRECTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/audio_output_redirector_input.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector_input.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/audio_output_redirector_input.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/audio_output_redirector_input.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_AUDIO_OUTPUT_REDIRECTOR_INPUT_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_AUDIO_OUTPUT_REDIRECTOR_INPUT_H_ - -namespace media { -class AudioBus; -} // namespace media - -namespace chromecast { -namespace media { - -// Interface used by matching MixerInputs to pass audio data to an output -// redirector. -class AudioOutputRedirectorInput { - public: - // Returns the relative order of the output redirector (used if there are - // multiple output redirectors that match a given MixerInput). - virtual int Order() = 0; - - // Returns any extra delay that the output redirector will add. Used for A/V - // sync. - virtual int64_t GetDelayMicroseconds() = 0; - - // Called to handle audio from a single input stream. Note that all audio - // output redirectors will receive this data, even if they are not first in - // the queue of redirectors; this is to allow smooth fading in/out when - // redirectors are added or removed. - virtual void Redirect( - ::media::AudioBus* const buffer, - int num_frames, - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay, - bool redirected) = 0; - - protected: - virtual ~AudioOutputRedirectorInput() = default; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_AUDIO_OUTPUT_REDIRECTOR_INPUT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/channel_layout.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/channel_layout.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/channel_layout.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/channel_layout.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// 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 "chromecast/media/cma/backend/mixer/channel_layout.h" - -#include "base/check_op.h" - -namespace chromecast { -namespace media { -namespace mixer { - -::media::ChannelLayout GuessChannelLayout(int num_channels) { - if (num_channels > ::media::kMaxConcurrentChannels) { - return ::media::CHANNEL_LAYOUT_DISCRETE; - } - return ::media::GuessChannelLayout(num_channels); -} - -::media::AudioParameters CreateAudioParameters( - ::media::AudioParameters::Format format, - ::media::ChannelLayout channel_layout, - int num_channels, - int sample_rate, - int frames_per_buffer) { - ::media::AudioParameters parameters(format, {channel_layout, num_channels}, - sample_rate, frames_per_buffer); - return parameters; -} - -::media::AudioParameters CreateAudioParametersForChannelMixer( - ::media::ChannelLayout channel_layout, - int num_channels) { - if (channel_layout == ::media::CHANNEL_LAYOUT_NONE) { - channel_layout = GuessChannelLayout(num_channels); - } - if (channel_layout != ::media::CHANNEL_LAYOUT_DISCRETE) { - DCHECK_EQ(num_channels, - ::media::ChannelLayoutToChannelCount(channel_layout)); - } - // Sample rate and frames per buffer don't matter for channel mixer. - return CreateAudioParameters(::media::AudioParameters::AUDIO_PCM_LINEAR, - channel_layout, num_channels, 48000, 1024); -} - -} // namespace mixer -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/channel_layout.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/channel_layout.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/channel_layout.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/channel_layout.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_CHANNEL_LAYOUT_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_CHANNEL_LAYOUT_H_ - -#include "media/base/audio_parameters.h" -#include "media/base/channel_layout.h" - -namespace chromecast { -namespace media { -namespace mixer { - -// Guesses the channel layout based on the number of channels; supports using -// CHANNEL_LAYOUT_DISCRETE is there are more than 8 channels. -::media::ChannelLayout GuessChannelLayout(int num_channels); - -// Creates an AudioParameters with correct support for CHANNEL_LAYOUT_DISCRETE. -::media::AudioParameters CreateAudioParameters( - ::media::AudioParameters::Format format, - ::media::ChannelLayout channel_layout, - int num_channels, - int sample_rate, - int frames_per_buffer); - -// Creates AudioParameters for constructing a ChannelMixer. -::media::AudioParameters CreateAudioParametersForChannelMixer( - ::media::ChannelLayout channel_layout, - int num_channels); - -} // namespace mixer -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_CHANNEL_LAYOUT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/filter_group.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/filter_group.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,358 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/filter_group.h" - -#include - -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/time/time.h" -#include "base/values.h" -#include "chromecast/media/audio/audio_log.h" -#include "chromecast/media/audio/interleaved_channel_mixer.h" -#include "chromecast/media/cma/backend/mixer/channel_layout.h" -#include "chromecast/media/cma/backend/mixer/mixer_input.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_sample_types.h" -#include "media/base/vector_math.h" - -namespace chromecast { -namespace media { - -namespace { - -bool ParseVolumeLimit(const base::Value::Dict* dict, float* min, float* max) { - auto min_value = dict->FindDouble("min"); - auto max_value = dict->FindDouble("max"); - if (!min_value && !max_value) { - return false; - } - *min = 0.0f; - *max = 1.0f; - if (min_value) { - *min = std::clamp(static_cast(min_value.value()), 0.0f, 1.0f); - } - if (max_value) { - *max = std::clamp(static_cast(max_value.value()), *min, 1.0f); - } - return true; -} - -} // namespace - -FilterGroup::GroupInput::GroupInput( - FilterGroup* group, - std::unique_ptr channel_mixer) - : group(group), channel_mixer(std::move(channel_mixer)) {} - -FilterGroup::GroupInput::GroupInput(GroupInput&& other) = default; -FilterGroup::GroupInput::~GroupInput() = default; - -FilterGroup::FilterGroup(int num_channels, - std::string name, - base::Value prerender_filter_list, - const base::Value* filter_list, - PostProcessingPipelineFactory* ppp_factory, - const base::Value* volume_limits) - : num_channels_(num_channels), - name_(std::move(name)), - prerender_filter_list_(std::move(prerender_filter_list)), - ppp_factory_(ppp_factory), - tag_(base::MakeRefCounted()), - post_processing_pipeline_( - ppp_factory_->CreatePipeline(name_, filter_list, num_channels_)) { - LOG(INFO) << "Done creating postrender pipeline for " << name_; - ParseVolumeLimits(volume_limits); -} - -FilterGroup::~FilterGroup() = default; - -std::unique_ptr FilterGroup::CreatePrerenderPipeline( - int num_channels) { - ++prerender_creation_count_; - LOG(INFO) << "Creating prerender pipeline for " << name_; - auto pipeline = ppp_factory_->CreatePipeline( - "prerender_" + name_ + base::NumberToString(prerender_creation_count_), - &prerender_filter_list_, num_channels); - for (const auto& config : post_processing_configs_) { - LOG(INFO) << "Setting prerender post processing config for " << config.first - << " to " << config.second; - pipeline->SetPostProcessorConfig(config.first, config.second); - } - LOG(INFO) << "Done creating prerender pipeline for " << name_; - return pipeline; -} - -void FilterGroup::AddMixedInput(FilterGroup* input) { - // Channel mixers are created in Initialize(). - mixed_inputs_.emplace_back(input, std::unique_ptr()); - DCHECK_EQ(input->GetOutputChannelCount(), num_channels_); -} - -void FilterGroup::AddStreamType(const std::string& stream_type) { - stream_types_.push_back(stream_type); -} - -void FilterGroup::Initialize(const AudioPostProcessor2::Config& output_config) { - output_config_ = output_config; - - CHECK(post_processing_pipeline_->SetOutputConfig(output_config_)); - input_samples_per_second_ = post_processing_pipeline_->GetInputSampleRate(); - input_frames_per_write_ = output_config_.output_frames_per_write * - input_samples_per_second_ / - output_config_.output_sample_rate; - DCHECK_EQ(input_frames_per_write_ * output_config_.output_sample_rate, - output_config_.output_frames_per_write * input_samples_per_second_) - << "Unable to produce stable buffer sizes for resampling rate " - << input_samples_per_second_ << " : " - << output_config_.output_sample_rate; - - AudioPostProcessor2::Config input_config = output_config; - input_config.output_sample_rate = input_samples_per_second_; - input_config.output_frames_per_write = input_frames_per_write_; - - for (auto& input : mixed_inputs_) { - input.group->Initialize(input_config); - input.channel_mixer = std::make_unique( - mixer::GuessChannelLayout(input.group->GetOutputChannelCount()), - input.group->GetOutputChannelCount(), - mixer::GuessChannelLayout(num_channels_), num_channels_, - input_frames_per_write_); - } - post_processing_pipeline_->SetContentType(content_type_); - active_inputs_.clear(); - ResizeBuffers(); - - // Run a buffer of 0's to initialize rendering delay. - std::fill_n(interleaved_.data(), interleaved_.size(), 0.0f); - post_processing_pipeline_->ProcessFrames( - interleaved_.data(), input_frames_per_write_, last_volume_, last_volume_, - true /* is_silence */); - delay_seconds_ = post_processing_pipeline_->GetDelaySeconds(); -} - -void FilterGroup::ParseVolumeLimits(const base::Value* volume_limits) { - if (!volume_limits) { - return; - } - - DCHECK(volume_limits->is_dict()); - // Get default limits. - if (ParseVolumeLimit(&volume_limits->GetDict(), &default_volume_min_, - &default_volume_max_)) { - AUDIO_LOG(INFO) << "Default volume limits for '" << name_ << "' group: [" - << default_volume_min_ << ", " << default_volume_max_ - << "]"; - } - - float min, max; - for (const auto item : volume_limits->GetDict()) { - if (item.second.is_dict() && - ParseVolumeLimit(&item.second.GetDict(), &min, &max)) { - AUDIO_LOG(INFO) << "Volume limits for device ID '" << item.first - << "' = [" << min << ", " << max << "]"; - volume_limits_.insert({item.first, {min, max}}); - } - } -} - -void FilterGroup::AddInput(MixerInput* input) { - active_inputs_.insert(input); - - auto it = volume_limits_.find(input->device_id()); - if (it != volume_limits_.end()) { - input->SetVolumeLimits(it->second.first, it->second.second); - return; - } - - input->SetVolumeLimits(default_volume_min_, default_volume_max_); -} - -void FilterGroup::RemoveInput(MixerInput* input) { - active_inputs_.erase(input); -} - -float FilterGroup::MixAndFilter( - int num_output_frames, - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay) { - DCHECK_NE(output_config_.output_sample_rate, 0); - DCHECK_EQ(num_output_frames, output_config_.output_frames_per_write); - - float volume = 0.0f; - float target_volume = 0.0f; - AudioContentType content_type = static_cast(-1); - - rendering_delay.delay_microseconds += GetRenderingDelayMicroseconds(); - rendering_delay_to_output_ = rendering_delay; - - // Recursively mix inputs. - for (const auto& filter_group : mixed_inputs_) { - volume = std::max(volume, filter_group.group->MixAndFilter( - input_frames_per_write_, rendering_delay)); - target_volume = - std::max(target_volume, filter_group.group->target_volume()); - content_type = std::max(content_type, filter_group.group->content_type()); - } - - // Render direct inputs. - for (MixerInput* input : active_inputs_) { - if (input->Render(input_frames_per_write_, rendering_delay)) { - volume = std::max(volume, input->InstantaneousVolume()); - target_volume = std::max(target_volume, input->TargetVolume()); - content_type = std::max(content_type, input->content_type()); - } - } - - // |volume| can only be 0 if no |mixed_inputs_| or |active_inputs_| have data. - // This is true because FilterGroup can only return 0 if: - // a) It has no data and its PostProcessorPipeline is not ringing. - // (early return, below) or - // b) The output volume is 0 and has NEVER been non-zero, - // since FilterGroup will use last_volume_ if volume is 0. - // In this case, there was never any data in the pipeline. - if (active_inputs_.empty() && volume == 0.0f && - !post_processing_pipeline_->IsRinging()) { - last_volume_ = 0.0f; - output_buffer_ = interleaved_.data(); - ZeroOutputBufferIfNeeded(); - return 0.0f; // Output will be silence, no need to mix/process. - } - - output_frames_zeroed_ = 0; - std::fill_n(interleaved_.data(), interleaved_.size(), 0.0f); - - // Mix FilterGroups - for (const auto& input : mixed_inputs_) { - if (input.group->last_volume() > 0.0f) { - float* buffer = input.channel_mixer->Transform( - input.group->GetOutputBuffer(), input_frames_per_write_); - for (int i = 0; i < input_frames_per_write_ * num_channels_; ++i) { - interleaved_[i] += buffer[i]; - } - } - } - - // Mix direct inputs. - for (MixerInput* input : active_inputs_) { - if (input->has_render_output()) { - float* buffer = input->RenderedAudioBuffer(); - for (int i = 0; i < input_frames_per_write_ * num_channels_; ++i) { - interleaved_[i] += buffer[i]; - } - } - } - - // Allow paused streams to "ring out" at the last valid volume. - // If the stream volume is actually 0, this doesn't matter, since the - // data is 0's anyway. - bool is_silence = (volume == 0.0f); - if (!is_silence) { - last_volume_ = volume; - target_volume_ = target_volume; - DCHECK_NE(-1, static_cast(content_type)) - << "Got frames without content type."; - if (content_type != content_type_) { - content_type_ = content_type; - post_processing_pipeline_->SetContentType(content_type_); - } - } - - post_processing_pipeline_->ProcessFrames( - interleaved_.data(), input_frames_per_write_, last_volume_, - target_volume_, is_silence); - delay_seconds_ = post_processing_pipeline_->GetDelaySeconds(); - output_buffer_ = post_processing_pipeline_->GetOutputBuffer(); - return last_volume_; -} - -float* FilterGroup::GetOutputBuffer() { - DCHECK(output_buffer_); - return output_buffer_; -} - -int64_t FilterGroup::GetRenderingDelayMicroseconds() { - if (output_config_.output_sample_rate == 0) { - return 0; - } - return delay_seconds_ * base::Time::kMicrosecondsPerSecond; -} - -MediaPipelineBackend::AudioDecoder::RenderingDelay -FilterGroup::GetRenderingDelayToOutput() { - return rendering_delay_to_output_; -} - -int FilterGroup::GetOutputChannelCount() const { - return post_processing_pipeline_->NumOutputChannels(); -} - -void FilterGroup::ZeroOutputBufferIfNeeded() { - const int num_output_frames = output_config_.output_frames_per_write; - if (output_frames_zeroed_ < num_output_frames) { - float* buffer = GetOutputBuffer(); - std::fill_n(buffer, num_output_frames * GetOutputChannelCount(), 0); - output_frames_zeroed_ = num_output_frames; - } -} - -void FilterGroup::ResizeBuffers() { - int frames = - std::max(input_frames_per_write_, output_config_.output_frames_per_write); - int channels = std::max(num_channels_, GetOutputChannelCount()); - interleaved_.assign(frames * channels, 0.0f); - output_frames_zeroed_ = 0; -} - -void FilterGroup::SetPostProcessorConfig(const std::string& name, - const std::string& config) { - post_processing_pipeline_->SetPostProcessorConfig(name, config); - post_processing_configs_.insert_or_assign(name, config); - for (MixerInput* input : active_inputs_) { - input->SetPostProcessorConfig(name, config); - } -} - -bool FilterGroup::IsRinging() const { - return post_processing_pipeline_->IsRinging(); -} - -void FilterGroup::PrintTopology() const { - std::string filter_groups; - for (const auto& mixed_input : mixed_inputs_) { - mixed_input.group->PrintTopology(); - filter_groups += "[GROUP]" + mixed_input.group->name() + ", "; - } - - std::string input_groups; - for (const std::string& stream_type : stream_types_) { - input_groups += "[STREAM]" + stream_type + ", "; - } - - // Trim trailing comma. - if (!filter_groups.empty()) { - filter_groups.resize(filter_groups.size() - 2); - } - if (!input_groups.empty()) { - input_groups.resize(input_groups.size() - 2); - } - - std::string all_inputs; - if (filter_groups.empty()) { - all_inputs = input_groups; - } else if (input_groups.empty()) { - all_inputs = filter_groups; - } else { - all_inputs = input_groups + " + " + filter_groups; - } - LOG(INFO) << all_inputs << ": " << num_channels_ << "ch@" - << input_samples_per_second_ << "hz -> [GROUP]" << name_ << " -> " - << GetOutputChannelCount() << "ch@" - << output_config_.output_sample_rate << "hz"; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/filter_group.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/filter_group.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,186 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_FILTER_GROUP_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_FILTER_GROUP_H_ - -#include - -#include -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/containers/flat_set.h" -#include "base/memory/ref_counted.h" -#include "base/values.h" -#include "chromecast/media/base/aligned_buffer.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { -class InterleavedChannelMixer; -class MixerInput; -class PostProcessingPipeline; -class PostProcessingPipelineFactory; - -// FilterGroup mixes MixerInputs and/or FilterGroups, mixes their outputs, and -// applies DSP to them. - -// Tag to avoid ABA problem. -class FilterGroupTag : public base::RefCountedThreadSafe { - private: - friend class base::RefCountedThreadSafe; - ~FilterGroupTag() = default; -}; - -// FilterGroups are added at construction. These cannot be removed. -class FilterGroup { - public: - // |num_channels| indicates number of input audio channels. - // |name| is used for debug printing - FilterGroup(int num_channels, - std::string name, - base::Value prerender_filter_list, - const base::Value* filter_list, - PostProcessingPipelineFactory* ppp_factory, - const base::Value* volume_limits); - - FilterGroup(const FilterGroup&) = delete; - FilterGroup& operator=(const FilterGroup&) = delete; - - ~FilterGroup(); - - int num_channels() const { return num_channels_; } - float last_volume() const { return last_volume_; } - float target_volume() const { return target_volume_; } - std::string name() const { return name_; } - AudioContentType content_type() const { return content_type_; } - int input_frames_per_write() const { return input_frames_per_write_; } - int input_samples_per_second() const { return input_samples_per_second_; } - int system_output_sample_rate() const { - return output_config_.system_output_sample_rate; - } - scoped_refptr tag() const { return tag_; } - - // |input| will be recursively mixed into this FilterGroup's input buffer when - // MixAndFilter() is called. Registering a FilterGroup as an input to more - // than one FilterGroup will result in incorrect behavior. - void AddMixedInput(FilterGroup* input); - - // Recursively sets the sample rate of the post-processors and FilterGroups. - // This should only be called externally on the output node of the FilterGroup - // tree. - // Groups that feed this group may receive different values due to resampling. - // After calling Initialize(), input_samples_per_second() and - // input_frames_per_write() may be called to determine the input rate/size. - void Initialize(const AudioPostProcessor2::Config& output_config); - - // Adds/removes |input| from |active_inputs_|. - void AddInput(MixerInput* input); - void RemoveInput(MixerInput* input); - - // Mixes all active inputs and passes them through the audio filter. - // Returns the largest volume of all streams with data. - // return value will be zero IFF there is no data and - // the PostProcessingPipeline is not ringing. - float MixAndFilter( - int num_frames, - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay); - - // Gets the current delay of this filter group's AudioPostProcessors. - // (Not recursive). - int64_t GetRenderingDelayMicroseconds(); - - // Gets the delay of this FilterGroup and all downstream FilterGroups. - // Computed recursively when MixAndFilter() is called. - MediaPipelineBackend::AudioDecoder::RenderingDelay - GetRenderingDelayToOutput(); - - std::unique_ptr CreatePrerenderPipeline( - int num_channels); - - // Retrieves a pointer to the output buffer. This will crash if called before - // MixAndFilter(), and the data & memory location may change each time - // MixAndFilter() is called. - float* GetOutputBuffer(); - - // Returns number of audio output channels from the filter group. - int GetOutputChannelCount() const; - - // Returns the expected sample rate for inputs to this group. - int GetInputSampleRate() const { return input_samples_per_second_; } - - // Sends configuration string |config| to all post processors with the given - // |name|. - void SetPostProcessorConfig(const std::string& name, - const std::string& config); - - // Determines whether this group is still ringing out after all input streams - // have stopped playing. - bool IsRinging() const; - - // Recursively print the layout of the pipeline. - void PrintTopology() const; - - // Add |stream_type| to the list of streams this processor handles. - void AddStreamType(const std::string& stream_type); - - private: - using VolumeLimitsMap = base::flat_map>; - - struct GroupInput { - GroupInput(FilterGroup* group, - std::unique_ptr channel_mixer); - GroupInput(GroupInput&& other); - ~GroupInput(); - - FilterGroup* group; - std::unique_ptr channel_mixer; - }; - - void ParseVolumeLimits(const base::Value* volume_limits); - void ZeroOutputBufferIfNeeded(); - void ResizeBuffers(); - - const int num_channels_; - const std::string name_; - base::Value prerender_filter_list_; - base::flat_map post_processing_configs_; - PostProcessingPipelineFactory* const ppp_factory_; - int prerender_creation_count_ = 0; - const scoped_refptr tag_; - - VolumeLimitsMap volume_limits_; - float default_volume_min_ = 0.0f; - float default_volume_max_ = 1.0f; - - std::vector mixed_inputs_; - std::vector stream_types_; - base::flat_set active_inputs_; - - AudioPostProcessor2::Config output_config_; - int input_samples_per_second_ = 0; - int input_frames_per_write_ = 0; - int output_frames_zeroed_ = 0; - float last_volume_ = 0.0f; - float target_volume_ = 0.0f; - double delay_seconds_ = 0; - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay_to_output_; - AudioContentType content_type_ = AudioContentType::kMedia; - - // Interleaved data must be aligned to 16 bytes. - AlignedBuffer interleaved_; - - std::unique_ptr post_processing_pipeline_; - float* output_buffer_ = nullptr; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_FILTER_GROUP_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/filter_group_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/filter_group_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/filter_group_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,248 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/filter_group.h" - -#include "base/containers/flat_set.h" -#include "base/memory/ptr_util.h" -#include "chromecast/media/cma/backend/mixer/mixer_input.h" -#include "chromecast/media/cma/backend/mixer/mock_mixer_source.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline.h" -#include "chromecast/media/cma/backend/mixer/stream_mixer.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" -#include "chromecast/public/volume_control.h" -#include "media/base/audio_bus.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -using ::testing::_; -using ::testing::NiceMock; - -namespace { - -// Total of Test samples including left and right channels. -#define NUM_SAMPLES 64 - -constexpr int kNumInputChannels = 2; -constexpr int kInputSampleRate = 48000; -constexpr int kInputFrames = NUM_SAMPLES / 2; - -constexpr AudioContentType kDefaultContentType = AudioContentType::kMedia; - -class MockPostProcessingPipeline : public PostProcessingPipeline { - public: - MockPostProcessingPipeline() - : MockPostProcessingPipeline(kNumInputChannels) {} - - explicit MockPostProcessingPipeline(int num_output_channels) - : num_output_channels_(num_output_channels) { - ON_CALL(*this, ProcessFrames(_, _, _, _, _)) - .WillByDefault( - testing::Invoke(this, &MockPostProcessingPipeline::StorePtr)); - } - - MockPostProcessingPipeline(const MockPostProcessingPipeline&) = delete; - MockPostProcessingPipeline& operator=(const MockPostProcessingPipeline&) = - delete; - - ~MockPostProcessingPipeline() override {} - MOCK_METHOD5(ProcessFrames, - void(float* data, - int num_frames, - float current_volume, - float target_volume, - bool is_silence)); - MOCK_METHOD2(SetPostProcessorConfig, - void(const std::string& name, const std::string& config)); - MOCK_METHOD1(SetContentType, void(AudioContentType)); - MOCK_METHOD1(UpdatePlayoutChannel, void(int)); - MOCK_METHOD0(GetDelaySeconds, double()); - - protected: - bool SetOutputConfig(const AudioPostProcessor2::Config& config) override { - sample_rate_ = config.output_sample_rate; - return true; - } - int GetInputSampleRate() const override { return sample_rate_; } - bool IsRinging() override { return false; } - float* GetOutputBuffer() override { return output_buffer_; } - int NumOutputChannels() const override { return num_output_channels_; } - int delay() { return 0; } - std::string name() const { return "mock"; } - void StorePtr(float* data, - int num_frames, - float current_volume, - float target_volume, - bool is_silence) { - output_buffer_ = data; - } - - float* output_buffer_; - const int num_output_channels_; - int sample_rate_; -}; - -} // namespace - -// Note: Test data should be represented as 32-bit integers and copied into -// ::media::AudioBus instances, rather than wrapping statically declared float -// arrays. -constexpr int32_t kTestData[NUM_SAMPLES] = { - 74343736, -1333200799, -1360871126, 1138806283, 1931811865, - 1856308487, 649203634, 564640023, 1676630678, 23416591, - -1293255456, 547928305, -976258952, 1840550252, 1714525174, - 358704931, 983646295, 1264863573, 442473973, 1222979052, - 317404525, 366912613, 1393280948, -1022004648, -2054669405, - -159762261, 1127018745, -1984491787, 1406988336, -693327981, - -1549544744, 1232236854, 970338338, -1750160519, -783213057, - 1231504562, 1155296810, -820018779, 1155689800, -1108462340, - -150535168, 1033717023, 2121241397, 1829995370, -1893006836, - -819097508, -495186107, 1001768909, -1441111852, 692174781, - 1916569026, -687787473, -910565280, 1695751872, 994166817, - 1775451433, 909418522, 492671403, -761744663, -2064315902, - 1357716471, -1580019684, 1872702377, -1524457840, -}; - -// Return a scoped pointer filled with the data above. -std::unique_ptr<::media::AudioBus> GetTestData() { - int samples = NUM_SAMPLES / kNumInputChannels; - auto data = ::media::AudioBus::Create(kNumInputChannels, samples); - data->FromInterleaved<::media::SignedInt32SampleTypeTraits>(kTestData, - samples); - return data; -} - -class FilterGroupTest : public testing::Test, - public PostProcessingPipelineFactory { - public: - FilterGroupTest(const FilterGroupTest&) = delete; - FilterGroupTest& operator=(const FilterGroupTest&) = delete; - - protected: - using RenderingDelay = MixerInput::RenderingDelay; - FilterGroupTest() : source_(kInputSampleRate) { - source_.SetData(GetTestData()); - } - - ~FilterGroupTest() override {} - - void MakeFilterGroup(int num_channels = kNumInputChannels) { - filter_group_ = std::make_unique( - kNumInputChannels, "test_filter", base::Value(base::Value::Type::LIST), - nullptr, this, nullptr); - AudioPostProcessor2::Config config; - config.output_sample_rate = kInputSampleRate; - config.system_output_sample_rate = kInputSampleRate; - config.output_frames_per_write = kInputFrames; - filter_group_->Initialize(config); - input_ = std::make_unique(&source_, filter_group_.get()); - input_->Initialize(); - } - - // PostProcessingPipelineFactory implementation: - std::unique_ptr CreatePipeline( - const std::string& name, - const base::Value* filter_description_list, - int num_channels) override { - if (name.compare(0, 10, "prerender_") != 0) { - num_channels = post_processor_channels_; - } - auto pipeline = - std::make_unique>(num_channels); - if (!post_processor_) { - post_processor_ = pipeline.get(); - EXPECT_CALL(*post_processor_, SetContentType(kDefaultContentType)); - } - return pipeline; - } - - float Input(int channel, int frame) { - DCHECK_LE(channel, source_.data().channels()); - DCHECK_LE(frame, source_.data().frames()); - return source_.data().channel(channel)[frame]; - } - - void AssertPassthrough() { - // Verify if the fiter group output matches the source. - float* interleaved_data = filter_group_->GetOutputBuffer(); - for (int f = 0; f < kInputFrames; ++f) { - for (int ch = 0; ch < kNumInputChannels; ++ch) { - ASSERT_EQ(Input(ch, f), interleaved_data[f * kNumInputChannels + ch]) - << f; - } - } - } - - float LeftInput(int frame) { return Input(0, frame); } - float RightInput(int frame) { return Input(1, frame); } - - NiceMock source_; - std::unique_ptr filter_group_; - std::unique_ptr input_; - MockPostProcessingPipeline* post_processor_ = nullptr; - int post_processor_channels_ = kNumInputChannels; -}; - -TEST_F(FilterGroupTest, Passthrough) { - MakeFilterGroup(); - EXPECT_CALL(*post_processor_, ProcessFrames(_, kInputFrames, _, _, false)); - - filter_group_->MixAndFilter(kInputFrames, RenderingDelay()); - AssertPassthrough(); -} - -TEST_F(FilterGroupTest, ChecksContentType) { - MakeFilterGroup(); - - NiceMock tts_source(kInputSampleRate); - tts_source.set_content_type(AudioContentType::kCommunication); - MixerInput tts_input(&tts_source, filter_group_.get()); - - NiceMock alarm_source(kInputSampleRate); - alarm_source.set_content_type(AudioContentType::kAlarm); - MixerInput alarm_input(&alarm_source, filter_group_.get()); - - // Media input stream + tts input stream -> tts content type. - tts_input.Initialize(); - EXPECT_CALL(*post_processor_, - SetContentType(AudioContentType::kCommunication)); - tts_source.SetData(GetTestData()); - filter_group_->MixAndFilter(kInputFrames, RenderingDelay()); - - // Media input + tts input + alarm input -> tts content type (no update). - alarm_input.Initialize(); - EXPECT_CALL(*post_processor_, - SetContentType(AudioContentType::kCommunication)) - .Times(0); - source_.SetData(GetTestData()); - tts_source.SetData(GetTestData()); - alarm_source.SetData(GetTestData()); - filter_group_->MixAndFilter(kInputFrames, RenderingDelay()); - - // Media input + alarm input -> alarm content type. - filter_group_->RemoveInput(&tts_input); - EXPECT_CALL(*post_processor_, SetContentType(AudioContentType::kAlarm)); - source_.SetData(GetTestData()); - alarm_source.SetData(GetTestData()); - filter_group_->MixAndFilter(kInputFrames, RenderingDelay()); - - // Media input stream -> media input - EXPECT_CALL(*post_processor_, SetContentType(AudioContentType::kMedia)); - filter_group_->RemoveInput(&alarm_input); - source_.SetData(GetTestData()); - filter_group_->MixAndFilter(kInputFrames, RenderingDelay()); -} - -TEST_F(FilterGroupTest, ReportsOutputChannels) { - post_processor_channels_ = 4; - MakeFilterGroup(); - - EXPECT_EQ(4, filter_group_->GetOutputChannelCount()); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/loopback_handler.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_handler.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/loopback_handler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_handler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,248 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/loopback_handler.h" - -#include -#include - -#include "base/check_op.h" -#include "base/containers/flat_map.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/synchronization/lock.h" -#include "base/task/sequenced_task_runner.h" -#include "base/thread_annotations.h" -#include "chromecast/media/audio/mixer_service/loopback_interrupt_reason.h" -#include "chromecast/media/cma/backend/mixer/mixer_loopback_connection.h" -#include "chromecast/net/io_buffer_pool.h" -#include "chromecast/public/media/external_audio_pipeline_shlib.h" - -namespace chromecast { -namespace media { - -class LoopbackHandler::LoopbackIO { - public: - LoopbackIO() = default; - - LoopbackIO(const LoopbackIO&) = delete; - LoopbackIO& operator=(const LoopbackIO&) = delete; - - ~LoopbackIO() = default; - - void AddConnection(std::unique_ptr connection) { - MixerLoopbackConnection* ptr = connection.get(); - connections_[ptr] = std::move(connection); - ptr->SetErrorCallback(base::BindOnce(&LoopbackIO::RemoveConnection, - base::Unretained(this), ptr)); - if (sample_format_ != kUnknownSampleFormat) { - ptr->SetStreamConfig(sample_format_, sample_rate_, num_channels_, - data_size_); - } - } - - void SetStreamConfig(SampleFormat sample_format, - int sample_rate, - int num_channels, - int data_size) { - sample_format_ = sample_format; - sample_rate_ = sample_rate; - num_channels_ = num_channels; - data_size_ = data_size; - - for (const auto& c : connections_) { - c.second->SetStreamConfig(sample_format_, sample_rate_, num_channels_, - data_size_); - } - } - - void SendData(scoped_refptr audio_buffer, - int data_size_bytes, - int64_t timestamp) { - for (const auto& c : connections_) { - c.second->SendAudio(audio_buffer, data_size_bytes, timestamp); - } - } - - void SendInterrupt(LoopbackInterruptReason reason) { - for (const auto& c : connections_) { - c.second->SendInterrupt(reason); - } - } - - private: - void RemoveConnection(MixerLoopbackConnection* connection) { - connections_.erase(connection); - } - - base::flat_map> - connections_; - - SampleFormat sample_format_ = kUnknownSampleFormat; - int sample_rate_ = 0; - int num_channels_ = 0; - int data_size_ = 0; -}; - -class LoopbackHandler::ExternalLoopbackHandler - : public ExternalAudioPipelineShlib::LoopbackAudioObserver { - public: - explicit ExternalLoopbackHandler(LoopbackHandler* owner) : owner_(owner) { - DCHECK(owner_); - ExternalAudioPipelineShlib::AddExternalLoopbackAudioObserver(this); - } - - ExternalLoopbackHandler(const ExternalLoopbackHandler&) = delete; - ExternalLoopbackHandler& operator=(const ExternalLoopbackHandler&) = delete; - - void Destroy() { - { - base::AutoLock lock(lock_); - destroyed_ = true; - } - - ExternalAudioPipelineShlib::RemoveExternalLoopbackAudioObserver(this); - } - - private: - ~ExternalLoopbackHandler() override = default; - - // ExternalAudioPipelineShlib::LoopbackAudioObserver implementation: - void OnLoopbackAudio(int64_t timestamp, - SampleFormat format, - int sample_rate, - int num_channels, - uint8_t* data, - int length) override { - base::AutoLock lock(lock_); - if (!destroyed_) { - owner_->SendDataInternal(timestamp, format, sample_rate, num_channels, - data, length); - } - } - - void OnLoopbackInterrupted() override { - base::AutoLock lock(lock_); - if (!destroyed_) { - owner_->SendInterruptInternal(LoopbackInterruptReason::kUnderrun); - } - } - - void OnRemoved() override { - delete this; - } - - LoopbackHandler* const owner_; - - base::Lock lock_; - bool destroyed_ GUARDED_BY(lock_) = false; -}; - -void LoopbackHandler::ExternalDeleter::operator()( - ExternalLoopbackHandler* obj) { - obj->Destroy(); -} - -LoopbackHandler::LoopbackHandler( - scoped_refptr io_task_runner) - : LoopbackHandler(std::move(io_task_runner), - ExternalAudioPipelineShlib::IsSupported()) {} - -LoopbackHandler::LoopbackHandler( - scoped_refptr io_task_runner, - bool use_external_audio_pipeline) - : io_(std::move(io_task_runner)) { - if (use_external_audio_pipeline) { - external_handler_.reset(new ExternalLoopbackHandler(this)); - } -} - -LoopbackHandler::~LoopbackHandler() = default; - -void LoopbackHandler::AddConnection( - std::unique_ptr connection) { - io_.AsyncCall(&LoopbackIO::AddConnection).WithArgs(std::move(connection)); -} - -void LoopbackHandler::SetDataSize(int data_size_bytes) { - if (external_handler_) { - return; - } - - if (SetDataSizeInternal(data_size_bytes) && sample_rate_ != 0) { - io_.AsyncCall(&LoopbackIO::SetStreamConfig) - .WithArgs(format_, sample_rate_, num_channels_, data_size_); - } -} - -void LoopbackHandler::SendData(int64_t timestamp, - int sample_rate, - int num_channels, - float* data, - int frames) { - if (external_handler_) { - return; - } - - int data_size_bytes = frames * num_channels * sizeof(float); - SendDataInternal(timestamp, kSampleFormatF32, sample_rate, num_channels, data, - data_size_bytes); -} - -void LoopbackHandler::SendInterrupt(LoopbackInterruptReason reason) { - if (external_handler_) { - return; - } - SendInterruptInternal(reason); -} - -bool LoopbackHandler::SetDataSizeInternal(int data_size_bytes) { - if (buffer_pool_ && data_size_ >= data_size_bytes) { - return false; - } - - data_size_ = data_size_bytes; - buffer_pool_ = base::MakeRefCounted( - data_size_ + mixer_service::MixerSocket::kAudioMessageHeaderSize, - std::numeric_limits::max(), true /* threadsafe */); - buffer_pool_->Preallocate(4); - return true; -} - -void LoopbackHandler::SendDataInternal(int64_t timestamp, - SampleFormat format, - int sample_rate, - int num_channels, - void* data, - int data_size_bytes) { - bool data_size_changed = SetDataSizeInternal(data_size_bytes); - if (format != format_ || sample_rate != sample_rate_ || - num_channels != num_channels_ || data_size_changed) { - format_ = format; - sample_rate_ = sample_rate; - num_channels_ = num_channels; - io_.AsyncCall(&LoopbackIO::SetStreamConfig) - .WithArgs(format_, sample_rate_, num_channels_, data_size_); - } - - DCHECK_LE(data_size_bytes, data_size_); - DCHECK(buffer_pool_); - auto buffer = buffer_pool_->GetBuffer(); - memcpy(buffer->data() + mixer_service::MixerSocket::kAudioMessageHeaderSize, - data, data_size_bytes); - io_.AsyncCall(&LoopbackIO::SendData) - .WithArgs(std::move(buffer), data_size_bytes, timestamp); -} - -void LoopbackHandler::SendInterruptInternal(LoopbackInterruptReason reason) { - if (!buffer_pool_) { - return; - } - - io_.AsyncCall(&LoopbackIO::SendInterrupt).WithArgs(reason); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/loopback_handler.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_handler.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/loopback_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_LOOPBACK_HANDLER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_LOOPBACK_HANDLER_H_ - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "base/threading/sequence_bound.h" -#include "chromecast/public/media/decoder_config.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace chromecast { -class IOBufferPool; - -namespace media { -enum class LoopbackInterruptReason; -class MixerLoopbackConnection; - -// Handles loopback audio from the mixer or external audio pipeline. -class LoopbackHandler { - public: - explicit LoopbackHandler( - scoped_refptr io_task_runner); - LoopbackHandler(scoped_refptr io_task_runner, - bool use_external_audio_pipeline); - - LoopbackHandler(const LoopbackHandler&) = delete; - LoopbackHandler& operator=(const LoopbackHandler&) = delete; - - ~LoopbackHandler(); - - // Adds a new loopback connection. - void AddConnection(std::unique_ptr connection); - - // Sets the expected size of audio data (in bytes) of audio data from the - // mixer. - void SetDataSize(int data_size_bytes); - - // Passes loopback data from the mixer to any connected observers. - void SendData(int64_t timestamp, - int sample_rate, - int num_channels, - float* data, - int frames); - - // Sends a 'loopback interrupted' signal to any connected observers. - void SendInterrupt(LoopbackInterruptReason reason); - - private: - class ExternalLoopbackHandler; - struct ExternalDeleter { - void operator()(ExternalLoopbackHandler* obj); - }; - class LoopbackIO; - - bool SetDataSizeInternal(int data_size_bytes); - void SendDataInternal(int64_t timestamp, - SampleFormat format, - int sample_rate, - int num_channels, - void* data, - int data_size_bytes); - void SendInterruptInternal(LoopbackInterruptReason reason); - - scoped_refptr buffer_pool_; - - int data_size_ = 0; - SampleFormat format_ = kUnknownSampleFormat; - int sample_rate_ = 0; - int num_channels_ = 0; - - base::SequenceBound io_; - std::unique_ptr external_handler_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_LOOPBACK_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/loopback_test_support.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_test_support.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/loopback_test_support.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_test_support.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/loopback_test_support.h" - -#include - -#include "base/task/sequenced_task_runner.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/cma/backend/mixer/loopback_handler.h" -#include "chromecast/media/cma/backend/mixer/mixer_loopback_connection.h" - -namespace chromecast { -namespace media { - -namespace { - -class FakeMixerDelegate : public mixer_service::MixerSocket::Delegate { - public: - ~FakeMixerDelegate() override = default; -}; - -} // namespace - -std::unique_ptr CreateLoopbackConnectionForTest( - LoopbackHandler* loopback_handler) { - auto receiver_socket = std::make_unique(); - auto caller_socket = std::make_unique(); - - receiver_socket->SetLocalCounterpart( - caller_socket->GetAudioSocketWeakPtr(), - base::SequencedTaskRunner::GetCurrentDefault()); - caller_socket->SetLocalCounterpart( - receiver_socket->GetAudioSocketWeakPtr(), - base::SequencedTaskRunner::GetCurrentDefault()); - - auto mixer_side = - std::make_unique(std::move(receiver_socket)); - loopback_handler->AddConnection(std::move(mixer_side)); - - return caller_socket; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/loopback_test_support.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_test_support.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/loopback_test_support.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/loopback_test_support.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_LOOPBACK_TEST_SUPPORT_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_LOOPBACK_TEST_SUPPORT_H_ - -#include - -namespace chromecast { -namespace media { -class LoopbackHandler; - -namespace mixer_service { -class MixerSocket; -} // namespace mixer_service - -std::unique_ptr CreateLoopbackConnectionForTest( - LoopbackHandler* loopback_handler); -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_LOOPBACK_TEST_SUPPORT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_input.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_input.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,527 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mixer_input.h" - -#include - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "chromecast/media/audio/audio_fader.h" -#include "chromecast/media/audio/audio_log.h" -#include "chromecast/media/audio/interleaved_channel_mixer.h" -#include "chromecast/media/cma/backend/mixer/audio_output_redirector_input.h" -#include "chromecast/media/cma/backend/mixer/channel_layout.h" -#include "chromecast/media/cma/backend/mixer/filter_group.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_timestamp_helper.h" -#include "media/base/multi_channel_resampler.h" - -namespace chromecast { -namespace media { - -namespace { - -const int64_t kMicrosecondsPerSecond = 1000 * 1000; -const int kDefaultSlewTimeMs = 50; -const int kDefaultFillBufferFrames = 2048; -constexpr int kMaxChannels = 32; - -int RoundUpMultiple(int value, int multiple) { - return multiple * ((value + (multiple - 1)) / multiple); -} - -} // namespace - -MixerInput::MixerInput(Source* source, FilterGroup* filter_group) - : source_(source), - num_channels_(source->num_channels()), - channel_layout_(source->channel_layout()), - input_samples_per_second_(source->sample_rate()), - output_samples_per_second_(filter_group->input_samples_per_second()), - primary_(source->primary()), - device_id_(source->device_id()), - content_type_(source->content_type()), - slew_volume_(kDefaultSlewTimeMs, true) { - DCHECK(source_); - DCHECK(filter_group); - DCHECK_GT(num_channels_, 0); - DCHECK_GT(input_samples_per_second_, 0); - DETACH_FROM_SEQUENCE(sequence_checker_); - - fill_buffer_ = - ::media::AudioBus::Create(num_channels_, kDefaultFillBufferFrames); - fill_buffer_->Zero(); - interleaved_.assign(kDefaultFillBufferFrames * num_channels_, 0.0f); - - source_read_size_ = filter_group->input_frames_per_write(); - if (output_samples_per_second_ == 0) { - // Mixer is not running. OnError() will be called shortly. - return; - } - if (source_->require_clock_rate_simulation() || - output_samples_per_second_ != input_samples_per_second_) { - if (source_->require_clock_rate_simulation()) { - // Minimize latency. - source_read_size_ = ::media::SincResampler::kSmallRequestSize; - } else { - // Round up to nearest multiple of SincResampler::kMaxKernelSize. The read - // size must be > kMaxKernelSize, so we round up to at least 2 * - // kMaxKernelSize. - source_read_size_ = - RoundUpMultiple(std::max(source_->desired_read_size(), - ::media::SincResampler::kMaxKernelSize + 1), - ::media::SincResampler::kMaxKernelSize); - } - resample_ratio_ = static_cast(input_samples_per_second_) / - output_samples_per_second_; - resampler_ = std::make_unique<::media::MultiChannelResampler>( - num_channels_, resample_ratio_, source_read_size_, - base::BindRepeating(&MixerInput::ResamplerReadCallback, - base::Unretained(this))); - resampler_->PrimeWithSilence(); - } - - slew_volume_.SetSampleRate(output_samples_per_second_); - - SetFilterGroupInternal(filter_group); - // Don't add to the filter group yet, since this may not be the correct - // sequence. It will be added in Initialize(). -} - -MixerInput::~MixerInput() { - source_->FinalizeAudioPlayback(); -} - -void MixerInput::Initialize() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(filter_group_); - MediaPipelineBackend::AudioDecoder::RenderingDelay initial_rendering_delay = - filter_group_->GetRenderingDelayToOutput(); - initial_rendering_delay.delay_microseconds += - prerender_delay_seconds_ * base::Time::kMicrosecondsPerSecond; - - if (resampler_) { - double resampler_queued_frames = resampler_->BufferedFrames(); - initial_rendering_delay.delay_microseconds += - static_cast(resampler_queued_frames * kMicrosecondsPerSecond / - input_samples_per_second_); - } - - source_->InitializeAudioPlayback(source_read_size_, initial_rendering_delay); - filter_group_->AddInput(this); -} - -void MixerInput::Destroy() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - SetFilterGroup(nullptr); -} - -void MixerInput::SetFilterGroup(FilterGroup* filter_group) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (SetFilterGroupInternal(filter_group)) { - filter_group->AddInput(this); - } -} - -bool MixerInput::SetFilterGroupInternal(FilterGroup* filter_group) { - if (output_samples_per_second_ == 0) { - LOG(ERROR) << "Attempt to set filter group when output sample rate is 0"; - return false; - } - if (filter_group == filter_group_ && - (!filter_group || filter_group_tag_ == filter_group->tag())) { - return false; - } - if (filter_group_) { - filter_group_->RemoveInput(this); - } - if (filter_group) { - filter_group_tag_ = filter_group->tag(); - - prerender_pipeline_ = filter_group->CreatePrerenderPipeline(num_channels_); - playout_channel_ = source_->playout_channel(); - - AudioPostProcessor2::Config config; - config.output_sample_rate = output_samples_per_second_; - config.system_output_sample_rate = - filter_group->system_output_sample_rate(); - config.output_frames_per_write = filter_group->input_frames_per_write(); - CHECK(prerender_pipeline_->SetOutputConfig(config)); - prerender_pipeline_->SetContentType(content_type_); - prerender_pipeline_->UpdatePlayoutChannel(playout_channel_); - DCHECK_EQ(prerender_pipeline_->GetInputSampleRate(), - output_samples_per_second_); - DCHECK_EQ(prerender_pipeline_->NumOutputChannels(), num_channels_); - prerender_delay_seconds_ = prerender_pipeline_->GetDelaySeconds(); - - CreateChannelMixer(playout_channel_, filter_group); - } - filter_group_ = filter_group; - return (filter_group != nullptr); -} - -void MixerInput::SetPostProcessorConfig(const std::string& name, - const std::string& config) { - prerender_pipeline_->SetPostProcessorConfig(name, config); -} - -void MixerInput::CreateChannelMixer(int playout_channel, - FilterGroup* filter_group) { - int effective_channels = num_channels_; - ::media::ChannelLayout channel_layout = channel_layout_; - if (playout_channel != kChannelAll && playout_channel < num_channels_) { - effective_channels = 1; - channel_layout = ::media::CHANNEL_LAYOUT_MONO; - } - channel_mixer_ = std::make_unique( - channel_layout, effective_channels, - mixer::GuessChannelLayout(filter_group->num_channels()), - filter_group->num_channels(), filter_group->input_frames_per_write()); -} - -void MixerInput::AddAudioOutputRedirector( - AudioOutputRedirectorInput* redirector) { - AUDIO_LOG(INFO) << "Add redirector to " << device_id_ << "(" << source_ - << ")"; - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(redirector); - audio_output_redirectors_.insert( - std::upper_bound( - audio_output_redirectors_.begin(), audio_output_redirectors_.end(), - redirector, - [](AudioOutputRedirectorInput* a, AudioOutputRedirectorInput* b) { - return (a->Order() < b->Order()); - }), - redirector); -} - -void MixerInput::RemoveAudioOutputRedirector( - AudioOutputRedirectorInput* redirector) { - AUDIO_LOG(INFO) << "Remove redirector from " << device_id_ << "(" << source_ - << ")"; - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(redirector); - audio_output_redirectors_.erase( - std::remove(audio_output_redirectors_.begin(), - audio_output_redirectors_.end(), redirector), - audio_output_redirectors_.end()); -} - -bool MixerInput::Render( - int num_output_frames, - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay) { - if (num_output_frames > fill_buffer_->frames()) { - fill_buffer_ = ::media::AudioBus::Create(num_channels_, num_output_frames); - interleaved_.assign(num_output_frames * num_channels_, 0.0f); - } - - if (incomplete_previous_fill_) { - slew_volume_.Interrupted(); - } - - rendering_delay.delay_microseconds += - prerender_delay_seconds_ * base::Time::kMicrosecondsPerSecond; - int filled = - FillAudioData(num_output_frames, rendering_delay, fill_buffer_.get()); - if (filled == 0) { - if (!prerender_pipeline_->IsRinging()) { - render_output_ = nullptr; - return false; - } - } - - fill_buffer_->ZeroFramesPartial(filled, num_output_frames - filled); - - fill_buffer_->ToInterleaved<::media::FloatSampleTypeTraitsNoClip>( - num_output_frames, interleaved_.data()); - slew_volume_.ProcessFMUL(false /* repeat_transition */, interleaved_.data(), - num_output_frames, num_channels_, - interleaved_.data()); - - const int playout_channel = source_->playout_channel(); - if (playout_channel != playout_channel_) { - prerender_pipeline_->UpdatePlayoutChannel(playout_channel); - CreateChannelMixer(playout_channel, filter_group_); - playout_channel_ = playout_channel; - } - - const bool is_silence = (filled == 0); - prerender_pipeline_->ProcessFrames(interleaved_.data(), num_output_frames, - InstantaneousVolume(), TargetVolume(), - is_silence); - prerender_delay_seconds_ = prerender_pipeline_->GetDelaySeconds(); - - RenderInterleaved(num_output_frames); - return true; -} - -void MixerInput::RenderInterleaved(int num_output_frames) { - // TODO(kmackay): If we ever support channel selections other than L and R, - // we should remix channels to a format that includes the selected channel - // and then do channel selection. Currently if the input is mono we don't - // bother doing channel selection since the result would be the same as - // doing nothing anyway. - float* data = prerender_pipeline_->GetOutputBuffer(); - - if (playout_channel_ != kChannelAll && playout_channel_ < num_channels_) { - // Keep only the samples from the selected channel. - float* dest = interleaved_.data(); - for (int f = 0; f < num_output_frames; ++f) { - dest[f] = data[f * num_channels_ + playout_channel_]; - } - data = dest; - } - - render_output_ = channel_mixer_->Transform(data, num_output_frames); -} - -float* MixerInput::RenderedAudioBuffer() { - DCHECK(render_output_); - return render_output_; -} - -int MixerInput::FillAudioData(int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* dest) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(dest); - DCHECK_GE(dest->frames(), num_frames); - - RenderingDelay redirected_delay = rendering_delay; - if (!audio_output_redirectors_.empty()) { - redirected_delay.delay_microseconds += - audio_output_redirectors_[0]->GetDelayMicroseconds(); - } - int filled = FillBuffer(num_frames, redirected_delay, dest); - incomplete_previous_fill_ = (filled != num_frames); - - bool redirected = false; - for (auto* redirector : audio_output_redirectors_) { - redirector->Redirect(dest, filled, rendering_delay, redirected); - redirected = true; - } - - CHECK_LE(num_channels_, kMaxChannels); - float* channels[kMaxChannels]; - for (int c = 0; c < num_channels_; ++c) { - channels[c] = dest->channel(c); - } - if (first_buffer_ && redirected) { - // If the first buffer is redirected, don't provide any data to the mixer - // (we want to avoid a 'blip' of sound from the first buffer if it is being - // redirected). - filled = 0; - } else if (previous_ended_in_silence_) { - if (redirected) { - // Previous buffer ended in silence, and the current buffer was redirected - // by the output chain, so maintain silence. - filled = 0; - } else { - // Smoothly fade in from previous silence. - AudioFader::FadeInHelper(channels, num_channels_, filled, filled, filled); - } - } else if (redirected) { - // Smoothly fade out to silence, since output is now being redirected. - AudioFader::FadeOutHelper(channels, num_channels_, filled, filled, filled); - } - previous_ended_in_silence_ = redirected; - first_buffer_ = false; - - return filled; -} - -int MixerInput::FillBuffer(int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* dest) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(dest); - DCHECK_EQ(num_channels_, dest->channels()); - DCHECK_GE(dest->frames(), num_frames); - - if (resampler_) { - mixer_rendering_delay_ = rendering_delay; - // resampler_->BufferedFrames() gives incorrect values in the read callback, - // so track the number of buffered frames ourselves. - // Based on testing, the buffered frames reported by SincResampler does not - // include the delay incurred by the filter kernel, so add it explicitly. - resampler_buffered_frames_ = - resampler_->BufferedFrames() + resampler_->KernelSize() / 2; - filled_for_resampler_ = 0; - tried_to_fill_resampler_ = false; - resampler_->Resample(num_frames, dest); - // If the source is not providing any audio anymore, we want to stop filling - // frames so we can reduce processing overhead. However, since the resampler - // fill size doesn't necessarily match the mixer's request size at all, we - // need to be careful. The resampler could have a lot of data buffered - // internally, so we only count cases where the resampler needed more data - // from the source but none was available. Then, to make sure all data is - // flushed out of the resampler, we require that to happen twice before we - // stop filling audio. - if (tried_to_fill_resampler_) { - if (filled_for_resampler_ == 0) { - resampled_silence_count_ = std::min(resampled_silence_count_ + 1, 2); - } else { - resampled_silence_count_ = 0; - } - } - if (resampled_silence_count_ > 1) { - return 0; - } - return num_frames; - } else { - return source_->FillAudioPlaybackFrames(num_frames, rendering_delay, dest); - } -} - -void MixerInput::ResamplerReadCallback(int frame_delay, - ::media::AudioBus* output) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - RenderingDelay delay = mixer_rendering_delay_; - int64_t resampler_delay = - std::round(resampler_buffered_frames_ * kMicrosecondsPerSecond / - input_samples_per_second_); - delay.delay_microseconds += resampler_delay; - - const int needed_frames = output->frames(); - tried_to_fill_resampler_ = true; - int filled = source_->FillAudioPlaybackFrames(needed_frames, delay, output); - filled_for_resampler_ += filled; - if (filled < needed_frames) { - output->ZeroFramesPartial(filled, needed_frames - filled); - } - resampler_buffered_frames_ += output->frames(); -} - -void MixerInput::SignalError(Source::MixerError error) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (filter_group_) { - filter_group_->RemoveInput(this); - filter_group_ = nullptr; - } - source_->OnAudioPlaybackError(error); -} - -void MixerInput::VolumeScaleAccumulate(const float* src, - int frames, - float* dest, - int channel_index) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - const bool same_volume_transition = (channel_index != 0); - slew_volume_.ProcessFMAC(same_volume_transition, src, frames, 1, dest); -} - -void MixerInput::SetVolumeMultiplier(float multiplier) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - float old_target_volume = TargetVolume(); - stream_volume_multiplier_ = std::max(0.0f, multiplier); - float target_volume = TargetVolume(); - AUDIO_LOG(INFO) << device_id_ << "(" << source_ - << "): stream volume = " << stream_volume_multiplier_ - << ", effective multiplier = " << target_volume; - if (target_volume != old_target_volume) { - slew_volume_.SetMaxSlewTimeMs(kDefaultSlewTimeMs); - slew_volume_.SetVolume(target_volume); - } -} - -void MixerInput::SetContentTypeVolume(float volume) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(content_type_ != AudioContentType::kOther); - - float old_target_volume = TargetVolume(); - type_volume_multiplier_ = volume; - float target_volume = TargetVolume(); - AUDIO_LOG(INFO) << device_id_ << "(" << source_ - << "): type volume = " << type_volume_multiplier_ - << ", effective multiplier = " << target_volume; - if (target_volume != old_target_volume) { - slew_volume_.SetMaxSlewTimeMs(kDefaultSlewTimeMs); - slew_volume_.SetVolume(target_volume); - } -} - -void MixerInput::SetVolumeLimits(float volume_min, float volume_max) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - float old_target_volume = TargetVolume(); - volume_min_ = volume_min; - volume_max_ = volume_max; - float target_volume = TargetVolume(); - AUDIO_LOG(INFO) << device_id_ << "(" << source_ << "): set volume limits to [" - << volume_min_ << ", " << volume_max_ << "]"; - if (target_volume != old_target_volume) { - slew_volume_.SetMaxSlewTimeMs(kDefaultSlewTimeMs); - slew_volume_.SetVolume(target_volume); - } -} - -void MixerInput::SetOutputLimit(float limit, int fade_ms) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - float old_target_volume = TargetVolume(); - output_volume_limit_ = limit; - float target_volume = TargetVolume(); - AUDIO_LOG(INFO) << device_id_ << "(" << source_ - << "): output limit = " << output_volume_limit_ - << ", effective multiplier = " << target_volume; - if (fade_ms < 0) { - fade_ms = kDefaultSlewTimeMs; - } else { - AUDIO_LOG(INFO) << "Fade over " << fade_ms << " ms"; - } - if (target_volume != old_target_volume) { - slew_volume_.SetMaxSlewTimeMs(fade_ms); - slew_volume_.SetVolume(target_volume); - } -} - -void MixerInput::SetMuted(bool muted) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(content_type_ != AudioContentType::kOther); - - float old_target_volume = TargetVolume(); - mute_volume_multiplier_ = muted ? 0.0f : 1.0f; - float target_volume = TargetVolume(); - AUDIO_LOG(INFO) << device_id_ << "(" << source_ - << "): mute volume = " << mute_volume_multiplier_ - << ", effective multiplier = " << target_volume; - if (target_volume != old_target_volume) { - slew_volume_.SetMaxSlewTimeMs(kDefaultSlewTimeMs); - slew_volume_.SetVolume(target_volume); - } -} - -float MixerInput::TargetVolume() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - float output_volume = stream_volume_multiplier_ * type_volume_multiplier_; - float clamped_volume = std::clamp(output_volume, volume_min_, volume_max_); - float limited_volume = std::min(clamped_volume, output_volume_limit_); - float muted_volume = limited_volume * mute_volume_multiplier_; - // Volume is clamped after all gains have been multiplied, to avoid clipping. - // TODO(kmackay): Consider removing this clamp and use a postprocessor filter - // to avoid clipping instead. - return std::clamp(muted_volume, 0.0f, 1.0f); -} - -float MixerInput::InstantaneousVolume() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return slew_volume_.LastBufferMaxMultiplier(); -} - -void MixerInput::SetSimulatedClockRate(double new_clock_rate) { - if (new_clock_rate == simulated_clock_rate_ || !resampler_) { - return; - } - simulated_clock_rate_ = new_clock_rate; - resampler_->SetRatio(resample_ratio_ * simulated_clock_rate_); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_input.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_input.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,248 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_INPUT_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_INPUT_H_ - -#include -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "base/sequence_checker.h" -#include "chromecast/media/base/aligned_buffer.h" -#include "chromecast/media/base/slew_volume.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/volume_control.h" -#include "media/base/channel_layout.h" - -namespace media { -class AudioBus; -class MultiChannelResampler; -} // namespace media - -namespace chromecast { -namespace media { - -class AudioOutputRedirectorInput; -class FilterGroup; -class FilterGroupTag; -class InterleavedChannelMixer; -class PostProcessingPipeline; - -// Input stream to the mixer. Handles pulling data from the data source and -// resampling it to the mixer's output sample rate, as well as volume control. -// All methods must be called on the mixer thread. -class MixerInput { - public: - using RenderingDelay = MediaPipelineBackend::AudioDecoder::RenderingDelay; - - // Data source for the mixer. All methods are called on the mixer thread and - // must return promptly to avoid audio underruns. The source must remain valid - // until FinalizeAudioPlayback() is called. - class Source { - public: - enum class MixerError { - // This input is being ignored due to a sample rate change. - kInputIgnored, - // An internal mixer error occurred. The input is no longer usable. - kInternalError, - }; - - virtual size_t num_channels() const = 0; - virtual ::media::ChannelLayout channel_layout() const = 0; - virtual int sample_rate() const = 0; - virtual bool primary() = 0; - virtual const std::string& device_id() = 0; - virtual AudioContentType content_type() = 0; - virtual AudioContentType focus_type() = 0; - virtual int desired_read_size() = 0; - virtual int playout_channel() = 0; - // Returns true if the source is currently providing audio to be mixed. - virtual bool active() = 0; - virtual bool require_clock_rate_simulation() const = 0; - - // Called when the input has been added to the mixer, before any other - // calls are made. The |read_size| is the number of frames that will be - // requested for each call to FillAudioPlaybackFrames(). The - // |initial_rendering_delay| is the rendering delay estimate for the first - // call to FillAudioPlaybackFrames(). - virtual void InitializeAudioPlayback( - int read_size, - RenderingDelay initial_rendering_delay) = 0; - - // Called to read more audio data from the source. The source must fill in - // |buffer| with up to |num_frames| of audio. The |rendering_delay| - // indicates when the first frame of the filled data will be played out. - // Returns the number of frames filled into |buffer|. - virtual int FillAudioPlaybackFrames(int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* buffer) = 0; - - // Called when a mixer error occurs. No more data will be pulled from the - // source. - virtual void OnAudioPlaybackError(MixerError error) = 0; - - // Called when an underrun error occurs on mixer output. - virtual void OnOutputUnderrun() {} - - // Called when the mixer has finished removing this input. The source may be - // deleted at this point. - virtual void FinalizeAudioPlayback() = 0; - - protected: - virtual ~Source() = default; - }; - - MixerInput(Source* source, FilterGroup* filter_group); - - MixerInput(const MixerInput&) = delete; - MixerInput& operator=(const MixerInput&) = delete; - - ~MixerInput(); - - void Initialize(); - void Destroy(); - void SetFilterGroup(FilterGroup* filter_group); - - void SetPostProcessorConfig(const std::string& name, - const std::string& config); - - Source* source() const { return source_; } - int num_channels() const { return num_channels_; } - ::media::ChannelLayout channel_layout() const { return channel_layout_; } - int input_samples_per_second() const { return input_samples_per_second_; } - int output_samples_per_second() const { return output_samples_per_second_; } - bool primary() const { return primary_; } - const std::string& device_id() const { return device_id_; } - AudioContentType content_type() const { return content_type_; } - AudioContentType focus_type() const { return source_->focus_type(); } - bool has_render_output() const { return (render_output_ != nullptr); } - - // Adds/removes an output redirector. When the mixer asks for more audio data, - // the lowest-ordered redirector (based on redirector->GetOrder()) is passed - // the audio data that would ordinarily have been mixed for local output; - // no audio from this MixerInput is passed to the mixer. - void AddAudioOutputRedirector(AudioOutputRedirectorInput* redirector); - void RemoveAudioOutputRedirector(AudioOutputRedirectorInput* redirector); - - // Renders data from the source. Returns |true| if any audio was rendered. - bool Render( - int num_output_frames, - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay); - float* RenderedAudioBuffer(); - - // Propagates |error| to the source. - void SignalError(Source::MixerError error); - - // Scales |frames| frames at |src| by the current volume (smoothing as - // needed). Adds the scaled result to |dest|. - // VolumeScaleAccumulate will be called once for each channel of audio - // present. - // |src| and |dest| should be 16-byte aligned. - void VolumeScaleAccumulate(const float* src, - int frames, - float* dest, - int channel_index); - - // Sets the per-stream volume multiplier. If |multiplier| < 0, sets the - // volume multiplier to 0. - void SetVolumeMultiplier(float multiplier); - - // Sets the multiplier based on this stream's content type. The resulting - // output volume should be the content type volume * the per-stream volume - // multiplier. - void SetContentTypeVolume(float volume); - - // Sets min/max output volume for this stream (ie, limits the product of - // content type volume and per-stream volume multiplier). Note that mute - // and runtime output limits (for ducking) are applied after these limits. - void SetVolumeLimits(float volume_min, float volume_max); - - // Limits the output volume for this stream to below |limit|. Used for - // ducking. If |fade_ms| is >= 0, the resulting volume change should be - // faded over that many milliseconds; otherwise, the default fade time should - // be used. - void SetOutputLimit(float limit, int fade_ms); - - // Sets whether or not this stream should be muted. - void SetMuted(bool muted); - - // Returns the target volume multiplier of the stream. Fading in or out may - // cause this to be different from the actual multiplier applied in the last - // buffer. For the actual multiplier applied, use InstantaneousVolume(). - float TargetVolume(); - - // Returns the largest volume multiplier applied to the last buffer - // retrieved. This differs from TargetVolume() during transients. - float InstantaneousVolume(); - - // Sets the simulated audio clock rate (by changing the resample rate). - void SetSimulatedClockRate(double new_clock_rate); - - private: - bool SetFilterGroupInternal(FilterGroup* filter_group); - void CreateChannelMixer(int playout_channel, FilterGroup* filter_group); - // Reads data from the source. Returns the number of frames actually filled - // (<= |num_frames|). - int FillAudioData(int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* dest); - int FillBuffer(int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* dest); - void RenderInterleaved(int num_output_frames); - - void ResamplerReadCallback(int frame_delay, ::media::AudioBus* output); - - Source* const source_; - const int num_channels_; - const ::media::ChannelLayout channel_layout_; - const int input_samples_per_second_; - const int output_samples_per_second_; - const bool primary_; - const std::string device_id_; - const AudioContentType content_type_; - int source_read_size_ = 0; - int playout_channel_ = 0; - - FilterGroup* filter_group_ = nullptr; - scoped_refptr filter_group_tag_; - std::unique_ptr<::media::AudioBus> fill_buffer_; - AlignedBuffer interleaved_; - std::unique_ptr channel_mixer_; - - float stream_volume_multiplier_ = 1.0f; - float type_volume_multiplier_ = 1.0f; - float volume_min_ = 0.0f; - float volume_max_ = 1.0f; - float output_volume_limit_ = 1.0f; - float mute_volume_multiplier_ = 1.0f; - SlewVolume slew_volume_; - bool incomplete_previous_fill_ = false; - bool previous_ended_in_silence_ = false; - bool first_buffer_ = true; - - RenderingDelay mixer_rendering_delay_; - double resampler_buffered_frames_ = 0.0; - int filled_for_resampler_; - bool tried_to_fill_resampler_; - int resampled_silence_count_ = 0; - std::unique_ptr<::media::MultiChannelResampler> resampler_; - double resample_ratio_ = 1.0; - double simulated_clock_rate_ = 1.0; - - std::unique_ptr prerender_pipeline_; - float* render_output_ = nullptr; - double prerender_delay_seconds_ = 0.0; - - std::vector audio_output_redirectors_; - - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_INPUT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_input_connection.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input_connection.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_input_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,1397 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mixer_input_connection.h" - -#include -#include - -#include -#include -#include -#include - -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/media/api/audio_provider.h" -#include "chromecast/media/audio/audio_fader.h" -#include "chromecast/media/audio/audio_log.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/media/audio/rate_adjuster.h" -#include "chromecast/media/cma/backend/mixer/channel_layout.h" -#include "chromecast/media/cma/backend/mixer/stream_mixer.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/net/io_buffer_pool.h" -#include "chromecast/public/media/decoder_config.h" -#include "media/audio/audio_device_description.h" -#include "media/base/audio_buffer.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_timestamp_helper.h" -#include "media/filters/audio_renderer_algorithm.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr int kDefaultQueueSize = 8192; -constexpr base::TimeDelta kDefaultFillTime = base::Milliseconds(5); -constexpr base::TimeDelta kDefaultFadeTime = base::Milliseconds(5); -constexpr base::TimeDelta kInactivityTimeout = base::Seconds(5); -constexpr int64_t kDefaultMaxTimestampError = 2000; -// Max absolute value for timestamp errors, to avoid overflow/underflow. -constexpr int64_t kTimestampErrorLimit = 1000000; -constexpr int kMaxChannels = 32; - -constexpr int kAudioMessageHeaderSize = - mixer_service::MixerSocket::kAudioMessageHeaderSize; - -enum MessageTypes : int { - kReadyForPlayback = 1, - kPushResult, - kEndOfStream, - kUnderrun, - kError, -}; - -int64_t SamplesToMicroseconds(double samples, int sample_rate) { - return std::round(samples * 1000000 / sample_rate); -} - -int GetFillSize(const mixer_service::OutputStreamParams& params) { - if (params.has_fill_size_frames()) { - return params.fill_size_frames(); - } - // Use 10 milliseconds by default. - return params.sample_rate() / 100; -} - -int GetStartThreshold(const mixer_service::OutputStreamParams& params) { - return std::max(params.start_threshold_frames(), 0); -} - -int GetQueueSize(const mixer_service::OutputStreamParams& params) { - int queue_size = kDefaultQueueSize; - if (params.has_max_buffered_frames()) { - queue_size = params.max_buffered_frames(); - } - int start_threshold = GetStartThreshold(params); - if (queue_size < start_threshold) { - queue_size = start_threshold; - LOG(INFO) << "Increase queue size to " << start_threshold - << " to match start threshold"; - } - return queue_size; -} - -int64_t GetMaxTimestampError(const mixer_service::OutputStreamParams& params) { - int64_t result = params.timestamped_audio_config().max_timestamp_error(); - if (result == 0) { - result = kDefaultMaxTimestampError; - } - return result; -} - -template -bool ValidAudioData(char* data) { - if (reinterpret_cast(data) % sizeof(T) != 0u) { - LOG(ERROR) << "Misaligned audio data"; - return false; - } - return true; -} - -template -void ConvertInterleavedData(int num_channels, - char* data, - int data_size, - float* dest) { - DCHECK(ValidAudioData(data)); - int num_frames = - data_size / (sizeof(typename Traits::ValueType) * num_channels); - typename Traits::ValueType* source = - reinterpret_cast(data); - for (int c = 0; c < num_channels; ++c) { - float* channel_data = dest + c * num_frames; - for (int f = 0, read_pos = c; f < num_frames; - ++f, read_pos += num_channels) { - channel_data[f] = Traits::ToFloat(source[read_pos]); - } - } -} - -template -void ConvertPlanarData(char* data, int data_size, float* dest) { - DCHECK(ValidAudioData(data)); - int samples = data_size / sizeof(typename Traits::ValueType); - typename Traits::ValueType* source = - reinterpret_cast(data); - for (int s = 0; s < samples; ++s) { - dest[s] = Traits::ToFloat(source[s]); - } -} - -int GetFrameCount(net::IOBuffer* buffer) { - int32_t num_frames; - memcpy(&num_frames, buffer->data(), sizeof(num_frames)); - return num_frames; -} - -int64_t GetTimestamp(net::IOBuffer* buffer) { - int64_t timestamp; - memcpy(×tamp, buffer->data() + sizeof(int32_t), sizeof(timestamp)); - return timestamp; -} - -void AdjustTimestamp(net::IOBuffer* buffer, int64_t adjustment) { - void* ptr = buffer->data() + sizeof(int32_t); - int64_t timestamp; - memcpy(×tamp, ptr, sizeof(timestamp)); - timestamp += adjustment; - memcpy(ptr, ×tamp, sizeof(timestamp)); -} - -void AdjustTimestampForRateChange(net::IOBuffer* buffer, - double ratio, - int64_t base_timestamp) { - void* ptr = buffer->data() + sizeof(int32_t); - int64_t timestamp; - memcpy(×tamp, ptr, sizeof(timestamp)); - int64_t diff = timestamp - base_timestamp; - timestamp = base_timestamp + diff * ratio; - memcpy(ptr, ×tamp, sizeof(timestamp)); -} - -float* GetAudioData(net::IOBuffer* buffer) { - return reinterpret_cast(buffer->data() + kAudioMessageHeaderSize); -} - -::media::ChannelLayout GetChannelLayout(audio_service::ChannelLayout layout, - int num_channels) { - DCHECK_NE(layout, audio_service::CHANNEL_LAYOUT_BITSTREAM); - if (layout == audio_service::CHANNEL_LAYOUT_NONE) { - return mixer::GuessChannelLayout(num_channels); - } - return DecoderConfigAdapter::ToMediaChannelLayout( - ConvertChannelLayout(layout)); -} - -std::unique_ptr CreateRateAdjuster( - const mixer_service::OutputStreamParams& params, - RateAdjuster::RateChangeCallback callback) { - const auto& c = params.timestamped_audio_config(); - media::RateAdjuster::Config config; - if (c.has_rate_change_interval()) { - config.rate_change_interval = base::Microseconds(c.rate_change_interval()); - } - if (c.has_linear_regression_window()) { - config.linear_regression_window = - base::Microseconds(c.linear_regression_window()); - } - if (c.has_max_ignored_current_error()) { - config.max_ignored_current_error = c.max_ignored_current_error(); - } - if (c.has_max_current_error_correction()) { - config.max_current_error_correction = c.max_current_error_correction(); - } - if (c.has_min_rate_change()) { - config.min_rate_change = c.min_rate_change(); - } - - auto adjuster = - std::make_unique(config, std::move(callback), 1.0); - int64_t expected_error_samples = - config.linear_regression_window.InSecondsF() * params.sample_rate() / - GetFillSize(params); - adjuster->Reserve(2 * expected_error_samples); - return adjuster; -} - -} // namespace - -class MixerInputConnection::TimestampedFader : public AudioProvider { - class FaderProvider : public AudioProvider { - public: - FaderProvider(TimestampedFader& owner, int num_channels, int sample_rate) - : owner_(owner), - num_channels_(num_channels), - sample_rate_(sample_rate) {} - - // AudioProvider implementation: - size_t num_channels() const override { return num_channels_; } - int sample_rate() const override { return sample_rate_; } - int FillFrames(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) override; - - private: - TimestampedFader& owner_; - const int num_channels_; - const int sample_rate_; - }; - - public: - TimestampedFader(MixerInputConnection* mixer_input, int fade_frames) - : mixer_input_(mixer_input), - num_channels_(mixer_input_->num_channels()), - sample_rate_(mixer_input_->sample_rate()), - fader_provider_(*this, num_channels_, sample_rate_), - fader_(&fader_provider_, fade_frames, 1.0) {} - - ~TimestampedFader() override = default; - - int BufferedFrames() { return fader_.buffered_frames(); } - - void SetPlaybackRate(double rate) { fader_.set_playback_rate(rate); } - - // AudioProvider implementation: - int FillFrames(int num_frames, - int64_t expected_playout_time, - float* const* channels) override NO_THREAD_SAFETY_ANALYSIS { - int filled = 0; - while (filled < num_frames) { - int remaining = num_frames - filled; - const int64_t playout_time = - expected_playout_time + - SamplesToMicroseconds(filled / mixer_input_->playback_rate_, - sample_rate_); - float* fill_channel_data[kMaxChannels]; - for (int c = 0; c < num_channels_; ++c) { - fill_channel_data[c] = channels[c] + filled; - } - int faded = fader_.FillFrames(remaining, playout_time, fill_channel_data); - filled += faded; - if (faded == remaining) { - if (pending_silence_) { - // Still waiting for fade to complete, but we should re-evaluate how - // much silence to add for the next fill. - pending_silence_.emplace(0); - } - return filled; - } - - if (!pending_silence_) { - // No pending silence, and we are not able to fill any more. - for (int c = 0; c < num_channels_; ++c) { - std::fill_n(channels[c] + filled, num_frames - filled, 0.0f); - } - return num_frames; - } - - if (faded == 0) { - // Fade complete; fill some silence. - int silence_frames = - std::min(pending_silence_.value(), num_frames - filled); - for (int c = 0; c < num_channels_; ++c) { - std::fill_n(channels[c] + filled, silence_frames, 0.0f); - } - filled += silence_frames; - // Reset since we'll want to re-evaluate for the next fill. - pending_silence_.reset(); - after_silence_ = true; - } - } - return filled; - } - - void AddSilence(int frames) { pending_silence_.emplace(frames); } - - private: - static constexpr size_t kMaxChannels = 32; - - int FillFramesForFader(int num_frames, - int64_t playout_timestamp, - float* const* channel_data) NO_THREAD_SAFETY_ANALYSIS { - if (pending_silence_) { - return 0; - } - int filled = mixer_input_->FillAudio(num_frames, playout_timestamp, - channel_data, after_silence_); - if (filled) { - after_silence_ = false; - } - return filled; - } - - size_t num_channels() const override { return num_channels_; } - int sample_rate() const override { return sample_rate_; } - - MixerInputConnection* const mixer_input_; - const int num_channels_; - const int sample_rate_; - - std::optional pending_silence_; - FaderProvider fader_provider_; - AudioFader fader_; - bool after_silence_ = true; -}; - -int MixerInputConnection::TimestampedFader::FaderProvider::FillFrames( - int num_frames, - int64_t playout_timestamp, - float* const* channel_data) { - return owner_.FillFramesForFader(num_frames, playout_timestamp, channel_data); -} - -MixerInputConnection::MixerInputConnection( - StreamMixer* mixer, - std::unique_ptr socket, - const mixer_service::OutputStreamParams& params) - : mixer_(mixer), - socket_(std::move(socket)), - ignore_for_stream_count_(params.ignore_for_stream_count()), - fill_size_(GetFillSize(params)), - algorithm_fill_size_(std::min( - static_cast(fill_size_), - ::media::AudioTimestampHelper::TimeToFrames(kDefaultFillTime, - params.sample_rate()))), - num_channels_(params.num_channels()), - channel_layout_( - GetChannelLayout(params.channel_layout(), params.num_channels())), - input_samples_per_second_(params.sample_rate()), - sample_format_(params.sample_format()), - primary_(params.stream_type() != - mixer_service::OutputStreamParams::STREAM_TYPE_SFX), - device_id_(params.has_device_id() - ? params.device_id() - : ::media::AudioDeviceDescription::kDefaultDeviceId), - content_type_(audio_service::ConvertContentType(params.content_type())), - focus_type_(params.has_focus_type() - ? audio_service::ConvertContentType(params.focus_type()) - : content_type_), - playout_channel_(params.channel_selection()), - pts_is_timestamp_(params.has_timestamped_audio_config()), - max_timestamp_error_(GetMaxTimestampError(params)), - never_crop_(params.timestamped_audio_config().never_crop()), - enable_audio_clock_simulation_(pts_is_timestamp_ || - params.enable_audio_clock_simulation()), - effective_playout_channel_(playout_channel_), - io_task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()), - max_queued_frames_(std::max(GetQueueSize(params), algorithm_fill_size_)), - start_threshold_frames_(GetStartThreshold(params)), - never_timeout_connection_(params.never_timeout_connection()), - rate_adjuster_( - pts_is_timestamp_ - ? CreateRateAdjuster( - params, - base::BindRepeating(&MixerInputConnection::ChangeAudioRate, - base::Unretained(this))) - : nullptr), - fade_frames_(params.has_fade_frames() - ? params.fade_frames() - : ::media::AudioTimestampHelper::TimeToFrames( - kDefaultFadeTime, - input_samples_per_second_)), - timestamped_fader_( - std::make_unique(this, fade_frames_)), - rate_shifter_(timestamped_fader_.get(), - channel_layout_, - num_channels_, - input_samples_per_second_, - algorithm_fill_size_), - use_start_timestamp_(params.use_start_timestamp()), - playback_start_timestamp_(use_start_timestamp_ ? INT64_MAX : INT64_MIN), - weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); - - LOG(INFO) << "Create " << this << " (" << device_id_ - << "), content type: " << content_type_ - << ", focus type: " << focus_type_ << ", fill size: " << fill_size_ - << ", algorithm fill size: " << algorithm_fill_size_ - << ", channel count: " << num_channels_ - << ", input sample rate: " << input_samples_per_second_ - << ", start threshold: " << start_threshold_frames_ - << ", max queue size: " << max_queued_frames_ - << ", pts_is_timestamp: " << pts_is_timestamp_; - DCHECK(mixer_); - DCHECK(socket_); - CHECK_GT(num_channels_, 0); - CHECK_GT(input_samples_per_second_, 0); - DCHECK_LE(start_threshold_frames_, max_queued_frames_); - - socket_->SetDelegate(this); - - pcm_completion_task_ = - base::BindRepeating(&MixerInputConnection::PostPcmCompletion, weak_this_); - eos_task_ = base::BindRepeating(&MixerInputConnection::PostEos, weak_this_); - ready_for_playback_task_ = base::BindRepeating( - &MixerInputConnection::PostAudioReadyForPlayback, weak_this_); - post_stream_underrun_task_ = base::BindRepeating( - &MixerInputConnection::PostStreamUnderrun, weak_this_); - - CreateBufferPool(fill_size_); - mixer_->AddInput(this); - - inactivity_timer_.Start(FROM_HERE, kInactivityTimeout, this, - &MixerInputConnection::OnInactivityTimeout); -} - -MixerInputConnection::~MixerInputConnection() { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - LOG(INFO) << "Delete " << this; -} - -void MixerInputConnection::CreateBufferPool(int frame_count) { - DCHECK_GT(frame_count, 0); - buffer_pool_frames_ = frame_count; - - int converted_buffer_size = - kAudioMessageHeaderSize + num_channels_ * sizeof(float) * frame_count; - buffer_pool_ = base::MakeRefCounted( - converted_buffer_size, std::numeric_limits::max(), - true /* threadsafe */); - buffer_pool_->Preallocate(start_threshold_frames_ / frame_count + 1); - if (sample_format_ == audio_service::SAMPLE_FORMAT_FLOAT_P) { - // No format conversion needed, so just use the received buffers directly. - socket_->UseBufferPool(buffer_pool_); - } -} - -bool MixerInputConnection::HandleMetadata( - const mixer_service::Generic& message) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - if (inactivity_timer_.IsRunning()) { - inactivity_timer_.Reset(); - } - - if (message.has_set_start_timestamp()) { - RestartPlaybackAt(message.set_start_timestamp().start_timestamp(), - message.set_start_timestamp().start_pts()); - } - if (message.has_set_stream_volume()) { - mixer_->SetVolumeMultiplier(this, message.set_stream_volume().volume()); - } - if (message.has_set_playback_rate()) { - SetMediaPlaybackRate(message.set_playback_rate().playback_rate()); - } - if (message.has_set_audio_clock_rate()) { - SetAudioClockRate(message.set_audio_clock_rate().rate()); - } - if (message.has_set_paused()) { - SetPaused(message.set_paused().paused()); - } - if (message.has_timestamp_adjustment()) { - AdjustTimestamps(message.timestamp_adjustment().adjustment()); - } - if (message.has_eos_played_out()) { - // Explicit EOS. - HandleAudioData(nullptr, 0, INT64_MIN); - } - return true; -} - -bool MixerInputConnection::HandleAudioData(char* data, - size_t size, - int64_t timestamp) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - const int frame_size = - num_channels_ * audio_service::GetSampleSizeBytes(sample_format_); - if (size % frame_size != 0) { - LOG(ERROR) << this - << ": audio data size is not an integer number of frames"; - OnConnectionError(); - return false; - } - - int32_t num_frames = size / frame_size; - if (num_frames > buffer_pool_frames_) { - CreateBufferPool(num_frames * 2); - } - auto buffer = buffer_pool_->GetBuffer(); - - size_t converted_size = - num_frames * num_channels_ * sizeof(float) + kAudioMessageHeaderSize; - DCHECK_LE(converted_size, buffer_pool_->buffer_size()); - - memcpy(buffer->data(), &num_frames, sizeof(int32_t)); - memcpy(buffer->data() + sizeof(int32_t), ×tamp, sizeof(timestamp)); - - float* dest = - reinterpret_cast(buffer->data() + kAudioMessageHeaderSize); - switch (sample_format_) { - case audio_service::SAMPLE_FORMAT_INT16_I: - ConvertInterleavedData<::media::SignedInt16SampleTypeTraits>( - num_channels_, data, size, dest); - break; - case audio_service::SAMPLE_FORMAT_INT32_I: - ConvertInterleavedData<::media::SignedInt32SampleTypeTraits>( - num_channels_, data, size, dest); - break; - case audio_service::SAMPLE_FORMAT_FLOAT_I: - ConvertInterleavedData<::media::Float32SampleTypeTraits>( - num_channels_, data, size, dest); - break; - case audio_service::SAMPLE_FORMAT_INT16_P: - ConvertPlanarData<::media::SignedInt16SampleTypeTraits>(data, size, dest); - break; - case audio_service::SAMPLE_FORMAT_INT32_P: - ConvertPlanarData<::media::SignedInt32SampleTypeTraits>(data, size, dest); - break; - case audio_service::SAMPLE_FORMAT_FLOAT_P: - memcpy(dest, data, size); - break; - default: - NOTREACHED() << "Unhandled sample format " << sample_format_; - } - - WritePcm(std::move(buffer)); - return true; -} - -bool MixerInputConnection::HandleAudioBuffer( - scoped_refptr buffer, - char* data, - size_t size, - int64_t timestamp) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - DCHECK_EQ(data - buffer->data(), kAudioMessageHeaderSize); - if (sample_format_ != audio_service::SAMPLE_FORMAT_FLOAT_P) { - return HandleAudioData(data, size, timestamp); - } - - int32_t num_frames = size / (sizeof(float) * num_channels_); - DCHECK_EQ(sizeof(int32_t), 4u); - memcpy(buffer->data(), &num_frames, sizeof(int32_t)); - - WritePcm(std::move(buffer)); - - if (num_frames > buffer_pool_frames_) { - CreateBufferPool(num_frames * 2); - } - return true; -} - -void MixerInputConnection::OnConnectionError() { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - if (connection_error_) { - return; - } - connection_error_ = true; - socket_.reset(); - weak_factory_.InvalidateWeakPtrs(); - - LOG(INFO) << "Remove " << this; - { - base::AutoLock lock(lock_); - pending_data_ = nullptr; - state_ = State::kRemoved; - SetMediaPlaybackRateLocked(1.0); - if (mixer_error_) { - RemoveSelf(); - } - } -} - -void MixerInputConnection::OnInactivityTimeout() { - if (never_timeout_connection_) { - return; - } - - LOG(INFO) << "Timed out " << this << " due to inactivity"; - OnConnectionError(); -} - -void MixerInputConnection::RestartPlaybackAt(int64_t timestamp, int64_t pts) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - - LOG(INFO) << this << " RestartPlaybackAt timestamp=" << timestamp - << " pts=" << pts; - { - base::AutoLock lock(lock_); - playback_start_pts_ = pts; - playback_start_timestamp_ = timestamp; - use_start_timestamp_ = true; - started_ = false; - queued_frames_ += current_buffer_offset_; - current_buffer_offset_ = 0; - - while (!queue_.empty()) { - net::IOBuffer* buffer = queue_.front().get(); - int64_t frames = GetFrameCount(buffer); - if (GetTimestamp(buffer) + - SamplesToMicroseconds(frames, input_samples_per_second_) >= - pts) { - break; - } - - queued_frames_ -= frames; - queue_.pop_front(); - } - } -} - -void MixerInputConnection::SetMediaPlaybackRate(double rate) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - LOG(INFO) << this << " SetMediaPlaybackRate rate=" << rate; - DCHECK_GT(rate, 0); - - base::AutoLock lock(lock_); - if (state_ == State::kGotEos || state_ == State::kRemoved) { - LOG(INFO) << this << " ignore playback rate change after EOS/removed"; - return; - } - SetMediaPlaybackRateLocked(rate); -} - -void MixerInputConnection::SetMediaPlaybackRateLocked(double rate) { - double old_rate = playback_rate_; - rate_shifter_.SetPlaybackRate(rate); - playback_rate_ = rate_shifter_.playback_rate(); - if (rate_adjuster_) { - rate_adjuster_->Reset(); - total_filled_frames_ = 0; - } - timestamped_fader_->SetPlaybackRate(playback_rate_); - if (playback_rate_ == 1.0) { - effective_playout_channel_.store(playout_channel_, - std::memory_order_relaxed); - } else { - // Always play all channels when playback is rate-shifted (b/151393870). - effective_playout_channel_.store(kChannelAll, std::memory_order_relaxed); - } - - // Adjust timestamps. - if (pts_is_timestamp_ && !queue_.empty()) { - double timestamp_ratio = old_rate / playback_rate_; - auto it = queue_.begin(); - int64_t base_timestamp = GetTimestamp(it->get()); - for (++it; it != queue_.end(); ++it) { - AdjustTimestampForRateChange(it->get(), timestamp_ratio, base_timestamp); - } - if (pending_data_) { - AdjustTimestampForRateChange(pending_data_.get(), timestamp_ratio, - base_timestamp); - } - } -} - -void MixerInputConnection::SetAudioClockRate(double rate) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - if (pts_is_timestamp_) { - AUDIO_LOG(ERROR) << "Cannot set audio clock rate in timestamped mode"; - return; - } - - if (!enable_audio_clock_simulation_) { - AUDIO_LOG(ERROR) << "Audio clock rate simulation not enabled"; - return; - } - mixer_->SetSimulatedClockRate(this, rate); -} - -double MixerInputConnection::ChangeAudioRate(double desired_clock_rate, - double error_slope, - double current_error) { - mixer_->SetSimulatedClockRate(this, desired_clock_rate); - return desired_clock_rate; -} - -void MixerInputConnection::AdjustTimestamps(int64_t timestamp_adjustment) { - if (timestamp_adjustment == 0) { - return; - } - - base::AutoLock lock(lock_); - if (pending_data_) { - AdjustTimestamp(pending_data_.get(), timestamp_adjustment); - } - for (const auto& buffer : queue_) { - AdjustTimestamp(buffer.get(), timestamp_adjustment); - } -} - -void MixerInputConnection::SetPaused(bool paused) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - LOG(INFO) << (paused ? "Pausing " : "Unpausing ") << this; - if (paused) { - inactivity_timer_.Stop(); - } else { - inactivity_timer_.Start(FROM_HERE, kInactivityTimeout, this, - &MixerInputConnection::OnInactivityTimeout); - } - - { - base::AutoLock lock(lock_); - if (paused == paused_) { - return; - } - - paused_ = paused; - if (paused_) { - // Drain data out of the rate shifter. - rate_shifter_.SetPlaybackRate(1.0); - } else { - rate_shifter_.SetPlaybackRate(playback_rate_); - playback_rate_ = rate_shifter_.playback_rate(); - } - mixer_rendering_delay_ = RenderingDelay(); - // Clear start timestamp, since a pause should invalidate the start - // timestamp anyway. The AV sync code can restart (hard correction) on - // resume if needed. - use_start_timestamp_ = false; - playback_start_timestamp_ = INT64_MIN; - filled_some_since_resume_ = false; - if (rate_adjuster_) { - rate_adjuster_->Reset(); - total_filled_frames_ = 0; - } - } - mixer_->UpdateStreamCounts(); -} - -size_t MixerInputConnection::num_channels() const { - return num_channels_; -} - -::media::ChannelLayout MixerInputConnection::channel_layout() const { - return channel_layout_; -} - -int MixerInputConnection::sample_rate() const { - return input_samples_per_second_; -} - -bool MixerInputConnection::primary() { - return primary_; -} - -const std::string& MixerInputConnection::device_id() { - return device_id_; -} - -AudioContentType MixerInputConnection::content_type() { - return content_type_; -} - -AudioContentType MixerInputConnection::focus_type() { - return focus_type_; -} - -int MixerInputConnection::desired_read_size() { - return algorithm_fill_size_; -} - -int MixerInputConnection::playout_channel() { - return effective_playout_channel_.load(std::memory_order_relaxed); -} - -bool MixerInputConnection::active() { - base::AutoLock lock(lock_); - return !ignore_for_stream_count_ && !paused_; -} - -bool MixerInputConnection::require_clock_rate_simulation() const { - return enable_audio_clock_simulation_; -} - -void MixerInputConnection::WritePcm(scoped_refptr data) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - if (inactivity_timer_.IsRunning()) { - inactivity_timer_.Reset(); - } - - RenderingDelay rendering_delay; - bool queued; - { - base::AutoLock lock(lock_); - if (state_ == State::kUninitialized || - queued_frames_ >= max_queued_frames_) { - if (pending_data_) { - if (pts_is_timestamp_) { - QueueData(std::move(pending_data_)); - } else { - LOG(ERROR) << "Got unexpected audio data for " << this; - } - } - pending_data_ = std::move(data); - queued = false; - } else { - rendering_delay = QueueData(std::move(data)); - queued = true; - } - } - - if (queued) { - mixer_service::Generic message; - auto* push_result = message.mutable_push_result(); - push_result->set_delay_timestamp(rendering_delay.timestamp_microseconds); - push_result->set_delay(rendering_delay.delay_microseconds); - socket_->SendProto(kPushResult, message); - } -} - -MixerInputConnection::RenderingDelay MixerInputConnection::QueueData( - scoped_refptr data) { - int frames = GetFrameCount(data.get()); - if (frames == 0) { - AUDIO_LOG(INFO) << "End of stream for " << this; - state_ = State::kGotEos; - SetMediaPlaybackRateLocked(1.0); - if (!started_) { - io_task_runner_->PostTask(FROM_HERE, ready_for_playback_task_); - } - } else if (pts_is_timestamp_ || started_ || - GetTimestamp(data.get()) + - SamplesToMicroseconds(frames, input_samples_per_second_) >= - playback_start_pts_) { - queued_frames_ += frames; - queue_.push_back(std::move(data)); - - if (!started_ && queued_frames_ >= start_threshold_frames_) { - io_task_runner_->PostTask(FROM_HERE, ready_for_playback_task_); - } - } - // Otherwise, drop |data| since it is before the start PTS. - - if (!started_ || paused_ || - mixer_rendering_delay_.timestamp_microseconds == INT64_MIN) { - return RenderingDelay(); - } - - RenderingDelay delay = mixer_rendering_delay_; - delay.delay_microseconds += - SamplesToMicroseconds(ExtraDelayFrames(), input_samples_per_second_); - return delay; -} - -double MixerInputConnection::ExtraDelayFrames() { - // The next playback timestamp will be the timestamp from the last mixer fill - // request, plus the time required to play out the other data in the pipeline. - // The other data includes: - // * The number of frames of the last mixer fill (since that will be played - // out starting at the last mixer rendering delay). - // * Data in the rate shifter. - // * Data buffered in the fader. - // * Queued data in |queue_|. - // Note that the delay for data that will be pushed into the rate shifter - // (ie, fader and queue_) needs to be adjusted for the current playback rate. - return mixer_read_size_ + rate_shifter_.BufferedFrames() + - ((timestamped_fader_->BufferedFrames() + queued_frames_) / - playback_rate_); -} - -void MixerInputConnection::InitializeAudioPlayback( - int read_size, - RenderingDelay initial_rendering_delay) { - // Start accepting buffers into the queue. - bool queued_data = false; - { - base::AutoLock lock(lock_); - mixer_read_size_ = read_size; - AUDIO_LOG(INFO) << this << " Mixer read size: " << read_size; - // How many fills is >= 1 read? - const int fills_per_read = (read_size + fill_size_ - 1) / fill_size_; - // How many reads is >= 1 fill? - const int reads_per_fill = (fill_size_ + read_size - 1) / read_size; - // We need enough data to satisfy all the reads until the next fill, and - // enough to fill enough data before the next read (in case the next read - // happens immediately after we hit the start threshold) (+ fader buffer). - min_start_threshold_ = - std::max(fills_per_read * fill_size_, reads_per_fill * read_size) + - fade_frames_; - if (start_threshold_frames_ < min_start_threshold_) { - start_threshold_frames_ = min_start_threshold_; - AUDIO_LOG(INFO) << this << " Updated start threshold: " - << start_threshold_frames_; - } - if (max_queued_frames_ < start_threshold_frames_) { - AUDIO_LOG(INFO) << this << " Boost queue size to " - << start_threshold_frames_ << " to allow stream to start"; - max_queued_frames_ = start_threshold_frames_; - } - mixer_rendering_delay_ = initial_rendering_delay; - if (state_ == State::kUninitialized) { - state_ = State::kNormalPlayback; - } else { - DCHECK_EQ(state_, State::kRemoved); - } - - if (pending_data_ && queued_frames_ < max_queued_frames_) { - next_delay_ = QueueData(std::move(pending_data_)); - queued_data = true; - } - } - - if (queued_data) { - io_task_runner_->PostTask(FROM_HERE, pcm_completion_task_); - } -} - -void MixerInputConnection::CheckAndStartPlaybackIfNecessary( - int num_frames, - int64_t playback_absolute_timestamp) { - DCHECK(state_ == State::kNormalPlayback || state_ == State::kGotEos); - DCHECK(!started_); - - if (pts_is_timestamp_) { - remaining_silence_frames_ = 0; - AUDIO_LOG(INFO) << "Start " << this; - started_ = true; - return; - } - - const bool have_enough_queued_frames = - (state_ == State::kGotEos || queued_frames_ >= start_threshold_frames_); - if (!have_enough_queued_frames) { - return; - } - - remaining_silence_frames_ = 0; - if (!use_start_timestamp_ || (queue_.empty() && state_ == State::kGotEos)) { - // No start timestamp, so start as soon as there are enough queued frames. - AUDIO_LOG(INFO) << "Start " << this; - started_ = true; - return; - } - - if (playback_absolute_timestamp + - SamplesToMicroseconds(num_frames, input_samples_per_second_) < - playback_start_timestamp_) { - // Haven't reached the start timestamp yet. - return; - } - - DCHECK(!queue_.empty()); - // Reset the current buffer offset to 0 so we can ignore it below. We need to - // do this here because we may not have started playback even after dropping - // all necessary frames the last time we checked. - queued_frames_ += current_buffer_offset_; - current_buffer_offset_ = 0; - - int64_t desired_pts_now = playback_start_pts_ + (playback_absolute_timestamp - - playback_start_timestamp_) * - playback_rate_; - int64_t actual_pts_now = GetTimestamp(queue_.front().get()); - int64_t drop_us = (desired_pts_now - actual_pts_now) / playback_rate_; - - if (drop_us >= 0) { - AUDIO_LOG(INFO) << this << " Dropping audio, duration = " << drop_us; - DropAudio(::media::AudioTimestampHelper::TimeToFrames( - base::Microseconds(drop_us), input_samples_per_second_)); - // Only start if we still have enough data to do so. - started_ = (queued_frames_ >= start_threshold_frames_); - - if (started_) { - int64_t start_pts = GetTimestamp(queue_.front().get()) + - SamplesToMicroseconds(current_buffer_offset_, - input_samples_per_second_) * - playback_rate_; - AUDIO_LOG(INFO) << this << " Start playback of PTS " << start_pts - << " at " << playback_absolute_timestamp; - } - } else { - int64_t silence_duration = -drop_us; - AUDIO_LOG(INFO) << this - << " Adding silence. Duration = " << silence_duration; - remaining_silence_frames_ = ::media::AudioTimestampHelper::TimeToFrames( - base::Microseconds(silence_duration), input_samples_per_second_); - // Round to nearest multiple of 4 to preserve buffer alignment. - remaining_silence_frames_ = ((remaining_silence_frames_ + 2) / 4) * 4; - started_ = true; - AUDIO_LOG(INFO) << this << " Should start playback of PTS " - << actual_pts_now << " at " - << (playback_absolute_timestamp + silence_duration); - } -} - -void MixerInputConnection::DropAudio(int64_t frames_to_drop) { - while (frames_to_drop && !queue_.empty()) { - int64_t first_buffer_frames = GetFrameCount(queue_.front().get()); - int64_t frames_left = first_buffer_frames - current_buffer_offset_; - - if (frames_left > frames_to_drop) { - current_buffer_offset_ += frames_to_drop; - queued_frames_ -= frames_to_drop; - frames_to_drop = 0; - break; - } - - queued_frames_ -= first_buffer_frames; - frames_to_drop -= first_buffer_frames; - queue_.pop_front(); - current_buffer_offset_ = 0; - } - - if (frames_to_drop > 0) { - AUDIO_LOG(INFO) << this << " Still need to drop " << frames_to_drop - << " frames"; - } -} - -int MixerInputConnection::FillAudioPlaybackFrames( - int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* buffer) { - DCHECK(buffer); - DCHECK_EQ(num_channels_, buffer->channels()); - DCHECK_GE(buffer->frames(), num_frames); - - int64_t playback_absolute_timestamp = rendering_delay.delay_microseconds + - rendering_delay.timestamp_microseconds; - - int filled = 0; - bool post_pcm_completion = false; - bool signal_eos = false; - bool remove_self = false; - { - base::AutoLock lock(lock_); - - mixer_read_size_ = num_frames; - - // Playback start check. - if (!started_ && - (state_ == State::kNormalPlayback || state_ == State::kGotEos)) { - CheckAndStartPlaybackIfNecessary(num_frames, playback_absolute_timestamp); - } - - DCHECK_GE(remaining_silence_frames_, 0); - if (remaining_silence_frames_ >= num_frames) { - remaining_silence_frames_ -= num_frames; - return 0; - } - - int write_offset = 0; - if (remaining_silence_frames_ > 0) { - buffer->ZeroFramesPartial(0, remaining_silence_frames_); - filled += remaining_silence_frames_; - num_frames -= remaining_silence_frames_; - write_offset = remaining_silence_frames_; - remaining_silence_frames_ = 0; - } - - CHECK_LE(num_channels_, kMaxChannels); - float* channels[kMaxChannels]; - for (int c = 0; c < num_channels_; ++c) { - channels[c] = buffer->channel(c) + write_offset; - } - filled += rate_shifter_.FillFrames(num_frames, playback_absolute_timestamp, - channels); - - mixer_rendering_delay_ = rendering_delay; - - // See if we can accept more data into the queue. - if (pending_data_ && queued_frames_ < max_queued_frames_) { - next_delay_ = QueueData(std::move(pending_data_)); - post_pcm_completion = true; - } else if (pts_is_timestamp_) { - next_delay_ = rendering_delay; - next_delay_.delay_microseconds += - SamplesToMicroseconds(ExtraDelayFrames(), input_samples_per_second_); - } - - // Check if we have played out EOS. - if (state_ == State::kGotEos && queued_frames_ == 0 && - timestamped_fader_->BufferedFrames() == 0 && - rate_shifter_.BufferedFrames() == 0) { - signal_eos = true; - state_ = State::kSignaledEos; - } - - // If the caller has removed this source, delete once we have faded out. - if (state_ == State::kRemoved && - timestamped_fader_->BufferedFrames() == 0 && - rate_shifter_.BufferedFrames() == 0) { - if (fed_one_silence_buffer_after_removal_) { - remove_self = true; - } - fed_one_silence_buffer_after_removal_ = true; - } - - if (pts_is_timestamp_ && queued_frames_ < max_queued_frames_) { - post_pcm_completion = true; - } - } - - if (post_pcm_completion) { - io_task_runner_->PostTask(FROM_HERE, pcm_completion_task_); - } - if (signal_eos) { - io_task_runner_->PostTask(FROM_HERE, eos_task_); - } - - if (remove_self) { - base::AutoLock lock(lock_); - RemoveSelf(); - } - - return filled; -} - -int MixerInputConnection::FillAudio(int num_frames, - int64_t expected_playout_time, - float* const* channels, - bool after_silence) { - if (paused_ || state_ == State::kRemoved) { - return 0; - } - - DCHECK(channels); - if (pts_is_timestamp_) { - return FillTimestampedAudio(num_frames, expected_playout_time, channels, - after_silence); - } - - if (!started_ || num_frames == 0) { - return 0; - } - - if (in_underrun_ && (queued_frames_ < min_start_threshold_)) { - // Allow buffer to refill a bit to prevent continuous underrun. - return 0; - } - - int num_filled = 0; - int frames_left = num_frames; - while (frames_left && !queue_.empty()) { - int copied = FillFromQueue(frames_left, channels, num_filled); - frames_left -= copied; - num_filled += copied; - } - - LogUnderrun(num_frames, num_filled); - return num_filled; -} - -void MixerInputConnection::LogUnderrun(int num_frames, int filled) { - if (filled != num_frames) { - if (!in_underrun_ && state_ == State::kNormalPlayback) { - AUDIO_LOG(INFO) << "Stream underrun for " << this; - in_underrun_ = true; - io_task_runner_->PostTask(FROM_HERE, post_stream_underrun_task_); - } - } else if (in_underrun_) { - AUDIO_LOG(INFO) << "Stream underrun recovered for " << this << " with " - << queued_frames_ << " queued frames"; - in_underrun_ = false; - } -} - -int MixerInputConnection::FillTimestampedAudio(int num_frames, - int64_t expected_playout_time, - float* const* channels, - bool after_silence) { - if (expected_playout_time < 0) { - // Invalid playout time. - return 0; - } - int filled = 0; - while (filled < num_frames && !queue_.empty()) { - net::IOBuffer* buffer = queue_.front().get(); - - const int64_t buffer_timestamp = GetTimestamp(buffer); - const int64_t playout_time = - expected_playout_time + - SamplesToMicroseconds(filled / playback_rate_, - input_samples_per_second_); - const int64_t desired_playout_time = - buffer_timestamp + - SamplesToMicroseconds(current_buffer_offset_ / playback_rate_, - input_samples_per_second_); - - const int64_t error = - std::clamp(playout_time - desired_playout_time, -kTimestampErrorLimit, - kTimestampErrorLimit); - if (error < -max_timestamp_error_ || - (after_silence && - error < -1e6 / (input_samples_per_second_ * playback_rate_))) { - int64_t silence_frames = - std::round(-error * input_samples_per_second_ * playback_rate_ / 1e6); - if (filled_some_since_resume_) { - AUDIO_LOG(INFO) << this << " adding " << silence_frames - << " frames of silence, buffer ts = " - << buffer_timestamp; - } - timestamped_fader_->AddSilence(silence_frames); - rate_adjuster_->Reset(); - total_filled_frames_ = 0; - return filled; // Need to fade out. - } else if (error > max_timestamp_error_ || (after_silence && error > 0)) { - // Crop buffer that would be played too late. - rate_adjuster_->Reset(); - total_filled_frames_ = 0; - const int buffer_frames = GetFrameCount(buffer) - current_buffer_offset_; - const int frames_to_crop = - (never_crop_ ? 0 - : std::round(error * input_samples_per_second_ * - playback_rate_ / 1e6)); - if (frames_to_crop > 0 && filled_some_since_resume_) { - AUDIO_LOG(INFO) << this << " cropping " << frames_to_crop - << " frames, buffer ts = " << buffer_timestamp; - } - if (frames_to_crop >= buffer_frames) { - queued_frames_ -= buffer_frames; - queue_.pop_front(); - current_buffer_offset_ = 0; - if (after_silence) { - continue; // Continue to next buffer in the queue. - } - } else { - current_buffer_offset_ += frames_to_crop; - queued_frames_ -= frames_to_crop; - } - - if (!after_silence && !never_crop_) { - timestamped_fader_->AddSilence(0); - return filled; // Fade out. - } - } else { - rate_adjuster_->AddError( - error, SamplesToMicroseconds(total_filled_frames_ / playback_rate_, - input_samples_per_second_)); - } - - int f = FillFromQueue(num_frames - filled, channels, filled); - filled += f; - total_filled_frames_ += f; - after_silence = false; - } - - if (filled_some_since_resume_) { - LogUnderrun(num_frames, filled); - } - if (filled > 0) { - if (!filled_some_since_resume_) { - AUDIO_LOG(INFO) << "Start timestamped playback"; - } - filled_some_since_resume_ = true; - } - return filled; -} - -int MixerInputConnection::FillFromQueue(int num_frames, - float* const* channels, - int write_offset) { - net::IOBuffer* buffer = queue_.front().get(); - const int buffer_frames = GetFrameCount(buffer); - const int frames_to_copy = - std::min(num_frames, buffer_frames - current_buffer_offset_); - DCHECK(frames_to_copy >= 0 && frames_to_copy <= num_frames) - << " frames_to_copy=" << frames_to_copy << " num_frames=" << num_frames - << " buffer_frames=" << buffer_frames << " write_offset=" << write_offset - << " current_buffer_offset_=" << current_buffer_offset_; - - const float* buffer_samples = GetAudioData(buffer); - for (int c = 0; c < num_channels_; ++c) { - const float* buffer_channel = buffer_samples + (buffer_frames * c); - std::copy_n(buffer_channel + current_buffer_offset_, frames_to_copy, - channels[c] + write_offset); - } - queued_frames_ -= frames_to_copy; - - current_buffer_offset_ += frames_to_copy; - if (current_buffer_offset_ == buffer_frames) { - queue_.pop_front(); - current_buffer_offset_ = 0; - } - return frames_to_copy; -} - -void MixerInputConnection::PostPcmCompletion() { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - - mixer_service::Generic message; - auto* push_result = message.mutable_push_result(); - { - base::AutoLock lock(lock_); - push_result->set_delay_timestamp(next_delay_.timestamp_microseconds); - push_result->set_delay(next_delay_.delay_microseconds); - } - socket_->SendProto(kPushResult, message); -} - -void MixerInputConnection::PostEos() { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - mixer_service::Generic message; - message.mutable_eos_played_out(); - socket_->SendProto(kEndOfStream, message); -} - -void MixerInputConnection::PostAudioReadyForPlayback() { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - - if (audio_ready_for_playback_fired_) { - return; - } - AUDIO_LOG(INFO) << this << " ready for playback"; - - mixer_service::Generic message; - auto* ready_for_playback = message.mutable_ready_for_playback(); - { - base::AutoLock lock(lock_); - ready_for_playback->set_delay_microseconds( - mixer_rendering_delay_.delay_microseconds); - } - socket_->SendProto(kReadyForPlayback, message); - audio_ready_for_playback_fired_ = true; -} - -void MixerInputConnection::PostStreamUnderrun() { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - mixer_service::Generic message; - message.mutable_mixer_underrun()->set_type( - mixer_service::MixerUnderrun::INPUT_UNDERRUN); - socket_->SendProto(kUnderrun, message); -} - -void MixerInputConnection::PostOutputUnderrun() { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - mixer_service::Generic message; - message.mutable_mixer_underrun()->set_type( - mixer_service::MixerUnderrun::OUTPUT_UNDERRUN); - socket_->SendProto(kUnderrun, message); -} - -void MixerInputConnection::OnAudioPlaybackError(MixerError error) { - if (error == MixerError::kInputIgnored) { - AUDIO_LOG(INFO) << "Mixer input " << this - << " now being ignored due to output sample rate change"; - } - - io_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MixerInputConnection::PostError, weak_this_, error)); - - base::AutoLock lock(lock_); - mixer_error_ = true; - if (state_ == State::kRemoved) { - RemoveSelf(); - } -} - -void MixerInputConnection::RemoveSelf() { - if (removed_self_) { - return; - } - removed_self_ = true; - mixer_->RemoveInput(this); -} - -void MixerInputConnection::OnOutputUnderrun() { - io_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MixerInputConnection::PostOutputUnderrun, weak_this_)); -} - -void MixerInputConnection::PostError(MixerError error) { - DCHECK(io_task_runner_->RunsTasksInCurrentSequence()); - mixer_service::Generic message; - message.mutable_error()->set_type(mixer_service::Error::INVALID_STREAM_ERROR); - socket_->SendProto(kError, message); - - OnConnectionError(); -} - -void MixerInputConnection::FinalizeAudioPlayback() { - io_task_runner_->DeleteSoon(FROM_HERE, this); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_input_connection.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input_connection.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_input_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_input_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,239 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_INPUT_CONNECTION_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_INPUT_CONNECTION_H_ - -#include -#include -#include - -#include "base/containers/circular_deque.h" -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/synchronization/lock.h" -#include "base/thread_annotations.h" -#include "base/timer/timer.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/media/audio/playback_rate_shifter.h" -#include "chromecast/media/cma/backend/mixer/mixer_input.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/volume_control.h" -#include "media/base/channel_layout.h" -#include "media/base/media_util.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace media { -class AudioBus; -} // namespace media - -namespace net { -class IOBuffer; -} // namespace net - -namespace chromecast { -class IOBufferPool; - -namespace media { -class RateAdjuster; -class StreamMixer; - -namespace mixer_service { -class Generic; -class OutputStreamParams; -} // namespace mixer_service - -// A mixer source that receives audio data from a mixer service connection and -// buffers/fades it as requested before feeding it to the mixer. Must be created -// on an IO thread. This class manages its own lifetime and should not be -// externally deleted. -class MixerInputConnection : public mixer_service::MixerSocket::Delegate, - public MixerInput::Source { - public: - using RenderingDelay = MediaPipelineBackend::AudioDecoder::RenderingDelay; - - MixerInputConnection(StreamMixer* mixer, - std::unique_ptr socket, - const mixer_service::OutputStreamParams& params); - - MixerInputConnection(const MixerInputConnection&) = delete; - MixerInputConnection& operator=(const MixerInputConnection&) = delete; - - // Only public to allow task_runner->DeleteSoon() to work. - ~MixerInputConnection() override; - - private: - friend class MixerServiceReceiver; - class TimestampedFader; - - enum class State { - kUninitialized, // Not initialized by the mixer yet. - kNormalPlayback, // Normal playback. - kGotEos, // Got the end-of-stream buffer (normal playback). - kSignaledEos, // Sent EOS signal up to delegate. - kRemoved, // The caller has removed this source; finish playing out. - }; - - // mixer_service::MixerSocket::Delegate implementation: - bool HandleMetadata(const mixer_service::Generic& message) override; - bool HandleAudioData(char* data, size_t size, int64_t timestamp) override; - bool HandleAudioBuffer(scoped_refptr buffer, - char* data, - size_t size, - int64_t timestamp) override; - void OnConnectionError() override; - - void CreateBufferPool(int frame_count); - void OnInactivityTimeout(); - void RestartPlaybackAt(int64_t timestamp, int64_t pts); - void SetMediaPlaybackRate(double rate); - void SetMediaPlaybackRateLocked(double rate) EXCLUSIVE_LOCKS_REQUIRED(lock_); - void SetAudioClockRate(double rate); - double ChangeAudioRate(double desired_clock_rate, - double error_slope, - double current_error) EXCLUSIVE_LOCKS_REQUIRED(lock_); - void AdjustTimestamps(int64_t timestamp_adjustment); - void SetPaused(bool paused); - - // MixerInput::Source implementation: - size_t num_channels() const override; - ::media::ChannelLayout channel_layout() const override; - int sample_rate() const override; - bool primary() override; - const std::string& device_id() override; - AudioContentType content_type() override; - AudioContentType focus_type() override; - int desired_read_size() override; - int playout_channel() override; - bool active() override; - bool require_clock_rate_simulation() const override; - - void InitializeAudioPlayback(int read_size, - RenderingDelay initial_rendering_delay) override; - int FillAudioPlaybackFrames(int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* buffer) override; - void OnAudioPlaybackError(MixerError error) override; - void OnOutputUnderrun() override; - void FinalizeAudioPlayback() override; - - int FillAudio(int num_frames, - int64_t expected_playout_time, - float* const* channels, - bool after_silence) EXCLUSIVE_LOCKS_REQUIRED(lock_); - int FillTimestampedAudio(int num_frames, - int64_t expected_playout_time, - float* const* channels, - bool after_silence) EXCLUSIVE_LOCKS_REQUIRED(lock_); - int FillFromQueue(int num_frames, float* const* channels, int write_offset) - EXCLUSIVE_LOCKS_REQUIRED(lock_); - void LogUnderrun(int num_frames, int filled) EXCLUSIVE_LOCKS_REQUIRED(lock_); - - void WritePcm(scoped_refptr data); - RenderingDelay QueueData(scoped_refptr data) - EXCLUSIVE_LOCKS_REQUIRED(lock_); - double ExtraDelayFrames() EXCLUSIVE_LOCKS_REQUIRED(lock_); - - void RemoveSelf() EXCLUSIVE_LOCKS_REQUIRED(lock_); - void PostPcmCompletion(); - void PostEos(); - void PostError(MixerError error); - void PostStreamUnderrun(); - void PostOutputUnderrun(); - void PostAudioReadyForPlayback(); - void DropAudio(int64_t frames) EXCLUSIVE_LOCKS_REQUIRED(lock_); - void CheckAndStartPlaybackIfNecessary(int num_frames, - int64_t playback_absolute_timestamp) - EXCLUSIVE_LOCKS_REQUIRED(lock_); - - StreamMixer* const mixer_; - std::unique_ptr socket_; - - const bool ignore_for_stream_count_; - const int fill_size_; - const int algorithm_fill_size_; - const int num_channels_; - const ::media::ChannelLayout channel_layout_; - const int input_samples_per_second_; - const audio_service::SampleFormat sample_format_; - const bool primary_; - const std::string device_id_; - const AudioContentType content_type_; - const AudioContentType focus_type_; - const int playout_channel_; - const bool pts_is_timestamp_; - const int64_t max_timestamp_error_; - const bool never_crop_; - const bool enable_audio_clock_simulation_; - - std::atomic effective_playout_channel_; - - const scoped_refptr io_task_runner_; - int max_queued_frames_; - // Minimum number of frames buffered before starting to fill data. - int start_threshold_frames_; - int min_start_threshold_; - - scoped_refptr buffer_pool_; - - // Only used on the IO thread. - bool audio_ready_for_playback_fired_ = false; - bool never_timeout_connection_ = false; - base::OneShotTimer inactivity_timer_; - bool connection_error_ = false; - int buffer_pool_frames_ = 0; - - base::Lock lock_; - State state_ GUARDED_BY(lock_) = State::kUninitialized; - bool paused_ GUARDED_BY(lock_) = false; - bool mixer_error_ GUARDED_BY(lock_) = false; - scoped_refptr pending_data_ GUARDED_BY(lock_); - base::circular_deque> queue_ GUARDED_BY(lock_); - int queued_frames_ GUARDED_BY(lock_) = 0; - RenderingDelay mixer_rendering_delay_ GUARDED_BY(lock_); - RenderingDelay next_delay_ GUARDED_BY(lock_); - int mixer_read_size_ GUARDED_BY(lock_) = 0; - int current_buffer_offset_ GUARDED_BY(lock_) = 0; - std::unique_ptr rate_adjuster_ GUARDED_BY(lock_); - int64_t total_filled_frames_ GUARDED_BY(lock_) = 0; - bool filled_some_since_resume_ GUARDED_BY(lock_) = false; - const int fade_frames_; - std::unique_ptr timestamped_fader_ GUARDED_BY(lock_); - PlaybackRateShifter rate_shifter_ GUARDED_BY(lock_); - bool in_underrun_ GUARDED_BY(lock_) = false; - bool started_ GUARDED_BY(lock_) = false; - double playback_rate_ GUARDED_BY(lock_) = 1.0; - bool use_start_timestamp_ GUARDED_BY(lock_) = false; - // The absolute timestamp relative to clock monotonic (raw) at which the - // playback should start. INT64_MIN indicates playback should start ASAP. - // INT64_MAX indicates playback should start at a specified timestamp, - // but we don't know what that timestamp is. - int64_t playback_start_timestamp_ GUARDED_BY(lock_) = INT64_MIN; - // The PTS the playback should start at. We will drop audio pushed to us - // with PTS values below this value. If the audio doesn't have a starting - // PTS, then this value can be INT64_MIN, to play whatever audio is sent - // to us. - int64_t playback_start_pts_ GUARDED_BY(lock_) = INT64_MIN; - int remaining_silence_frames_ GUARDED_BY(lock_) = 0; - bool fed_one_silence_buffer_after_removal_ GUARDED_BY(lock_) = false; - bool removed_self_ GUARDED_BY(lock_) = false; - - base::RepeatingClosure pcm_completion_task_; - base::RepeatingClosure eos_task_; - base::RepeatingClosure ready_for_playback_task_; - base::RepeatingClosure post_stream_underrun_task_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_INPUT_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_loopback_connection.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_loopback_connection.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_loopback_connection.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_loopback_connection.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mixer_loopback_connection.h" - -#include - -#include "base/check.h" -#include "chromecast/media/audio/mixer_service/loopback_interrupt_reason.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/net/io_buffer_pool.h" - -namespace chromecast { -namespace media { - -namespace { - -enum MessageTypes : int { - kStreamConfig = 1, - kInterrupt, -}; - -} // namespace - -MixerLoopbackConnection::MixerLoopbackConnection( - std::unique_ptr socket) - : socket_(std::move(socket)) { - DCHECK(socket_); - socket_->SetDelegate(this); -} - -MixerLoopbackConnection::~MixerLoopbackConnection() = default; - -void MixerLoopbackConnection::SetErrorCallback(base::OnceClosure callback) { - if (pending_error_) { - pending_error_ = false; - std::move(callback).Run(); - return; - } - error_callback_ = std::move(callback); -} - -void MixerLoopbackConnection::SetStreamConfig(SampleFormat sample_format, - int sample_rate, - int num_channels, - int data_size) { - mixer_service::Generic message; - mixer_service::StreamConfig* config = message.mutable_stream_config(); - config->set_sample_format(audio_service::ConvertSampleFormat(sample_format)); - config->set_sample_rate(sample_rate); - config->set_num_channels(num_channels); - config->set_data_size(data_size); - socket_->SendProto(kStreamConfig, message); - - sent_stream_config_ = true; -} - -void MixerLoopbackConnection::SendAudio( - scoped_refptr audio_buffer, - int data_size_bytes, - int64_t timestamp) { - DCHECK(sent_stream_config_); - if (!socket_->SendAudioBuffer(std::move(audio_buffer), data_size_bytes, - timestamp)) { - SendInterrupt(LoopbackInterruptReason::kSocketOverflow); - } -} - -void MixerLoopbackConnection::SendInterrupt(LoopbackInterruptReason reason) { - mixer_service::Generic message; - mixer_service::StreamInterruption* interrupt = - message.mutable_stream_interruption(); - interrupt->set_reason( - static_cast( - reason)); - socket_->SendProto(kInterrupt, message); -} - -bool MixerLoopbackConnection::HandleMetadata( - const mixer_service::Generic& message) { - return true; -} - -bool MixerLoopbackConnection::HandleAudioData(char* data, - size_t size, - int64_t timestamp) { - return true; -} - -void MixerLoopbackConnection::OnConnectionError() { - if (error_callback_) { - std::move(error_callback_).Run(); - return; - } - pending_error_ = true; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_loopback_connection.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_loopback_connection.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_loopback_connection.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_loopback_connection.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_LOOPBACK_CONNECTION_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_LOOPBACK_CONNECTION_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/public/media/decoder_config.h" - -namespace net { -class IOBuffer; -} // namespace net - -namespace chromecast { -namespace media { -enum class LoopbackInterruptReason; - -namespace mixer_service { -class Generic; -} // namespace mixer_service - -class MixerLoopbackConnection : public mixer_service::MixerSocket::Delegate { - public: - explicit MixerLoopbackConnection( - std::unique_ptr socket); - - MixerLoopbackConnection(const MixerLoopbackConnection&) = delete; - MixerLoopbackConnection& operator=(const MixerLoopbackConnection&) = delete; - - ~MixerLoopbackConnection() override; - - void SetErrorCallback(base::OnceClosure callback); - - void SetStreamConfig(SampleFormat sample_format, - int sample_rate, - int num_channels, - int data_size); - - void SendAudio(scoped_refptr audio_buffer, - int data_size_bytes, - int64_t timestamp); - - void SendInterrupt(LoopbackInterruptReason reason); - - private: - // mixer_service::MixerSocket::Delegate implementation: - bool HandleMetadata(const mixer_service::Generic& message) override; - bool HandleAudioData(char* data, size_t size, int64_t timestamp) override; - void OnConnectionError() override; - - const std::unique_ptr socket_; - - base::OnceClosure error_callback_; - - bool pending_error_ = false; - bool sent_stream_config_ = false; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_LOOPBACK_CONNECTION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.h" - -namespace chromecast { -namespace media { - -MixerOutputStreamDummy::MixerOutputStreamDummy() = default; - -MixerOutputStreamDummy::~MixerOutputStreamDummy() = default; - -bool MixerOutputStreamDummy::Start(int requested_sample_rate, int channels) { - return true; -} - -int MixerOutputStreamDummy::GetNumChannels() { - return 2; -} - -int MixerOutputStreamDummy::GetSampleRate() { - return 48000; -} - -MediaPipelineBackend::AudioDecoder::RenderingDelay -MixerOutputStreamDummy::GetRenderingDelay() { - return MediaPipelineBackend::AudioDecoder::RenderingDelay(); -} - -int MixerOutputStreamDummy::OptimalWriteFramesCount() { - return 256; -} - -bool MixerOutputStreamDummy::Write(const float* data, - int data_size, - bool* out_playback_interrupted) { - return true; -} - -void MixerOutputStreamDummy::Stop() {} - -// static -std::unique_ptr MixerOutputStream::Create() { - return std::make_unique(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_output_stream_dummy.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_OUTPUT_STREAM_DUMMY -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_OUTPUT_STREAM_DUMMY - -#include "chromecast/public/media/mixer_output_stream.h" - -namespace chromecast { -namespace media { - -// Dummy MixerOutputStream implementation. -class MixerOutputStreamDummy : public MixerOutputStream { - public: - MixerOutputStreamDummy(); - ~MixerOutputStreamDummy() override; - MixerOutputStreamDummy(const MixerOutputStreamDummy&) = delete; - MixerOutputStreamDummy& operator=(const MixerOutputStreamDummy&) = delete; - - // MixerOutputStream implementation: - bool Start(int requested_sample_rate, int channels) override; - int GetNumChannels() override; - int GetSampleRate() override; - MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelay() - override; - int OptimalWriteFramesCount() override; - bool Write(const float* data, - int data_size, - bool* out_playback_interrupted) override; - void Stop() override; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_OUTPUT_STREAM_DUMMY diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_pipeline.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_pipeline.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_pipeline.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_pipeline.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,228 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mixer_pipeline.h" - -#include -#include - -#include "base/containers/flat_set.h" -#include "base/logging.h" -#include "chromecast/media/base/audio_device_ids.h" -#include "chromecast/media/cma/backend/mixer/filter_group.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" -#include "media/audio/audio_device_description.h" - -namespace chromecast { -namespace media { - -namespace { - -bool IsOutputDeviceId(const std::string& device) { - return device == ::media::AudioDeviceDescription::kDefaultDeviceId || - device == ::media::AudioDeviceDescription::kCommunicationsDeviceId || - device == kLocalAudioDeviceId || device == kAlarmAudioDeviceId || - device == kNoDelayDeviceId || device == kLowLatencyDeviceId || - device == kPlatformAudioDeviceId /* e.g. bluetooth and aux */ || - device == kTtsAudioDeviceId || device == kBypassAudioDeviceId; -} - -} // namespace - -// static -std::unique_ptr MixerPipeline::CreateMixerPipeline( - PostProcessingPipelineParser* config, - PostProcessingPipelineFactory* factory, - int expected_input_channels) { - std::unique_ptr mixer_pipeline(new MixerPipeline()); - if (mixer_pipeline->BuildPipeline(config, factory, expected_input_channels)) { - return mixer_pipeline; - } - return nullptr; -} - -MixerPipeline::MixerPipeline() = default; -MixerPipeline::~MixerPipeline() = default; - -bool MixerPipeline::BuildPipeline(PostProcessingPipelineParser* config, - PostProcessingPipelineFactory* factory, - int expected_input_channels) { - DCHECK(config); - DCHECK(factory); - int mix_group_input_channels = -1; - - // Create "stream" processor groups: - for (auto& stream_pipeline : config->GetStreamPipelines()) { - const base::Value::List& device_ids = - stream_pipeline.stream_types->GetList(); - int input_channels = (stream_pipeline.num_input_channels.has_value() - ? stream_pipeline.num_input_channels.value() - : expected_input_channels); - DCHECK(!device_ids.empty()); - DCHECK(device_ids[0].is_string()); - const std::string& name = device_ids[0].GetString(); - LOG(INFO) << input_channels << " input channels to '" << name << "' group"; - - filter_groups_.push_back(std::make_unique( - input_channels, name, stream_pipeline.prerender_pipeline.Clone(), - &stream_pipeline.pipeline, factory, stream_pipeline.volume_limits)); - - if (!SetGroupDeviceIds(stream_pipeline.stream_types, - filter_groups_.back().get())) { - return false; - } - - mix_group_input_channels = - std::max(mix_group_input_channels, - filter_groups_.back()->GetOutputChannelCount()); - } - - if (mix_group_input_channels == -1) { - mix_group_input_channels = expected_input_channels; - } - - // Create "mix" processor group: - const auto mix_pipeline = config->GetMixPipeline(); - if (mix_pipeline.num_input_channels.has_value()) { - mix_group_input_channels = mix_pipeline.num_input_channels.value(); - } - LOG(INFO) << mix_group_input_channels << " input channels to 'mix' group"; - auto mix_filter = std::make_unique( - mix_group_input_channels, "mix", mix_pipeline.prerender_pipeline.Clone(), - &mix_pipeline.pipeline, factory, mix_pipeline.volume_limits); - for (std::unique_ptr& group : filter_groups_) { - mix_filter->AddMixedInput(group.get()); - } - if (!SetGroupDeviceIds(mix_pipeline.stream_types, mix_filter.get())) { - return false; - } - loopback_output_group_ = mix_filter.get(); - filter_groups_.push_back(std::move(mix_filter)); - - // Create "linearize" processor group: - const auto linearize_pipeline = config->GetLinearizePipeline(); - int linearize_group_input_channels = - loopback_output_group_->GetOutputChannelCount(); - if (linearize_pipeline.num_input_channels.has_value()) { - linearize_group_input_channels = - linearize_pipeline.num_input_channels.value(); - } - LOG(INFO) << linearize_group_input_channels - << " input channels to 'linearize' group"; - filter_groups_.push_back(std::make_unique( - linearize_group_input_channels, "linearize", - linearize_pipeline.prerender_pipeline.Clone(), - &linearize_pipeline.pipeline, factory, linearize_pipeline.volume_limits)); - output_group_ = filter_groups_.back().get(); - output_group_->AddMixedInput(loopback_output_group_); - if (!SetGroupDeviceIds(linearize_pipeline.stream_types, output_group_)) { - return false; - } - - // If no default group is provided, use the "mix" group. - if (stream_sinks_.find(::media::AudioDeviceDescription::kDefaultDeviceId) == - stream_sinks_.end()) { - stream_sinks_[::media::AudioDeviceDescription::kDefaultDeviceId] = - loopback_output_group_; - } - - return true; -} - -bool MixerPipeline::SetGroupDeviceIds(const base::Value* ids, - FilterGroup* filter_group) { - if (!ids) { - return true; - } - DCHECK(filter_group); - DCHECK(ids->is_list()); - - for (const base::Value& stream_type_val : ids->GetList()) { - DCHECK(stream_type_val.is_string()); - const std::string& stream_type = stream_type_val.GetString(); - if (!IsOutputDeviceId(stream_type)) { - LOG(ERROR) << stream_type - << " is not a stream type. Stream types are listed " - << "in chromecast/media/base/audio_device_ids.cc and " - << "media/audio/audio_device_description.cc"; - return false; - } - if (stream_sinks_.find(stream_type) != stream_sinks_.end()) { - LOG(ERROR) << "Multiple instances of stream type '" << stream_type - << "' in cast_audio.json"; - return false; - } - stream_sinks_[stream_type] = filter_group; - filter_group->AddStreamType(stream_type); - } - return true; -} - -void MixerPipeline::Initialize(int output_samples_per_second, - int frames_per_write) { - // The output group will recursively set the sample rate of all other - // FilterGroups. - AudioPostProcessor2::Config config; - config.output_sample_rate = output_samples_per_second; - config.system_output_sample_rate = output_samples_per_second; - config.output_frames_per_write = frames_per_write; - output_group_->Initialize(config); - output_group_->PrintTopology(); -} - -FilterGroup* MixerPipeline::GetInputGroup(const std::string& device_id) { - auto got = stream_sinks_.find(device_id); - if (got != stream_sinks_.end()) { - return got->second; - } - - return stream_sinks_[::media::AudioDeviceDescription::kDefaultDeviceId]; -} - -void MixerPipeline::MixAndFilter( - int frames_per_write, - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay) { - output_group_->MixAndFilter(frames_per_write, rendering_delay); -} - -float* MixerPipeline::GetLoopbackOutput() { - return loopback_output_group_->GetOutputBuffer(); -} - -float* MixerPipeline::GetOutput() { - return output_group_->GetOutputBuffer(); -} - -int MixerPipeline::GetLoopbackChannelCount() const { - return loopback_output_group_->GetOutputChannelCount(); -} - -int MixerPipeline::GetOutputChannelCount() const { - return output_group_->GetOutputChannelCount(); -} - -int64_t MixerPipeline::GetPostLoopbackRenderingDelayMicroseconds() const { - return output_group_->GetRenderingDelayMicroseconds(); -} - -void MixerPipeline::SetPostProcessorConfig(const std::string& name, - const std::string& config) { - for (auto&& filter_group : filter_groups_) { - filter_group->SetPostProcessorConfig(name, config); - } -} - -bool MixerPipeline::IsRinging() const { - for (auto& filter_group : filter_groups_) { - if (filter_group->IsRinging()) { - return true; - } - } - return false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_pipeline.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_pipeline.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_pipeline.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_pipeline.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_PIPELINE_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_PIPELINE_H_ - -#include -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "chromecast/public/media/audio_post_processor_shlib.h" -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace base { -class Value; -} // namespace base - -namespace chromecast { -namespace media { - -class FilterGroup; -class PostProcessingPipelineParser; -class PostProcessingPipelineFactory; - -// Provides mixer and post-processing functionality for StreamMixer. -// Internally, MixerPipeline is a tree of post processors with two taps - -// LoopbackOutput and Output. Calling MixAndFilter causes the pipeline to pull -// data from inputs, mixing and filtering as described in cast_audio.json. -class MixerPipeline { - public: - // Attempts to create a pipeline from |config|. - // Returns nullptr if config fails to parse. - static std::unique_ptr CreateMixerPipeline( - PostProcessingPipelineParser* parser, - PostProcessingPipelineFactory* factory, - int expected_input_channels); - - MixerPipeline(const MixerPipeline&) = delete; - MixerPipeline& operator=(const MixerPipeline&) = delete; - - ~MixerPipeline(); - - // Sets the sample rate of all processors. - void Initialize(int samples_per_second, int frames_per_write); - - // Returns the FilterGroup that should process a stream with |device_id| or - // |nullptr| if no matching FilterGroup is found. - FilterGroup* GetInputGroup(const std::string& device_id); - - // Polls |MixerInput|s for |frames_per_write| frames of audio data, mixes the - // inputs, and applies PostProcessors. - // |rendering_delay| is the rendering delay of the output device, and is used - // to calculate the delay from various points in the pipeline. - void MixAndFilter( - int frames_per_write, - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay); - - // Returns the output data from the "mix" group. - float* GetLoopbackOutput(); - - // Returns the output data from the "linearize" group. - float* GetOutput(); - - // Returns the number of channels that will be present in GetLoopbackOutput(). - int GetLoopbackChannelCount() const; - - // Returns the number of channels that will be present in GetOutput(). - int GetOutputChannelCount() const; - - // Attempts to send |config| to PostProcessors with |name|. - void SetPostProcessorConfig(const std::string& name, - const std::string& config); - - // Returns the rendering delay between audio coming from GetLoopbackOutput() - // and GetOutput(), i.e. the group delay of PostProcessors in "linearize" - int64_t GetPostLoopbackRenderingDelayMicroseconds() const; - - // Determines whether the pipeline is still ringing out after all input - // streams have stopped playing. - bool IsRinging() const; - - private: - // External classes should call CreateMixerPipeline. - MixerPipeline(); - - // Attempts to build a pipeline using |config|. Returns |true| IFF successful. - bool BuildPipeline(PostProcessingPipelineParser* config, - PostProcessingPipelineFactory* factory, - int expected_input_channels); - - // Adds |ids| to the list of DeviceIds |filter_group| can process. - bool SetGroupDeviceIds(const base::Value* ids, FilterGroup* filter_group); - - std::vector> filter_groups_; - base::flat_map stream_sinks_; - FilterGroup* loopback_output_group_ = nullptr; - FilterGroup* output_group_ = nullptr; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_PIPELINE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_service_receiver.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_service_receiver.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_service_receiver.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_service_receiver.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,202 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mixer_service_receiver.h" - -#include -#include - -#include "base/logging.h" -#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/audio/net/common.pb.h" -#include "chromecast/media/audio/net/conversions.h" -#include "chromecast/media/cma/backend/mixer/audio_output_redirector.h" -#include "chromecast/media/cma/backend/mixer/loopback_handler.h" -#include "chromecast/media/cma/backend/mixer/mixer_input_connection.h" -#include "chromecast/media/cma/backend/mixer/mixer_loopback_connection.h" -#include "chromecast/media/cma/backend/mixer/post_processor_registry.h" -#include "chromecast/media/cma/backend/mixer/stream_mixer.h" - -namespace chromecast { -namespace media { - -namespace { - -enum MessageTypes : int { - kStreamCounts = 1, - kPostProcessorList, -}; - -} // namespace - -class MixerServiceReceiver::ControlConnection - : public mixer_service::MixerSocket::Delegate { - public: - ControlConnection(StreamMixer* mixer, - MixerServiceReceiver* receiver, - std::unique_ptr socket) - : mixer_(mixer), receiver_(receiver), socket_(std::move(socket)) { - DCHECK(mixer_); - DCHECK(receiver_); - DCHECK(socket_); - - socket_->SetDelegate(this); - } - - ControlConnection(const ControlConnection&) = delete; - ControlConnection& operator=(const ControlConnection&) = delete; - - ~ControlConnection() override = default; - - void OnStreamCountChanged() { - if (!send_stream_count_) { - return; - } - mixer_service::Generic message; - auto* counts = message.mutable_stream_count(); - counts->set_primary(receiver_->primary_stream_count_); - counts->set_sfx(receiver_->sfx_stream_count_); - socket_->SendProto(kStreamCounts, message); - } - - private: - friend class MixerServiceReceiver; - - // mixer_service::MixerSocket::Delegate implementation: - bool HandleMetadata(const mixer_service::Generic& message) override { - if (message.has_set_volume_limit()) { - mixer_->SetOutputLimit( - audio_service::ConvertContentType( - message.set_volume_limit().content_type()), - message.set_volume_limit().max_volume_multiplier()); - } - if (message.has_set_device_muted()) { - mixer_->SetMuted(audio_service::ConvertContentType( - message.set_device_muted().content_type()), - message.set_device_muted().muted()); - } - if (message.has_set_device_volume()) { - mixer_->SetVolume(audio_service::ConvertContentType( - message.set_device_volume().content_type()), - message.set_device_volume().volume_multiplier()); - } - if (message.has_list_postprocessors()) { - OnListPostprocessors(); - } - if (message.has_configure_postprocessor()) { - mixer_->SetPostProcessorConfig( - message.configure_postprocessor().name(), - message.configure_postprocessor().config()); - } - if (message.has_reload_postprocessors()) { - mixer_->ResetPostProcessors([](bool, const std::string&) {}); - } - if (message.has_request_stream_count()) { - send_stream_count_ = message.request_stream_count().subscribe(); - OnStreamCountChanged(); - } - if (message.has_set_num_output_channels()) { - mixer_->SetNumOutputChannels( - message.set_num_output_channels().channels()); - } - - return true; - } - - bool HandleAudioData(char* data, size_t size, int64_t timestamp) override { - return true; - } - - bool HandleAudioBuffer(scoped_refptr buffer, - char* data, - size_t size, - int64_t timestamp) override { - return true; - } - - void OnListPostprocessors() { - mixer_service::Generic message; - auto* postprocessor_list = message.mutable_postprocessor_list(); - for (const auto& library_pair : PostProcessorRegistry::Get()->Libraries()) { - postprocessor_list->add_postprocessors(library_pair.first); - } - socket_->SendProto(kPostProcessorList, message); - } - - void OnConnectionError() override { - receiver_->RemoveControlConnection(this); - } - - StreamMixer* const mixer_; - MixerServiceReceiver* const receiver_; - const std::unique_ptr socket_; - - bool send_stream_count_ = false; -}; - -MixerServiceReceiver::MixerServiceReceiver(StreamMixer* mixer, - LoopbackHandler* loopback_handler) - : mixer_(mixer), loopback_handler_(loopback_handler) { - DCHECK(mixer_); - DCHECK(loopback_handler_); -} - -MixerServiceReceiver::~MixerServiceReceiver() = default; - -void MixerServiceReceiver::OnStreamCountChanged(int primary, int sfx) { - primary_stream_count_ = primary; - sfx_stream_count_ = sfx; - - for (const auto& control : control_connections_) { - control.second->OnStreamCountChanged(); - } -} - -void MixerServiceReceiver::CreateOutputStream( - std::unique_ptr socket, - const mixer_service::Generic& message) { - DCHECK(message.has_output_stream_params()); - // MixerInputConnection manages its own lifetime. - auto* connection = new MixerInputConnection(mixer_, std::move(socket), - message.output_stream_params()); - connection->HandleMetadata(message); -} - -void MixerServiceReceiver::CreateLoopbackConnection( - std::unique_ptr socket, - const mixer_service::Generic& message) { - auto connection = - std::make_unique(std::move(socket)); - loopback_handler_->AddConnection(std::move(connection)); -} - -void MixerServiceReceiver::CreateAudioRedirection( - std::unique_ptr socket, - const mixer_service::Generic& message) { - if (message.redirection_request().has_num_channels() && - message.redirection_request().num_channels() <= 0) { - LOG(INFO) << "Bad redirection request"; - return; - } - mixer_->AddAudioOutputRedirector(std::make_unique( - mixer_, std::move(socket), message)); -} - -void MixerServiceReceiver::CreateControlConnection( - std::unique_ptr socket, - const mixer_service::Generic& message) { - auto connection = - std::make_unique(mixer_, this, std::move(socket)); - ControlConnection* ptr = connection.get(); - control_connections_[ptr] = std::move(connection); - ptr->HandleMetadata(message); -} - -void MixerServiceReceiver::RemoveControlConnection(ControlConnection* ptr) { - control_connections_.erase(ptr); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_service_receiver.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_service_receiver.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mixer_service_receiver.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mixer_service_receiver.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,65 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_SERVICE_RECEIVER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_SERVICE_RECEIVER_H_ - -#include - -#include "base/containers/flat_map.h" -#include "chromecast/media/audio/mixer_service/receiver/receiver.h" - -namespace chromecast { -namespace media { -class LoopbackHandler; -class StreamMixer; - -namespace mixer_service { -class Generic; -class MixerSocket; -} // namespace mixer_service - -class MixerServiceReceiver : public mixer_service::Receiver { - public: - MixerServiceReceiver(StreamMixer* mixer, LoopbackHandler* loopback_handler); - - MixerServiceReceiver(const MixerServiceReceiver&) = delete; - MixerServiceReceiver& operator=(const MixerServiceReceiver&) = delete; - - ~MixerServiceReceiver() override; - - // Called by the mixer when the active stream count changes. - void OnStreamCountChanged(int primary, int sfx); - - private: - class ControlConnection; - - // mixer_service::Receiver implementation: - void CreateOutputStream(std::unique_ptr socket, - const mixer_service::Generic& message) override; - void CreateLoopbackConnection( - std::unique_ptr socket, - const mixer_service::Generic& message) override; - void CreateAudioRedirection( - std::unique_ptr socket, - const mixer_service::Generic& message) override; - void CreateControlConnection( - std::unique_ptr socket, - const mixer_service::Generic& message) override; - - void RemoveControlConnection(ControlConnection* ptr); - - StreamMixer* const mixer_; - LoopbackHandler* const loopback_handler_; - - base::flat_map> - control_connections_; - int primary_stream_count_ = 0; - int sfx_stream_count_ = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MIXER_SERVICE_RECEIVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_mixer_source.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_mixer_source.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_mixer_source.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_mixer_source.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mock_mixer_source.h" - -#include -#include - -#include "base/check_op.h" -#include "media/base/audio_bus.h" - -using testing::_; - -namespace chromecast { -namespace media { - -MockMixerSource::MockMixerSource(int samples_per_second, - const std::string& device_id) - : samples_per_second_(samples_per_second), device_id_(device_id) { - DCHECK_GT(num_channels_, 0); - ON_CALL(*this, FillAudioPlaybackFrames(_, _, _)) - .WillByDefault(testing::Invoke(this, &MockMixerSource::GetData)); -} -MockMixerSource::~MockMixerSource() = default; - -void MockMixerSource::SetData(std::unique_ptr<::media::AudioBus> data) { - data_ = std::move(data); - data_offset_ = 0; -} - -int MockMixerSource::GetData(int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* buffer) { - CHECK(buffer); - CHECK_GE(buffer->frames(), num_frames); - if (data_) { - int frames_to_copy = std::min(num_frames, data_->frames() - data_offset_); - data_->CopyPartialFramesTo(data_offset_, frames_to_copy, 0, buffer); - data_offset_ += frames_to_copy; - return frames_to_copy; - } else { - return 0; - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_mixer_source.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_mixer_source.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_mixer_source.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_mixer_source.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_MIXER_SOURCE_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_MIXER_SOURCE_H_ - -#include -#include - -#include "chromecast/media/cma/backend/mixer/mixer_input.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/audio_device_description.h" -#include "media/base/channel_layout.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace media { -class AudioBus; -} // namespace media - -namespace chromecast { -namespace media { - -class MockMixerSource : public MixerInput::Source { - public: - using RenderingDelay = MixerInput::RenderingDelay; - - MockMixerSource(int samples_per_second, - const std::string& device_id = - ::media::AudioDeviceDescription::kDefaultDeviceId); - - MockMixerSource(const MockMixerSource&) = delete; - MockMixerSource& operator=(const MockMixerSource&) = delete; - - ~MockMixerSource() override; - - // MixerInput::Source implementation: - size_t num_channels() const override { return num_channels_; } - ::media::ChannelLayout channel_layout() const override { - return channel_layout_; - } - int sample_rate() const override { return samples_per_second_; } - bool primary() override { return primary_; } - const std::string& device_id() override { return device_id_; } - AudioContentType content_type() override { return content_type_; } - AudioContentType focus_type() override { return focus_type_; } - int desired_read_size() override { return 1; } - int playout_channel() override { return playout_channel_; } - bool active() override { return true; } - bool require_clock_rate_simulation() const override { return false; } - - MOCK_METHOD2(InitializeAudioPlayback, void(int, RenderingDelay)); - MOCK_METHOD3(FillAudioPlaybackFrames, - int(int, RenderingDelay, ::media::AudioBus*)); - MOCK_METHOD1(OnAudioPlaybackError, void(MixerError)); - MOCK_METHOD0(FinalizeAudioPlayback, void()); - - // Setters and getters for test control. - void SetData(std::unique_ptr<::media::AudioBus> data); - - void set_num_channels(int num_channels) { num_channels_ = num_channels; } - void set_channel_layout(::media::ChannelLayout channel_layout) { - channel_layout_ = channel_layout; - } - void set_primary(bool primary) { primary_ = primary; } - void set_content_type(AudioContentType content_type) { - content_type_ = content_type; - if (!set_focus_type_) { - focus_type_ = content_type; - } - } - void set_focus_type(AudioContentType focus_type) { - focus_type_ = focus_type; - set_focus_type_ = true; - } - void set_playout_channel(int channel) { playout_channel_ = channel; } - void set_multiplier(float multiplier) { multiplier_ = multiplier; } - float multiplier() const { return multiplier_; } - - const ::media::AudioBus& data() { return *data_; } - - private: - int GetData(int num_frames, - RenderingDelay rendering_delay, - ::media::AudioBus* buffer); - - const int samples_per_second_; - bool primary_ = true; - int num_channels_ = 2; - ::media::ChannelLayout channel_layout_ = ::media::CHANNEL_LAYOUT_STEREO; - const std::string device_id_; - AudioContentType content_type_ = AudioContentType::kMedia; - AudioContentType focus_type_ = AudioContentType::kMedia; - bool set_focus_type_ = false; - int playout_channel_ = kChannelAll; - float multiplier_ = 1.0f; - - std::unique_ptr<::media::AudioBus> data_; - int data_offset_ = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_MIXER_SOURCE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_post_processor_factory.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_post_processor_factory.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_post_processor_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_post_processor_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mock_post_processor_factory.h" - -#include "base/check.h" -#include "base/values.h" - -namespace chromecast { -namespace media { - -using testing::_; -using testing::NiceMock; - -MockPostProcessor::MockPostProcessor(MockPostProcessorFactory* factory, - const std::string& name, - const base::Value* filter_description_list, - int channels) - : factory_(factory), name_(name), num_output_channels_(channels) { - DCHECK(factory_); - CHECK(factory_->instances.insert({name_, this}).second); - - ON_CALL(*this, ProcessFrames(_, _, _, _, _)) - .WillByDefault( - testing::Invoke(this, &MockPostProcessor::DoProcessFrames)); - - if (!filter_description_list) { - // This happens for PostProcessingPipeline with no post-processors. - return; - } - - // Parse |filter_description_list| for parameters. - for (const base::Value& elem : filter_description_list->GetList()) { - CHECK(elem.is_dict()); - const std::string* solib = elem.GetDict().FindString("processor"); - CHECK(solib); - - if (*solib == "delay.so") { - const base::Value::Dict* processor_config_dict = - elem.GetDict().FindDict("config"); - CHECK(processor_config_dict); - std::optional delay = processor_config_dict->FindInt("delay"); - CHECK(delay.has_value()); - rendering_delay_frames_ += *delay; - std::optional ringing = processor_config_dict->FindBool("ringing"); - if (ringing.has_value()) { - ringing_ = *ringing; - } - - std::optional output_ch = - processor_config_dict->FindInt("output_channels"); - if (output_ch.has_value()) { - num_output_channels_ = *output_ch; - } - } - } -} - -MockPostProcessor::~MockPostProcessor() { - factory_->instances.erase(name_); -} - -std::unique_ptr -MockPostProcessorFactory::CreatePipeline( - const std::string& name, - const base::Value* filter_description_list, - int channels) { - return std::make_unique>( - this, name, filter_description_list, channels); -} - -MockPostProcessorFactory::MockPostProcessorFactory() = default; -MockPostProcessorFactory::~MockPostProcessorFactory() = default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_post_processor_factory.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_post_processor_factory.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_post_processor_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_post_processor_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,93 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_POST_PROCESSOR_FACTORY_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_POST_PROCESSOR_FACTORY_H_ - -#include -#include -#include - -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace base { -class Value; -} // namespace base - -namespace chromecast { -namespace media { - -class MockPostProcessorFactory; -class MockPostProcessor : public PostProcessingPipeline { - public: - MockPostProcessor(MockPostProcessorFactory* factory, - const std::string& name, - const base::Value* filter_description_list, - int channels); - - MockPostProcessor(const MockPostProcessor&) = delete; - MockPostProcessor& operator=(const MockPostProcessor&) = delete; - - ~MockPostProcessor() override; - MOCK_METHOD5(ProcessFrames, - void(float* data, - int num_frames, - float current_volume, - float target_volume, - bool is_silence)); - MOCK_METHOD1(SetContentType, void(AudioContentType)); - bool SetOutputConfig(const AudioPostProcessor2::Config& config) override { - sample_rate_ = config.output_sample_rate; - return true; - } - int GetInputSampleRate() const override { return sample_rate_; } - bool IsRinging() override { return ringing_; } - int delay() { return rendering_delay_frames_; } - std::string name() const { return name_; } - float* GetOutputBuffer() override { return output_buffer_; } - int NumOutputChannels() const override { return num_output_channels_; } - - MOCK_METHOD2(SetPostProcessorConfig, - void(const std::string& name, const std::string& config)); - MOCK_METHOD1(UpdatePlayoutChannel, void(int)); - double GetDelaySeconds() override { - return static_cast(rendering_delay_frames_) / sample_rate_; - } - - private: - void DoProcessFrames(float* data, - int num_frames, - float current_volume, - float target_volume, - bool is_silence) { - output_buffer_ = data; - } - - MockPostProcessorFactory* const factory_; - const std::string name_; - int sample_rate_; - int rendering_delay_frames_ = 0; - bool ringing_ = false; - float* output_buffer_ = nullptr; - int num_output_channels_; -}; - -class MockPostProcessorFactory : public PostProcessingPipelineFactory { - public: - MockPostProcessorFactory(); - ~MockPostProcessorFactory() override; - std::unique_ptr CreatePipeline( - const std::string& name, - const base::Value* filter_description_list, - int channels) override; - - std::unordered_map instances; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_POST_PROCESSOR_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/mock_redirected_audio_output.h" - -#include - -#include "base/check.h" -#include "media/base/audio_bus.h" - -using testing::_; - -namespace chromecast { -namespace media { - -MockRedirectedAudioOutput::MockRedirectedAudioOutput( - const mixer_service::RedirectedAudioConnection::Config& config) - : config_(config), - connection_(config_, this), - last_output_timestamp_(INT64_MIN) { - ON_CALL(*this, OnRedirectedAudio(_, _, _)) - .WillByDefault(testing::Invoke( - this, &MockRedirectedAudioOutput::HandleRedirectedAudio)); - connection_.Connect(); -} - -MockRedirectedAudioOutput::~MockRedirectedAudioOutput() = default; - -void MockRedirectedAudioOutput::SetStreamMatchPatterns( - std::vector> patterns) { - connection_.SetStreamMatchPatterns(std::move(patterns)); -} - -void MockRedirectedAudioOutput::HandleRedirectedAudio(int64_t timestamp, - float* data, - int frames) { - CHECK(data); - last_buffer_ = ::media::AudioBus::Create(config_.num_output_channels, frames); - for (int c = 0; c < config_.num_output_channels; ++c) { - std::copy_n(data + c * frames, frames, last_buffer_->channel(c)); - } - - last_output_timestamp_ = timestamp; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/mock_redirected_audio_output.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_REDIRECTED_AUDIO_OUTPUT_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_REDIRECTED_AUDIO_OUTPUT_H_ - -#include -#include -#include -#include -#include - -#include "chromecast/media/audio/mixer_service/redirected_audio_connection.h" -#include "chromecast/public/volume_control.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace media { -class AudioBus; -} // namespace media - -namespace chromecast { -namespace media { - -class MockRedirectedAudioOutput - : public mixer_service::RedirectedAudioConnection::Delegate { - public: - explicit MockRedirectedAudioOutput( - const mixer_service::RedirectedAudioConnection::Config& config); - - MockRedirectedAudioOutput(const MockRedirectedAudioOutput&) = delete; - MockRedirectedAudioOutput& operator=(const MockRedirectedAudioOutput&) = - delete; - - ~MockRedirectedAudioOutput() override; - - ::media::AudioBus* last_buffer() const { return last_buffer_.get(); } - int64_t last_output_timestamp() const { return last_output_timestamp_; } - - MOCK_METHOD3(OnRedirectedAudio, void(int64_t, float*, int)); - MOCK_METHOD1(SetSampleRate, void(int)); - - void SetStreamMatchPatterns( - std::vector> patterns); - - private: - void HandleRedirectedAudio(int64_t timestamp, - float* data, - int frames); - - const mixer_service::RedirectedAudioConnection::Config config_; - mixer_service::RedirectedAudioConnection connection_; - - std::unique_ptr<::media::AudioBus> last_buffer_; - int64_t last_output_timestamp_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_MOCK_REDIRECTED_AUDIO_OUTPUT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_H_ - -#include -#include -#include - -#include "chromecast/public/media/audio_post_processor2_shlib.h" -#include "chromecast/public/volume_control.h" - -namespace base { -class Value; -} // namespace base - -namespace chromecast { -namespace media { - -class PostProcessingPipeline { - public: - virtual ~PostProcessingPipeline() = default; - - virtual void ProcessFrames(float* data, - int num_frames, - float current_multiplier, - float target_volume, - bool is_silence) = 0; - virtual float* GetOutputBuffer() = 0; - virtual int NumOutputChannels() const = 0; - - virtual bool SetOutputConfig( - const AudioPostProcessor2::Config& output_config) = 0; - virtual int GetInputSampleRate() const = 0; - virtual bool IsRinging() = 0; - virtual void SetPostProcessorConfig(const std::string& name, - const std::string& config) = 0; - virtual void SetContentType(AudioContentType content_type) = 0; - virtual void UpdatePlayoutChannel(int channel) = 0; - // Returns the rendering delay in seconds. - virtual double GetDelaySeconds() = 0; -}; - -class PostProcessingPipelineFactory { - public: - virtual ~PostProcessingPipelineFactory() = default; - - virtual std::unique_ptr CreatePipeline( - const std::string& name, - const base::Value* filter_description_list, - int num_channels) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,293 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h" - -#include -#include -#include - -#include "base/files/file_path.h" -#include "base/json/json_writer.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/scoped_native_library.h" -#include "base/values.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -namespace { - -// Used for AudioPostProcessor(1) -const char kJsonKeyProcessor[] = "processor"; - -// Used for AudioPostProcessor2 -const char kJsonKeyLib[] = "lib"; - -const char kJsonKeyName[] = "name"; -const char kJsonKeyConfig[] = "config"; - -} // namespace - -PostProcessingPipelineFactoryImpl::PostProcessingPipelineFactoryImpl() = - default; -PostProcessingPipelineFactoryImpl::~PostProcessingPipelineFactoryImpl() = - default; - -std::unique_ptr -PostProcessingPipelineFactoryImpl::CreatePipeline( - const std::string& name, - const base::Value* filter_description_list, - int num_channels) { - return std::make_unique( - name, filter_description_list, num_channels); -} - -PostProcessingPipelineImpl::PostProcessingPipelineImpl( - const std::string& name, - const base::Value* filter_description_list, - int channels) - : name_(name), num_output_channels_(channels) { - if (!filter_description_list) { - return; // Warning logged. - } - - LOG(INFO) << "Create pipeline for " << channels << " input channels"; - for (const base::Value& processor_description_value : - filter_description_list->GetList()) { - DCHECK(processor_description_value.is_dict()); - const base::Value::Dict& processor_description_dict = - processor_description_value.GetDict(); - - std::string processor_name; - const std::string* name_val = - processor_description_dict.FindString(kJsonKeyName); - if (name_val) { - processor_name = *name_val; - } - - if (!processor_name.empty()) { - std::vector::iterator it = - find_if(processors_.begin(), processors_.end(), - [&processor_name](PostProcessorInfo& p) { - return p.name == processor_name; - }); - LOG_IF(DFATAL, it != processors_.end()) - << "Duplicate postprocessor name " << processor_name; - } - - std::string library_path; - - // Keys for AudioPostProcessor2: - const std::string* library_val = - processor_description_dict.FindString(kJsonKeyLib); - if (library_val) { - library_path = *library_val; - } else { - // Keys for AudioPostProcessor - // TODO(bshaya): Remove when AudioPostProcessor support is removed. - library_val = processor_description_dict.FindString(kJsonKeyProcessor); - DCHECK(library_val) << "Post processor description is missing key " - << kJsonKeyLib; - library_path = *library_val; - } - - std::string processor_config_string; - const base::Value* processor_config_val = - processor_description_dict.Find(kJsonKeyConfig); - if (processor_config_val) { - DCHECK(processor_config_val->is_dict() || - processor_config_val->is_string()); - base::JSONWriter::Write(*processor_config_val, &processor_config_string); - } - - LOG(INFO) << "Creating '" << processor_name << "', an instance of " - << library_path << ", for " << channels << " channels"; - - processors_.emplace_back(PostProcessorInfo{ - factory_.CreatePostProcessor(library_path, processor_config_string, - channels), - 1 /* output_frames_per_input_frame */, processor_name}); - channels = processors_.back().ptr->GetStatus().output_channels; - } - num_output_channels_ = channels; - LOG(INFO) << "Created pipeline with " << channels << " output channels"; -} - -PostProcessingPipelineImpl::~PostProcessingPipelineImpl() = default; - -void PostProcessingPipelineImpl::ProcessFrames(float* data, - int num_input_frames, - float current_multiplier, - float target_multiplier, - bool is_silence) { - DCHECK_GT(input_sample_rate_, 0); - DCHECK(data); - if (processors_.size() > 0) { - DCHECK_EQ(processors_[0].input_frames_per_write, num_input_frames); - } - - output_buffer_ = data; - - if (is_silence) { - if (!IsRinging()) { - // If the input sample rate differs from the output sample rate, then the - // input data will be the incorrect size without any resampling. Output a - // zeroed buffer of correct size. - if (input_sample_rate_ != output_sample_rate_) { - // We cannot guarantee that the consumer of the output buffer will not - // mutate it, so set it back to zero. - std::fill_n(silence_buffer_.data(), silence_buffer_.size(), 0.0); - output_buffer_ = silence_buffer_.data(); - } - return; - } - silence_frames_processed_ += num_input_frames; - } else { - silence_frames_processed_ = 0; - } - - UpdateCastVolume(current_multiplier, target_multiplier); - AudioPostProcessor2::Metadata metadata = {current_dbfs_, target_dbfs_, - cast_volume_}; - - delay_s_ = 0; - for (auto& processor : processors_) { - processor.ptr->ProcessFrames(output_buffer_, - processor.input_frames_per_write, &metadata); - const auto& status = processor.ptr->GetStatus(); - delay_s_ += static_cast(status.rendering_delay_frames) / - status.input_sample_rate; - output_buffer_ = status.output_buffer; - } -} - -int PostProcessingPipelineImpl::NumOutputChannels() const { - return num_output_channels_; -} - -float* PostProcessingPipelineImpl::GetOutputBuffer() { - DCHECK(output_buffer_); - return output_buffer_; -} - -bool PostProcessingPipelineImpl::SetOutputConfig( - const AudioPostProcessor2::Config& output_config) { - output_sample_rate_ = output_config.output_sample_rate; - AudioPostProcessor2::Config processor_config = output_config; - - // Each Processor's output rate must be the following processor's input rate. - for (int i = static_cast(processors_.size()) - 1; i >= 0; --i) { - if (!processors_[i].ptr->SetConfig(processor_config)) { - return false; - } - int input_sample_rate = processors_[i].ptr->GetStatus().input_sample_rate; - DCHECK_GT(input_sample_rate, 0) - << processors_[i].name << " did not set its sample rate"; - processors_[i].input_frames_per_write = - processor_config.output_frames_per_write * input_sample_rate / - processor_config.output_sample_rate; - processor_config.output_sample_rate = input_sample_rate; - processor_config.output_frames_per_write = - processors_[i].input_frames_per_write; - } - - input_sample_rate_ = processor_config.output_sample_rate; - ringing_time_in_frames_ = GetRingingTimeInFrames(); - silence_frames_processed_ = 0; - - if (input_sample_rate_ != output_sample_rate_) { - size_t silence_size = num_output_channels_ * - processors_[0].input_frames_per_write * - output_sample_rate_ / input_sample_rate_; - silence_buffer_.resize(silence_size); - } - - delay_s_ = 0; - for (auto& processor : processors_) { - const auto& status = processor.ptr->GetStatus(); - delay_s_ += static_cast(status.rendering_delay_frames) / - status.input_sample_rate; - } - - return true; -} - -int PostProcessingPipelineImpl::GetInputSampleRate() const { - return input_sample_rate_; -} - -bool PostProcessingPipelineImpl::IsRinging() { - return ringing_time_in_frames_ < 0 || - silence_frames_processed_ < ringing_time_in_frames_; -} - -int PostProcessingPipelineImpl::GetRingingTimeInFrames() { - int memory_frames = 0; - for (auto& processor : processors_) { - int ringing_time = processor.ptr->GetStatus().ringing_time_frames; - if (ringing_time < 0) { - return -1; - } - memory_frames += ringing_time; - } - return memory_frames; -} - -void PostProcessingPipelineImpl::UpdateCastVolume(float multiplier, - float target) { - DCHECK_GE(multiplier, 0.0); - - if (multiplier != current_multiplier_) { - current_multiplier_ = multiplier; - current_dbfs_ = - (multiplier == 0.0f ? -200.0f : std::log10(multiplier) * 20); - DCHECK(chromecast::media::VolumeControl::DbFSToVolume); - cast_volume_ = - chromecast::media::VolumeControl::DbFSToVolume(current_dbfs_); - } - - if (target != target_multiplier_) { - target_multiplier_ = target; - target_dbfs_ = (target == 0.0f ? -200.0f : std::log10(target) * 20); - } -} - -// Send string |config| to postprocessor |name|. -void PostProcessingPipelineImpl::SetPostProcessorConfig( - const std::string& name, - const std::string& config) { - DCHECK(!name.empty()); - std::vector::iterator it = - find_if(processors_.begin(), processors_.end(), - [&name](PostProcessorInfo& p) { return p.name == name; }); - if (it != processors_.end()) { - it->ptr->UpdateParameters(config); - DVLOG(2) << "Config string: " << config - << " was delivered to postprocessor " << name; - } -} - -// Set content type. -void PostProcessingPipelineImpl::SetContentType(AudioContentType content_type) { - for (auto& processor : processors_) { - processor.ptr->SetContentType(content_type); - } -} - -void PostProcessingPipelineImpl::UpdatePlayoutChannel(int channel) { - for (auto& processor : processors_) { - processor.ptr->SetPlayoutChannel(channel); - } -} - -double PostProcessingPipelineImpl::GetDelaySeconds() { - return delay_s_; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_IMPL_H_ - -#include -#include -#include - -#include "chromecast/media/base/aligned_buffer.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline.h" -#include "chromecast/media/cma/backend/mixer/post_processor_factory.h" -#include "chromecast/public/volume_control.h" - -namespace base { -class Value; -} // namespace base - -namespace chromecast { -namespace media { - -class AudioPostProcessor2; - -// Creates and contains multiple AudioPostProcessors, as specified in ctor. -// Provides convenience methods to access and use the AudioPostProcessors. -class PostProcessingPipelineImpl : public PostProcessingPipeline { - public: - PostProcessingPipelineImpl(const std::string& name, - const base::Value* filter_description_list, - int channels); - - PostProcessingPipelineImpl(const PostProcessingPipelineImpl&) = delete; - PostProcessingPipelineImpl& operator=(const PostProcessingPipelineImpl&) = - delete; - - ~PostProcessingPipelineImpl() override; - - void ProcessFrames(float* data, - int num_frames, - float current_volume, - float target_volume, - bool is_silence) override; - - float* GetOutputBuffer() override; - int NumOutputChannels() const override; - - bool SetOutputConfig(const AudioPostProcessor2::Config& config) override; - int GetInputSampleRate() const override; - bool IsRinging() override; - - // Send string |config| to post processor |name|. - void SetPostProcessorConfig(const std::string& name, - const std::string& config) override; - void SetContentType(AudioContentType content_type) override; - void UpdatePlayoutChannel(int channel) override; - double GetDelaySeconds() override; - - private: - // Note: typedef is used to silence chromium-style mandatory constructor in - // structs. - typedef struct { - std::unique_ptr ptr; - int input_frames_per_write; - std::string name; - } PostProcessorInfo; - - int GetRingingTimeInFrames(); - void UpdateCastVolume(float multiplier, float target); - - std::string name_; - int input_sample_rate_ = 0; - int output_sample_rate_ = 0; - int ringing_time_in_frames_ = 0; - int silence_frames_processed_ = 0; - double delay_s_ = 0; - float current_multiplier_ = 0.0; - float cast_volume_ = 0.0; - float current_dbfs_ = 0.0; - float target_multiplier_ = 0.0; - float target_dbfs_ = 0.0; - int num_output_channels_ = 0; - float* output_buffer_ = nullptr; - AlignedBuffer silence_buffer_; - - // factory_ keeps shared libraries open, so it must outlive processors_. - PostProcessorFactory factory_; - - std::vector processors_; -}; - -class PostProcessingPipelineFactoryImpl : public PostProcessingPipelineFactory { - public: - PostProcessingPipelineFactoryImpl(); - ~PostProcessingPipelineFactoryImpl() override; - - // PostProcessingPipelineFactory interface. - std::unique_ptr CreatePipeline( - const std::string& name, - const base::Value* filter_description_list, - int num_channels) override; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,215 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h" - -#include - -#include "base/check.h" -#include "base/files/file_util.h" -#include "base/json/json_file_value_serializer.h" -#include "base/logging.h" -#include "chromecast/media/base/audio_device_ids.h" -#include "media/audio/audio_device_description.h" - -namespace chromecast { -namespace media { - -namespace { - -const char kLinearizePipelineKey[] = "linearize"; -const char kMixPipelineKey[] = "mix"; -const char kNameKey[] = "name"; -const char kNumInputChannelsKey[] = "num_input_channels"; -const char kOutputStreamsKey[] = "output_streams"; -const char kPostProcessorsKey[] = "postprocessors"; -const char kProcessorsKey[] = "processors"; -const char kRenderNameTag[] = "render"; -const char kStreamsKey[] = "streams"; -const char kVolumeLimitsKey[] = "volume_limits"; - -void SplitPipeline(const base::Value::List& processors_list, - base::Value::List& prerender_pipeline, - base::Value::List& postrender_pipeline) { - bool has_render = false; - for (const base::Value& processor_description_value : processors_list) { - DCHECK(processor_description_value.is_dict()); - const std::string* name = - processor_description_value.GetDict().FindString(kNameKey); - if (name && *name == kRenderNameTag) { - has_render = true; - break; - } - } - - bool is_prerender = has_render; - - for (const base::Value& processor_description_dict : processors_list) { - const std::string* name = - processor_description_dict.GetDict().FindString(kNameKey); - if (name && *name == kRenderNameTag) { - is_prerender = false; - continue; - } - - if (is_prerender) { - prerender_pipeline.Append(processor_description_dict.Clone()); - } else { - postrender_pipeline.Append(processor_description_dict.Clone()); - } - } -} - -} // namespace - -StreamPipelineDescriptor::StreamPipelineDescriptor( - base::Value prerender_pipeline_in, - base::Value pipeline_in, - const base::Value* stream_types_in, - const std::optional num_input_channels_in, - const base::Value* volume_limits_in) - : prerender_pipeline(std::move(prerender_pipeline_in)), - pipeline(std::move(pipeline_in)), - stream_types(stream_types_in), - num_input_channels(std::move(num_input_channels_in)), - volume_limits(volume_limits_in) {} - -StreamPipelineDescriptor::~StreamPipelineDescriptor() = default; - -StreamPipelineDescriptor::StreamPipelineDescriptor( - StreamPipelineDescriptor&& other) = default; -StreamPipelineDescriptor& StreamPipelineDescriptor::operator=( - StreamPipelineDescriptor&& other) = default; - -PostProcessingPipelineParser::PostProcessingPipelineParser( - base::Value config_dict) - : file_path_(""), config_dict_(std::move(config_dict).TakeDict()) { - postprocessor_config_ = config_dict_.FindDict(kPostProcessorsKey); - if (!postprocessor_config_) { - LOG(WARNING) << "No post-processor config found."; - } -} - -PostProcessingPipelineParser::PostProcessingPipelineParser( - const base::FilePath& file_path) - : file_path_(file_path) { - if (!base::PathExists(file_path_)) { - LOG(WARNING) << "No post-processing config found at " << file_path_ << "."; - return; - } - - JSONFileValueDeserializer deserializer(file_path_); - int error_code = -1; - std::string error_msg; - auto config_dict_ptr = deserializer.Deserialize(&error_code, &error_msg); - CHECK(config_dict_ptr) << "Invalid JSON in " << file_path_ << " error " - << error_code << ":" << error_msg; - config_dict_ = std::move(config_dict_ptr->GetDict()); - - postprocessor_config_ = config_dict_.FindDict(kPostProcessorsKey); - if (!postprocessor_config_) { - LOG(WARNING) << "No post-processor config found."; - } -} - -PostProcessingPipelineParser::~PostProcessingPipelineParser() = default; - -std::vector -PostProcessingPipelineParser::GetStreamPipelines() { - std::vector descriptors; - if (!postprocessor_config_) { - return descriptors; - } - const base::Value::List* pipelines_list = - postprocessor_config_->FindList(kOutputStreamsKey); - if (!pipelines_list) { - LOG(WARNING) << "No post-processors found for streams (key = " - << kOutputStreamsKey - << ").\n No stream-specific processing will occur."; - return descriptors; - } - for (const base::Value& pipeline_description_val : *pipelines_list) { - CHECK(pipeline_description_val.is_dict()); - const base::Value::Dict& pipeline_description_dict = - pipeline_description_val.GetDict(); - - const base::Value::List* processors_list = - pipeline_description_dict.FindList(kProcessorsKey); - CHECK(processors_list); - - base::Value::List prerender_pipeline; - base::Value::List postrender_pipeline; - SplitPipeline(*processors_list, prerender_pipeline, postrender_pipeline); - - const base::Value* streams_list = - pipeline_description_dict.Find(kStreamsKey); - CHECK(streams_list && streams_list->is_list()); - - auto num_input_channels = - pipeline_description_dict.FindInt(kNumInputChannelsKey); - - const base::Value* volume_limits = - pipeline_description_dict.Find(kVolumeLimitsKey); - CHECK(!volume_limits || volume_limits->is_list()); - - descriptors.emplace_back(base::Value(std::move(prerender_pipeline)), - base::Value(std::move(postrender_pipeline)), - streams_list, std::move(num_input_channels), - volume_limits); - } - return descriptors; -} - -StreamPipelineDescriptor PostProcessingPipelineParser::GetMixPipeline() { - return GetPipelineByKey(kMixPipelineKey); -} - -StreamPipelineDescriptor PostProcessingPipelineParser::GetLinearizePipeline() { - return GetPipelineByKey(kLinearizePipelineKey); -} - -StreamPipelineDescriptor PostProcessingPipelineParser::GetPipelineByKey( - const std::string& key) { - const base::Value* stream_value = - postprocessor_config_ ? postprocessor_config_->FindByDottedPath(key) - : nullptr; - if (!postprocessor_config_ || !stream_value) { - LOG(WARNING) << "No post-processor description found for \"" << key - << "\" in " << file_path_ << ". Using passthrough."; - return StreamPipelineDescriptor(base::Value(base::Value::Type::LIST), - base::Value(base::Value::Type::LIST), - nullptr, std::nullopt, nullptr); - } - - const base::Value::Dict& stream_dict = stream_value->GetDict(); - const base::Value::List* processors_list = - stream_dict.FindList(kProcessorsKey); - CHECK(processors_list); - - base::Value::List prerender_pipeline; - base::Value::List postrender_pipeline; - SplitPipeline(*processors_list, prerender_pipeline, postrender_pipeline); - - const base::Value* streams_list = stream_dict.Find(kStreamsKey); - if (streams_list && !streams_list->is_list()) { - streams_list = nullptr; - } - - const base::Value* volume_limits = stream_dict.Find(kVolumeLimitsKey); - if (volume_limits && !volume_limits->is_dict()) { - volume_limits = nullptr; - } - - return StreamPipelineDescriptor( - base::Value(std::move(prerender_pipeline)), - base::Value(std::move(postrender_pipeline)), streams_list, - stream_dict.FindInt(kNumInputChannelsKey), volume_limits); -} - -base::FilePath PostProcessingPipelineParser::GetFilePath() const { - return file_path_; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_PARSER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_PARSER_H_ - -#include -#include -#include -#include - -#include "base/files/file_path.h" -#include "base/values.h" - -namespace chromecast { -namespace media { - -// Helper class to hold information about a stream pipeline. -struct StreamPipelineDescriptor { - // The format for pipeline is: - // [ {"processor": "PATH_TO_SHARED_OBJECT", - // "config": "CONFIGURATION_STRING"}, - // {"processor": "PATH_TO_SHARED_OBJECT", - // "config": "CONFIGURATION_STRING"}, - // ... ] - base::Value prerender_pipeline; - base::Value pipeline; - const base::Value* stream_types; - std::optional num_input_channels; - const base::Value* volume_limits; - - StreamPipelineDescriptor(base::Value prerender_pipeline_in, - base::Value pipeline_in, - const base::Value* stream_types_in, - const std::optional num_input_channels_in, - const base::Value* volume_limits_in); - ~StreamPipelineDescriptor(); - StreamPipelineDescriptor(StreamPipelineDescriptor&& other); - StreamPipelineDescriptor& operator=(StreamPipelineDescriptor&& other); - - StreamPipelineDescriptor(const StreamPipelineDescriptor&) = delete; - StreamPipelineDescriptor& operator=(const StreamPipelineDescriptor&) = delete; -}; - -// Helper class to parse post-processing pipeline descriptor file. -class PostProcessingPipelineParser { - public: - explicit PostProcessingPipelineParser(const base::FilePath& path); - - // For testing only: - explicit PostProcessingPipelineParser(base::Value config_dict); - - PostProcessingPipelineParser(const PostProcessingPipelineParser&) = delete; - PostProcessingPipelineParser& operator=(const PostProcessingPipelineParser&) = - delete; - - ~PostProcessingPipelineParser(); - - std::vector GetStreamPipelines(); - - // Gets the list of processors for the mix/linearize stages. - // Same format as StreamPipelineDescriptor.pipeline - StreamPipelineDescriptor GetMixPipeline(); - StreamPipelineDescriptor GetLinearizePipeline(); - - // Returns the file path used to load this object. - base::FilePath GetFilePath() const; - - private: - StreamPipelineDescriptor GetPipelineByKey(const std::string& key); - - const base::FilePath file_path_; - base::Value::Dict config_dict_; - const base::Value::Dict* postprocessor_config_ = nullptr; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSING_PIPELINE_PARSER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_factory.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_factory.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,126 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processor_factory.h" - -#include - -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/scoped_native_library.h" -#include "chromecast/media/audio/audio_log.h" -#include "chromecast/media/cma/backend/mixer/post_processor_paths.h" -#include "chromecast/media/cma/backend/mixer/post_processor_registry.h" -#include "chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" -#include "chromecast/public/media/audio_post_processor_shlib.h" - -namespace chromecast { -namespace media { - -namespace { - -const char kV1SoCreateFunction[] = "AudioPostProcessorShlib_Create"; -const char kV2SoCreateFunction[] = "AudioPostProcessor2Shlib_Create"; -const char kInitLoggingFunction[] = "AudioPostProcessor2Shlib_InitLogging"; - -base::FilePath FindLibrary(const std::string& library_name) { - base::FilePath relative_path(library_name); - base::FilePath full_path = GetPostProcessorDirectory(); - full_path = full_path.Append(relative_path); - if (base::PathExists(full_path)) { - return full_path; - } - full_path = GetOemPostProcessorDirectory(); - full_path = full_path.Append(relative_path); - if (base::PathExists(full_path)) { - return full_path; - } - LOG(WARNING) << library_name << " not found in " - << GetPostProcessorDirectory().AsUTF8Unsafe() << " or " - << GetOemPostProcessorDirectory().AsUTF8Unsafe() - << ". Prefer storing post processors in these directories."; - return relative_path; -} - -} // namespace - -using CreatePostProcessor2Function = - AudioPostProcessor2* (*)(const std::string&, int); - -using CreatePostProcessorFunction = AudioPostProcessor* (*)(const std::string&, - int); - -using InitLoggingFunction = void (*)(logging::AudioLogMessage::BufferManager*); - -PostProcessorFactory::PostProcessorFactory() = default; -PostProcessorFactory::~PostProcessorFactory() = default; - -std::unique_ptr PostProcessorFactory::CreatePostProcessor( - const std::string& library_name, - const std::string& config, - int channels) { - std::unique_ptr builtin = - PostProcessorRegistry::Get()->Create(library_name, config, channels); - if (builtin) { - LOG(INFO) << "Loaded builtin " << library_name; - return builtin; - } - - base::FilePath path = FindLibrary(library_name); - libraries_.push_back(std::make_unique(path)); - CHECK(libraries_.back()->is_valid()) - << "Could not open post processing library " << path; - - auto init_logging = reinterpret_cast( - libraries_.back()->GetFunctionPointer(kInitLoggingFunction)); - if (init_logging) { - init_logging(logging::AudioLogMessage::GetBufferManager()); - } - - auto v2_create = reinterpret_cast( - libraries_.back()->GetFunctionPointer(kV2SoCreateFunction)); - if (v2_create) { - return base::WrapUnique(v2_create(config, channels)); - } - - auto v1_create = reinterpret_cast( - libraries_.back()->GetFunctionPointer(kV1SoCreateFunction)); - - DCHECK(v1_create) << "Could not find " << kV1SoCreateFunction << "() in " - << library_name; - - LOG(WARNING) << "[Deprecated]: AudioPostProcessor will be deprecated soon." - << " Please update " << library_name - << " to AudioPostProcessor2."; - - return std::make_unique( - base::WrapUnique(v1_create(config, channels)), channels); -} - -// static -bool PostProcessorFactory::IsPostProcessorLibrary( - const base::FilePath& library_path) { - base::ScopedNativeLibrary library(library_path); - DCHECK(library.is_valid()) << "Could not open library " << library_path; - - // Check if library is V1 post processor. - void* v1_create = library.GetFunctionPointer(kV1SoCreateFunction); - if (v1_create) { - return true; - } - - // Check if library is V2 post processor. - void* v2_create = library.GetFunctionPointer(kV2SoCreateFunction); - if (v2_create) { - return true; - } - - return false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_factory.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_factory.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_FACTORY_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_FACTORY_H_ - -#include -#include -#include - -namespace base { -class FilePath; -class ScopedNativeLibrary; -} // namespace base - -namespace chromecast { -namespace media { - -class AudioPostProcessor2; - -class PostProcessorFactory { - public: - PostProcessorFactory(); - - PostProcessorFactory(const PostProcessorFactory&) = delete; - PostProcessorFactory& operator=(const PostProcessorFactory&) = delete; - - ~PostProcessorFactory(); - - // Checks if a library is a V1 or V2 post processor. - static bool IsPostProcessorLibrary(const base::FilePath& library_path); - - // Creates an instance of AudioPostProcessor2 or a wrapped AudioPostProcessor. - // By default, will attempt to find the library in - // /system/chrome/lib/processors/|library_name|. Will fall back to - // searching for /oem_cast_shlib/processors/|library_name|, and finally - // searching for |library_name| in LD_LIBRARY_PATH. - std::unique_ptr CreatePostProcessor( - const std::string& library_name, - const std::string& config, - int channels); - - private: - // Contains all libraries in use; - // Functions in shared objects cannot be used once library is closed. - std::vector> libraries_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_paths.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_paths.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_paths.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_paths.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processor_paths.h" - -namespace chromecast { -namespace media { - -namespace { - -const char kPreferredLibraryPath[] = "/system/chrome/lib/processors"; -const char kPreferredOemLibraryPath[] = "/oem_cast_shlib/processors"; - -} // namespace - -// static -base::FilePath GetPostProcessorDirectory() { - return base::FilePath(kPreferredLibraryPath); -} - -// static -base::FilePath GetOemPostProcessorDirectory() { - return base::FilePath(kPreferredOemLibraryPath); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_paths.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_paths.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_paths.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_paths.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_PATHS_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_PATHS_H_ - -#include "base/files/file_path.h" - -namespace chromecast { -namespace media { - -// Returns the preferred directory for 1P Post Processors. -base::FilePath GetPostProcessorDirectory(); - -// Returns the preferred directory for 3P Post Processors. -base::FilePath GetOemPostProcessorDirectory(); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_PATHS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_registry.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_registry.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_registry.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_registry.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// 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 "chromecast/media/cma/backend/mixer/post_processor_registry.h" - -#include - -#include "base/no_destructor.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" - -namespace chromecast { -namespace media { - -// static -PostProcessorRegistry* PostProcessorRegistry::Get() { - static base::NoDestructor g_registry; - return g_registry.get(); -} - -void PostProcessorRegistry::Register(const std::string& library_name, - CreateFunction create_function) { - creators_.emplace(library_name, std::move(create_function)); -} - -std::unique_ptr PostProcessorRegistry::Create( - const std::string& library_name, - const std::string& config, - int channels) { - auto it = creators_.find(library_name); - if (it == creators_.end()) { - return nullptr; - } - return it->second.Run(config, channels); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_registry.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_registry.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processor_registry.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processor_registry.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_REGISTRY_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_REGISTRY_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" - -namespace chromecast { -namespace media { - -// Global registry for built-in postprocessors. -class PostProcessorRegistry { - public: - using CreateFunction = base::RepeatingCallback(const std::string& config, int channels)>; - - // Returns the global registry instance for the current process. - static PostProcessorRegistry* Get(); - - PostProcessorRegistry(); - ~PostProcessorRegistry(); - - PostProcessorRegistry(const PostProcessorRegistry&) = delete; - PostProcessorRegistry& operator=(const PostProcessorRegistry&) = delete; - - // Registers a function to create a postprocessor for the given - // |library_name|, which should match the name used for the shlib for that - // postprocessor. - void Register(const std::string& library_name, - CreateFunction create_function); - - // Creates a postprocessor instance for the given |library_name|, if it has - // been registered. Returns nullptr if no creation function has been - // registered for that name. - std::unique_ptr Create(const std::string& library_name, - const std::string& config, - int channels); - - // Returns a map of registered libraries and their create functions. - const base::flat_map& Libraries() const { - return creators_; - } - - private: - base::flat_map creators_; -}; - -inline PostProcessorRegistry::PostProcessorRegistry() = default; -inline PostProcessorRegistry::~PostProcessorRegistry() = default; - -// Helper class and macro for auto-registering postprocessors with simple -// constructors. -template -struct PostProcessorCreator { - PostProcessorCreator(const std::string& library_name) { - PostProcessorRegistry::Get()->Register( - library_name, base::BindRepeating(&PostProcessorCreator::Create)); - } - - static std::unique_ptr Create(const std::string& config, - int channels) { - return std::make_unique(config, channels); - } -}; - -#define REGISTER_POSTPROCESSOR(Type, library_name) \ - static PostProcessorCreator* static_postprocessor_registration = \ - new PostProcessorCreator(library_name) - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSOR_REGISTRY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/governor.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/governor.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,100 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processors/governor.h" - -#include -#include -#include - -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/numerics/ranges.h" -#include "base/values.h" -#include "chromecast/media/base/slew_volume.h" -#include "chromecast/media/cma/backend/mixer/post_processor_registry.h" - -namespace chromecast { -namespace media { - -namespace { - -const int kNoVolume = -1; -const float kEpsilon = std::numeric_limits::epsilon(); -const float kMaxOnSetVolume = 0.989; // -0.1dB - -// Configuration strings: -const char kOnsetVolumeKey[] = "onset_volume"; -const char kClampMultiplierKey[] = "clamp_multiplier"; - -} // namespace - -Governor::Governor(const std::string& config, int input_channels) - : volume_(kNoVolume) { - status_.output_channels = input_channels; - status_.rendering_delay_frames = 0; - status_.ringing_time_frames = 0; - auto config_dict = base::JSONReader::ReadDict(config); - CHECK(config_dict) << "Governor config is not valid json: " << config; - auto onset_volume = config_dict->FindDouble(kOnsetVolumeKey); - CHECK(onset_volume); - onset_volume_ = onset_volume.value(); - auto clamp_multiplier = config_dict->FindDouble(kClampMultiplierKey); - CHECK(clamp_multiplier); - clamp_multiplier_ = clamp_multiplier.value(); - CHECK_LE(onset_volume_, clamp_multiplier_); - CHECK_LE(onset_volume_, kMaxOnSetVolume); - slew_volume_.SetVolume(1.0); - LOG(INFO) << "Created a governor: onset_volume = " << onset_volume_ - << ", clamp_multiplier = " << clamp_multiplier_; -} - -Governor::~Governor() = default; - -bool Governor::SetConfig(const AudioPostProcessor2::Config& config) { - status_.input_sample_rate = config.output_sample_rate; - slew_volume_.SetSampleRate(status_.input_sample_rate); - return true; -} - -const AudioPostProcessor2::Status& Governor::GetStatus() { - return status_; -} - -void Governor::ProcessFrames(float* data, int frames, Metadata* metadata) { - DCHECK(data); - status_.output_buffer = data; - - // If the volume has changed. - if (!base::IsApproximatelyEqual(metadata->system_volume, volume_, kEpsilon)) { - volume_ = metadata->system_volume; - slew_volume_.SetVolume(GetGovernorMultiplier()); - } - - slew_volume_.ProcessFMUL(false, data, frames, status_.output_channels, data); -} - -float Governor::GetGovernorMultiplier() { - if (volume_ > onset_volume_) { - float effective_volume = - onset_volume_ + (volume_ - onset_volume_) * - (clamp_multiplier_ - onset_volume_) / - (1. - onset_volume_); - return effective_volume / volume_; - } - return 1.0; -} - -bool Governor::UpdateParameters(const std::string& message) { - return false; -} - -void Governor::SetSlewTimeMsForTest(int slew_time_ms) { - slew_volume_.SetMaxSlewTimeMs(slew_time_ms); -} - -REGISTER_POSTPROCESSOR(Governor, "libcast_governor_2.0.so"); - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/governor.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/governor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_GOVERNOR_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_GOVERNOR_H_ - -#include -#include -#include - -#include "chromecast/media/base/slew_volume.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" - -namespace chromecast { -namespace media { - -// Provides linear reduction in output volume if the input volume is above a -// given threshold. -// Used to protect speakers at high output levels while providing dynamic range -// at low output level. -// The configuration string for this plugin is: -// {"onset_volume": |VOLUME_TO_CLAMP|, "clamp_multiplier": |CLAMP_MULTIPLIER|} -// Input volumes > |VOLUME_TO_CLAMP| will be attenuated by linear approximation, -// changing from 0 (at VOLUME_TO_CLAMP) to |CLAMP_MULTIPLIER| (at 1.0). -// |CLAMP_MULTIPLIER| must be >= |VOLUME_TO_CLAMP|. -class Governor : public AudioPostProcessor2 { - public: - Governor(const std::string& config, int input_channels); - - Governor(const Governor&) = delete; - Governor& operator=(const Governor&) = delete; - - ~Governor() override; - - // AudioPostProcessor2 implementation: - bool SetConfig(const Config& config) override; - const Status& GetStatus() override; - void ProcessFrames(float* data, int frames, Metadata* metadata) override; - bool UpdateParameters(const std::string& message) override; - - void SetSlewTimeMsForTest(int slew_time_ms); - - private: - float GetGovernorMultiplier(); - - Status status_; - float volume_; - double onset_volume_; - double clamp_multiplier_; - SlewVolume slew_volume_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_GOVERNOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/governor_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/governor_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/governor_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,138 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processors/governor.h" - -#include -#include -#include -#include -#include -#include - -#include "base/strings/stringprintf.h" -#include "chromecast/media/base/aligned_buffer.h" -#include "chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace post_processor_test { - -namespace { - -constexpr char kConfigTemplate[] = - R"config({"onset_volume": %f, "clamp_multiplier": %f})config"; - -const float kDefaultClamp = 0.6f; -const int kNumFrames = 100; -const int kSampleRate = 44100; - -std::string MakeConfigString(float onset_volume, float clamp_multiplier) { - return base::StringPrintf(kConfigTemplate, onset_volume, clamp_multiplier); -} - -void ScaleData(float* data, int frames, float scale) { - for (int f = 0; f < frames; ++f) { - data[f] *= scale; - } -} - -} // namespace - -class GovernorTest : public ::testing::TestWithParam { - public: - GovernorTest(const GovernorTest&) = delete; - GovernorTest& operator=(const GovernorTest&) = delete; - - protected: - GovernorTest() - : clamp_(kDefaultClamp), - onset_volume_(GetParam()), - governor_( - std::make_unique(MakeConfigString(onset_volume_, clamp_), - kNumChannels)), - data_(LinearChirp(kNumFrames, - std::vector(kNumChannels, 0.0), - std::vector(kNumChannels, 1.0))), - expected_(data_) {} - - ~GovernorTest() = default; - void SetUp() override { - governor_->SetSlewTimeMsForTest(0); - governor_->SetConfig({kSampleRate}); - } - - void ProcessFrames(float volume) { - AudioPostProcessor2::Metadata metadata = {0, 0, volume}; - governor_->ProcessFrames(data_.data(), kNumFrames, &metadata); - } - - void CompareBuffers() { - CheckArraysEqual(expected_.data(), data_.data(), expected_.size()); - } - - float clamp_; - float onset_volume_; - std::unique_ptr governor_; - AlignedBuffer data_; - AlignedBuffer expected_; -}; - -TEST_P(GovernorTest, ZeroVolume) { - ProcessFrames(0.0f); - CompareBuffers(); -} - -TEST_P(GovernorTest, EpsilonBelowOnset) { - // Approximately equaling is inclusive, thus needs more than one epsilon to - // make sure triggering volume change. - float volume = onset_volume_ - 2 * std::numeric_limits::epsilon(); - ProcessFrames(volume); - CompareBuffers(); -} - -TEST_P(GovernorTest, MaxVolume) { - ProcessFrames(1.0); - if (onset_volume_ <= 1.0) { - ScaleData(expected_.data(), kNumFrames * kNumChannels, clamp_); - } - CompareBuffers(); -} - -INSTANTIATE_TEST_SUITE_P(GovernorClampVolumeTest, - GovernorTest, - ::testing::Values(0.0f, 0.1f, 0.5f)); - -// Default tests from post_processor_test -TEST_P(PostProcessorTest, GovernorDelay) { - std::string config = MakeConfigString(0.8, 0.9); - auto pp = std::make_unique(config, kNumChannels); - TestDelay(pp.get(), sample_rate_); -} - -TEST_P(PostProcessorTest, GovernorRinging) { - std::string config = MakeConfigString(0.8, 0.9); - auto pp = std::make_unique(config, kNumChannels); - TestRingingTime(pp.get(), sample_rate_); -} - -TEST_P(PostProcessorTest, GovernorBenchmark) { - std::string config = MakeConfigString(0.8, 0.9); - auto pp = std::make_unique(config, kNumChannels); - AudioProcessorBenchmark(pp.get(), sample_rate_); -} - -} // namespace post_processor_test -} // namespace media -} // namespace chromecast - -/* -Benchmark results: -Device: Google Home Max, test audio duration: 1 sec. -Benchmark Sample Rate CPU(%) ----------------------------------------------------- -GovernorBenchmark 44100 0.0013% -GovernorBenchmark 48000 0.0015% -*/ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_name.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_name.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_name.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_name.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/public/chromecast_export.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" - -#define STRINGIFY(x) #x -#define STRINGIFY_WRAPPER(x) STRINGIFY(x) - -#include STRINGIFY_WRAPPER(DEFINED_POSTPROCESSOR_HEADER) - -extern "C" CHROMECAST_EXPORT chromecast::media::AudioPostProcessor2* -AudioPostProcessor2Shlib_Create(const std::string& config, - int num_channels_in) { - return new DEFINED_POSTPROCESSOR_NAME(config, num_channels_in); -} diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,356 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.h" - -#include - -#include -#include -#include -#include -#include - -#include "base/check_op.h" -#include "base/logging.h" -#include "chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.h" - -namespace chromecast { -namespace media { -namespace post_processor_test { - -namespace { - -const float kEpsilon = std::numeric_limits::epsilon() * 2; - -// Benchmark parameters. -const float kTestDurationSec = 10.0; - -} // namespace - -using Status = AudioPostProcessor2::Status; - -AudioPostProcessor2::Config MakeProcessorConfig(int sample_rate_hz) { - AudioPostProcessor2::Config config; - config.output_sample_rate = sample_rate_hz; - config.system_output_sample_rate = sample_rate_hz; - config.output_frames_per_write = kBufSizeFrames; - return config; -} - -AlignedBuffer LinearChirp(int frames, - const std::vector& start_frequencies, - const std::vector& end_frequencies) { - DCHECK_EQ(start_frequencies.size(), end_frequencies.size()); - AlignedBuffer chirp(frames * start_frequencies.size()); - for (size_t ch = 0; ch < start_frequencies.size(); ++ch) { - double angle = 0.0; - for (int f = 0; f < frames; ++f) { - angle += (start_frequencies[ch] + - (end_frequencies[ch] - start_frequencies[ch]) * f / frames) * - M_PI; - chirp[ch + f * start_frequencies.size()] = sin(angle); - } - } - return chirp; -} - -AlignedBuffer GetStereoChirp(int frames, - float start_frequency_left, - float end_frequency_left, - float start_frequency_right, - float end_frequency_right) { - std::vector start_frequencies(2); - std::vector end_frequencies(2); - start_frequencies[0] = start_frequency_left; - start_frequencies[1] = start_frequency_right; - end_frequencies[0] = end_frequency_left; - end_frequencies[1] = end_frequency_right; - - return LinearChirp(frames, start_frequencies, end_frequencies); -} - -void TestDelay(AudioPostProcessor2* pp, - int output_sample_rate, - int num_input_channels) { - ASSERT_TRUE(pp->SetConfig(MakeProcessorConfig(output_sample_rate))); - - const Status& status = pp->GetStatus(); - ASSERT_GT(status.input_sample_rate, 0); - ASSERT_GT(status.output_channels, 0); - ASSERT_GE(status.rendering_delay_frames, 0); - ASSERT_GE(status.ringing_time_frames, 0); - - const int input_size_frames = kBufSizeFrames * 100; - const int resample_factor = output_sample_rate / status.input_sample_rate; - const int output_size_frames = input_size_frames * resample_factor; - - AlignedBuffer data_in = LinearChirp( - input_size_frames, std::vector(num_input_channels, 0.0), - std::vector(num_input_channels, 1.0)); - - AlignedBuffer data_expected = LinearChirp( - output_size_frames, std::vector(num_input_channels, 0.0), - std::vector(num_input_channels, 1.0 / resample_factor)); - - AlignedBuffer data_out(data_in.size() * resample_factor); - const int output_buf_size = kBufSizeFrames * resample_factor * - status.output_channels * sizeof(data_out[0]); - AudioPostProcessor2::Metadata metadata = {0, 0, 1.0}; - for (int i = 0; i < input_size_frames; i += kBufSizeFrames) { - pp->ProcessFrames(&data_in[i * num_input_channels], kBufSizeFrames, - &metadata); - std::memcpy(&data_out[i * status.output_channels * resample_factor], - status.output_buffer, output_buf_size); - } - - double max_sum = 0; - int max_idx = -1; // index (offset), corresponding to maximum x-correlation. - // Find the offset of maximum x-correlation of in/out. - // Search range should be larger than post-processor's expected delay. - int search_range = - status.rendering_delay_frames * resample_factor + kBufSizeFrames; - for (int offset = 0; offset < search_range; ++offset) { - double sum = 0.0; - int upper_search_limit_frames = output_size_frames - search_range; - for (int f = 0; f < upper_search_limit_frames; ++f) { - for (int ch = 0; ch < status.output_channels; ++ch) { - sum += data_expected[f * num_input_channels] * - data_out[(f + offset) * status.output_channels + ch]; - } - } - - // No need to normalize because every dot product is the same length. - if (sum > max_sum) { - max_sum = sum; - max_idx = offset; - } - } - EXPECT_EQ(max_idx / resample_factor, status.rendering_delay_frames); -} - -void TestRingingTime(AudioPostProcessor2* pp, - int sample_rate, - int num_input_channels) { - ASSERT_TRUE(pp->SetConfig(MakeProcessorConfig(sample_rate))); - - const Status& status = pp->GetStatus(); - ASSERT_GT(status.input_sample_rate, 0); - ASSERT_GT(status.output_channels, 0); - ASSERT_GE(status.rendering_delay_frames, 0); - ASSERT_GE(status.ringing_time_frames, 0); - - const int kNumFrames = kBufSizeFrames; - const int kSinFreq = 2000; - - // Send a second of data to excite the filter. - AudioPostProcessor2::Metadata metadata = {0, 0, 1.0}; - for (int i = 0; i < sample_rate; i += kNumFrames) { - AlignedBuffer data = - GetSineData(kNumFrames, kSinFreq, sample_rate, num_input_channels); - pp->ProcessFrames(data.data(), kNumFrames, &metadata); - } - AlignedBuffer data = - GetSineData(kNumFrames, kSinFreq, sample_rate, num_input_channels); - pp->ProcessFrames(data.data(), kNumFrames, &metadata); - - // Compute the amplitude of the last buffer - ASSERT_NE(status.output_buffer, nullptr); - float original_amplitude = - SineAmplitude(status.output_buffer, status.output_channels * kNumFrames); - - EXPECT_GE(original_amplitude, 0) - << "Output of nonzero data is 0; cannot test ringing"; - - // Feed |ringing_time_frames| of silence. - int frames_remaining = status.ringing_time_frames; - int frames_to_process = std::min(frames_remaining, kNumFrames); - while (frames_remaining > 0) { - // Make sure |frames_to_process| is an even multiple of 8. - frames_to_process = std::min(frames_to_process, frames_remaining); - frames_to_process = (frames_to_process + 7); - frames_to_process -= frames_to_process % 8; - data.assign(frames_to_process * num_input_channels, 0); - pp->ProcessFrames(data.data(), frames_to_process, &metadata); - frames_remaining -= frames_to_process; - } - - // Send a little more data and ensure the amplitude is < 1% the original. - data.assign(kNumFrames * num_input_channels, 0); - pp->ProcessFrames(data.data(), kNumFrames, &metadata); - - // Only look at the amplitude of the first few frames. - EXPECT_LE(SineAmplitude(status.output_buffer, 10 * status.output_channels) / - original_amplitude, - 0.01) - << "Output level after " << status.ringing_time_frames - << " is more than 1%."; -} - -void TestPassthrough(AudioPostProcessor2* pp, - int sample_rate, - int num_input_channels) { - ASSERT_TRUE(pp->SetConfig(MakeProcessorConfig(sample_rate))); - - const Status& status = pp->GetStatus(); - ASSERT_GT(status.input_sample_rate, 0); - ASSERT_GT(status.output_channels, 0); - ASSERT_GE(status.rendering_delay_frames, 0); - - ASSERT_EQ(status.output_channels, num_input_channels) - << "\"Passthrough\" is not well defined for " - << "num_input_channels != num_output_channels"; - - ASSERT_EQ(status.input_sample_rate, sample_rate); - - const int kNumFrames = kBufSizeFrames; - const int kSinFreq = 2000; - - AlignedBuffer data = - GetSineData(kNumFrames, kSinFreq, sample_rate, num_input_channels); - AlignedBuffer expected(data); - - AudioPostProcessor2::Metadata metadata = {0, 0, 1.0}; - pp->ProcessFrames(data.data(), kNumFrames, &metadata); - int delayed_frames = 0; - - while (status.rendering_delay_frames >= delayed_frames + kNumFrames) { - delayed_frames += kNumFrames; - for (int i = 0; i < kNumFrames * num_input_channels; ++i) { - EXPECT_EQ(0.0f, data[i]) << i; - } - data = expected; - pp->ProcessFrames(data.data(), kNumFrames, &metadata); - - ASSERT_GE(status.rendering_delay_frames, delayed_frames); - } - - int delay_samples = - (status.rendering_delay_frames - delayed_frames) * status.output_channels; - ASSERT_LE(delay_samples, status.output_channels * kNumFrames); - - CheckArraysEqual(expected.data(), status.output_buffer + delay_samples, - data.size() - delay_samples); -} - -void AudioProcessorBenchmark(AudioPostProcessor2* pp, - int sample_rate, - int num_input_channels) { - ASSERT_TRUE(pp->SetConfig(MakeProcessorConfig(sample_rate))); - - int test_size_frames = kTestDurationSec * pp->GetStatus().input_sample_rate; - // Make test_size multiple of kBufSizeFrames and calculate effective - // duration. - test_size_frames -= test_size_frames % kBufSizeFrames; - float effective_duration = static_cast(test_size_frames) / sample_rate; - AlignedBuffer data_in = LinearChirp( - test_size_frames, std::vector(num_input_channels, 0.0), - std::vector(num_input_channels, 1.0)); - clock_t start_clock = clock(); - AudioPostProcessor2::Metadata metadata = {0, 0, 1.0}; - for (int i = 0; i < test_size_frames; i += kBufSizeFrames * kNumChannels) { - pp->ProcessFrames(&data_in[i], kBufSizeFrames, &metadata); - } - clock_t stop_clock = clock(); - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - LOG(INFO) << test_info->test_suite_name() << "." << test_info->name() - << " At " << sample_rate - << " frames per second and channels number " << num_input_channels - << " CPU usage: " << std::defaultfloat - << 100.0 * (stop_clock - start_clock) / - (CLOCKS_PER_SEC * effective_duration) - << "%"; -} - -void AudioProcessorBenchmark(AudioPostProcessor* pp, int sample_rate) { - AudioPostProcessorWrapper wrapper(pp, kNumChannels); - AudioProcessorBenchmark(&wrapper, sample_rate, kNumChannels); -} - -template -void CheckArraysEqual(const T* expected, const T* actual, size_t size) { - std::vector differing_values = CompareArray(expected, actual, size); - if (differing_values.empty()) { - return; - } - - size_t size_to_print = - std::min(static_cast(differing_values[0] + 8), size); - EXPECT_EQ(differing_values.size(), 0u) - << "Arrays differ at indices " - << ::testing::PrintToString(differing_values) - << "\n Expected: " << ArrayToString(expected, size_to_print) - << "\n Actual: " << ArrayToString(actual, size_to_print); -} - -template -std::vector CompareArray(const T* expected, const T* actual, size_t size) { - std::vector diffs; - for (size_t i = 0; i < size; ++i) { - if (std::abs(expected[i] - actual[i]) > kEpsilon) { - diffs.push_back(i); - } - } - return diffs; -} - -template -std::string ArrayToString(const T* array, size_t size) { - std::string result; - for (size_t i = 0; i < size; ++i) { - result += ::testing::PrintToString(array[i]) + " "; - } - return result; -} - -float SineAmplitude(const float* data, int num_frames) { - double power = 0; - for (int i = 0; i < num_frames; ++i) { - power += std::pow(data[i], 2); - } - return std::sqrt(power / num_frames) * sqrt(2); -} - -AlignedBuffer GetSineData(int frames, - float frequency, - int sample_rate, - int num_channels) { - AlignedBuffer sine(frames * num_channels); - for (int f = 0; f < frames; ++f) { - for (int ch = 0; ch < num_channels; ++ch) { - // Offset by a little so that first value is non-zero - sine[f * num_channels + ch] = - sin(static_cast(f + ch) * frequency * 2 * M_PI / sample_rate); - } - } - return sine; -} - -void TestDelay(AudioPostProcessor* pp, int sample_rate) { - AudioPostProcessorWrapper ppw(pp, kNumChannels); - TestDelay(&ppw, sample_rate, kNumChannels); -} - -void TestRingingTime(AudioPostProcessor* pp, int sample_rate) { - AudioPostProcessorWrapper ppw(pp, kNumChannels); - TestRingingTime(&ppw, sample_rate, kNumChannels); -} -void TestPassthrough(AudioPostProcessor* pp, int sample_rate) { - AudioPostProcessorWrapper ppw(pp, kNumChannels); - TestPassthrough(&ppw, sample_rate, kNumChannels); -} - -PostProcessorTest::PostProcessorTest() : sample_rate_(GetParam()) {} -PostProcessorTest::~PostProcessorTest() = default; - -INSTANTIATE_TEST_SUITE_P(SampleRates, - PostProcessorTest, - ::testing::Values(44100, 48000)); - -GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PostProcessorTest); - -} // namespace post_processor_test -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,133 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_POST_PROCESSOR_UNITTEST_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_POST_PROCESSOR_UNITTEST_H_ - -#include -#include - -#include "chromecast/media/base/aligned_buffer.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" -#include "chromecast/public/media/audio_post_processor_shlib.h" -#include "testing/gtest/include/gtest/gtest.h" - -// This file contains basic tests for AudioPostProcessors. -// All AudioPostProcessors should run (and pass) the following tests: -// TestDelay (tests return value from ProcessFrames) -// TestRingingTime (from GetRingingTimeFrames) -// Additionally, if it is possible to configure the PostProcessor to be a -// passthrough (no-op), then you should also run -// TestPassthrough (tests data in = data out, accounting for delay). -// -// Usage: -// TEST_P(PostProcessorTest, DelayTest) { -// std::unique_ptr my_post_processor( -// AudioPostProcessorShlib_Create(my_config, 2)); -// TestDelay(my_post_processor, sample_rate_); -// } -// (Repeat for TestRingingTime, TestPassthrough). -// -// This will run your test with 44100 and 48000 sample rates. -// You can also make your own tests using the provided helper functions. - -namespace chromecast { -namespace media { -namespace post_processor_test { - -const int kBufSizeFrames = 256; -const int kNumChannels = 2; - -AudioPostProcessor2::Config MakeProcessorConfig(int sample_rate_hz); - -void TestDelay(AudioPostProcessor2* pp, - int sample_rate, - int num_input_channels = 2); -void TestRingingTime(AudioPostProcessor2* pp, - int sample_rate, - int num_input_channels = 2); - -// Requires that num_output_channels == |input_channels| -void TestPassthrough(AudioPostProcessor2* pp, - int sample_rate, - int num_input_channels = 2); - -// Legacy tests for AudioPostProcessor(1). -void TestDelay(AudioPostProcessor* pp, int sample_rate); -void TestRingingTime(AudioPostProcessor* pp, int sample_rate); -void TestPassthrough(AudioPostProcessor* pp, int sample_rate); - -// Measure amount of CPU time |pp| takes to run [x] seconds of stereo audio at -// |sample_rate|. -void AudioProcessorBenchmark(AudioPostProcessor2* pp, - int sample_rate, - int num_input_channels = kNumChannels); -void AudioProcessorBenchmark(AudioPostProcessor* pp, int sample_rate); - -// Returns the maximum number of frames a PostProcessor may be asked to handle -// in a single call. -int GetMaximumFrames(int sample_rate); - -// Tests that the first |size| elements of |expected| and |actual| are the same. -template -void CheckArraysEqual(const T* expected, const T* actual, size_t size); - -// Returns a list of indexes at which |expected| and |actual| differ. -template -std::vector CompareArray(const T* expected, const T* actual, size_t size); - -// Print the first |size| elemenents of |array| to a string. -template -std::string ArrayToString(const T* array, size_t size); - -// Compute the amplitude of a sinusoid as power * sqrt(2) -// This is more robust that looking for the maximum value. -float SineAmplitude(const float* data, int num_samples); - -// Return a vector of |frames| frames of |num_channels| interleaved data. -// |frequency| is in hz. -// Each channel, ch, will be sin(2 *pi * frequency / sample_rate * (n + ch)). -AlignedBuffer GetSineData(int frames, - float frequency, - int sample_rate, - int num_channels = kNumChannels); - -// Returns a vector of interleaved chirp waveforms with |frames| frames and -// number of channels equal to |start_frequencies.size()|. -// |start_frequencies| and |end_frequencies| must be the same size. -// Each channel, ch, will have frequency linearly interpolated from -// |start_frequencies[ch]| to |end_frequencies[ch]| -// Frequencies are normalized to (2 * freq_in_hz / sample_rate); 0 = DC, 1 = -// nyquist. -AlignedBuffer LinearChirp(int frames, - const std::vector& start_frequencies, - const std::vector& end_frequencies); - -// Returns a vector of interleaved stereo chirp waveform with |frames| frames -// from |start_frequency_left| to |start_frequency_left| for left channel and -// from |start_frequency_right| to |end_frequency_right| for right channel, -// where |start_frequency_x| and |end_frequency_x| are normalized frequencies -// (2 * freq_in_hz / sample_rate) i.e. 0 - DC, 1 - nyquist. -// Equivalent to LinearChirp(frames, -// {start_frequency_left, start_frequency_right}, -// {end_frequency_left, end_frequency_right}) -AlignedBuffer GetStereoChirp(int frames, - float start_frequency_left, - float end_frequency_left, - float start_frequency_right, - float end_frequency_right); - -class PostProcessorTest : public ::testing::TestWithParam { - protected: - PostProcessorTest(); - ~PostProcessorTest() override; - - int sample_rate_; -}; - -} // namespace post_processor_test -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_POST_PROCESSOR_UNITTEST_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.h" - -#include "base/check.h" -#include "chromecast/public/media/audio_post_processor_shlib.h" - -namespace chromecast { -namespace media { - -AudioPostProcessorWrapper::AudioPostProcessorWrapper( - std::unique_ptr pp, - int channels) - : owned_pp_(std::move(pp)), pp_(owned_pp_.get()) { - DCHECK(owned_pp_); - status_.output_channels = channels; -} - -AudioPostProcessorWrapper::AudioPostProcessorWrapper(AudioPostProcessor* pp, - int channels) - : pp_(pp) { - DCHECK(pp_); - status_.output_channels = channels; -} - -AudioPostProcessorWrapper::~AudioPostProcessorWrapper() = default; - -bool AudioPostProcessorWrapper::SetConfig( - const AudioPostProcessor2::Config& config) { - if (!pp_->SetSampleRate(config.output_sample_rate)) { - return false; - } - status_.input_sample_rate = config.output_sample_rate; - status_.ringing_time_frames = pp_->GetRingingTimeInFrames(); - return true; -} - -const AudioPostProcessor2::Status& AudioPostProcessorWrapper::GetStatus() { - return status_; -} - -void AudioPostProcessorWrapper::ProcessFrames(float* data, - int frames, - Metadata* metadata) { - status_.output_buffer = data; - status_.rendering_delay_frames = pp_->ProcessFrames( - data, frames, metadata->system_volume, metadata->volume_dbfs); -} - -bool AudioPostProcessorWrapper::UpdateParameters(const std::string& message) { - pp_->UpdateParameters(message); - return true; -} - -void AudioPostProcessorWrapper::SetContentType(AudioContentType content_type) { - pp_->SetContentType(content_type); -} - -void AudioPostProcessorWrapper::SetPlayoutChannel(int channel) { - pp_->SetPlayoutChannel(channel); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/post_processor_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_POST_PROCESSOR_WRAPPER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_POST_PROCESSOR_WRAPPER_H_ - -// Provides a wrapper for AudioPostProcessor to allow using it as an -// AudioPostProcessor2. This works by simply fowarding the input buffer as the -// output buffer, since the original AudioPostProcessor API has equal numbers of -// input and output channels. -// -// Note that AudioPostProcessor is DEPRECATED and support will be dropped -// entirely in the near future. - -#include -#include - -#include "chromecast/public/media/audio_post_processor2_shlib.h" - -namespace chromecast { -namespace media { - -class AudioPostProcessor; - -class AudioPostProcessorWrapper : public AudioPostProcessor2 { - public: - // AudioPostProcessorWrapper owns |pp|. - AudioPostProcessorWrapper(std::unique_ptr pp, - int channels); - - // AudioPostProcessorWrapper does not own |pp|. Calling code is responsible - // for owning the lifetime of |pp|. This should only be used for testing. - AudioPostProcessorWrapper(AudioPostProcessor* pp, int channels); - - AudioPostProcessorWrapper(const AudioPostProcessorWrapper&) = delete; - AudioPostProcessorWrapper& operator=(const AudioPostProcessorWrapper&) = - delete; - - ~AudioPostProcessorWrapper() override; - - private: - // AudioPostProcessor2 implementation: - bool SetConfig(const Config& config) override; - const Status& GetStatus() override; - void ProcessFrames(float* data, int frames, Metadata* metadata) override; - bool UpdateParameters(const std::string& message) override; - void SetContentType(AudioContentType content_type) override; - void SetPlayoutChannel(int channel) override; - - std::unique_ptr owned_pp_; - Status status_; - AudioPostProcessor* pp_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_POST_PROCESSOR_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/mixer/post_processors/saturated_gain.h" - -#include -#include - -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/values.h" -#include "chromecast/media/base/slew_volume.h" -#include "chromecast/media/cma/backend/mixer/post_processor_registry.h" - -namespace chromecast { -namespace media { - -namespace { - -const char kGainKey[] = "gain_db"; - -float DbFsToScale(float db) { - return std::pow(10, db / 20); -} - -} // namespace - -SaturatedGain::SaturatedGain(const std::string& config, int channels) - : last_volume_dbfs_(-1) { - status_.output_channels = channels; - status_.ringing_time_frames = 0; - status_.rendering_delay_frames = 0; - auto config_dict = base::JSONReader::ReadDict(config); - CHECK(config_dict) << "SaturatedGain config is not valid json: " << config; - auto gain_db = config_dict->FindDouble(kGainKey); - CHECK(gain_db) << config; - gain_ = DbFsToScale(*gain_db); - LOG(INFO) << "Created a SaturatedGain: gain = " << *gain_db << "db"; -} - -SaturatedGain::~SaturatedGain() = default; - -bool SaturatedGain::SetConfig(const AudioPostProcessor2::Config& config) { - status_.input_sample_rate = config.output_sample_rate; - slew_volume_.SetSampleRate(status_.input_sample_rate); - return true; -} - -const AudioPostProcessor2::Status& SaturatedGain::GetStatus() { - return status_; -} - -void SaturatedGain::ProcessFrames(float* data, int frames, Metadata* metadata) { - DCHECK(data); - - status_.output_buffer = data; - if (metadata->volume_dbfs != last_volume_dbfs_) { - last_volume_dbfs_ = metadata->volume_dbfs; - // Don't apply more gain than attenuation. - float effective_gain = std::min(DbFsToScale(-last_volume_dbfs_), gain_); - slew_volume_.SetVolume(effective_gain); - } - - slew_volume_.ProcessFMUL(false, data, frames, status_.output_channels, data); -} - -bool SaturatedGain::UpdateParameters(const std::string& message) { - return false; -} - -REGISTER_POSTPROCESSOR(SaturatedGain, "libcast_saturated_gain_2.0.so"); - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_SATURATED_GAIN_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_SATURATED_GAIN_H_ - -#include - -#include "chromecast/media/base/slew_volume.h" -#include "chromecast/public/media/audio_post_processor2_shlib.h" - -namespace chromecast { -namespace media { - -// Applys a gain to audio, limited such that gain + system_volume <= 0dB. -class SaturatedGain : public AudioPostProcessor2 { - public: - SaturatedGain(const std::string& config, int channels); - - SaturatedGain(const SaturatedGain&) = delete; - SaturatedGain& operator=(const SaturatedGain&) = delete; - - ~SaturatedGain() override; - - // AudioPostProcessor implementation: - bool SetConfig(const Config& config) override; - const Status& GetStatus() override; - void ProcessFrames(float* data, int frames, Metadata* metadata) override; - bool UpdateParameters(const std::string& message) override; - - private: - Status status_; - float last_volume_dbfs_; - SlewVolume slew_volume_; - float gain_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_POST_PROCESSORS_SATURATED_GAIN_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/saturated_gain_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/post_processors/saturated_gain_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/post_processors/saturated_gain_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include - -#include "base/strings/stringprintf.h" -#include "chromecast/media/cma/backend/mixer/post_processors/post_processor_unittest.h" -#include "chromecast/media/cma/backend/mixer/post_processors/saturated_gain.h" - -namespace chromecast { -namespace media { -namespace post_processor_test { - -namespace { - -const char kConfigTemplate[] = R"config({"gain_db": %f})config"; - -std::string MakeConfigString(float gain_db) { - return base::StringPrintf(kConfigTemplate, gain_db); -} - -} // namespace - -// Default tests from post_processor_test -TEST_P(PostProcessorTest, SaturatedGainDelay) { - std::string config = MakeConfigString(0.0); - auto pp = std::make_unique(config, kNumChannels); - TestDelay(pp.get(), sample_rate_); -} - -TEST_P(PostProcessorTest, SaturatedGainRinging) { - std::string config = MakeConfigString(0.0); - auto pp = std::make_unique(config, kNumChannels); - TestRingingTime(pp.get(), sample_rate_); -} - -// Also tests clipping (by attempting to set gain way too high). -TEST_P(PostProcessorTest, SaturatedGainPassthrough) { - std::string config = MakeConfigString(100.0); - auto pp = std::make_unique(config, kNumChannels); - TestPassthrough(pp.get(), sample_rate_); -} - -TEST_P(PostProcessorTest, Gain) { - const int kNumFrames = 256; - std::string config = MakeConfigString(20.0); // Exactly 10x multiplier. - auto pp = std::make_unique(config, kNumChannels); - auto data = LinearChirp(kNumFrames, std::vector(kNumChannels, 0.0), - std::vector(kNumChannels, 1.0)); - - for (size_t i = 0; i < data.size(); ++i) { - data[i] /= 100.0; - } - float original_amplitude = - SineAmplitude(data.data(), kNumChannels * kNumFrames); - AudioPostProcessor2::Metadata metadata = {-20.0, -20.0, 1.0}; - pp->ProcessFrames(data.data(), kNumFrames, &metadata); - - EXPECT_FLOAT_EQ(original_amplitude * 10.0, - SineAmplitude(data.data(), kNumChannels * kNumFrames)) - << "Expected a gain of 20dB"; -} - -TEST_P(PostProcessorTest, SaturatedGainBenchmark) { - std::string config = MakeConfigString(20.0); - auto pp = std::make_unique(config, kNumChannels); - AudioProcessorBenchmark(pp.get(), sample_rate_); -} - -} // namespace post_processor_test -} // namespace media -} // namespace chromecast - -/* -Benchmark results: -Device: Google Home Max, test audio duration: 1 sec. -Benchmark Sample Rate CPU(%) ----------------------------------------------------- -SaturatedGainBenchmark 44100 0.0014% -SaturatedGainBenchmark 48000 0.0016% -*/ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/stream_mixer.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/stream_mixer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,1105 +0,0 @@ -// 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 "chromecast/media/cma/backend/mixer/stream_mixer.h" - -#include - -#include -#include -#include -#include -#include - -#include "base/compiler_specific.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/message_loop/message_pump_type.h" -#include "base/synchronization/condition_variable.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/threading/platform_thread.h" -#include "build/build_config.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/thread_health_checker.h" -#include "chromecast/media/audio/audio_io_thread.h" -#include "chromecast/media/audio/audio_log.h" -#include "chromecast/media/audio/interleaved_channel_mixer.h" -#include "chromecast/media/audio/mixer_service/loopback_interrupt_reason.h" -#include "chromecast/media/base/audio_device_ids.h" -#include "chromecast/media/cma/backend/cast_audio_json.h" -#include "chromecast/media/cma/backend/mixer/audio_output_redirector.h" -#include "chromecast/media/cma/backend/mixer/channel_layout.h" -#include "chromecast/media/cma/backend/mixer/filter_group.h" -#include "chromecast/media/cma/backend/mixer/loopback_handler.h" -#include "chromecast/media/cma/backend/mixer/mixer_service_receiver.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline_impl.h" -#include "chromecast/media/cma/backend/mixer/post_processing_pipeline_parser.h" -#include "chromecast/media/cma/backend/volume_map.h" -#include "chromecast/public/media/mixer_output_stream.h" -#include "media/audio/audio_device_description.h" - -#define RUN_ON_MIXER_THREAD(method, ...) \ - do { \ - mixer_task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&StreamMixer::method, \ - base::Unretained(this), ##__VA_ARGS__)); \ - } while (0) - -namespace chromecast { -namespace media { - -namespace { - -const size_t kMinInputChannels = 2; -const int kDefaultInputChannels = 2; -const int kInvalidNumChannels = 0; - -const int kDefaultCheckCloseTimeoutMs = 2000; - -// Resample all audio below this frequency. -const unsigned int kLowSampleRateCutoff = 32000; - -// Sample rate to fall back if input sample rate is below kLowSampleRateCutoff. -const unsigned int kLowSampleRateFallback = 48000; - -const int64_t kNoTimestamp = std::numeric_limits::min(); - -const int kUseDefaultFade = -1; -const int kMediaDuckFadeMs = 150; -const int kMediaUnduckFadeMs = 700; -const int kDefaultFilterFrameAlignment = 64; - -constexpr base::TimeDelta kMixerThreadCheckTimeout = base::Seconds(10); -constexpr base::TimeDelta kHealthCheckInterval = base::Seconds(5); - -int GetFixedOutputSampleRate() { - int fixed_sample_rate = GetSwitchValueNonNegativeInt( - switches::kAudioOutputSampleRate, MixerOutputStream::kInvalidSampleRate); - - if (fixed_sample_rate == MixerOutputStream::kInvalidSampleRate) { - fixed_sample_rate = - GetSwitchValueNonNegativeInt(switches::kAlsaFixedOutputSampleRate, - MixerOutputStream::kInvalidSampleRate); - } - return fixed_sample_rate; -} - -base::TimeDelta GetNoInputCloseTimeout() { - // --accept-resource-provider should imply a check close timeout of 0. - int default_close_timeout_ms = - GetSwitchValueBoolean(switches::kAcceptResourceProvider, false) - ? 0 - : kDefaultCheckCloseTimeoutMs; - int close_timeout_ms = GetSwitchValueInt(switches::kAlsaCheckCloseTimeout, - default_close_timeout_ms); - if (close_timeout_ms < 0) { - return base::TimeDelta::Max(); - } - return base::Milliseconds(close_timeout_ms); -} - -void UseHighPriority() { -#if !BUILDFLAG(IS_FUCHSIA) && !BUILDFLAG(IS_ANDROID) - struct sched_param params; - params.sched_priority = sched_get_priority_max(SCHED_FIFO); - pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶ms); - - int policy = 0; - struct sched_param actual_params; - pthread_getschedparam(pthread_self(), &policy, &actual_params); - LOG(INFO) << "Actual priority = " << actual_params.sched_priority - << ", policy = " << policy; -#endif -} - -const char* ChannelString(int num_channels) { - if (num_channels == 1) { - return "channel"; - } - return "channels"; -} - -} // namespace - -class StreamMixer::ExternalMediaVolumeChangeRequestObserver - : public StreamMixer::BaseExternalMediaVolumeChangeRequestObserver { - public: - explicit ExternalMediaVolumeChangeRequestObserver(StreamMixer* mixer) - : mixer_(mixer) { - DCHECK(mixer_); - } - - // ExternalAudioPipelineShlib::ExternalMediaVolumeChangeRequestObserver - // implementation: - void OnVolumeChangeRequest(float new_volume) override { - mixer_->SetVolume(AudioContentType::kMedia, new_volume); - } - - void OnMuteChangeRequest(bool new_muted) override { - mixer_->SetMuted(AudioContentType::kMedia, new_muted); - } - - private: - StreamMixer* const mixer_; -}; - -class StreamMixer::MixerThread : public base::PlatformThread::Delegate, - public base::TaskRunner { - public: - MixerThread() : cond_(&lock_) { - tasks_.reserve(64); - swapped_tasks_.reserve(64); - - CHECK(base::PlatformThread::CreateWithType( - 256 * 1024, this, &thread_, base::ThreadType::kRealtimeAudio)); - } - - void Stop() { - { - base::AutoLock lock(lock_); - if (stopped_) { - return; - } - stopped_ = true; - } - cond_.Signal(); - - base::PlatformThread::Join(thread_); - } - - // base::TaskRunner implementation: - bool PostDelayedTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta delay) override { - // Delay is ignored. - DCHECK_EQ(delay, base::TimeDelta()); - { - base::AutoLock lock(lock_); - if (stopped_) { - return false; - } - tasks_.push_back(std::move(task)); - } - cond_.Signal(); - return true; - } - - private: - friend class RefCountedThreadSafe; - - ~MixerThread() override { Stop(); } - - // base::PlatformThread::Delegate implementation: - void ThreadMain() override { - base::PlatformThread::SetName("CMA mixer"); - UseHighPriority(); - - base::AutoLock lock(lock_); - for (;;) { - swapped_tasks_.swap(tasks_); - if (swapped_tasks_.empty()) { - if (stopped_) { - return; - } - cond_.Wait(); - } else { - base::AutoUnlock unlock(lock_); - for (auto& task : swapped_tasks_) { - std::move(task).Run(); - } - swapped_tasks_.clear(); - } - } - } - - base::Lock lock_; - base::ConditionVariable cond_; - bool stopped_ GUARDED_BY(lock_) = false; - std::vector tasks_ GUARDED_BY(lock_); - - // Only used on the mixer thread. - std::vector swapped_tasks_; - - base::PlatformThreadHandle thread_; -}; - -StreamMixer::StreamMixer( - scoped_refptr io_task_runner) - : StreamMixer(nullptr, - nullptr, - "", - std::move(io_task_runner)) {} - -StreamMixer::StreamMixer( - std::unique_ptr output, - scoped_refptr mixer_task_runner, - const std::string& pipeline_json, - scoped_refptr io_task_runner) - : output_(std::move(output)), - post_processing_pipeline_factory_( - std::make_unique()), - mixer_task_runner_(mixer_task_runner), - io_task_runner_(std::move(io_task_runner)), - enable_dynamic_channel_count_( - GetSwitchValueBoolean(switches::kMixerEnableDynamicChannelCount, - false)), - low_sample_rate_cutoff_( - GetSwitchValueBoolean(switches::kAlsaEnableUpsampling, false) - ? kLowSampleRateCutoff - : MixerOutputStream::kInvalidSampleRate), - fixed_num_output_channels_( - GetSwitchValueNonNegativeInt(switches::kAudioOutputChannels, - kInvalidNumChannels)), - fixed_output_sample_rate_(GetFixedOutputSampleRate()), - no_input_close_timeout_(GetNoInputCloseTimeout()), - filter_frame_alignment_(kDefaultFilterFrameAlignment), - state_(kStateStopped), - external_audio_pipeline_supported_( - ExternalAudioPipelineShlib::IsSupported()), - weak_factory_(this) { - LOG(INFO) << __func__; - DETACH_FROM_SEQUENCE(mixer_sequence_checker_); - logging::InitializeAudioLog(); - - volume_info_[AudioContentType::kOther].volume = 1.0f; - volume_info_[AudioContentType::kOther].limit = 1.0f; - volume_info_[AudioContentType::kOther].muted = false; - - if (mixer_task_runner_) { - // Test mode. - if (!io_task_runner_) { - io_task_runner_ = mixer_task_runner; - } - } else { - mixer_thread_ = base::MakeRefCounted(); - mixer_task_runner_ = mixer_thread_; - - if (!io_task_runner_) { - io_task_runner_ = AudioIoThread::Get()->task_runner(); - } - - health_checker_ = std::make_unique( - mixer_task_runner_, io_task_runner_, kHealthCheckInterval, - kMixerThreadCheckTimeout, - base::BindRepeating(&StreamMixer::OnHealthCheckFailed, - base::Unretained(this))); - LOG(INFO) << "Mixer health checker started"; - } - - if (fixed_output_sample_rate_ != MixerOutputStream::kInvalidSampleRate) { - LOG(INFO) << "Setting fixed sample rate to " << fixed_output_sample_rate_; - } - - { - base::AutoLock lock(input_creation_lock_); - CreatePostProcessors([](bool, const std::string&) {}, pipeline_json, - kDefaultInputChannels); - } - - // TODO(jyw): command line flag for filter frame alignment. - DCHECK_EQ(filter_frame_alignment_ & (filter_frame_alignment_ - 1), 0) - << "Alignment must be a power of 2."; - - if (external_audio_pipeline_supported_) { - external_volume_observer_ = - std::make_unique(this); - ExternalAudioPipelineShlib::AddExternalMediaVolumeChangeRequestObserver( - external_volume_observer_.get()); - } - - loopback_handler_ = std::make_unique(io_task_runner_); - receiver_ = base::SequenceBound( - io_task_runner_, this, loopback_handler_.get()); - UpdateStreamCounts(); -} - -void StreamMixer::OnHealthCheckFailed() { - LOG(FATAL) << "Crash on mixer thread health check failure!"; -} - -void StreamMixer::ResetPostProcessors(CastMediaShlib::ResultCallback callback) { - VolumeMap::Reload(); - RUN_ON_MIXER_THREAD(ResetPostProcessorsOnThread, std::move(callback), ""); -} - -void StreamMixer::ResetPostProcessorsOnThread( - CastMediaShlib::ResultCallback callback, - const std::string& override_config) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - - { - base::AutoLock lock(input_creation_lock_); - // Detach inputs. - for (const auto& input : inputs_) { - input.second->SetFilterGroup(nullptr); - } - - int expected_input_channels = kDefaultInputChannels; - for (const auto& input : inputs_) { - if (input.second->primary()) { - expected_input_channels = - std::max(expected_input_channels, input.second->num_channels()); - } - } - CreatePostProcessors(std::move(callback), override_config, - expected_input_channels); - } - - // Re-attach inputs. - for (const auto& input : inputs_) { - FilterGroup* input_group = - mixer_pipeline_->GetInputGroup(input.first->device_id()); - DCHECK(input_group) << "No input group for input.first->device_id()"; - input.second->SetFilterGroup(input_group); - } -} - -// May be called on mixer_task_runner_ or from ctor -void StreamMixer::CreatePostProcessors(CastMediaShlib::ResultCallback callback, - const std::string& override_config, - int expected_input_channels) { - // (Re)-create post processors. - mixer_pipeline_.reset(); - - if (!override_config.empty()) { - auto value = base::JSONReader::Read(override_config); - CHECK(value) << "Invalid JSON"; - PostProcessingPipelineParser parser(std::move(*value)); - mixer_pipeline_ = MixerPipeline::CreateMixerPipeline( - &parser, post_processing_pipeline_factory_.get(), - expected_input_channels); - } else { - PostProcessingPipelineParser parser(CastAudioJson::GetFilePath()); - mixer_pipeline_ = MixerPipeline::CreateMixerPipeline( - &parser, post_processing_pipeline_factory_.get(), - expected_input_channels); - } - - // Attempt to fall back to built-in cast_audio.json, unless we were reset with - // an override config. - if (!mixer_pipeline_ && override_config.empty()) { - AUDIO_LOG(WARNING) << "Invalid cast_audio.json config loaded. Retrying with" - " read-only config"; - callback(false, - "Unable to build pipeline."); // TODO(bshaya): Send more specific - // error message. - callback = nullptr; - PostProcessingPipelineParser parser(CastAudioJson::GetReadOnlyFilePath()); - mixer_pipeline_.reset(); - mixer_pipeline_ = MixerPipeline::CreateMixerPipeline( - &parser, post_processing_pipeline_factory_.get(), - expected_input_channels); - } - - CHECK(mixer_pipeline_) << "Unable to load post processor config!"; - if (fixed_num_output_channels_ != kInvalidNumChannels && - fixed_num_output_channels_ != mixer_pipeline_->GetOutputChannelCount()) { - // Just log a warning, but this is still fine because we will remap the - // channels prior to output. - AUDIO_LOG(WARNING) << "PostProcessor configuration output channel count" - << " does not match command line flag: " - << mixer_pipeline_->GetOutputChannelCount() << " vs " - << fixed_num_output_channels_ - << ". Channels will be remapped"; - } - - if (state_ == kStateRunning) { - mixer_pipeline_->Initialize(output_samples_per_second_, frames_per_write_); - } - - post_processor_input_channels_ = expected_input_channels; - - if (callback) { - callback(true, ""); - } -} - -void StreamMixer::ResetPostProcessorsForTest( - std::unique_ptr pipeline_factory, - const std::string& pipeline_json) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - LOG(INFO) << __FUNCTION__ << " disregard previous PostProcessor messages."; - mixer_pipeline_.reset(); - post_processing_pipeline_factory_ = std::move(pipeline_factory); - ResetPostProcessorsOnThread([](bool, const std::string&) {}, pipeline_json); -} - -void StreamMixer::SetNumOutputChannelsForTest(int num_output_channels) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - fixed_num_output_channels_ = num_output_channels; -} - -void StreamMixer::EnableDynamicChannelCountForTest(bool enable) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - enable_dynamic_channel_count_ = enable; -} - -LoopbackHandler* StreamMixer::GetLoopbackHandlerForTest() { - return loopback_handler_.get(); -} - -StreamMixer::~StreamMixer() { - LOG(INFO) << __func__; - - receiver_.Reset(); - - mixer_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&StreamMixer::FinalizeOnMixerThread, - base::Unretained(this))); - if (mixer_thread_) { - mixer_thread_->Stop(); - } - - if (external_volume_observer_) { - ExternalAudioPipelineShlib::RemoveExternalMediaVolumeChangeRequestObserver( - external_volume_observer_.get()); - } -} - -void StreamMixer::FinalizeOnMixerThread() { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - { - base::AutoLock lock(input_creation_lock_); - Stop(LoopbackInterruptReason::kOutputStopped); - } - - inputs_.clear(); - ignored_inputs_.clear(); -} - -void StreamMixer::SetNumOutputChannels(int num_channels) { - RUN_ON_MIXER_THREAD(SetNumOutputChannelsOnThread, num_channels); -} - -void StreamMixer::SetNumOutputChannelsOnThread(int num_channels) { - AUDIO_LOG(INFO) << "Set the number of output channels to " << num_channels; - enable_dynamic_channel_count_ = true; - fixed_num_output_channels_ = num_channels; - - if (state_ == kStateRunning && num_channels != num_output_channels_) { - { - base::AutoLock lock(input_creation_lock_); - Stop(LoopbackInterruptReason::kConfigChange); - } - Start(); - } -} - -void StreamMixer::Start() { - AUDIO_LOG(INFO) << __func__ << " with " << inputs_.size() << " active inputs"; - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - DCHECK(state_ == kStateStopped); - - { - base::AutoLock lock(input_creation_lock_); - // Detach inputs. - for (const auto& input : inputs_) { - input.second->SetFilterGroup(nullptr); - } - - if (post_processor_input_channels_ != requested_input_channels_) { - CreatePostProcessors([](bool, const std::string&) {}, - "" /* override_config */, requested_input_channels_); - } - - if (!output_) { - if (external_audio_pipeline_supported_) { - output_ = ExternalAudioPipelineShlib::CreateMixerOutputStream(); - } else { - output_ = MixerOutputStream::Create(); - } - } - DCHECK(output_); - - int requested_output_channels; - if (fixed_num_output_channels_ != kInvalidNumChannels) { - requested_output_channels = fixed_num_output_channels_; - } else { - requested_output_channels = mixer_pipeline_->GetOutputChannelCount(); - } - - int requested_sample_rate; - if (fixed_output_sample_rate_ != MixerOutputStream::kInvalidSampleRate) { - requested_sample_rate = fixed_output_sample_rate_; - } else if (low_sample_rate_cutoff_ != - MixerOutputStream::kInvalidSampleRate && - requested_output_samples_per_second_ < low_sample_rate_cutoff_) { - requested_sample_rate = - output_samples_per_second_ != MixerOutputStream::kInvalidSampleRate - ? output_samples_per_second_ - : kLowSampleRateFallback; - } else { - requested_sample_rate = requested_output_samples_per_second_; - } - - if (!output_->Start(requested_sample_rate, requested_output_channels)) { - Stop(LoopbackInterruptReason::kOutputStopped); - return; - } - - num_output_channels_ = output_->GetNumChannels(); - output_samples_per_second_ = output_->GetSampleRate(); - AUDIO_LOG(INFO) << "Output " << num_output_channels_ << " " - << ChannelString(num_output_channels_) << " at " - << output_samples_per_second_ << " samples per second"; - // Make sure the number of frames meets the filter alignment requirements. - frames_per_write_ = - output_->OptimalWriteFramesCount() & ~(filter_frame_alignment_ - 1); - CHECK_GT(frames_per_write_, 0); - - output_channel_mixer_ = std::make_unique( - mixer::GuessChannelLayout(mixer_pipeline_->GetOutputChannelCount()), - mixer_pipeline_->GetOutputChannelCount(), - mixer::GuessChannelLayout(num_output_channels_), num_output_channels_, - frames_per_write_); - - int num_loopback_channels = mixer_pipeline_->GetLoopbackChannelCount(); - if (!enable_dynamic_channel_count_ && num_output_channels_ == 1) { - num_loopback_channels = 1; - } - AUDIO_LOG(INFO) << "Using " << num_loopback_channels << " loopback " - << ChannelString(num_loopback_channels); - loopback_channel_mixer_ = std::make_unique( - mixer::GuessChannelLayout(mixer_pipeline_->GetLoopbackChannelCount()), - mixer_pipeline_->GetLoopbackChannelCount(), - mixer::GuessChannelLayout(num_loopback_channels), num_loopback_channels, - frames_per_write_); - - loopback_handler_->SetDataSize(frames_per_write_ * - mixer_pipeline_->GetLoopbackChannelCount() * - sizeof(float)); - - // Initialize filters. - mixer_pipeline_->Initialize(output_samples_per_second_, frames_per_write_); - - // Determine the appropriate sample rate for the redirector. If a product - // needs to have these be different and support redirecting, then we will - // need to add/update the per-input resamplers before redirecting. - redirector_samples_per_second_ = GetSampleRateForDeviceId( - ::media::AudioDeviceDescription::kDefaultDeviceId); - - const std::vector redirectable_device_ids = { - kPlatformAudioDeviceId, kAlarmAudioDeviceId, kTtsAudioDeviceId, - ::media::AudioDeviceDescription::kDefaultDeviceId, - ::media::AudioDeviceDescription::kCommunicationsDeviceId}; - - for (const char* device_id : redirectable_device_ids) { - DCHECK_EQ(redirector_samples_per_second_, - GetSampleRateForDeviceId(device_id)); - } - - redirector_frames_per_write_ = redirector_samples_per_second_ * - frames_per_write_ / - output_samples_per_second_; - for (auto& redirector : audio_output_redirectors_) { - redirector.second->SetSampleRate(redirector_samples_per_second_); - } - - state_ = kStateRunning; - playback_loop_task_ = base::BindRepeating(&StreamMixer::PlaybackLoop, - weak_factory_.GetWeakPtr()); - - // Write one buffer of silence to get correct rendering delay in the - // postprocessors. - WriteOneBuffer(); - } - - // Re-attach inputs. - for (const auto& input : inputs_) { - FilterGroup* input_group = - mixer_pipeline_->GetInputGroup(input.first->device_id()); - DCHECK(input_group) << "No input group for input.first->device_id()"; - input.second->SetFilterGroup(input_group); - } - - mixer_task_runner_->PostTask(FROM_HERE, playback_loop_task_); -} - -void StreamMixer::Stop(LoopbackInterruptReason reason) { - AUDIO_LOG(INFO) << __func__; - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - - weak_factory_.InvalidateWeakPtrs(); - loopback_handler_->SendInterrupt(reason); - - if (output_) { - output_->Stop(); - } - - state_ = kStateStopped; - output_samples_per_second_ = MixerOutputStream::kInvalidSampleRate; -} - -void StreamMixer::CheckChangeOutputParams(int num_input_channels, - int input_samples_per_second) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - if (state_ != kStateRunning) { - return; - } - - bool num_input_channels_unchanged = - (num_input_channels == post_processor_input_channels_); - - bool sample_rate_unchanged = - (fixed_output_sample_rate_ != MixerOutputStream::kInvalidSampleRate || - input_samples_per_second == requested_output_samples_per_second_ || - input_samples_per_second == output_samples_per_second_ || - input_samples_per_second < static_cast(low_sample_rate_cutoff_)); - - if (num_input_channels_unchanged && sample_rate_unchanged) { - return; - } - - for (const auto& input : inputs_) { - if (input.second->primary()) { - return; - } - } - - // Ignore existing inputs. - SignalError(MixerInput::Source::MixerError::kInputIgnored); - - requested_input_channels_ = num_input_channels; - requested_output_samples_per_second_ = input_samples_per_second; - - // Restart the output so that the new output params take effect. - { - base::AutoLock lock(input_creation_lock_); - Stop(LoopbackInterruptReason::kConfigChange); - } - Start(); -} - -void StreamMixer::SignalError(MixerInput::Source::MixerError error) { - // Move all current inputs to the ignored list and inform them of the error. - for (auto& input : inputs_) { - input.second->SignalError(error); - ignored_inputs_.insert(std::move(input)); - } - inputs_.clear(); - SetCloseTimeout(); - UpdateStreamCountsOnThread(); -} - -int StreamMixer::GetEffectiveChannelCount(MixerInput::Source* input_source) { - AUDIO_LOG(INFO) << "Input source channel count = " - << input_source->num_channels(); - if (!enable_dynamic_channel_count_) { - AUDIO_LOG(INFO) << "Dynamic channel count not enabled; using stereo"; - return kDefaultInputChannels; - } - - // Most streams are at least stereo; to avoid unnecessary pipeline - // reconfiguration, treat mono streams as stereo when calculating pipeline - // inputs channel count. - return std::max(input_source->num_channels(), kMinInputChannels); -} - -void StreamMixer::AddInput(MixerInput::Source* input_source) { - std::unique_ptr input; - { - base::AutoLock lock(input_creation_lock_); - if (state_ == kStateRunning) { - input = CreateInput(input_source); - } - } - RUN_ON_MIXER_THREAD(AddInputOnThread, input_source, std::move(input)); -} - -std::unique_ptr StreamMixer::CreateInput( - MixerInput::Source* input_source) { - FilterGroup* input_group = - mixer_pipeline_->GetInputGroup(input_source->device_id()); - DCHECK(input_group) << "Could not find a processor for " - << input_source->device_id(); - - AUDIO_LOG(INFO) << "Add input " << input_source << " to " - << input_group->name() << " @ " - << input_group->GetInputSampleRate() - << " samples per second. Is primary source? = " - << input_source->primary(); - - return std::make_unique(input_source, input_group); -} - -void StreamMixer::AddInputOnThread(MixerInput::Source* input_source, - std::unique_ptr input) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - DCHECK(input_source); - - // If the new input is a primary one (or there were no inputs previously), we - // may need to change the output sample rate to match the input sample rate. - // We only change the output rate if it is not set to a fixed value. - if (input_source->primary() || inputs_.empty()) { - CheckChangeOutputParams(GetEffectiveChannelCount(input_source), - input_source->sample_rate()); - } - - if (state_ == kStateStopped) { - requested_input_channels_ = GetEffectiveChannelCount(input_source); - requested_output_samples_per_second_ = input_source->sample_rate(); - Start(); - } - - if (!input) { - input = CreateInput(input_source); - } else { - // Make sure the input is using the right filter group (since config could - // have been changed since the input was created). - FilterGroup* input_group = - mixer_pipeline_->GetInputGroup(input_source->device_id()); - DCHECK(input_group) << "Could not find a processor for " - << input_source->device_id(); - input->SetFilterGroup(input_group); - } - DCHECK(input); - input->Initialize(); - if (state_ != kStateRunning) { - // Mixer error occurred, signal error. - MixerInput* input_ptr = input.get(); - ignored_inputs_[input_source] = std::move(input); - input_ptr->SignalError(MixerInput::Source::MixerError::kInternalError); - return; - } - - auto type = input->content_type(); - if (type != AudioContentType::kOther) { - input->SetContentTypeVolume(volume_info_[type].volume); - input->SetMuted(volume_info_[type].muted); - } - if (input->primary() && input->focus_type() != AudioContentType::kOther) { - input->SetOutputLimit(volume_info_[input->focus_type()].limit, - kUseDefaultFade); - } - - for (auto& redirector : audio_output_redirectors_) { - redirector.second->AddInput(input.get()); - } - - inputs_[input_source] = std::move(input); - UpdateStreamCountsOnThread(); -} - -void StreamMixer::RemoveInput(MixerInput::Source* input_source) { - // Always post a task to avoid synchronous deletion. - RUN_ON_MIXER_THREAD(RemoveInputOnThread, input_source); -} - -void StreamMixer::RemoveInputOnThread(MixerInput::Source* input_source) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - DCHECK(input_source); - - AUDIO_LOG(INFO) << "Remove input " << input_source; - - std::unique_ptr input; - auto it = inputs_.find(input_source); - if (it != inputs_.end()) { - for (auto& redirector : audio_output_redirectors_) { - redirector.second->RemoveInput(it->second.get()); - } - input = std::move(it->second); - inputs_.erase(it); - } else { - it = ignored_inputs_.find(input_source); - if (it != ignored_inputs_.end()) { - input = std::move(it->second); - ignored_inputs_.erase(it); - } - } - - if (input) { - input->Destroy(); - io_task_runner_->DeleteSoon(FROM_HERE, std::move(input)); - } - UpdateStreamCountsOnThread(); - - if (inputs_.empty()) { - SetCloseTimeout(); - } -} - -void StreamMixer::SetCloseTimeout() { - close_timestamp_ = (no_input_close_timeout_.is_max() - ? base::TimeTicks::Max() - : base::TimeTicks::Now() + no_input_close_timeout_); -} - -void StreamMixer::UpdateStreamCounts() { - RUN_ON_MIXER_THREAD(UpdateStreamCountsOnThread); -} - -void StreamMixer::UpdateStreamCountsOnThread() { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - int primary = 0; - int sfx = 0; - for (const auto& it : inputs_) { - MixerInput* input = it.second.get(); - if (input->source()->active() && - (input->TargetVolume() > 0.0f || input->InstantaneousVolume() > 0.0f)) { - (input->primary() ? primary : sfx) += 1; - } - } - - if (primary != last_sent_primary_stream_count_ || - sfx != last_sent_sfx_stream_count_) { - last_sent_primary_stream_count_ = primary; - last_sent_sfx_stream_count_ = sfx; - receiver_.AsyncCall(&MixerServiceReceiver::OnStreamCountChanged) - .WithArgs(primary, sfx); - } -} - -MediaPipelineBackend::AudioDecoder::RenderingDelay -StreamMixer::GetTotalRenderingDelay(FilterGroup* filter_group) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - if (!output_) { - return MediaPipelineBackend::AudioDecoder::RenderingDelay(); - } - if (!filter_group) { - return output_->GetRenderingDelay(); - } - - // Includes |output_->GetRenderingDelay()|. - return filter_group->GetRenderingDelayToOutput(); -} - -void StreamMixer::PlaybackLoop() { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - if (inputs_.empty() && base::TimeTicks::Now() >= close_timestamp_ && - !mixer_pipeline_->IsRinging()) { - AUDIO_LOG(INFO) << "Close timeout"; - base::AutoLock lock(input_creation_lock_); - Stop(LoopbackInterruptReason::kOutputStopped); - return; - } - - WriteOneBuffer(); - UpdateStreamCountsOnThread(); - - mixer_task_runner_->PostTask(FROM_HERE, playback_loop_task_); -} - -void StreamMixer::WriteOneBuffer() { - for (auto& redirector : audio_output_redirectors_) { - redirector.second->PrepareNextBuffer(redirector_frames_per_write_); - } - - // Recursively mix and filter each group. - MediaPipelineBackend::AudioDecoder::RenderingDelay rendering_delay = - output_->GetRenderingDelay(); - mixer_pipeline_->MixAndFilter(frames_per_write_, rendering_delay); - - int64_t expected_playback_time; - if (rendering_delay.timestamp_microseconds == kNoTimestamp) { - expected_playback_time = kNoTimestamp; - } else { - expected_playback_time = - rendering_delay.timestamp_microseconds + - rendering_delay.delay_microseconds + - mixer_pipeline_->GetPostLoopbackRenderingDelayMicroseconds(); - } - - for (auto& redirector : audio_output_redirectors_) { - redirector.second->FinishBuffer(); - } - - WriteMixedPcm(frames_per_write_, expected_playback_time); -} - -void StreamMixer::WriteMixedPcm(int frames, int64_t expected_playback_time) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - - int loopback_channel_count = loopback_channel_mixer_->output_channel_count(); - float* loopback_data = loopback_channel_mixer_->Transform( - mixer_pipeline_->GetLoopbackOutput(), frames); - - // Hard limit to [1.0, -1.0] - for (int i = 0; i < frames * loopback_channel_count; ++i) { - // TODO(bshaya): Warn about clipping here. - loopback_data[i] = std::clamp(loopback_data[i], -1.0f, 1.0f); - } - - loopback_handler_->SendData(expected_playback_time, - output_samples_per_second_, - loopback_channel_count, loopback_data, frames); - - float* linearized_data = - output_channel_mixer_->Transform(mixer_pipeline_->GetOutput(), frames); - - // Hard limit to [1.0, -1.0]. - for (int i = 0; i < frames * num_output_channels_; ++i) { - linearized_data[i] = std::clamp(linearized_data[i], -1.0f, 1.0f); - } - - bool playback_interrupted = false; - output_->Write(linearized_data, frames * num_output_channels_, - &playback_interrupted); - - if (playback_interrupted) { - loopback_handler_->SendInterrupt(LoopbackInterruptReason::kUnderrun); - - for (const auto& input : inputs_) { - input.first->OnOutputUnderrun(); - } - } -} - -void StreamMixer::AddAudioOutputRedirector( - std::unique_ptr redirector) { - RUN_ON_MIXER_THREAD(AddAudioOutputRedirectorOnThread, std::move(redirector)); -} - -void StreamMixer::AddAudioOutputRedirectorOnThread( - std::unique_ptr redirector) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - AUDIO_LOG(INFO) << __func__; - DCHECK(redirector); - - AudioOutputRedirector* key = redirector.get(); - audio_output_redirectors_[key] = std::move(redirector); - - if (state_ == kStateRunning) { - key->SetSampleRate(redirector_samples_per_second_); - } - - for (const auto& input : inputs_) { - key->AddInput(input.second.get()); - } -} - -void StreamMixer::RemoveAudioOutputRedirector( - AudioOutputRedirector* redirector) { - // Always post a task to avoid synchronous deletion. - RUN_ON_MIXER_THREAD(RemoveAudioOutputRedirectorOnThread, redirector); -} - -void StreamMixer::RemoveAudioOutputRedirectorOnThread( - AudioOutputRedirector* redirector) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - AUDIO_LOG(INFO) << __func__; - audio_output_redirectors_.erase(redirector); -} - -void StreamMixer::SetVolume(AudioContentType type, float level) { - RUN_ON_MIXER_THREAD(SetVolumeOnThread, type, level); -} - -void StreamMixer::SetVolumeOnThread(AudioContentType type, float level) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - DCHECK(type != AudioContentType::kOther); - - volume_info_[type].volume = level; - for (const auto& input : inputs_) { - if (input.second->content_type() == type) { - input.second->SetContentTypeVolume(level); - } - } - if (external_audio_pipeline_supported_ && type == AudioContentType::kMedia) { - ExternalAudioPipelineShlib::SetExternalMediaVolume( - std::min(level, volume_info_[type].limit)); - } - UpdateStreamCountsOnThread(); -} - -void StreamMixer::SetMuted(AudioContentType type, bool muted) { - RUN_ON_MIXER_THREAD(SetMutedOnThread, type, muted); -} - -void StreamMixer::SetMutedOnThread(AudioContentType type, bool muted) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - DCHECK(type != AudioContentType::kOther); - - volume_info_[type].muted = muted; - for (const auto& input : inputs_) { - if (input.second->content_type() == type) { - input.second->SetMuted(muted); - } - } - if (external_audio_pipeline_supported_ && type == AudioContentType::kMedia) { - ExternalAudioPipelineShlib::SetExternalMediaMuted(muted); - } - UpdateStreamCountsOnThread(); -} - -void StreamMixer::SetOutputLimit(AudioContentType type, float limit) { - RUN_ON_MIXER_THREAD(SetOutputLimitOnThread, type, limit); -} - -void StreamMixer::SetOutputLimitOnThread(AudioContentType type, float limit) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - DCHECK(type != AudioContentType::kOther); - - AUDIO_LOG(INFO) << "Set volume limit for " << type << " to " << limit; - volume_info_[type].limit = limit; - int fade_ms = kUseDefaultFade; - if (type == AudioContentType::kMedia) { - if (limit >= 1.0f) { // Unducking. - fade_ms = kMediaUnduckFadeMs; - } else { - fade_ms = kMediaDuckFadeMs; - } - } - for (const auto& input : inputs_) { - // Volume limits don't apply to effects streams. - if (input.second->primary() && input.second->focus_type() == type) { - input.second->SetOutputLimit(limit, fade_ms); - } - } - if (external_audio_pipeline_supported_ && type == AudioContentType::kMedia) { - ExternalAudioPipelineShlib::SetExternalMediaVolume( - std::min(volume_info_[type].volume, limit)); - } - UpdateStreamCountsOnThread(); -} - -void StreamMixer::SetVolumeMultiplier(MixerInput::Source* source, - float multiplier) { - RUN_ON_MIXER_THREAD(SetVolumeMultiplierOnThread, source, multiplier); -} - -void StreamMixer::SetVolumeMultiplierOnThread(MixerInput::Source* source, - float multiplier) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - auto it = inputs_.find(source); - if (it != inputs_.end()) { - it->second->SetVolumeMultiplier(multiplier); - } - UpdateStreamCountsOnThread(); -} - -void StreamMixer::SetSimulatedClockRate(MixerInput::Source* source, - double new_clock_rate) { - RUN_ON_MIXER_THREAD(SetSimulatedClockRateOnThread, source, new_clock_rate); -} - -void StreamMixer::SetSimulatedClockRateOnThread(MixerInput::Source* source, - double new_clock_rate) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - auto it = inputs_.find(source); - if (it != inputs_.end()) { - it->second->SetSimulatedClockRate(new_clock_rate); - } -} - -void StreamMixer::SetPostProcessorConfig(std::string name, std::string config) { - RUN_ON_MIXER_THREAD(SetPostProcessorConfigOnThread, std::move(name), - std::move(config)); -} - -void StreamMixer::SetPostProcessorConfigOnThread(std::string name, - std::string config) { - DCHECK_CALLED_ON_VALID_SEQUENCE(mixer_sequence_checker_); - mixer_pipeline_->SetPostProcessorConfig(name, config); -} - -int StreamMixer::GetSampleRateForDeviceId(const std::string& device) { - DCHECK(mixer_pipeline_); - return mixer_pipeline_->GetInputGroup(device)->GetInputSampleRate(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/stream_mixer.h chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/stream_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,276 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MIXER_STREAM_MIXER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MIXER_STREAM_MIXER_H_ - -#include - -#include -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "base/synchronization/lock.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/task_runner.h" -#include "base/threading/sequence_bound.h" -#include "base/time/time.h" -#include "chromecast/media/cma/backend/mixer/mixer_input.h" -#include "chromecast/media/cma/backend/mixer/mixer_pipeline.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/external_audio_pipeline_shlib.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -class ThreadHealthChecker; - -namespace media { - -class AudioOutputRedirector; -class InterleavedChannelMixer; -class LoopbackHandler; -enum class LoopbackInterruptReason; -class MixerServiceReceiver; -class MixerOutputStream; -class PostProcessingPipelineFactory; - -// Mixer implementation. The mixer has zero or more inputs; these can be added -// or removed at any time. The mixer will pull from each input source whenever -// it needs more data; input sources provide data if available, and return the -// number of frames filled. Any unfilled frames will be filled with silence; -// the mixer always outputs audio when active, even if input sources underflow. -// The MixerInput class wraps each source and provides volume control and -// resampling to the output rate. The mixer will pass the current rendering -// delay to each source when it requests data; this delay indicates when the new -// data will play out of the speaker (the newly filled data will play out at -// delay.timestamp + delay.delay). -// -// The mixer chooses its output sample rate based on the sample rates of the -// current sources (unless the output sample rate is fixed via the -// --audio-output-sample-rate command line flag). When a new source is added: -// * If the mixer was not running, it is started with the output sample rate -// set to the input sample rate of the new source. -// * If the mixer previously had no input sources, the output sample rate is -// updated to match the input sample rate of the new source. -// * If the new input source is primary, and the mixer has no other primary -// input sources, then the output sample rate is updated to match the input -// sample rate of the new source. -// * Otherwise, the output sample rate remains unchanged. -class StreamMixer { - public: - StreamMixer( - scoped_refptr io_task_runner = nullptr); - - StreamMixer(const StreamMixer&) = delete; - StreamMixer& operator=(const StreamMixer&) = delete; - - ~StreamMixer(); - - int num_output_channels() const { return num_output_channels_; } - - scoped_refptr task_runner() const { - return mixer_task_runner_; - } - - // Adds an input source to the mixer. The |input_source| must live at least - // until input_source->FinalizeAudioPlayback() is called. - void AddInput(MixerInput::Source* input_source) - LOCKS_EXCLUDED(input_creation_lock_); - // Removes an input source from the mixer. The input source will be removed - // asynchronously. Once it has been removed, FinalizeAudioPlayback() will be - // called on it; at this point it is safe to delete the input source. - void RemoveInput(MixerInput::Source* input_source); - - // Adds/removes an output redirector. Output redirectors take audio from - // matching inputs and pass them to secondary output instead of the normal - // mixer output. - void AddAudioOutputRedirector( - std::unique_ptr redirector); - void RemoveAudioOutputRedirector(AudioOutputRedirector* redirector); - - // Sets the volume multiplier for the given content |type|. - void SetVolume(AudioContentType type, float level); - - // Sets the mute state for the given content |type|. - void SetMuted(AudioContentType type, bool muted); - - // Sets the volume multiplier limit for the given content |type|. - void SetOutputLimit(AudioContentType type, float limit); - - // Sets the per-stream volume multiplier for |source|. - void SetVolumeMultiplier(MixerInput::Source* source, float multiplier); - - // Sets the simulated audio clock rate for |source|. - void SetSimulatedClockRate(MixerInput::Source* source, double new_clock_rate); - - // Sends configuration string |config| to processor |name|. - void SetPostProcessorConfig(std::string name, std::string config); - - void ResetPostProcessors(CastMediaShlib::ResultCallback callback); - - // Updates the counts of active streams and signals any observing control - // connections. - void UpdateStreamCounts(); - - // Sets the desired number of output channels that the mixer should use. The - // actual number of output channels may differ from this value. - void SetNumOutputChannels(int num_channels); - - // Test-only methods. - StreamMixer( - std::unique_ptr output, - scoped_refptr mixer_task_runner, - const std::string& pipeline_json, - scoped_refptr io_task_runner = nullptr); - void ResetPostProcessorsForTest( - std::unique_ptr pipeline_factory, - const std::string& pipeline_json); - void SetNumOutputChannelsForTest(int num_output_channels); - void EnableDynamicChannelCountForTest(bool enable); - LoopbackHandler* GetLoopbackHandlerForTest(); - - private: - class BaseExternalMediaVolumeChangeRequestObserver - : public ExternalAudioPipelineShlib:: - ExternalMediaVolumeChangeRequestObserver { - public: - ~BaseExternalMediaVolumeChangeRequestObserver() override = default; - }; - class ExternalMediaVolumeChangeRequestObserver; - - class MixerThread; - - enum State { - kStateStopped, - kStateRunning, - }; - - // Contains volume control information for an audio content type. - struct VolumeInfo { - float volume = 0.0f; - float limit = 1.0f; - bool muted = false; - }; - - void SetNumOutputChannelsOnThread(int num_channels) - LOCKS_EXCLUDED(input_creation_lock_); - void ResetPostProcessorsOnThread(CastMediaShlib::ResultCallback callback, - const std::string& override_config) - LOCKS_EXCLUDED(input_creation_lock_); - void CreatePostProcessors(CastMediaShlib::ResultCallback callback, - const std::string& override_config, - int expected_input_channels) - EXCLUSIVE_LOCKS_REQUIRED(input_creation_lock_); - void FinalizeOnMixerThread() LOCKS_EXCLUDED(input_creation_lock_); - void Start() LOCKS_EXCLUDED(input_creation_lock_); - void Stop(LoopbackInterruptReason reason) - EXCLUSIVE_LOCKS_REQUIRED(input_creation_lock_); - void CheckChangeOutputParams(int num_input_channels, - int input_samples_per_second) - LOCKS_EXCLUDED(input_creation_lock_); - void SignalError(MixerInput::Source::MixerError error); - int GetEffectiveChannelCount(MixerInput::Source* input_source); - std::unique_ptr CreateInput(MixerInput::Source* input_source); - void AddInputOnThread(MixerInput::Source* input_source, - std::unique_ptr input); - void RemoveInputOnThread(MixerInput::Source* input_source); - void SetCloseTimeout(); - - void PlaybackLoop() LOCKS_EXCLUDED(input_creation_lock_); - void WriteOneBuffer(); - void WriteMixedPcm(int frames, int64_t expected_playback_time); - - void UpdateStreamCountsOnThread(); - void SetVolumeOnThread(AudioContentType type, float level); - void SetMutedOnThread(AudioContentType type, bool muted); - void SetOutputLimitOnThread(AudioContentType type, float limit); - void SetVolumeMultiplierOnThread(MixerInput::Source* source, - float multiplier); - void SetSimulatedClockRateOnThread(MixerInput::Source* source, - double new_clock_rate); - void SetPostProcessorConfigOnThread(std::string name, std::string config); - void AddAudioOutputRedirectorOnThread( - std::unique_ptr redirector); - void RemoveAudioOutputRedirectorOnThread(AudioOutputRedirector* redirector); - - int GetSampleRateForDeviceId(const std::string& device); - - void OnHealthCheckFailed(); - - MediaPipelineBackend::AudioDecoder::RenderingDelay GetTotalRenderingDelay( - FilterGroup* filter_group); - - std::unique_ptr output_; - std::unique_ptr - post_processing_pipeline_factory_; - std::unique_ptr mixer_pipeline_; - SEQUENCE_CHECKER(mixer_sequence_checker_); - scoped_refptr mixer_thread_; - scoped_refptr mixer_task_runner_; - scoped_refptr io_task_runner_; - std::unique_ptr health_checker_; - - std::unique_ptr loopback_channel_mixer_; - std::unique_ptr output_channel_mixer_; - - bool enable_dynamic_channel_count_; - const int low_sample_rate_cutoff_; - int fixed_num_output_channels_; - const int fixed_output_sample_rate_; - const base::TimeDelta no_input_close_timeout_; - // Force data to be filtered in multiples of |filter_frame_alignment_| frames. - // Must be a multiple of 4 for some NEON implementations. Some - // AudioPostProcessors require stricter alignment conditions. - const int filter_frame_alignment_; - - int requested_input_channels_ = 0; - int post_processor_input_channels_ = 0; - int num_output_channels_ = 0; - - int requested_output_samples_per_second_ = 0; - int output_samples_per_second_ = 0; - int frames_per_write_ = 0; - - int redirector_samples_per_second_ = 0; - int redirector_frames_per_write_ = 0; - - int last_sent_primary_stream_count_ = 0; - int last_sent_sfx_stream_count_ = 0; - - State state_; - base::TimeTicks close_timestamp_; - - base::Lock input_creation_lock_; - - base::RepeatingClosure playback_loop_task_; - base::flat_map> inputs_; - base::flat_map> - ignored_inputs_; - - base::flat_map volume_info_; - - base::flat_map> - audio_output_redirectors_; - - const bool external_audio_pipeline_supported_; - std::unique_ptr - external_volume_observer_; - - std::unique_ptr loopback_handler_; - base::SequenceBound receiver_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MIXER_STREAM_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/stream_mixer_external_audio_pipeline_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer_external_audio_pipeline_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/stream_mixer_external_audio_pipeline_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer_external_audio_pipeline_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,237 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "base/location.h" -#include "base/message_loop/message_pump_type.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "chromecast/media/audio/fake_external_audio_pipeline_support.h" -#include "chromecast/media/audio/mixer_service/loopback_connection.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/cma/backend/mixer/loopback_test_support.h" -#include "chromecast/media/cma/backend/mixer/mock_mixer_source.h" -#include "chromecast/media/cma/backend/mixer/mock_post_processor_factory.h" -#include "chromecast/media/cma/backend/mixer/stream_mixer.h" -#include "chromecast/public/media/external_audio_pipeline_shlib.h" -#include "chromecast/public/media/mixer_output_stream.h" -#include "media/base/audio_bus.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::_; -using ::testing::AtLeast; - -// Mock for saving and checking loopback audio data. -class MockLoopbackAudioObserver - : public mixer_service::LoopbackConnection::Delegate { - public: - MockLoopbackAudioObserver() { - ON_CALL(*this, OnLoopbackAudio(_, _, _, _, _, _)) - .WillByDefault(::testing::Invoke( - this, &MockLoopbackAudioObserver::OnLoopbackAudioImpl)); - } - - MockLoopbackAudioObserver(const MockLoopbackAudioObserver&) = delete; - MockLoopbackAudioObserver& operator=(const MockLoopbackAudioObserver&) = - delete; - - MOCK_METHOD6(OnLoopbackAudio, - void(int64_t timestamp, - SampleFormat sample_format, - int sample_rate, - int num_channels, - uint8_t* data, - int length)); - MOCK_METHOD1(OnLoopbackInterrupted, void(LoopbackInterruptReason)); - - const std::vector& data() const { return data_; } - - private: - void OnLoopbackAudioImpl(int64_t timestamp, - SampleFormat sample_format, - int sample_rate, - int num_channels, - uint8_t* data, - int length) { - data_.clear(); - // Save received data to local. - float* float_data = reinterpret_cast(const_cast(data)); - const size_t size = length / sizeof(float); - data_.insert(data_.end(), float_data, float_data + size); - } - - std::vector data_; -}; - -class ExternalAudioPipelineTest : public ::testing::Test { - public: - ExternalAudioPipelineTest() - : external_audio_pipeline_support_( - testing::GetFakeExternalAudioPipelineSupport()) {} - - ExternalAudioPipelineTest(const ExternalAudioPipelineTest&) = delete; - ExternalAudioPipelineTest& operator=(const ExternalAudioPipelineTest&) = - delete; - - void SetUp() override { - // Set that external library is supported. - external_audio_pipeline_support_->SetSupported(); - - mixer_ = std::make_unique( - nullptr, base::SingleThreadTaskRunner::GetCurrentDefault(), "{}"); - } - - void TearDown() override { - // Reset library internal state to use it for other unit tests. - external_audio_pipeline_support_->Reset(); - } - // Run async operations in the stream mixer. - void RunLoopForMixer() { - base::RunLoop run_loop; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, run_loop.QuitClosure()); - run_loop.Run(); - } - - std::unique_ptr AddLoopbackObserver( - mixer_service::LoopbackConnection::Delegate* observer) { - std::unique_ptr loopback_socket = - CreateLoopbackConnectionForTest(mixer_->GetLoopbackHandlerForTest()); - auto connection = std::make_unique( - observer, std::move(loopback_socket)); - connection->Connect(); - return connection; - } - - protected: - std::unique_ptr mixer_; - testing::FakeExternalAudioPipelineSupport* const - external_audio_pipeline_support_; - - base::test::SingleThreadTaskEnvironment task_environment_{ - base::test::TaskEnvironment::MainThreadType::IO}; -}; - -// Check that |expected| matches |actual| exactly. -void CompareAudioData(const ::media::AudioBus& expected, - const ::media::AudioBus& actual) { - ASSERT_EQ(expected.channels(), actual.channels()); - ASSERT_EQ(expected.frames(), actual.frames()); - for (int c = 0; c < expected.channels(); ++c) { - const float* expected_data = expected.channel(c); - const float* actual_data = actual.channel(c); - for (int f = 0; f < expected.frames(); ++f) { - EXPECT_FLOAT_EQ(*expected_data++, *actual_data++) << c << " " << f; - } - } -} - -// Unit tests for ExternalAudioPipelineShlib library. -// Test media volume notification. -TEST_F(ExternalAudioPipelineTest, SetMediaVolume) { - ASSERT_EQ(external_audio_pipeline_support_->GetVolume(), 0.0f); - - mixer_->SetVolume(AudioContentType::kMedia, 0.02); - RunLoopForMixer(); - ASSERT_EQ(external_audio_pipeline_support_->GetVolume(), 0.02f); -} -// Test media muted notification. -TEST_F(ExternalAudioPipelineTest, SetMediaMuted) { - ASSERT_EQ(external_audio_pipeline_support_->IsMuted(), false); - - mixer_->SetMuted(AudioContentType::kMedia, true); - RunLoopForMixer(); - ASSERT_EQ(external_audio_pipeline_support_->IsMuted(), true); -} -// Set media volume from library, check notification. -TEST_F(ExternalAudioPipelineTest, SetVolumeChangeRequest) { - ASSERT_EQ(external_audio_pipeline_support_->GetVolume(), 0.0f); - - external_audio_pipeline_support_->OnVolumeChangeRequest(0.03); - RunLoopForMixer(); - ASSERT_EQ(external_audio_pipeline_support_->GetVolume(), 0.03f); -} -// Set media mute from library, check notification. -TEST_F(ExternalAudioPipelineTest, SetMuteChangeRequest) { - ASSERT_EQ(external_audio_pipeline_support_->IsMuted(), false); - - external_audio_pipeline_support_->OnMuteChangeRequest(true); - RunLoopForMixer(); - ASSERT_EQ(external_audio_pipeline_support_->IsMuted(), true); -} -// Check external library loopback data. Check that passed input to StreamMixer -// comes to CastMediaShlib::LoopbackAudioObserver w/o changes. -TEST_F(ExternalAudioPipelineTest, ExternalAudioPipelineLoopbackData) { - // Set Volume to 1, because we'd like the input to be w/o changes. - mixer_->SetVolume(AudioContentType::kMedia, 1); - - // Add fake postprocessor to override test configuration running on device. - const int kNumChannels = 2; - mixer_->SetNumOutputChannelsForTest(kNumChannels); - mixer_->ResetPostProcessorsForTest( - std::make_unique(), "{}"); - - // Input. - MockMixerSource input(48000); - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(input, FinalizeAudioPlayback()).Times(1); - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(AtLeast(1)); - - // Prepare data for test. - const size_t kSampleSize = 64; - uint8_t test_data[kSampleSize]; - for (size_t i = 0; i < kSampleSize; ++i) - test_data[i] = i; - - // Set test data in AudioBus. - const auto kNumFrames = kSampleSize / kNumChannels; - auto data = ::media::AudioBus::Create(kNumChannels, kNumFrames); - data->FromInterleaved<::media::UnsignedInt8SampleTypeTraits>(test_data, - kNumFrames); - // Prepare data for compare. - auto expected = ::media::AudioBus::Create(kNumChannels, kNumFrames); - data->CopyTo(expected.get()); - - mixer_->AddInput(&input); - MockLoopbackAudioObserver mock_loopback_observer; - auto connection = AddLoopbackObserver(&mock_loopback_observer); - EXPECT_CALL(mock_loopback_observer, OnLoopbackAudio(_, _, _, _, _, _)) - .Times(AtLeast(1)); - RunLoopForMixer(); - - // Send data to the stream mixer. - input.SetData(std::move(data)); - RunLoopForMixer(); - RunLoopForMixer(); - RunLoopForMixer(); - - // Get actual data from our mocked loopback observer. - ASSERT_GE(mock_loopback_observer.data().size(), kNumFrames); - - auto actual = ::media::AudioBus::Create(kNumChannels, kNumFrames); - using FloatType = ::media::Float32SampleTypeTraits; - actual->FromInterleaved(mock_loopback_observer.data().data(), - kNumFrames); - - CompareAudioData(*expected, *actual); - - // Check OnRemoved. - mixer_->RemoveInput(&input); - - RunLoopForMixer(); - task_environment_.RunUntilIdle(); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/stream_mixer_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/mixer/stream_mixer_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mixer/stream_mixer_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,1687 +0,0 @@ -// 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 "chromecast/media/cma/backend/mixer/stream_mixer.h" - -#include -#include -#include -#include -#include - -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/ranges/algorithm.h" -#include "base/run_loop.h" -#include "base/strings/stringprintf.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "base/values.h" -#include "chromecast/media/audio/mixer_service/loopback_connection.h" -#include "chromecast/media/audio/mixer_service/mixer_socket.h" -#include "chromecast/media/audio/mixer_service/redirected_audio_connection.h" -#include "chromecast/media/cma/backend/mixer/audio_output_redirector.h" -#include "chromecast/media/cma/backend/mixer/channel_layout.h" -#include "chromecast/media/cma/backend/mixer/loopback_handler.h" -#include "chromecast/media/cma/backend/mixer/loopback_test_support.h" -#include "chromecast/media/cma/backend/mixer/mixer_input.h" -#include "chromecast/media/cma/backend/mixer/mock_mixer_source.h" -#include "chromecast/media/cma/backend/mixer/mock_post_processor_factory.h" -#include "chromecast/media/cma/backend/mixer/mock_redirected_audio_output.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/mixer_output_stream.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/audio_device_description.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_sample_types.h" -#include "media/base/channel_layout.h" -#include "media/base/channel_mixer.h" -#include "media/base/vector_math.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; -using testing::NiceMock; - -namespace chromecast { -namespace media { - -namespace { - -using FloatType = ::media::Float32SampleTypeTraits; -using StreamMatchPatterns = - std::vector>; -using RedirectionConfig = mixer_service::RedirectedAudioConnection::Config; - -// Testing constants that are common to multiple test cases. -const size_t kBytesPerSample = sizeof(int32_t); -const int kNumChannels = 2; -const int kOutputFrames = 256; - -// kTestSamplesPerSecond needs to be higher than kLowSampleRateCutoff for the -// mixer to use it. -const int kTestSamplesPerSecond = 48000; - -// This array holds |NUM_DATA_SETS| sets of arbitrary interleaved float data. -// Each set holds |NUM_SAMPLES| / kNumChannels frames of data. -#define NUM_DATA_SETS 2u -#define NUM_SAMPLES 64u - -// Note: Test data should be represented as 32-bit integers and copied into -// ::media::AudioBus instances, rather than wrapping statically declared float -// arrays. The latter method is brittle, as ::media::AudioBus requires 16-byte -// alignment for internal data. -const int32_t kTestData[NUM_DATA_SETS][NUM_SAMPLES] = { - { - 74343736, -1333200799, -1360871126, 1138806283, 1931811865, - 1856308487, 649203634, 564640023, 1676630678, 23416591, - -1293255456, 547928305, -976258952, 1840550252, 1714525174, - 358704931, 983646295, 1264863573, 442473973, 1222979052, - 317404525, 366912613, 1393280948, -1022004648, -2054669405, - -159762261, 1127018745, -1984491787, 1406988336, -693327981, - -1549544744, 1232236854, 970338338, -1750160519, -783213057, - 1231504562, 1155296810, -820018779, 1155689800, -1108462340, - -150535168, 1033717023, 2121241397, 1829995370, -1893006836, - -819097508, -495186107, 1001768909, -1441111852, 692174781, - 1916569026, -687787473, -910565280, 1695751872, 994166817, - 1775451433, 909418522, 492671403, -761744663, -2064315902, - 1357716471, -1580019684, 1872702377, -1524457840, - }, - { - 1951643876, 712069070, 1105286211, 1725522438, -986938388, - 229538084, 1042753634, 1888456317, 1477803757, 1486284170, - -340193623, -1828672521, 1418790906, -724453609, -1057163251, - 1408558147, -31441309, 1421569750, -1231100836, 545866721, - 1430262764, 2107819625, -2077050480, -1128358776, -1799818931, - -1041097926, 1911058583, -1177896929, -1911123008, -929110948, - 1267464176, 172218310, -2048128170, -2135590884, 734347065, - 1214930283, 1301338583, -326962976, -498269894, -1167887508, - -589067650, 591958162, 592999692, -788367017, -1389422, - 1466108561, 386162657, 1389031078, 936083827, -1438801160, - 1340850135, -1616803932, -850779335, 1666492408, 1290349909, - -492418001, 659200170, -542374913, -120005682, 1030923147, - -877887021, -870241979, 1322678128, -344799975, - }}; - -// Compensate for integer arithmetic errors. -const int kMaxDelayErrorUs = 2; - -const char kDelayModuleSolib[] = "delay.so"; - -// Should match # of "processors" blocks below. -const int kNumPostProcessors = 5; -const char kTestPipelineJsonTemplate[] = R"json( -{ - "postprocessors": { - "output_streams": [{ - "streams": [ "default" ], - "num_input_channels": 2, - "processors": [{ - "processor": "%s", - "config": { "delay": %d } - }] - }, { - "streams": [ "assistant-tts" ], - "num_input_channels": 2, - "processors": [{ - "processor": "%s", - "config": { "delay": %d } - }] - }, { - "streams": [ "communications" ], - "num_input_channels": 2, - "processors": [] - }], - "mix": { - "num_input_channels": 2, - "processors": [{ - "processor": "%s", - "config": { "delay": %d } - }] - }, - "linearize": { - "num_input_channels": 2, - "processors": [{ - "processor": "%s", - "config": { "delay": %d } - }] - } - } -} -)json"; - -const int kDefaultProcessorDelay = 10; -const int kTtsProcessorDelay = 100; -const int kMixProcessorDelay = 1000; -const int kLinearizeProcessorDelay = 10000; - -// Return a scoped pointer filled with the data laid out at |index| above. -std::unique_ptr<::media::AudioBus> GetTestData(size_t index) { - CHECK_LT(index, NUM_DATA_SETS); - int frames = NUM_SAMPLES / kNumChannels; - auto data = ::media::AudioBus::Create(kNumChannels, frames); - data->FromInterleaved<::media::SignedInt32SampleTypeTraits>(kTestData[index], - frames); - return data; -} - -class MockMixerOutput : public MixerOutputStream { - public: - MockMixerOutput() { - ON_CALL(*this, Start(_, _)) - .WillByDefault(testing::Invoke(this, &MockMixerOutput::StartImpl)); - ON_CALL(*this, GetSampleRate()) - .WillByDefault( - testing::Invoke(this, &MockMixerOutput::GetSampleRateImpl)); - ON_CALL(*this, GetNumChannels()) - .WillByDefault( - testing::Invoke(this, &MockMixerOutput::GetNumChannelsImpl)); - ON_CALL(*this, GetRenderingDelay()) - .WillByDefault( - testing::Invoke(this, &MockMixerOutput::GetRenderingDelayImpl)); - ON_CALL(*this, OptimalWriteFramesCount()) - .WillByDefault( - testing::Invoke(this, &MockMixerOutput::OptimalWriteFramesImpl)); - ON_CALL(*this, Write(_, _, _)) - .WillByDefault(testing::Invoke(this, &MockMixerOutput::WriteImpl)); - } - - MOCK_METHOD2(Start, bool(int, int)); - MOCK_METHOD0(GetNumChannels, int()); - MOCK_METHOD0(GetSampleRate, int()); - MOCK_METHOD0(GetRenderingDelay, - MediaPipelineBackend::AudioDecoder::RenderingDelay()); - MOCK_METHOD0(OptimalWriteFramesCount, int()); - MOCK_METHOD3(Write, bool(const float*, int, bool*)); - MOCK_METHOD0(Stop, void()); - - int sample_rate() const { return sample_rate_; } - const std::vector& data() const { return data_; } - - void ClearData() { data_.clear(); } - - private: - bool StartImpl(int requested_sample_rate, int channels) { - channels_ = channels; - sample_rate_ = requested_sample_rate; - return true; - } - - int GetNumChannelsImpl() { return channels_; } - int GetSampleRateImpl() { return sample_rate_; } - - MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelayImpl() { - return MediaPipelineBackend::AudioDecoder::RenderingDelay(); - } - - int OptimalWriteFramesImpl() { return kOutputFrames; } - - bool WriteImpl(const float* data, - int data_size, - bool* out_playback_interrupted) { - *out_playback_interrupted = false; - data_.insert(data_.end(), data, data + data_size); - return true; - } - - int channels_ = 0; - int sample_rate_ = 0; - std::vector data_; -}; - -#define EXPECT_CALL_ALL_POSTPROCESSORS(factory, call_sig) \ - do { \ - for (auto& itr : factory->instances) { \ - EXPECT_CALL(*itr.second, call_sig); \ - } \ - } while (0); - -void VerifyAndClearPostProcessors(MockPostProcessorFactory* factory) { - for (auto& itr : factory->instances) { - testing::Mock::VerifyAndClearExpectations(itr.second); - } -} - -class MockLoopbackAudioObserver - : public mixer_service::LoopbackConnection::Delegate { - public: - MockLoopbackAudioObserver() = default; - - MockLoopbackAudioObserver(const MockLoopbackAudioObserver&) = delete; - MockLoopbackAudioObserver& operator=(const MockLoopbackAudioObserver&) = - delete; - - ~MockLoopbackAudioObserver() override = default; - - MOCK_METHOD6(OnLoopbackAudio, - void(int64_t, SampleFormat, int, int, uint8_t*, int)); - MOCK_METHOD1(OnLoopbackInterrupted, void(LoopbackInterruptReason)); -}; - -// Given |inputs|, returns mixed audio data according to the mixing method used -// by the mixer. -std::unique_ptr<::media::AudioBus> GetMixedAudioData( - const std::vector& inputs, - bool apply_volume = true) { - int read_size = 0; - int num_channels = 1; - for (auto* input : inputs) { - CHECK(input); - read_size = std::max(input->data().frames(), read_size); - num_channels = std::max(num_channels, input->data().channels()); - } - - // Verify all inputs are the right size. - for (auto* input : inputs) { - CHECK_LE(read_size, input->data().frames()); - } - - // Currently, the mixing algorithm is simply to sum the scaled, clipped input - // streams. Go sample-by-sample and mix the data. - auto mixed = ::media::AudioBus::Create(num_channels, read_size); - for (int c = 0; c < mixed->channels(); ++c) { - for (int f = 0; f < read_size; ++f) { - float* result = mixed->channel(c) + f; - - // Sum the sample from each input stream, scaling each stream. - *result = 0.0; - for (auto* input : inputs) { - if (input->data().channels() <= c) { - continue; - } - if (input->data().frames() > f) { - if (apply_volume) { - *result += *(input->data().channel(c) + f) * input->multiplier(); - } else { - *result += *(input->data().channel(c) + f); - } - } - } - - *result = std::clamp(*result, -1.0f, 1.0f); - } - } - return mixed; -} - -// Like the method above, but accepts a single input. This returns an AudioBus -// with this input after it is scaled and clipped. -std::unique_ptr<::media::AudioBus> GetMixedAudioData(MockMixerSource* input) { - return GetMixedAudioData(std::vector(1, input)); -} - -std::unique_ptr<::media::AudioBus> GetMixedAudioData( - const std::vector>& inputs) { - std::vector ptrs; - for (const auto& i : inputs) { - ptrs.push_back(i.get()); - } - return GetMixedAudioData(ptrs); -} - -void ToPlanar(const float* interleaved, - int num_frames, - ::media::AudioBus* planar) { - ASSERT_GE(planar->frames(), num_frames); - - planar->FromInterleaved(interleaved, num_frames); -} - -// Asserts that |expected| matches |actual| exactly. -void CompareAudioData(const ::media::AudioBus& expected, - const ::media::AudioBus& actual, - const std::string& token = "") { - ASSERT_EQ(expected.channels(), actual.channels()); - ASSERT_EQ(expected.frames(), actual.frames()); - - for (int c = 0; c < expected.channels(); ++c) { - const float* expected_data = expected.channel(c); - const float* actual_data = actual.channel(c); - for (int f = 0; f < expected.frames(); ++f) { - EXPECT_NEAR(*expected_data++, *actual_data++, 0.0000001f) - << c << " " << f << " " << token; - } - } -} - -// Check that -// MediaPipelineBackend::AudioDecoder::RenderingDelay.delay_microseconds is -// within kMaxDelayErrorUs of |delay| -MATCHER_P2(MatchDelay, delay, id, "") { - bool result = std::abs(arg.delay_microseconds - delay) < kMaxDelayErrorUs; - if (!result) { - LOG(ERROR) << "Expected delay_microseconds for " << id << " to be " << delay - << " but got " << arg.delay_microseconds; - } - return result; -} - -// Convert a number of frames at kTestSamplesPerSecond to microseconds -int64_t FramesToDelayUs(int64_t frames) { - return frames * base::Time::kMicrosecondsPerSecond / kTestSamplesPerSecond; -} - -#if GTEST_HAS_DEATH_TEST - -std::string DeathRegex(const std::string& regex) { -// String arguments aren't passed to CHECK() in official builds. -#if BUILDFLAG(IS_ANDROID) || (defined(OFFICIAL_BUILD) && defined(NDEBUG)) - return ""; -#else - return regex; -#endif -} - -#endif // GTEST_HAS_DEATH_TEST - -} // namespace - -class StreamMixerTest : public testing::Test { - public: - StreamMixerTest(const StreamMixerTest&) = delete; - StreamMixerTest& operator=(const StreamMixerTest&) = delete; - - protected: - StreamMixerTest() { - auto output = std::make_unique>(); - mock_output_ = output.get(); - mixer_ = std::make_unique( - std::move(output), base::SingleThreadTaskRunner::GetCurrentDefault(), - "{}"); - mixer_->SetVolume(AudioContentType::kMedia, 1.0f); - mixer_->SetVolume(AudioContentType::kAlarm, 1.0f); - std::string test_pipeline_json = base::StringPrintf( - kTestPipelineJsonTemplate, kDelayModuleSolib, kDefaultProcessorDelay, - kDelayModuleSolib, kTtsProcessorDelay, kDelayModuleSolib, - kMixProcessorDelay, kDelayModuleSolib, kLinearizeProcessorDelay); - auto factory = std::make_unique(); - pp_factory_ = factory.get(); - mixer_->SetNumOutputChannelsForTest(2); - mixer_->ResetPostProcessorsForTest(std::move(factory), test_pipeline_json); - CHECK_EQ(pp_factory_->instances.size(), - static_cast(kNumPostProcessors)); - } - - void WaitForMixer() { - base::RunLoop run_loop1; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, run_loop1.QuitClosure()); - run_loop1.Run(); - } - - void PlaybackOnce() { - // Run one playback iteration. - EXPECT_CALL(*mock_output_, Write(_, - mock_output_->OptimalWriteFramesCount() * - mixer_->num_output_channels(), - _)) - .Times(1); - base::RunLoop run_loop; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, run_loop.QuitClosure()); - run_loop.Run(); - testing::Mock::VerifyAndClearExpectations(mock_output_); - } - - std::unique_ptr AddOutputRedirector( - const RedirectionConfig& config, - StreamMatchPatterns patterns) { - DCHECK_EQ(config.num_output_channels, kNumChannels); - auto redirected_output = - std::make_unique(config); - redirected_output->SetStreamMatchPatterns(std::move(patterns)); - WaitForMixer(); - return redirected_output; - } - - void CheckRedirectorOutput( - MockRedirectedAudioOutput* redirected_output, - const std::vector& normal_inputs, - const std::vector& redirected_inputs, - int num_frames, - bool apply_volume = false) { - auto actual_mixer_output = - ::media::AudioBus::Create(kNumChannels, num_frames); - ASSERT_GE(mock_output_->data().size(), static_cast(num_frames)); - ToPlanar(mock_output_->data().data(), num_frames, - actual_mixer_output.get()); - std::unique_ptr<::media::AudioBus> expected_mixer_output; - if (normal_inputs.empty()) { - expected_mixer_output = - ::media::AudioBus::Create(kNumChannels, num_frames); - expected_mixer_output->Zero(); - } else { - expected_mixer_output = GetMixedAudioData(normal_inputs); - } - CompareAudioData(*expected_mixer_output, *actual_mixer_output, "output"); - - auto actual_redirected_output = - ::media::AudioBus::Create(kNumChannels, num_frames); - CHECK(redirected_output->last_buffer()); - ASSERT_GE(redirected_output->last_buffer()->frames(), num_frames); - redirected_output->last_buffer()->CopyPartialFramesTo( - 0, num_frames, 0, actual_redirected_output.get()); - std::unique_ptr<::media::AudioBus> expected_redirected_output; - if (redirected_inputs.empty()) { - expected_redirected_output = - ::media::AudioBus::Create(kNumChannels, num_frames); - expected_redirected_output->Zero(); - } else { - expected_redirected_output = - GetMixedAudioData(redirected_inputs, apply_volume); - } - CompareAudioData(*expected_redirected_output, *actual_redirected_output, - "redirected"); - } - - std::unique_ptr AddLoopbackObserver( - mixer_service::LoopbackConnection::Delegate* observer) { - std::unique_ptr loopback_socket = - CreateLoopbackConnectionForTest(mixer_->GetLoopbackHandlerForTest()); - auto connection = std::make_unique( - observer, std::move(loopback_socket)); - connection->Connect(); - return connection; - } - - protected: - base::test::SingleThreadTaskEnvironment task_environment_{ - base::test::TaskEnvironment::MainThreadType::IO}; - MockMixerOutput* mock_output_; - std::unique_ptr mixer_; - MockPostProcessorFactory* pp_factory_; -}; - -TEST_F(StreamMixerTest, AddSingleInput) { - MockMixerSource input(kTestSamplesPerSecond); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input); - WaitForMixer(); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, AddMultipleInputs) { - MockMixerSource input1(kTestSamplesPerSecond); - MockMixerSource input2(kTestSamplesPerSecond * 2); - - EXPECT_CALL(input1, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(input2, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input1); - mixer_->AddInput(&input2); - WaitForMixer(); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, RemoveInput) { - std::vector> inputs; - const int kNumInputs = 3; - for (int i = 0; i < kNumInputs; ++i) { - inputs.push_back( - std::make_unique(kTestSamplesPerSecond * (i + 1))); - } - - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - - for (size_t i = 0; i < inputs.size(); ++i) { - EXPECT_CALL(*inputs[i], InitializeAudioPlayback(_, _)).Times(1); - mixer_->AddInput(inputs[i].get()); - } - - WaitForMixer(); - - for (size_t i = 0; i < inputs.size(); ++i) { - EXPECT_CALL(*inputs[i], FinalizeAudioPlayback()).Times(1); - mixer_->RemoveInput(inputs[i].get()); - } - - WaitForMixer(); - task_environment_.RunUntilIdle(); -} - -TEST_F(StreamMixerTest, WriteFrames) { - std::vector> inputs; - const int kNumInputs = 3; - for (int i = 0; i < kNumInputs; ++i) { - inputs.push_back(std::make_unique(kTestSamplesPerSecond)); - } - - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - - for (size_t i = 0; i < inputs.size(); ++i) { - EXPECT_CALL(*inputs[i], InitializeAudioPlayback(_, _)).Times(1); - mixer_->AddInput(inputs[i].get()); - } - - WaitForMixer(); - - for (size_t i = 0; i < inputs.size(); ++i) { - EXPECT_CALL(*inputs[i], FillAudioPlaybackFrames(_, _, _)).Times(1); - } - - PlaybackOnce(); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OneStreamMixesProperly) { - MockMixerSource input(kTestSamplesPerSecond); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input); - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the stream with data. - const int kNumFrames = 32; - input.SetData(GetTestData(0)); - - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(1); - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(kNumChannels, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - auto expected = GetMixedAudioData(&input); - CompareAudioData(*expected, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OneStreamStereoInput6ChannelOutput) { - mixer_->SetNumOutputChannelsForTest(6); - - MockMixerSource input(kTestSamplesPerSecond); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, 6)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input); - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the stream with data. - const int kNumFrames = 32; - input.SetData(GetTestData(0)); - - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(1); - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(6, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames * 6)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - - auto expected = GetMixedAudioData(&input); - - // Upmix stereo input to 5.1 before comparing. - ::media::ChannelLayout input_layout = - DecoderConfigAdapter::ToMediaChannelLayout(ChannelLayout::STEREO); - ::media::ChannelLayout output_layout = - DecoderConfigAdapter::ToMediaChannelLayout(ChannelLayout::SURROUND_5_1); - ::media::ChannelMixer channel_mixer( - input_layout, ::media::ChannelLayoutToChannelCount(input_layout), - output_layout, ::media::ChannelLayoutToChannelCount(output_layout)); - auto expected_5_1 = ::media::AudioBus::Create(6, expected->frames()); - channel_mixer.Transform(expected.get(), expected_5_1.get()); - CompareAudioData(*expected_5_1, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OneStreamStereoInput6ChannelFilters) { - const char k6ChannelPostprocessorJson[] = R"json( -{ - "postprocessors": { - "mix": { - "streams": [ "default" ], - "num_input_channels": 6, - "processors": [] - } - } -} -)json"; - - mixer_->EnableDynamicChannelCountForTest(true); - mixer_->SetNumOutputChannelsForTest(6); - auto factory = std::make_unique(); - mixer_->ResetPostProcessorsForTest(std::move(factory), - k6ChannelPostprocessorJson); - - MockMixerSource input(kTestSamplesPerSecond); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, 6)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input); - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the stream with data. - const int kNumFrames = 32; - input.SetData(GetTestData(0)); - - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(1); - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(6, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames * 6)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - - auto expected = GetMixedAudioData(&input); - - // Upmix stereo input to 5.1 before comparing. - ::media::ChannelLayout input_layout = - DecoderConfigAdapter::ToMediaChannelLayout(ChannelLayout::STEREO); - ::media::ChannelLayout output_layout = - DecoderConfigAdapter::ToMediaChannelLayout(ChannelLayout::SURROUND_5_1); - ::media::ChannelMixer channel_mixer( - input_layout, ::media::ChannelLayoutToChannelCount(input_layout), - output_layout, ::media::ChannelLayoutToChannelCount(output_layout)); - auto expected_5_1 = ::media::AudioBus::Create(6, expected->frames()); - channel_mixer.Transform(expected.get(), expected_5_1.get()); - CompareAudioData(*expected_5_1, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OneStreamStereoInput6ChannelFiltersStereoOutput) { - const char k6ChannelPostprocessorJson[] = R"json( -{ - "postprocessors": { - "mix": { - "streams": [ "default" ], - "num_input_channels": 6, - "processors": [] - } - } -} -)json"; - - mixer_->EnableDynamicChannelCountForTest(true); - mixer_->SetNumOutputChannelsForTest(2); - auto factory = std::make_unique(); - mixer_->ResetPostProcessorsForTest(std::move(factory), - k6ChannelPostprocessorJson); - - MockMixerSource input(kTestSamplesPerSecond); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, 2)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input); - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the stream with data. - const int kNumFrames = 32; - input.SetData(GetTestData(0)); - - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(1); - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(2, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames * 2)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - - auto expected = GetMixedAudioData(&input); - CompareAudioData(*expected, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OneStream10ChannelInputStereoOutput) { - mixer_->SetNumOutputChannelsForTest(2); - - MockMixerSource input(kTestSamplesPerSecond); - input.set_num_channels(10); - input.set_channel_layout(::media::CHANNEL_LAYOUT_DISCRETE); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, 2)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input); - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the stream with data. - const int kNumFrames = 32; - auto data = ::media::AudioBus::Create(10, kNumFrames); - for (int c = 0; c < 10; ++c) { - for (int f = 0; f < kNumFrames; ++f) { - data->channel(c)[f] = (c / 10 + f / kNumFrames) / 10; - } - } - input.SetData(std::move(data)); - - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(1); - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(2, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames * 2)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - - auto expected = GetMixedAudioData(&input); - - // Downmix 10-channel input to stereo before comparing. - ::media::ChannelMixer channel_mixer( - mixer::CreateAudioParametersForChannelMixer( - ::media::CHANNEL_LAYOUT_DISCRETE, 10), - mixer::CreateAudioParametersForChannelMixer( - ::media::CHANNEL_LAYOUT_STEREO, 2)); - auto expected_stereo = ::media::AudioBus::Create(2, expected->frames()); - channel_mixer.Transform(expected.get(), expected_stereo.get()); - CompareAudioData(*expected_stereo, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OneStream10ChannelInputAndOutput) { - mixer_->SetNumOutputChannelsForTest(10); - - MockMixerSource input(kTestSamplesPerSecond); - input.set_num_channels(10); - input.set_channel_layout(::media::CHANNEL_LAYOUT_DISCRETE); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, 10)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input); - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the stream with data. - const int kNumFrames = 32; - auto data = ::media::AudioBus::Create(10, kNumFrames); - for (int c = 0; c < 10; ++c) { - for (int f = 0; f < kNumFrames; ++f) { - data->channel(c)[f] = (c / 10 + f / kNumFrames) / 10; - } - } - input.SetData(std::move(data)); - - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(1); - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(10, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames * 10)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - - auto expected = GetMixedAudioData(&input); - CompareAudioData(*expected, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OneStreamIsScaledDownProperly) { - MockMixerSource input(kTestSamplesPerSecond); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - input.set_multiplier(0.75f); - mixer_->AddInput(&input); - mixer_->SetVolumeMultiplier(&input, input.multiplier()); - WaitForMixer(); - - // Populate the stream with data. - const int kNumFrames = 32; - ASSERT_EQ(sizeof(kTestData[0]), kNumChannels * kNumFrames * kBytesPerSample); - input.SetData(GetTestData(0)); - - mock_output_->ClearData(); - - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(1); - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(kNumChannels, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - auto expected = GetMixedAudioData(&input); - CompareAudioData(*expected, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, FocusType) { - MockMixerSource input(kTestSamplesPerSecond); - input.set_content_type(AudioContentType::kMedia); - input.set_focus_type(AudioContentType::kCommunication); - - EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - mixer_->AddInput(&input); - mixer_->SetVolume(AudioContentType::kMedia, 0.75); // This volume is used. - mixer_->SetOutputLimit(AudioContentType::kMedia, 0.5); // Limit is not used. - WaitForMixer(); - - // Populate the stream with data. - const int kNumFrames = 32; - ASSERT_EQ(sizeof(kTestData[0]), kNumChannels * kNumFrames * kBytesPerSample); - input.SetData(GetTestData(0)); - - mock_output_->ClearData(); - - EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(1); - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(kNumChannels, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - auto expected = GetMixedAudioData(&input); - expected->Scale(0.75); - CompareAudioData(*expected, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, TwoUnscaledStreamsMixProperly) { - // Create a group of input streams. - std::vector> inputs; - const int kNumInputs = 2; - for (int i = 0; i < kNumInputs; ++i) { - inputs.push_back(std::make_unique(kTestSamplesPerSecond)); - } - - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - - for (size_t i = 0; i < inputs.size(); ++i) { - EXPECT_CALL(*inputs[i], InitializeAudioPlayback(_, _)).Times(1); - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the streams with data. - const int kNumFrames = 32; - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - EXPECT_CALL(*inputs[i], FillAudioPlaybackFrames(_, _, _)).Times(1); - } - - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(kNumChannels, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - auto expected = GetMixedAudioData(inputs); - CompareAudioData(*expected, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, TwoUnscaledStreamsWithDifferentIdsMixProperly) { - // Create a group of input streams. - std::vector> inputs; - inputs.push_back(std::make_unique( - kTestSamplesPerSecond, - ::media::AudioDeviceDescription::kDefaultDeviceId)); - inputs.push_back(std::make_unique( - kTestSamplesPerSecond, - ::media::AudioDeviceDescription::kCommunicationsDeviceId)); - - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - - for (size_t i = 0; i < inputs.size(); ++i) { - EXPECT_CALL(*inputs[i], InitializeAudioPlayback(_, _)).Times(1); - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the streams with data. - const int kNumFrames = 32; - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - EXPECT_CALL(*inputs[i], FillAudioPlaybackFrames(_, _, _)).Times(1); - } - - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(kNumChannels, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - auto expected = GetMixedAudioData(inputs); - CompareAudioData(*expected, *actual); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, TwoUnscaledStreamsMixProperlyWithEdgeCases) { - // Create a group of input streams. - std::vector> inputs; - const int kNumInputs = 2; - for (int i = 0; i < kNumInputs; ++i) { - inputs.push_back(std::make_unique(kTestSamplesPerSecond)); - } - - EXPECT_CALL(*mock_output_, Start(kTestSamplesPerSecond, _)).Times(1); - EXPECT_CALL(*mock_output_, Stop()).Times(0); - - for (size_t i = 0; i < inputs.size(); ++i) { - EXPECT_CALL(*inputs[i], InitializeAudioPlayback(_, _)).Times(1); - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - mock_output_->ClearData(); - - // Create edge case data for the inputs. By mixing these two short streams, - // every combination of {-(2^31), 0, 2^31-1} is tested. This test case is - // intended to be a hand-checkable gut check. - // Note: Test data should be represented as 32-bit integers and copied into - // ::media::AudioBus instances, rather than wrapping statically declared float - // arrays. The latter method is brittle, as ::media::AudioBus requires 16-bit - // alignment for internal data. - const int kNumFrames = 4; - - const int32_t kMaxSample = std::numeric_limits::max(); - const int32_t kMinSample = std::numeric_limits::min(); - const int32_t kEdgeData[2][8] = {{ - kMinSample, - kMinSample, - kMinSample, - 0, - 0, - kMaxSample, - 0, - 0, - }, - { - kMinSample, - 0, - kMaxSample, - 0, - kMaxSample, - kMaxSample, - 0, - 0, - }}; - - // Hand-calculate the results. Index 0 is clamped to -(2^31). Index 5 is - // clamped to 2^31-1. - const int32_t kResult[8] = { - kMinSample, kMinSample, 0, 0, kMaxSample, kMaxSample, 0, 0, - }; - - // Populate the streams with data. - for (size_t i = 0; i < inputs.size(); ++i) { - auto test_data = ::media::AudioBus::Create(kNumChannels, kNumFrames); - test_data->FromInterleaved<::media::SignedInt32SampleTypeTraits>( - kEdgeData[i], kNumFrames); - inputs[i]->SetData(std::move(test_data)); - EXPECT_CALL(*inputs[i], FillAudioPlaybackFrames(_, _, _)).Times(1); - } - - PlaybackOnce(); - - // Get the actual mixed output, and compare it against the expected stream. - // The stream should match exactly. - auto actual = ::media::AudioBus::Create(kNumChannels, kNumFrames); - ASSERT_GE(mock_output_->data().size(), static_cast(kNumFrames)); - ToPlanar(mock_output_->data().data(), kNumFrames, actual.get()); - - // Use the hand-calculated results above. - auto expected = ::media::AudioBus::Create(kNumChannels, kNumFrames); - expected->FromInterleaved<::media::SignedInt32SampleTypeTraits>(kResult, - kNumFrames); - - CompareAudioData(*expected, *actual); - - mixer_.reset(); -} - -#define EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(map, name, times, frames, \ - silence) \ - do { \ - auto itr = map->find(name); \ - CHECK(itr != map->end()) << "Could not find processor for " << name; \ - EXPECT_CALL(*(itr->second), ProcessFrames(_, frames, _, _, silence)) \ - .Times(times); \ - } while (0); - -TEST_F(StreamMixerTest, PostProcessorDelayListedDeviceId) { - int common_delay = kMixProcessorDelay + kLinearizeProcessorDelay; - - std::vector> inputs; - std::vector delays; - inputs.push_back( - std::make_unique(kTestSamplesPerSecond, "default")); - delays.push_back(common_delay + kDefaultProcessorDelay); - - inputs.push_back(std::make_unique(kTestSamplesPerSecond, - "communications")); - delays.push_back(common_delay); - - inputs.push_back(std::make_unique(kTestSamplesPerSecond, - "assistant-tts")); - delays.push_back(common_delay + kTtsProcessorDelay); - - // Convert delay from frames to microseconds. - base::ranges::transform(delays, delays.begin(), &FramesToDelayUs); - - for (size_t i = 0; i < inputs.size(); ++i) { - EXPECT_CALL(*inputs[i], InitializeAudioPlayback(_, _)).Times(1); - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - - auto* post_processors = &pp_factory_->instances; - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "default", 1, _, - false); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "mix", 1, _, false); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "linearize", 1, _, - false); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "communications", 1, - _, false); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "assistant-tts", 1, - _, false); - - // Poll the inputs for data. Each input will get a different - // rendering delay based on their device type. - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(0)); - EXPECT_CALL(*inputs[i], - FillAudioPlaybackFrames( - _, MatchDelay(delays[i], inputs[i]->device_id()), _)) - .Times(1); - } - - PlaybackOnce(); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, PostProcessorDelayUnlistedDevice) { - const std::string device_id = "not-a-device-id"; - MockMixerSource input(kTestSamplesPerSecond, device_id); - input.SetData(GetTestData(0)); - auto* post_processors = &pp_factory_->instances; - // These will be called once to ensure their buffers are initialized. - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "default", - testing::AtLeast(1), _, _); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "mix", - testing::AtLeast(1), _, _); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "linearize", - testing::AtLeast(1), _, _); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "communications", - testing::AtLeast(1), _, _); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "assistant-tts", - testing::AtLeast(1), _, _); - mixer_->AddInput(&input); - WaitForMixer(); - - VerifyAndClearPostProcessors(pp_factory_); - input.SetData(GetTestData(0)); - - // Delay should be based on default processor. - int64_t delay = FramesToDelayUs( - kDefaultProcessorDelay + kLinearizeProcessorDelay + kMixProcessorDelay); - - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "default", 1, _, - false); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "mix", 1, _, false); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "linearize", 1, _, - false); - - EXPECT_CALL(input, - FillAudioPlaybackFrames(_, MatchDelay(delay, device_id), _)) - .Times(1); - PlaybackOnce(); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, PostProcessorRingingWithoutInput) { - const char kTestPipelineJson[] = R"json( -{ - "postprocessors": { - "output_streams": [{ - "streams": [ "default" ], - "processors": [{ - "processor": "%s", - "config": { "delay": 0, "ringing": true} - }] - }, { - "streams": [ "assistant-tts" ], - "processors": [{ - "processor": "%s", - "config": { "delay": 0, "ringing": true} - }] - }] - } -} -)json"; - - MockMixerSource input(kTestSamplesPerSecond, "default"); - input.SetData(GetTestData(0)); - - std::string test_pipeline_json = base::StringPrintf( - kTestPipelineJson, kDelayModuleSolib, kDelayModuleSolib); - auto factory = std::make_unique(); - MockPostProcessorFactory* factory_ptr = factory.get(); - mixer_->ResetPostProcessorsForTest(std::move(factory), test_pipeline_json); - mixer_->AddInput(&input); - WaitForMixer(); - - // "mix" + "linearize" should be automatic - EXPECT_GE(factory_ptr->instances.size(), 4u); - - auto* post_processors = &factory_ptr->instances; - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "default", 1, _, _); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "mix", 1, _, false); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "linearize", 1, _, - false); - EXPECT_POSTPROCESSOR_CALL_PROCESSFRAMES(post_processors, "assistant-tts", 1, - _, true); - - PlaybackOnce(); - mixer_.reset(); -} - -TEST_F(StreamMixerTest, PostProcessorProvidesDefaultPipeline) { - auto factory = std::make_unique(); - MockPostProcessorFactory* factory_ptr = factory.get(); - mixer_->ResetPostProcessorsForTest(std::move(factory), "{}"); - - auto* instances = &factory_ptr->instances; - CHECK(instances->find("default") == instances->end()); - CHECK(instances->find("mix") != instances->end()); - CHECK(instances->find("linearize") != instances->end()); - CHECK_EQ(instances->size(), 2u); -} - -TEST_F(StreamMixerTest, MultiplePostProcessorsInOneStream) { - const char kJsonTemplate[] = R"json( -{ - "postprocessors": { - "output_streams": [{ - "streams": [ "default" ], - "processors": [{ - "processor": "%s", - "name": "%s", - "config": { "delay": 10 } - }, { - "processor": "%s", - "name": "%s", - "config": { "delay": 100 } - }] - }], - "mix": { - "processors": [{ - "processor": "%s", - "name": "%s", - "config": { "delay": 1000 } - }, { - "processor": "%s", - "config": { "delay": 10000 } - }] - } - } -} -)json"; - - std::string json = base::StringPrintf( - kJsonTemplate, kDelayModuleSolib, "delayer_1", // unique processor name - kDelayModuleSolib, "delayer_2", // non-unique processor names - kDelayModuleSolib, "delayer_2", - kDelayModuleSolib // intentionally omitted processor name - ); - - auto factory = std::make_unique(); - MockPostProcessorFactory* factory_ptr = factory.get(); - mixer_->ResetPostProcessorsForTest(std::move(factory), json); - - // "mix" + "linearize" + "default" - EXPECT_EQ(factory_ptr->instances.size(), 3u); - - auto* post_processors = &factory_ptr->instances; - EXPECT_EQ(post_processors->find("default")->second->delay(), 110); - EXPECT_EQ(post_processors->find("mix")->second->delay(), 11000); - EXPECT_EQ(post_processors->find("linearize")->second->delay(), 0); -} - -TEST_F(StreamMixerTest, SetPostProcessorConfig) { - std::string name = "ThisIsMyName"; - std::string config = "ThisIsMyConfig"; - - for (auto const& x : pp_factory_->instances) { - EXPECT_CALL(*(x.second), SetPostProcessorConfig(name, config)); - } - - mixer_->SetPostProcessorConfig(name, config); - WaitForMixer(); -} - -TEST_F(StreamMixerTest, ObserverGets2ChannelsByDefault) { - MockMixerSource input(kTestSamplesPerSecond); - testing::StrictMock observer; - mixer_->AddInput(&input); - auto connection = AddLoopbackObserver(&observer); - EXPECT_CALL(observer, - OnLoopbackAudio(_, kSampleFormatF32, kTestSamplesPerSecond, - kNumChannels, _, _)) - .Times(testing::AtLeast(1)); - - WaitForMixer(); - PlaybackOnce(); - - WaitForMixer(); - mixer_.reset(); -} - -TEST_F(StreamMixerTest, ObserverGets1ChannelIfNumOutputChannelsIs1) { - const int kNumOutputChannels = 1; - mixer_->SetNumOutputChannelsForTest(kNumOutputChannels); - - MockMixerSource input(kTestSamplesPerSecond); - testing::StrictMock observer; - mixer_->AddInput(&input); - auto connection = AddLoopbackObserver(&observer); - - EXPECT_CALL(observer, - OnLoopbackAudio(_, kSampleFormatF32, kTestSamplesPerSecond, - kNumOutputChannels, _, _)) - .Times(testing::AtLeast(1)); - - WaitForMixer(); - PlaybackOnce(); - - WaitForMixer(); - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OneStreamOutputRedirection) { - RedirectionConfig config; - StreamMatchPatterns patterns = {{AudioContentType::kMedia, "*"}}; - std::unique_ptr redirected_output = - AddOutputRedirector(config, patterns); - WaitForMixer(); - - MockMixerSource input(kTestSamplesPerSecond); - mixer_->AddInput(&input); - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the stream with data. - const int kNumFrames = 32; - input.SetData(GetTestData(0)); - - testing::Expectation set_sample_rate_is_called = - EXPECT_CALL(*redirected_output, SetSampleRate(kTestSamplesPerSecond)) - .Times(testing::AtLeast(1)); - EXPECT_CALL(*redirected_output, OnRedirectedAudio(_, _, kOutputFrames)) - .Times(2) - .After(set_sample_rate_is_called); - PlaybackOnce(); // First buffer is faded in, so don't try to compare it. - input.SetData(GetTestData(0)); - PlaybackOnce(); - // Need to wait 2 extra times since we post a task on the mixer side (to the - // IO task runner) and again to actually "send" the data. - WaitForMixer(); - WaitForMixer(); - - CheckRedirectorOutput(redirected_output.get(), {}, {&input}, kNumFrames); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OutputRedirectionOrder) { - RedirectionConfig config; - StreamMatchPatterns patterns = {{AudioContentType::kMedia, "*"}}; - std::unique_ptr redirected_output1 = - AddOutputRedirector(config, patterns); - - config.order = 1; - std::unique_ptr redirected_output2 = - AddOutputRedirector(config, patterns); - WaitForMixer(); - - MockMixerSource input(kTestSamplesPerSecond); - mixer_->AddInput(&input); - WaitForMixer(); - mock_output_->ClearData(); - - // Populate the stream with data. - const int kNumFrames = 32; - input.SetData(GetTestData(0)); - - EXPECT_CALL(*redirected_output1, OnRedirectedAudio(_, _, kOutputFrames)) - .Times(2); - EXPECT_CALL(*redirected_output2, OnRedirectedAudio(_, _, kOutputFrames)) - .Times(0); - PlaybackOnce(); // First buffer is faded in, so don't try to compare it. - input.SetData(GetTestData(0)); - PlaybackOnce(); - WaitForMixer(); - WaitForMixer(); - - // First redirector should produce actual data, since it has a lower order. - CheckRedirectorOutput(redirected_output1.get(), {}, {&input}, kNumFrames); - // Second redirector should not have received any data. - EXPECT_FALSE(redirected_output2->last_buffer()); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, TwoStreamsOutputRedirection) { - std::vector> inputs; - const int kNumInputs = 2; - for (int i = 0; i < kNumInputs; ++i) { - inputs.push_back(std::make_unique(kTestSamplesPerSecond)); - } - - for (size_t i = 0; i < inputs.size(); ++i) { - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - mock_output_->ClearData(); - - RedirectionConfig config; - StreamMatchPatterns patterns = {{AudioContentType::kMedia, "*"}}; - std::unique_ptr redirected_output = - AddOutputRedirector(config, patterns); - WaitForMixer(); - - const int kNumFrames = 32; - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - WaitForMixer(); - WaitForMixer(); - - CheckRedirectorOutput(redirected_output.get(), {}, - {inputs[0].get(), inputs[1].get()}, kNumFrames); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, TwoStreamsOutputRedirectionWithVolume) { - std::vector> inputs; - const int kNumInputs = 2; - for (int i = 0; i < kNumInputs; ++i) { - inputs.push_back(std::make_unique(kTestSamplesPerSecond)); - } - inputs[0]->set_multiplier(0.5); - inputs[1]->set_multiplier(0.7); - - for (size_t i = 0; i < inputs.size(); ++i) { - mixer_->AddInput(inputs[i].get()); - mixer_->SetVolumeMultiplier(inputs[i].get(), inputs[i]->multiplier()); - } - WaitForMixer(); - mock_output_->ClearData(); - - RedirectionConfig config; - config.apply_volume = true; - StreamMatchPatterns patterns = {{AudioContentType::kMedia, "*"}}; - std::unique_ptr redirected_output = - AddOutputRedirector(config, patterns); - WaitForMixer(); - - const int kNumFrames = 32; - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - WaitForMixer(); - WaitForMixer(); - - CheckRedirectorOutput(redirected_output.get(), {}, - {inputs[0].get(), inputs[1].get()}, kNumFrames, - true /* apply_volume */); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OutputRedirectionMatchDeviceId) { - std::vector> inputs; - inputs.push_back( - std::make_unique(kTestSamplesPerSecond, "matches")); - inputs.push_back( - std::make_unique(kTestSamplesPerSecond, "asdf")); - - for (size_t i = 0; i < inputs.size(); ++i) { - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - mock_output_->ClearData(); - - RedirectionConfig config; - StreamMatchPatterns patterns = {{AudioContentType::kMedia, "*match*"}}; - std::unique_ptr redirected_output = - AddOutputRedirector(config, patterns); - WaitForMixer(); - - const int kNumFrames = 32; - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - mock_output_->ClearData(); - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - WaitForMixer(); - WaitForMixer(); - - CheckRedirectorOutput(redirected_output.get(), {inputs[1].get()}, - {inputs[0].get()}, kNumFrames); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OutputRedirectionMatchContentType) { - std::vector> inputs; - inputs.push_back( - std::make_unique(kTestSamplesPerSecond, "matches1")); - inputs.push_back( - std::make_unique(kTestSamplesPerSecond, "matches2")); - inputs[0]->set_content_type(AudioContentType::kAlarm); - - for (size_t i = 0; i < inputs.size(); ++i) { - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - mock_output_->ClearData(); - - RedirectionConfig config; - StreamMatchPatterns patterns = {{AudioContentType::kAlarm, "*match*"}}; - std::unique_ptr redirected_output = - AddOutputRedirector(config, patterns); - WaitForMixer(); - - const int kNumFrames = 32; - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - mock_output_->ClearData(); - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - WaitForMixer(); - WaitForMixer(); - - CheckRedirectorOutput(redirected_output.get(), {inputs[1].get()}, - {inputs[0].get()}, kNumFrames); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, OutputRedirectionNoMatch) { - std::vector> inputs; - inputs.push_back(std::make_unique(kTestSamplesPerSecond)); - inputs.push_back(std::make_unique(kTestSamplesPerSecond)); - - for (size_t i = 0; i < inputs.size(); ++i) { - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - mock_output_->ClearData(); - - RedirectionConfig config; - StreamMatchPatterns patterns = {{AudioContentType::kAlarm, "*"}}; - std::unique_ptr redirected_output = - AddOutputRedirector(config, patterns); - WaitForMixer(); - - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - mock_output_->ClearData(); - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - WaitForMixer(); - WaitForMixer(); - - // Redirector should not have received any data, since no inputs match. - EXPECT_FALSE(redirected_output->last_buffer()); - - mixer_.reset(); -} - -TEST_F(StreamMixerTest, ModifyOutputRedirection) { - std::vector> inputs; - inputs.push_back( - std::make_unique(kTestSamplesPerSecond, "matches")); - inputs.push_back( - std::make_unique(kTestSamplesPerSecond, "asdf")); - - for (size_t i = 0; i < inputs.size(); ++i) { - mixer_->AddInput(inputs[i].get()); - } - WaitForMixer(); - mock_output_->ClearData(); - - RedirectionConfig config; - StreamMatchPatterns patterns = {{AudioContentType::kMedia, "*match*"}}; - std::unique_ptr redirected_output = - AddOutputRedirector(config, patterns); - WaitForMixer(); - - const int kNumFrames = 32; - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - mock_output_->ClearData(); - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - WaitForMixer(); - WaitForMixer(); - - CheckRedirectorOutput(redirected_output.get(), {inputs[1].get()}, - {inputs[0].get()}, kNumFrames); - - StreamMatchPatterns new_patterns = {{AudioContentType::kMedia, "*asdf*"}}; - redirected_output->SetStreamMatchPatterns(new_patterns); - WaitForMixer(); - WaitForMixer(); - WaitForMixer(); - mock_output_->ClearData(); - - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - mock_output_->ClearData(); - for (size_t i = 0; i < inputs.size(); ++i) { - inputs[i]->SetData(GetTestData(i)); - } - PlaybackOnce(); - WaitForMixer(); - WaitForMixer(); - - CheckRedirectorOutput(redirected_output.get(), {inputs[0].get()}, - {inputs[1].get()}, kNumFrames); - - mixer_.reset(); -} - -#if GTEST_HAS_DEATH_TEST - -using StreamMixerDeathTest = StreamMixerTest; - -TEST_F(StreamMixerDeathTest, InvalidStreamTypeCrashes) { - const char json[] = R"json( -{ - "postprocessors": { - "output_streams": [{ - "streams": [ "foobar" ], - "processors": [{ - "processor": "dont_care.so", - "config": { "delay": 0 } - }] - }] - } -} -)json"; - - GTEST_FLAG_SET(death_test_style, "threadsafe"); - EXPECT_DEATH(mixer_->ResetPostProcessorsForTest( - std::make_unique(), json), - DeathRegex("foobar is not a stream type")); -} - -TEST_F(StreamMixerDeathTest, BadJsonCrashes) { - const std::string json("{{"); - GTEST_FLAG_SET(death_test_style, "threadsafe"); - EXPECT_DEATH(mixer_->ResetPostProcessorsForTest( - std::make_unique(), json), - DeathRegex("Invalid JSON")); -} - -#endif // GTEST_HAS_DEATH_TEST - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/mock_media_pipeline_backend_for_mixer.h chromium-132.0.6834.159/chromecast/media/cma/backend/mock_media_pipeline_backend_for_mixer.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/mock_media_pipeline_backend_for_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/mock_media_pipeline_backend_for_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_MOCK_MEDIA_PIPELINE_BACKEND_FOR_MIXER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_MOCK_MEDIA_PIPELINE_BACKEND_FOR_MIXER_H_ - -#include -#include - -#include "chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h" -#include "chromecast/media/cma/backend/mock_audio_decoder_for_mixer.h" -#include "chromecast/media/cma/backend/mock_video_decoder_for_mixer.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { - -class MockMediaPipelineBackendForMixer : public MediaPipelineBackendForMixer { - public: - explicit MockMediaPipelineBackendForMixer( - const MediaPipelineDeviceParams& params); - - void SetAudioDecoder( - std::unique_ptr audio_decoder) { - audio_decoder_ = std::move(audio_decoder); - } - - void SetVideoDecoder(std::unique_ptr video_decoder) { - video_decoder_ = std::move(video_decoder); - } - - int64_t MonotonicClockNow() const override; - - MockMediaPipelineBackendForMixer(const MockMediaPipelineBackendForMixer&) = - delete; - MockMediaPipelineBackendForMixer& operator=( - const MockMediaPipelineBackendForMixer&) = delete; - - ~MockMediaPipelineBackendForMixer() override; -}; - -inline MockMediaPipelineBackendForMixer::~MockMediaPipelineBackendForMixer() = - default; - -inline MockMediaPipelineBackendForMixer::MockMediaPipelineBackendForMixer( - const MediaPipelineDeviceParams& params) - : MediaPipelineBackendForMixer(params) {} - -inline int64_t MockMediaPipelineBackendForMixer::MonotonicClockNow() const { - return (static_cast(GetTaskRunner().get()) - ->NowTicks() - - base::TimeTicks()) - .InMicroseconds(); // 'now'... -} -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_MOCK_MEDIA_PIPELINE_BACKEND_FOR_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/multizone_backend_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/multizone_backend_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/multizone_backend_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/multizone_backend_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,410 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include - -#include -#include -#include -#include - -#include "base/check.h" -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/audio_device_description.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/decoder_buffer.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -class MultizoneBackendTest; - -namespace { - -// Total length of test, in microseconds. -const int64_t kPushTimeUs = 4 * base::Time::kMicrosecondsPerSecond; -const int64_t kStartPts = 0; -const int64_t kMaxRenderingDelayErrorUs = 200; -const int kNumEffectsStreams = 0; -const int64_t kNoTimestamp = std::numeric_limits::min(); - -void IgnoreEos() {} - -class BufferFeeder : public MediaPipelineBackend::Decoder::Delegate { - public: - BufferFeeder(const AudioConfig& config, - bool effects_only, - base::OnceClosure eos_cb, - double* rate_change_sequence, - int num_rate_changes); - - BufferFeeder(const BufferFeeder&) = delete; - BufferFeeder& operator=(const BufferFeeder&) = delete; - - ~BufferFeeder() override {} - - void Initialize(); - void Start(); - void Stop(); - - int64_t GetMaxRenderingDelayErrorUs() { - int64_t max = 0; - for (int64_t error : errors_) { - if (error == kNoTimestamp) { - continue; - } - max = std::max(max, std::abs(error)); - } - return max; - } - - private: - void FeedBuffer(); - - // MediaPipelineBackend::Decoder::Delegate implementation: - void OnPushBufferComplete(MediaPipelineBackend::BufferStatus status) override; - void OnEndOfStream() override; - void OnDecoderError() override { - DCHECK(thread_checker_.CalledOnValidThread()); - if (effects_only_) { - feeding_completed_ = true; - } else { - ASSERT_TRUE(false); - } - } - void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override { - DCHECK(thread_checker_.CalledOnValidThread()); - ASSERT_TRUE(false); - } - void OnVideoResolutionChanged(const Size& size) override { - DCHECK(thread_checker_.CalledOnValidThread()); - } - - const AudioConfig config_; - const bool effects_only_; - base::OnceClosure eos_cb_; - const int64_t push_limit_us_; - double* const rate_change_sequence_; - const int num_rate_changes_; - const int64_t playback_rate_change_interval_us_; - float playback_rate_; - std::vector errors_; - bool feeding_completed_; - TaskRunnerImpl task_runner_; - std::unique_ptr backend_; - MediaPipelineBackend::AudioDecoder* decoder_; - int64_t last_push_length_us_; - int64_t pushed_us_; - int64_t pushed_us_when_rate_changed_; - int64_t next_push_playback_timestamp_; - scoped_refptr pending_buffer_; - base::ThreadChecker thread_checker_; - int current_rate_index_ = 0; -}; - -double kTestRateSequence1[] = {0.5, 0.7, 0.99, 1.0, 1.01, 1.3, 2.0}; -double kTestRateSequence2[] = {2.0, 1.3, 1.01, 1.0, 0.99, 0.7, 0.5}; -double kTestRateSequence3[] = {1.0, 0.6, 0.7, 1.0, 1.3, 1.6, 1.0}; -double kTestRateSequence4[] = {2.0, 1.3, 1.0, 0.7, 0.6, 1.0, 0.5}; - -} // namespace - -using TestParams = std::tuple; - -class MultizoneBackendTest : public testing::TestWithParam { - public: - MultizoneBackendTest(); - - MultizoneBackendTest(const MultizoneBackendTest&) = delete; - MultizoneBackendTest& operator=(const MultizoneBackendTest&) = delete; - - ~MultizoneBackendTest() override; - - void SetUp() override { - srand(12345); - CastMediaShlib::Initialize(base::CommandLine::ForCurrentProcess()->argv()); - VolumeControl::Initialize(base::CommandLine::ForCurrentProcess()->argv()); - } - - void TearDown() override { - // Pipeline must be destroyed before finalizing media shlib. - audio_feeder_.reset(); - effects_feeders_.clear(); - VolumeControl::Finalize(); - CastMediaShlib::Finalize(); - } - - void AddEffectsStreams(); - - void Initialize(int sample_rate, - double* rate_change_sequence, - int num_rate_changes); - void Start(); - void OnEndOfStream(); - - private: - base::test::TaskEnvironment task_environment_; - std::vector> effects_feeders_; - std::unique_ptr audio_feeder_; - base::RunLoop loop_; -}; - -namespace { - -BufferFeeder::BufferFeeder(const AudioConfig& config, - bool effects_only, - base::OnceClosure eos_cb, - double* rate_change_sequence, - int num_rate_changes) - : config_(config), - effects_only_(effects_only), - eos_cb_(std::move(eos_cb)), - push_limit_us_(effects_only_ ? 0 : kPushTimeUs), - rate_change_sequence_(rate_change_sequence), - num_rate_changes_(num_rate_changes), - playback_rate_change_interval_us_(push_limit_us_ / - (num_rate_changes_ + 1)), - playback_rate_(1.0f), - feeding_completed_(false), - decoder_(nullptr), - last_push_length_us_(0), - pushed_us_(0), - pushed_us_when_rate_changed_(0), - next_push_playback_timestamp_(kNoTimestamp) { - CHECK(eos_cb_); - if (num_rate_changes_ > 0) { - CHECK(rate_change_sequence_); - } -} - -void BufferFeeder::Initialize() { - MediaPipelineDeviceParams params( - MediaPipelineDeviceParams::kModeIgnorePts, - effects_only_ ? MediaPipelineDeviceParams::kAudioStreamSoundEffects - : MediaPipelineDeviceParams::kAudioStreamNormal, - &task_runner_, AudioContentType::kMedia, - ::media::AudioDeviceDescription::kDefaultDeviceId); - backend_.reset(CastMediaShlib::CreateMediaPipelineBackend(params)); - CHECK(backend_); - - decoder_ = backend_->CreateAudioDecoder(); - CHECK(decoder_); - ASSERT_TRUE(decoder_->SetConfig(config_)); - decoder_->SetDelegate(this); - - ASSERT_TRUE(backend_->Initialize()); -} - -void BufferFeeder::Start() { - if (num_rate_changes_ > 0) { - playback_rate_ = rate_change_sequence_[0]; - } - // AMP devices only support playback rates between 0.5 and 2.0. - ASSERT_GE(playback_rate_, 0.5f); - ASSERT_LE(playback_rate_, 2.0f); - ASSERT_TRUE(backend_->Start(kStartPts)); - ASSERT_TRUE(backend_->SetPlaybackRate(playback_rate_)); - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&BufferFeeder::FeedBuffer, base::Unretained(this))); -} - -void BufferFeeder::Stop() { - feeding_completed_ = true; - backend_->Stop(); -} - -void BufferFeeder::FeedBuffer() { - CHECK(decoder_); - if (feeding_completed_) - return; - - if (current_rate_index_ < num_rate_changes_ - 1 && !effects_only_ && - pushed_us_ > - pushed_us_when_rate_changed_ + playback_rate_change_interval_us_) { - pushed_us_when_rate_changed_ = pushed_us_; - ++current_rate_index_; - playback_rate_ = rate_change_sequence_[current_rate_index_]; - LOG(INFO) << "Change playback rate to " << playback_rate_; - ASSERT_TRUE(backend_->SetPlaybackRate(playback_rate_)); - // Changing the playback rate will change the rendering delay on devices - // where playback rate changes apply to audio that has already been pushed. - // Ignore the next rendering delay. - next_push_playback_timestamp_ = kNoTimestamp; - } - - if (!effects_only_ && pushed_us_ >= push_limit_us_) { - pending_buffer_ = new media::DecoderBufferAdapter( - ::media::DecoderBuffer::CreateEOSBuffer()); - feeding_completed_ = true; - last_push_length_us_ = 0; - } else { - int size_bytes = (rand() % 96 + 32) * 16; - int num_samples = - size_bytes / (config_.bytes_per_channel * config_.channel_number); - last_push_length_us_ = num_samples * base::Time::kMicrosecondsPerSecond / - (config_.samples_per_second * playback_rate_); - scoped_refptr<::media::DecoderBuffer> silence_buffer( - new ::media::DecoderBuffer(size_bytes)); - memset(silence_buffer->writable_data(), 0, silence_buffer->size()); - pending_buffer_ = new media::DecoderBufferAdapter(silence_buffer); - pending_buffer_->set_timestamp(base::Microseconds(pushed_us_)); - } - BufferStatus status = decoder_->PushBuffer(pending_buffer_.get()); - ASSERT_NE(status, MediaPipelineBackend::kBufferFailed); - if (status == MediaPipelineBackend::kBufferPending) - return; - OnPushBufferComplete(MediaPipelineBackend::kBufferSuccess); -} - -void BufferFeeder::OnEndOfStream() { - DCHECK(thread_checker_.CalledOnValidThread()); - std::move(eos_cb_).Run(); -} - -void BufferFeeder::OnPushBufferComplete(BufferStatus status) { - DCHECK(thread_checker_.CalledOnValidThread()); - pending_buffer_ = nullptr; - - if (!effects_only_) { - ASSERT_NE(status, MediaPipelineBackend::kBufferFailed); - MediaPipelineBackend::AudioDecoder::RenderingDelay delay = - decoder_->GetRenderingDelay(); - - int64_t error = kNoTimestamp; - if (delay.timestamp_microseconds == kNoTimestamp) { - next_push_playback_timestamp_ = kNoTimestamp; - } else { - if (next_push_playback_timestamp_ == kNoTimestamp) { - next_push_playback_timestamp_ = - delay.timestamp_microseconds + delay.delay_microseconds; - } else { - int64_t expected_next_push_playback_timestamp = - next_push_playback_timestamp_ + last_push_length_us_; - next_push_playback_timestamp_ = - delay.timestamp_microseconds + delay.delay_microseconds; - error = next_push_playback_timestamp_ - - expected_next_push_playback_timestamp; - DVLOG(2) << "expected " << expected_next_push_playback_timestamp - << ", got " << next_push_playback_timestamp_ - << ", error = " << error; - } - } - errors_.push_back(error); - } - pushed_us_ += last_push_length_us_; - - if (feeding_completed_) - return; - - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&BufferFeeder::FeedBuffer, base::Unretained(this))); -} - -} // namespace - -MultizoneBackendTest::MultizoneBackendTest() - : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {} - -MultizoneBackendTest::~MultizoneBackendTest() {} - -void MultizoneBackendTest::Initialize(int sample_rate, - double* rate_change_sequence, - int num_rate_changes) { - AudioConfig config; - config.codec = kCodecPCM; - config.channel_layout = ChannelLayout::STEREO; - config.sample_format = kSampleFormatPlanarF32; - config.channel_number = 2; - config.bytes_per_channel = 4; - config.samples_per_second = sample_rate; - - audio_feeder_ = std::make_unique( - config, false /* effects_only */, - base::BindOnce(&MultizoneBackendTest::OnEndOfStream, - base::Unretained(this)), - rate_change_sequence, num_rate_changes); - audio_feeder_->Initialize(); -} - -void MultizoneBackendTest::AddEffectsStreams() { - AudioConfig effects_config; - effects_config.codec = kCodecPCM; - effects_config.channel_layout = ChannelLayout::STEREO; - effects_config.sample_format = kSampleFormatS16; - effects_config.channel_number = 2; - effects_config.bytes_per_channel = 2; - effects_config.samples_per_second = 48000; - - for (int i = 0; i < kNumEffectsStreams; ++i) { - auto feeder = - std::make_unique(effects_config, true /* effects_only */, - base::BindOnce(&IgnoreEos), nullptr, 0); - feeder->Initialize(); - effects_feeders_.push_back(std::move(feeder)); - } -} - -void MultizoneBackendTest::Start() { - for (auto& feeder : effects_feeders_) - feeder->Start(); - CHECK(audio_feeder_); - audio_feeder_->Start(); - loop_.Run(); -} - -void MultizoneBackendTest::OnEndOfStream() { - audio_feeder_->Stop(); - for (auto& feeder : effects_feeders_) - feeder->Stop(); - - loop_.QuitWhenIdle(); - - EXPECT_LT(audio_feeder_->GetMaxRenderingDelayErrorUs(), - kMaxRenderingDelayErrorUs); -} - -TEST_P(MultizoneBackendTest, RateChanges) { - const TestParams& params = GetParam(); - int sample_rate = testing::get<0>(params); - double* sequence = testing::get<1>(params); - Initialize(sample_rate, sequence, std::size(kTestRateSequence1)); - AddEffectsStreams(); - Start(); -} - -INSTANTIATE_TEST_SUITE_P( - Required, - MultizoneBackendTest, - testing::Combine(::testing::Values(44100, 48000), - ::testing::Values(kTestRateSequence1, - kTestRateSequence2, - kTestRateSequence3, - kTestRateSequence4))); - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/DEPS chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/DEPS --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include_rules = [ - "+third_party/cast_core/public/src/proto", - "+third_party/protobuf", -] diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/README.md chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/README.md --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/README.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,156 +0,0 @@ -# Objective - -As part of supporting a Chromium runtime for chromecast (as defined below), the -`CmaBackendProxy` class and related code contained in the -[`chromecast/media/cma/backend/proxy/`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/media/cma/backend/proxy/) -directory was added. This infrastructure exists to proxy audio data across the -CastRuntimeAudioChannel gRPC Service without impacting local playback of video -or audio media, and requires significant complexity in order to do so. This -document provides a high-level overview of the `CmaBackendProxy` implementation -and the pipeline into which it calls. It is intended to be used as a reference -for understanding this pipeline, to simplify both the code review and the -onboarding process. - -# Background - -## Existing Chromecast Media Pipeline - -The chromecast pipeline, as exists today in Chromium's -[`chromecast/`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/) -directory, is rather complex, so only the high-level will be discussed here. -When playing out media, an implementation of the -[`MediaPipelineBackend`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/public/media/media_pipeline_backend.h;l=36?q=mediapipelinebackend&ss=chromium%2Fchromium%2Fsrc:chromecast%2F) -API will be created, and this will be wrapped by a platform-specific (e.g. -Android, Fuchsia, Desktop, etc…) -[`CmaBackend`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/media/api/cma_backend.h;l=24?q=cmabackend&sq=&ss=chromium%2Fchromium%2Fsrc:chromecast%2F) -as -[exists today](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/media/cma/backend/) -in the Chromium repo. The `CmaBackend` will create an `AudioDecoder` and -`VideoDecoder` instance as needed, which is responsible for operations such as -playback control, queueing up media playout, and decrypting DRM (if needed), -then passing these commands to the `MediaPipelineBackend`. - -## gRPC - -[gRPC](https://grpc.io/) is a modern open source high performance RPC framework -that can run in any environment. It can efficiently connect services in and -across data centers with pluggable support for load balancing, tracing, health -checking and authentication. gRPC was chosen as the RPC framework to use for the -Chromium runtime to simplify the upgrade story for when both sides of the RPC -channel can upgrade independently. - -## Chromium Runtime - -A runtime to be used by hardware devices to play out audio and video data as -received from a Cast session. It is expected to run on an embedded device. - -# High Level Architecture - -At a high level, the `CmaBackendProxy` ("proxy backend") sits on top of another -`CmaBackend`, which for the purposes of this document will be referred to as the -delegated backend. The proxy backend acts to send all audio and video data to -the delegated backend on which it sits, while also sending the same audio to the -CastRuntimeAudioChannel gRPC Channel used to proxy data, along with -synchronization data to keep playback between the two in-line. -The architecture used for this pipeline can be seen as -[follows](https://charleshan.users.x20web.corp.google.com/www/nomnoml/nomnoml/index.html#view/%5B%3Cabstract%3ECmaBackend%7C%0A%20%20CreateAudioDecoder()%3B%0A%20%20CreateVideoDecoder()%3B%0A%20%20Initialize()%3B%0A%20%20Start(int64_t%20start_pts)%3B%0A%20%20Stop()%3B%0A%20%20Pause()%3B%0A%20%20Resume()%3B%0A%20%20GetCurrentPts()%3B%0A%20%20SetPlaybackRate()%5D%0A%5B%3Cabstract%3ECmaBackend%3A%3AAudioDecoder%7C%0A%20%20SetDelegate()%3B%0A%20%20PushBuffer()%3B%0A%20%20SetConfig()%3B%0A%20%20SetVolume()%3B%0A%20%20GetRenderingDelay()%3B%0A%20%20GetStatistics()%3B%0A%20%20RequiresDecryption()%3B%0A%20%20SetObserver()%5D%0A%5B%3Cabstract%3ECmaBackend%3A%3ADecoder%3A%3ADelegate%7C%0A%20%20OnPushBufferComplete()%3B%0A%20%20OnEndOfStream()%3B%0A%20%20OnDecoderError()%3B%0A%20%20OnKeyStatusChanged()%3B%0A%20%20OnVideoResolutionChanged()%5D%0A%20%20%0A%5BAudioDecoderPipelineNode%5D%0A%5BCmaBackendProxy%5D%0A%5BBufferIdManager%7C%0A%20%20AssignBufferId()%3B%0A%20%20GetCurrentlyProcessingBufferInfo()%3B%0A%20%20UpdateAndGetCurrentlyProcessingBufferInfo()%7C%0A%20%20%5BBufferId%5D%3B%0A%20%20%5BTargetBufferInfo%7Cbuffer_id%3A%20BufferId%3B%20timestamp_micros%3A%20int64_t%5D%5D%0A%5B%3Cabstract%3ECmaProxyHandler%7C%0A%20%20Initialize()%3B%0A%20%20Start()%3B%0A%20%20Stop()%3B%0A%20%20Pause()%3B%0A%20%20Resume()%3B%0A%20%20SetPlaybackRate()%3B%0A%20%20SetVolume()%3B%0A%20%20SetConfig()%3B%0A%20%20PushBuffer()%5D%0A%5BProxyCallTranslator%5D%0A%5B%3Cabstract%3EMultizoneAudioDecoderProxy%7C%0A%20%20Initialize()%3B%0A%20%20Start()%3B%0A%20%20Stop()%3B%0A%20%20Pause()%3B%0A%20%20Resume()%3B%0A%20%20SetPlaybackRate()%3B%0A%20%20LogicalPause()%3B%0A%20%20LogicalResume()%3B%0A%20%20GetCurrentPts()%20const%5D%0A%5BMultizoneAudioDecoderProxyImpl%5D%0A%5BMediaPipelineBufferExtension%5D%0A%5B%3Cabstract%3ECastRuntimeAudioChannelBroker%7C%0A%20%20InitializeAsync()%3B%0A%20%20SetVolumeAsync()%3B%0A%20%20SetPlaybackAsync()%3B%0A%20%20GetMediaTimeAsync()%3B%0A%20%20StartAsync()%3B%0A%20%20StopAsync()%3B%0A%20%20PauseAsync()%3B%0A%20%20ResumeAsync()%5D%0A%5B%3Cabstract%3EAudioChannelPushBufferHandler%7C%0A%20%20PushBuffer()%3B%0A%20%20HasBufferedData()%20const%3B%0A%20%20GetBufferedData()%5D%0A%5BPushBufferQueue%5D%0A%5BPushBufferPendingHandler%5D%0A%5BCastRuntimeAudioChannelEndpointManager%7C%0A%20%20GetAudioChannelEndpoint()%5D%0A%0A%5BCmaBackend%5D%3C%3A--1%5BCmaBackendProxy%5D%0A%5BCmaBackendProxy%5D1-%5BMultizoneAudioDecoderProxy%5D%0A%5BCmaBackend%3A%3AAudioDecoder%5D%3C%3A--%5BAudioDecoderPipelineNode%5D%0A%5BCmaBackend%3A%3ADecoder%3A%3ADelegate%5D%3C%3A--%5BAudioDecoderPipelineNode%5D%0A%5BAudioDecoderPipelineNode%5D%3C%3A--%5BMediaPipelineBufferExtension%5D%0A%5BAudioDecoderPipelineNode%5D%3C%3A--%5BMultizoneAudioDecoderProxy%5D%0A%5BMultizoneAudioDecoderProxy%5D%3C%3A--%5BMultizoneAudioDecoderProxyImpl%5D%0A%5BMultizoneAudioDecoderProxyImpl%5D1-%5BCmaProxyHandler%5D%0A%5BMultizoneAudioDecoderProxyImpl%5D1-%5BBufferIdManager%5D%0A%5BCmaProxyHandler%5D%3C%3A--%5BProxyCallTranslator%5D%0A%5BProxyCallTranslator%5D1-%5BCastRuntimeAudioChannelBroker%5D%0A%5BAudioChannelPushBufferHandler%5D%3C%3A-%5BPushBufferPendingHandler%5D%0A%5BAudioChannelPushBufferHandler%5D%3C%3A-%5BPushBufferQueue%5D%0A%5BProxyCallTranslator%5D1-%5BPushBufferPendingHandler%5D%0A%5BPushBufferPendingHandler%5D1-%5BPushBufferQueue%5D%0A%5BMultizoneAudioDecoderProxyImpl%5D1-%5BMediaPipelineBufferExtension%5D%0A%5BCmaBackend%3A%3AAudioDecoder%5D-1%5BMediaPipelineBufferExtension%5D%0A%5BCastRuntimeAudioChannelBroker%5D%3C%3A--%5BAudioChannelBrokerImpl%5D%0A%5BAudioChannelBrokerImpl%5D%3C%3A--%5BCastRuntimeAudioChannelEndpointManager%5D%0A): - -![image](https://services.google.com/fh/files/misc/cmabackendproxy_infra.png) - -# Implementation Specifics - -The pipeline can be roughly divided into two parts: - -- Local Media Playout, or how the `CmaBackendProxy` gets audio and video - data it receives to the platform-specific `MediaPipelineBackend`, resulting - in playout of the local device's speakers . -- Audio Data Proxying, or how the audio data is streamed across the - [CastRuntimeAudioChannel](https://source.chromium.org/chromium/chromium/src/+/main:third_party/cast_core/public/src/proto/runtime/cast_audio_decoder_service.proto;l=231?q=castruntimeaudiochannel&sq=&ss=chromium%2Fchromium%2Fsrc) - gRPC Service in parallel to the local playout, - -Both can be summarized in this -[diagram](https://sequencediagram.googleplex.com/view/5704799657918464), with -further details to follow: - -![image](https://services.google.com/fh/files/misc/cmabackendproxy_pushbuffer_flow.png) - -## Local Media Playout - -The `CmaBackendProxy`, by virtue of being a `BackendProxy`, can create an -AudioDecoder and a VideoDecoder. VideoDecoder creation and all video processing -is delegated to the underlying delegated backend with no changes, so it will not -be discussed further. The AudioDecoder is more interesting - there are 3 -`CmaBackend::AudioDecoder` types relevant in this architecture through which -audio data will pass - two `proxy` specific and the delegated backend's decoder. -In processing order, they are: - -1. [`MultizoneAudioDecoderProxy`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy.h): - This class is the starting-point for sending data over the - CastRuntimeAudioChannel gRPC, using the pipeline described in the [following - section](#heading=h.gkcc76texr45). -1. `MediaPipelineBufferExtension`: This class performs no processing itself, - but instead just acts to store the data from PushBuffer calls locally, so - that an extra few seconds of data may be queued up in addition to what the - local decoder stores. -1. _Delegated backend's audio decoder: _The `CmaBackend::AudioDecoder` for - this specific platform, as described above. This is owned by the Delegated - backend itself. - -All audio data passes through these three layers so that it may be played out -locally. For local playback as described here, this functionality is for the -most part uninteresting - by design, the end user should notice no difference in -audio playout. At an architecture level, the only noticeable difference for an -embedder is that extra data is queued locally in the -`MediaPipelineBufferExtension`. - -As an abstraction on top of the above, the `AudioDecoderPipelineNode` was -introduced as a parent for `MultizoneAudioDecoderProxy` and -`MediaPipelineBufferExtension`, though its existence can for the most part be -ignored. All functions in this base class act as pass-through methods, directly -calling into the lower layer's method of the same name. Meaning that this class -functions purely for software-engineering reasons, as a way to reduce code -complexity of the child classes. - -## Audio Data Proxying - -The `MultizoneAudioDecoderProxy`, as mentioned above, functions to proxy data -across the CastRuntimeAudioChannel gRPC channel. The pipeline used to do uses -the following classes, in order: - -1. [`MultizoneAudioDecoderProxyImpl`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.h): - As mentioned above, all `CmaBackend::AudioDecoder` methods call into here - first, as well as methods corresponding to the public calls on `CmaBackend`. - This class mostly acts as a pass-through, immediately calling into the below - for all above method calls, although the `BufferIdManager` owned by this - class adds a bit of complexity, in that it assigns Buffer Ids to PushBuffer - calls, to be used for audio timing synchronization between both sides of the - CastRuntimeAudioChannel gRPC channel. -1. [`ProxyCallTranslator`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/media/cma/backend/proxy/proxy_call_translator.h): - As the name suggests, this class exists to convert between the - media-pipeline understood types, as called into the above layer, with those - supported by CastRuntimeAudioChannel gRPC.To this end, `PushBufferQueue` - helps to turn the "Push" model used by the `CmaBackend::AudioDecoder`'s - `PushBuffer()` method into a "Pull" model that better aligns with the gRPC - async model. The `PendingPushBufferHelper` works with the above, to support - returning a `kBufferPending` response as required by the `PushBuffer()` - method's contract. In addition, this class is also responsible for handling - threading assumptions made by the above and below classes, such as how data - returned by the below layer must be processed on the correct thread in the - above layer. -1. [`CastRuntimeAudioChannelBroker`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h): - Implementations of this abstract class take the CastRuntimeAudioChannel gRPC - types supplied by the above, then use them to make calls against the gRPC - Service. - -# Configuring the Pipeline - -In order to support varied user scenarios, a number of build flags have been -introduced to customize the functionality of this pipeline: - -#### enable_chromium_runtime_cast_renderer - -This flag enables or disables support for sending data across the -CastRuntimeAudioChannel. When enabled, the -[`CmaBackendFactoryImpl`](https://source.chromium.org/chromium/chromium/src/+/main:chromecast/media/cma/backend/cma_backend_factory_impl.cc;l=32) -class will wrap the implementation-specific `CmaBackend` with a -`CmaBackendProxy` instance, as described above. This flag defaults to `False`. diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,207 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/proxy/audio_channel_broker_impl.h" - -#include - -#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_manager.h" -#include "chromecast/public/task_runner.h" -#include "third_party/grpc/src/include/grpcpp/create_channel.h" - -namespace chromecast { -namespace media { -namespace { - -constexpr int64_t kMsDelayBetweenPushBufferPollingChecks = 10; - -std::unique_ptr -GetRemoteStub() { - auto* endpoint_manager = CastRuntimeAudioChannelEndpointManager::Get(); - DCHECK(endpoint_manager); - - std::string endpoint = endpoint_manager->GetAudioChannelEndpoint(); - DCHECK(!endpoint.empty()); - - auto channel = - grpc::CreateChannel(endpoint, grpc::InsecureChannelCredentials()); - return cast::media::CastAudioChannelService::NewStub(channel); -} - -} // namespace - -// static -std::unique_ptr -CastRuntimeAudioChannelBroker::Create(TaskRunner* task_runner, - Handler* handler) { - return std::make_unique(task_runner, handler); -} - -AudioChannelBrokerImpl::LazyStubFactory::LazyStubFactory() = default; - -AudioChannelBrokerImpl::LazyStubFactory::~LazyStubFactory() = default; - -AudioChannelBrokerImpl::LazyStubFactory::Stub* -AudioChannelBrokerImpl::LazyStubFactory::GetStub() { - if (!stub_) { - stub_ = GetRemoteStub(); - } - - return stub_.get(); -} - -AudioChannelBrokerImpl::AudioChannelBrokerImpl(TaskRunner* task_runner, - Handler* handler) - : handler_(handler), task_runner_(task_runner), weak_factory_(this) { - DCHECK(task_runner_); - DCHECK(handler_); -} - -AudioChannelBrokerImpl::~AudioChannelBrokerImpl() = default; - -void AudioChannelBrokerImpl::InitializeAsync( - const std::string& cast_session_id, - CastAudioDecoderMode decoder_mode) { - auto request = InitializeCall::CreateRequest( - this, &GrpcStub::async_interface::Initialize, - &AudioChannelBrokerImpl::OnInitialize); - request.parameters().set_cast_session_id(cast_session_id); - request.parameters().set_mode(decoder_mode); - - request.CallAsync(); -} - -void AudioChannelBrokerImpl::SetVolumeAsync(float multiplier) { - auto request = - SetVolumeCall::CreateRequest(this, &GrpcStub::async_interface::SetVolume, - &AudioChannelBrokerImpl::OnSetVolume); - request.parameters().set_multiplier(multiplier); - - request.CallAsync(); -} - -void AudioChannelBrokerImpl::SetPlaybackAsync(double playback_rate) { - auto request = SetPlaybackCall::CreateRequest( - this, &GrpcStub::async_interface::SetPlaybackRate, - &AudioChannelBrokerImpl::OnSetPlayback); - request.parameters().set_rate(playback_rate); - - request.CallAsync(); -} - -void AudioChannelBrokerImpl::GetMediaTimeAsync() { - auto request = GetMediaTimeCall::CreateRequest( - this, &GrpcStub::async_interface::GetMediaTime, - &AudioChannelBrokerImpl::OnGetMediaTime); - - request.CallAsync(); -} - -AudioChannelBrokerImpl::StateChangeCall::Request -AudioChannelBrokerImpl::CreateStateChangeCallRequest() { - return StateChangeCall::CreateRequest(this, - &GrpcStub::async_interface::StateChange, - &AudioChannelBrokerImpl::OnStateChange); -} - -void AudioChannelBrokerImpl::StartAsync(int64_t pts_micros, - TimestampInfo timestamp_info) { - auto request = CreateStateChangeCallRequest(); - request.parameters().mutable_start()->set_pts_micros(pts_micros); - *request.parameters().mutable_start()->mutable_timestamp_info() = - timestamp_info; - request.CallAsync(); -} - -void AudioChannelBrokerImpl::StopAsync() { - auto request = CreateStateChangeCallRequest(); - request.parameters().set_allocated_stop(new cast::media::StopRequest()); - request.CallAsync(); -} - -void AudioChannelBrokerImpl::PauseAsync() { - auto request = CreateStateChangeCallRequest(); - request.parameters().set_allocated_pause(new cast::media::PauseRequest()); - request.CallAsync(); -} - -void AudioChannelBrokerImpl::ResumeAsync(TimestampInfo timestamp_info) { - auto request = CreateStateChangeCallRequest(); - *request.parameters().mutable_resume()->mutable_resume_timestamp_info() = - timestamp_info; - request.CallAsync(); -} - -void AudioChannelBrokerImpl::UpdateTimestampAsync( - TimestampInfo timestamp_info) { - auto request = CreateStateChangeCallRequest(); - *request.parameters().mutable_timestamp_update()->mutable_timestamp_info() = - timestamp_info; - request.CallAsync(); -} - -void AudioChannelBrokerImpl::TryPushBuffer() { - if (handler_->HasBufferedData()) { - auto request = handler_->GetBufferedData(); - if (request.has_value()) { - auto request_call = std::make_unique( - std::move(request.value())); - DCHECK(request_call.get()); - - auto push_buffer_request = PushBufferCall::CreateRequest( - this, &GrpcStub::async_interface::PushBuffer, - &AudioChannelBrokerImpl::OnPushBuffer); - push_buffer_request.parameters().CopyFrom(*request_call); - - push_buffer_request.CallAsync(); - return; - } - } - - auto* task = new TaskRunner::CallbackTask(base::BindOnce( - &AudioChannelBrokerImpl::TryPushBuffer, weak_factory_.GetWeakPtr())); - task_runner_->PostTask(task, kMsDelayBetweenPushBufferPollingChecks); -} - -void AudioChannelBrokerImpl::OnGetMediaTime( - std::unique_ptr request, - CastRuntimeAudioChannelBroker::StatusCode status_code) { - handler_->HandleGetMediaTimeResponse(request->response().media_time(), - status_code); -} - -void AudioChannelBrokerImpl::OnPushBuffer( - std::unique_ptr request, - CastRuntimeAudioChannelBroker::StatusCode status_code) { - handler_->HandlePushBufferResponse(request->response().decoded_bytes(), - status_code); - TryPushBuffer(); -} - -void AudioChannelBrokerImpl::OnSetPlayback( - std::unique_ptr request, - CastRuntimeAudioChannelBroker::StatusCode status_code) { - handler_->HandleSetPlaybackResponse(status_code); -} - -void AudioChannelBrokerImpl::OnSetVolume( - std::unique_ptr request, - CastRuntimeAudioChannelBroker::StatusCode status_code) { - handler_->HandleSetVolumeResponse(status_code); -} - -void AudioChannelBrokerImpl::OnStateChange( - std::unique_ptr request, - CastRuntimeAudioChannelBroker::StatusCode status_code) { - handler_->HandleStateChangeResponse(request->response().state(), status_code); -} - -void AudioChannelBrokerImpl::OnInitialize( - std::unique_ptr request, - CastRuntimeAudioChannelBroker::StatusCode status_code) { - handler_->HandleInitializeResponse(status_code); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_broker_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,250 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_CHANNEL_BROKER_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_CHANNEL_BROKER_IMPL_H_ - -#include - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h" -#include "third_party/cast_core/public/src/proto/runtime/cast_audio_channel_service.grpc.pb.h" -#include "third_party/cast_core/public/src/proto/runtime/cast_audio_channel_service.pb.h" -#include "third_party/grpc/src/include/grpcpp/impl/codegen/status.h" -#include "third_party/protobuf/src/google/protobuf/duration.pb.h" - -namespace chromecast { - -class TaskRunner; - -namespace media { - -// This class provides an implementation of the CastRuntimeAudioChannelBroker -// interface using the public gRPC library's asynchronous APIs. -class AudioChannelBrokerImpl - : public CastRuntimeAudioChannelBroker, - public cast::media::CastAudioChannelService::CallbackService { - public: - // |task_runner| and |handler| must remain valid for the lifetime of this - // object. - AudioChannelBrokerImpl(TaskRunner* task_runner, Handler* handler); - AudioChannelBrokerImpl(const AudioChannelBrokerImpl& other) = delete; - AudioChannelBrokerImpl(AudioChannelBrokerImpl&& other) = delete; - ~AudioChannelBrokerImpl() override; - - AudioChannelBrokerImpl& operator=(const AudioChannelBrokerImpl& other) = - delete; - AudioChannelBrokerImpl& operator=(AudioChannelBrokerImpl&& other) = delete; - - // CastRuntimeAudioChannelBroker overrides: - // - // Note that all below methods may be called from any thread. - void InitializeAsync(const std::string& cast_session_id, - CastAudioDecoderMode decoder_mode) override; - void SetVolumeAsync(float multiplier) override; - void SetPlaybackAsync(double playback_rate) override; - void GetMediaTimeAsync() override; - void StartAsync(int64_t pts_micros, TimestampInfo timestamp_info) override; - void StopAsync() override; - void PauseAsync() override; - void ResumeAsync(TimestampInfo timestamp_info) override; - void UpdateTimestampAsync(TimestampInfo timestamp_info) override; - - private: - using GrpcStub = cast::media::CastAudioChannelService::StubInterface; - - // Helper to abstract away the complexity of using gRPC Calls with the new - // gRPC async APIs. - // - // Handles creating a "Request" type which is then populated with call - // parameters, and an async call is sent with CallAsync(). This calls into - // the user-specified callback. - template - struct GrpcCall { - // The response to a gRPC Call. - class Response : public grpc::ClientUnaryReactor { - public: - using Callback = - base::OnceCallback; - - Response(std::unique_ptr params) - : parameters_(std::move(params)), - response_(std::make_unique()), - context_(std::make_unique()) {} - - ~Response() override = default; - - // Sets the callback to be called upon completion of the associated gRPC - // call. Must be set before this occurs. - void SetCallback(Callback callback) { callback_ = std::move(callback); } - - TParams& parameters() const { return *parameters_; } - TResult& response() const { return *response_; } - grpc::ClientContext& context() const { return *context_; } - - private: - // grpc::ClientUnaryReactor overrides: - // - // Per documentation, "If it is never called on an RPC, it indicates an - // application-level problem (like failure to remove a hold)." So this - // method should always be called, and the |callback_| will delete this - // instance - void OnDone(const grpc::Status& s) override { - std::move(callback_).Run(GetStatusCode(s)); - } - - static inline CastRuntimeAudioChannelBroker::StatusCode GetStatusCode( - const grpc::Status& status) { - return static_cast( - status.error_code()); - } - - std::unique_ptr parameters_; - std::unique_ptr response_; - std::unique_ptr context_; - Callback callback_; - }; - - // Handles populating and sending a gRPC Request. - class Request { - public: - using StubCallMethod = - base::OnceCallback; - using ResponseCallback = - base::OnceCallback, - CastRuntimeAudioChannelBroker::StatusCode)>; - - Request(StubCallMethod stub_call, ResponseCallback response_callback) - : stub_call_(std::move(stub_call)), - response_callback_(std::move(response_callback)), - parameters_(std::make_unique()) {} - - void CallAsync() { - // Create a new Response. - std::unique_ptr response = - std::make_unique(std::move(parameters_)); - Response* response_ptr = response.get(); - - // Transfer ownership of the response into a callback. - auto callback = - base::BindOnce(std::move(response_callback_), std::move(response)); - - // Transfer ownership of that callback to the the response object it now - // owns. - response_ptr->SetCallback(std::move(callback)); - - // Make the gRPC Call. The unique_ptr containing the transferred - // |response| instance will be moved to the callback method, and then - // deleted when it goes out of scope. - std::move(stub_call_) - .Run(&response_ptr->context(), &response_ptr->parameters(), - &response_ptr->response(), response_ptr); - } - - TParams& parameters() const { return *parameters_; } - - private: - StubCallMethod stub_call_; - ResponseCallback response_callback_; - std::unique_ptr parameters_; - }; - - // Helper for creating a gRPC Request using only the remote call and - // callback to be called. - // - // |async_call| is a member-function pointer to the gRPC Stub method to call - // asynchronously. - // |callback| is a member function pointer to the callback to use when a - // response occurs. This will ALWAYS be called, even on a failed or - // canceled gRPC call. - template - static Request CreateRequest( - AudioChannelBrokerImpl* instance, - void (CallStub::*async_call)(grpc::ClientContext*, - const TParams*, - TResult*, - grpc::ClientUnaryReactor*), - void (CallbackClass::*callback)( - std::unique_ptr, - CastRuntimeAudioChannelBroker::StatusCode)) { - auto bound_async_call = base::BindOnce( - async_call, - base::Unretained(instance->stub_factory_.GetStub()->async())); - auto bound_callback = - base::BindOnce(callback, instance->weak_factory_.GetWeakPtr()); - return Request(std::move(bound_async_call), std::move(bound_callback)); - } - }; - - // Helper to initialize the service stub at runtime instead of instance - // creation time. - class LazyStubFactory { - public: - using Stub = cast::media::CastAudioChannelService::StubInterface; - - LazyStubFactory(); - ~LazyStubFactory(); - - Stub* GetStub(); - - private: - std::unique_ptr stub_; - }; - - // Some aliases to make the code more readable. - using InitializeCall = - GrpcCall; - using StateChangeCall = GrpcCall; - using SetVolumeCall = - GrpcCall; - using SetPlaybackCall = GrpcCall; - using GetMediaTimeCall = GrpcCall; - using PushBufferCall = - GrpcCall; - - // Helper to create the call types used more than once. - StateChangeCall::Request CreateStateChangeCallRequest(); - - // Calls PushBuffer if data to push is available. Else, schedule this task to - // run again in the future. - void TryPushBuffer(); - - // Callbacks for asynchronous gRPC calls. Each calls into the appropriate - // |handler_| method. - void OnGetMediaTime(std::unique_ptr call_details, - CastRuntimeAudioChannelBroker::StatusCode status_code); - void OnSetPlayback(std::unique_ptr call_details, - CastRuntimeAudioChannelBroker::StatusCode status_code); - void OnSetVolume(std::unique_ptr call_details, - CastRuntimeAudioChannelBroker::StatusCode status_code); - void OnStateChange(std::unique_ptr call_details, - CastRuntimeAudioChannelBroker::StatusCode status_code); - void OnInitialize(std::unique_ptr call_details, - CastRuntimeAudioChannelBroker::StatusCode status_code); - - // Callback for PushBuffer asynchronous gRPC call. Calls into - // |handler_->HandlePushBufferResponse()| then tries to push more data. - void OnPushBuffer(std::unique_ptr call_details, - CastRuntimeAudioChannelBroker::StatusCode status_code); - - LazyStubFactory stub_factory_; - - Handler* const handler_; - TaskRunner* const task_runner_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_CHANNEL_BROKER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_CHANNEL_PUSH_BUFFER_HANDLER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_CHANNEL_PUSH_BUFFER_HANDLER_H_ - -#include - -#include "chromecast/media/api/cma_backend.h" -#include "third_party/cast_core/public/src/proto/runtime/cast_audio_channel_service.pb.h" - -namespace chromecast { -namespace media { - -// This class is responsible for buffering both DecoderBuffer and AudioConfig -// data, which are pushed together over gRPC using the PushData() API call. -// Two sequences are expected to access this object: -// - A PRODUCER sequence, which will push new data in. -// - A CONSUMER sequence which will pull this data back out. -class AudioChannelPushBufferHandler { - public: - // NOTE: This is needed to avoid introducing extra DEPS-file dependencies on - // third_party/openscreen. - using PushBufferRequest = cast::media::PushBufferRequest; - - class Client { - public: - // Called following a PushBuffer() call which returns kBufferPending, to - // provide the result of that call and signal that this instance is ready - // to handle more PushBuffer calls. - virtual void OnAudioChannelPushBufferComplete( - CmaBackend::BufferStatus status) = 0; - - protected: - virtual ~Client() = default; - }; - - virtual ~AudioChannelPushBufferHandler() = default; - - // Writes the next available PushBufferRequest to be processed. Return values - // are as follows: - // - kBufferSuccess: The data has been processed successfully - // - kBufferPending: The data will be processed at a later time. Do not call - // this method again until the associated client has provided a callback - // with type kBufferSuccess. - // - kBufferFailed: The data was NOT processed successfully, but the pipeline - // remains in a healthy state and you may try again at a later point - // Note that no call to this method will ever put the implementation into an - // undefined or unhealthy state. - // - // May only be called by the PRODUCER. - virtual CmaBackend::BufferStatus PushBuffer( - const PushBufferRequest& request) = 0; - - // Returns true if there is data available for reading. - // - // May only be called by the CONSUMER. - virtual bool HasBufferedData() const = 0; - - // Attempts to read the next available PushBufferRequest, returning the - // instance on success and empty. May only be called when HasBufferedData() is - // true. - // - // May only be called by the CONSUMER. - virtual std::optional GetBufferedData() = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_CHANNEL_PUSH_BUFFER_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,129 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h" - -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { - -AudioDecoderPipelineNode::AudioDecoderPipelineNode( - CmaBackend::AudioDecoder* delegated_decoder) - : delegated_decoder_(delegated_decoder) { - DCHECK(delegated_decoder_); -} - -AudioDecoderPipelineNode::~AudioDecoderPipelineNode() = default; - -void AudioDecoderPipelineNode::SetDelegate( - CmaBackend::Decoder::Delegate* delegate) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - delegated_decoder_delegate_ = delegate; - delegated_decoder_->SetDelegate(this); -} - -CmaBackend::Decoder::BufferStatus AudioDecoderPipelineNode::PushBuffer( - scoped_refptr buffer) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - return delegated_decoder_->PushBuffer(std::move(buffer)); -} - -bool AudioDecoderPipelineNode::SetConfig(const AudioConfig& config) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - return delegated_decoder_->SetConfig(config); -} - -bool AudioDecoderPipelineNode::SetVolume(float multiplier) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - return delegated_decoder_->SetVolume(multiplier); -} - -CmaBackend::AudioDecoder::RenderingDelay -AudioDecoderPipelineNode::GetRenderingDelay() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - return delegated_decoder_->GetRenderingDelay(); -} - -void AudioDecoderPipelineNode::GetStatistics( - CmaBackend::AudioDecoder::Statistics* statistics) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - return delegated_decoder_->GetStatistics(statistics); -} - -CmaBackend::AudioDecoder::AudioTrackTimestamp -AudioDecoderPipelineNode::GetAudioTrackTimestamp() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - return delegated_decoder_->GetAudioTrackTimestamp(); -} - -int AudioDecoderPipelineNode::GetStartThresholdInFrames() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - return delegated_decoder_->GetStartThresholdInFrames(); -} - -bool AudioDecoderPipelineNode::RequiresDecryption() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - return delegated_decoder_->RequiresDecryption(); -} - -void AudioDecoderPipelineNode::SetOwnedDecoder( - std::unique_ptr delegated_decoder) { - DCHECK_EQ(delegated_decoder.get(), delegated_decoder_); - - owned_delegated_decoder_ = std::move(delegated_decoder); -} - -void AudioDecoderPipelineNode::OnPushBufferComplete( - CmaBackend::Decoder::BufferStatus status) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(delegated_decoder_delegate_); - - delegated_decoder_delegate_->OnPushBufferComplete(status); -} - -void AudioDecoderPipelineNode::OnEndOfStream() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(delegated_decoder_delegate_); - - delegated_decoder_delegate_->OnEndOfStream(); -} - -void AudioDecoderPipelineNode::OnDecoderError() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(delegated_decoder_delegate_); - - delegated_decoder_delegate_->OnDecoderError(); -} - -void AudioDecoderPipelineNode::OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(delegated_decoder_delegate_); - - delegated_decoder_delegate_->OnKeyStatusChanged(key_id, key_status, - system_code); -} - -void AudioDecoderPipelineNode::OnVideoResolutionChanged(const Size& size) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(delegated_decoder_delegate_); - - delegated_decoder_delegate_->OnVideoResolutionChanged(size); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_DECODER_PIPELINE_NODE_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_DECODER_PIPELINE_NODE_H_ - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/threading/thread_checker.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/public/media/cast_key_status.h" - -namespace chromecast { - -struct Size; - -namespace media { - -// This class acts as a single node in a series of Audio Decoders which form an -// audio processing pipeline. This can be thought of as a tree with the -// following characteristics: -// - Each node has at most one child. -// - The single leaf node is a CmaBackend::AudioDecoder. -// - All other nodes are instances of this class. -// By default, all calls to this class's CmaBackend::AudioDecoder nodes are -// passed back to this node's child. Additionally, if SetDelegate() is called, -// any calls to this class's CmaBackendDecoder::Delegate methods are passed to -// the set delegate, forming a pipeline in the opposite order. All methods are -// expected to be called on the same thread. -class AudioDecoderPipelineNode : public CmaBackend::Decoder::Delegate, - public CmaBackend::AudioDecoder { - public: - explicit AudioDecoderPipelineNode( - CmaBackend::AudioDecoder* delegated_decoder); - AudioDecoderPipelineNode(const AudioDecoderPipelineNode& other) = delete; - - ~AudioDecoderPipelineNode() override; - - AudioDecoderPipelineNode& operator=(const AudioDecoderPipelineNode& other) = - delete; - - // CmaBackend::AudioDecoder overrides. - void SetDelegate(CmaBackend::Decoder::Delegate* delegate) override; - CmaBackend::Decoder::BufferStatus PushBuffer( - scoped_refptr buffer) override; - bool SetConfig(const AudioConfig& config) override; - bool SetVolume(float multiplier) override; - CmaBackend::AudioDecoder::RenderingDelay GetRenderingDelay() override; - void GetStatistics(CmaBackend::AudioDecoder::Statistics* statistics) override; - CmaBackend::AudioDecoder::AudioTrackTimestamp GetAudioTrackTimestamp() override; - int GetStartThresholdInFrames() override; - bool RequiresDecryption() override; - - protected: - inline void CheckCalledOnCorrectThread() const { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - } - - // Sets the decoder to be owned by this node of the pipeline. Must match the - // instance provided as |delegated_decoder_| in the ctor. - void SetOwnedDecoder( - std::unique_ptr delegated_decoder); - - // CmaBackend::Decoder::Delegate overrides. - void OnPushBufferComplete(CmaBackend::Decoder::BufferStatus status) override; - void OnEndOfStream() override; - void OnDecoderError() override; - void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override; - void OnVideoResolutionChanged(const Size& size) override; - - private: - friend class AudioDecoderPipelineNodeTests; - - // Local storage for the object backing |delegated_decoder_|, when it is - // owned by this class. Empty unless set by SetOwnedDecoder(). - std::unique_ptr owned_delegated_decoder_; - - // Decoder::Delegate to which all calls to CmaBackend::Decoder::Delegate - // methods should be forwarded. - CmaBackend::Decoder::Delegate* delegated_decoder_delegate_; - - // Decoder to which all calls to CmaBackend::AudioDecoder methods will be - // forwarded. - CmaBackend::AudioDecoder* const delegated_decoder_; - - THREAD_CHECKER(thread_checker_); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_AUDIO_DECODER_PIPELINE_NODE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,144 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h" - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/test/test_simple_task_runner.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/api/test/mock_cma_backend.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h" -#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" -#include "chromecast/public/media/cast_key_status.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/stream_id.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -class AudioDecoderPipelineNodeTests : public testing::Test { - public: - AudioDecoderPipelineNodeTests() - : parent_delegate_( - std::make_unique< - testing::StrictMock>()), - child_node_(std::make_unique< - testing::StrictMock>()) {} - - ~AudioDecoderPipelineNodeTests() override = default; - - protected: - std::unique_ptr parent_delegate_; - std::unique_ptr child_node_; -}; - -TEST_F(AudioDecoderPipelineNodeTests, TestAudioDecoderCalls) { - AudioDecoderPipelineNode test_node(child_node_.get()); - - // SetDelegate. - EXPECT_CALL(*child_node_, SetDelegate(&test_node)); - test_node.SetDelegate(parent_delegate_.get()); - testing::Mock::VerifyAndClearExpectations(child_node_.get()); - - // PushBuffer. - scoped_refptr buffer( - new CastDecoderBufferImpl(3, StreamId::kPrimary)); - buffer->writable_data()[0] = 1; - buffer->writable_data()[1] = 2; - buffer->writable_data()[2] = 3; - EXPECT_CALL(*child_node_, PushBuffer(testing::_)) - .WillOnce(testing::Invoke([ptr = buffer.get()](auto result) - -> CmaBackend::Decoder::BufferStatus { - EXPECT_EQ(ptr, result.get()); - return CmaBackend::Decoder::BufferStatus::kBufferSuccess; - })); - EXPECT_EQ(test_node.PushBuffer(buffer), - CmaBackend::Decoder::BufferStatus::kBufferSuccess); - testing::Mock::VerifyAndClearExpectations(child_node_.get()); - - // SetConfig. - AudioConfig config; - EXPECT_CALL(*child_node_, SetConfig(testing::_)) - .WillOnce(testing::Return(true)) - .WillOnce(testing::Return(false)); - EXPECT_EQ(test_node.SetConfig(config), true); - EXPECT_EQ(test_node.SetConfig(config), false); - testing::Mock::VerifyAndClearExpectations(child_node_.get()); - - // SetVolume. - EXPECT_CALL(*child_node_, SetVolume(42)).WillOnce(testing::Return(true)); - EXPECT_EQ(test_node.SetVolume(42), true); - EXPECT_CALL(*child_node_, SetVolume(23)).WillOnce(testing::Return(false)); - EXPECT_EQ(test_node.SetVolume(23), false); - testing::Mock::VerifyAndClearExpectations(child_node_.get()); - - // GetStatistics - CmaBackend::AudioDecoder::Statistics stats; - EXPECT_CALL(*child_node_, GetStatistics(&stats)); - test_node.GetStatistics(&stats); - testing::Mock::VerifyAndClearExpectations(child_node_.get()); - - // RequiresDecryption. - EXPECT_CALL(*child_node_, RequiresDecryption()) - .WillOnce(testing::Return(true)) - .WillOnce(testing::Return(false)); - EXPECT_EQ(test_node.RequiresDecryption(), true); - EXPECT_EQ(test_node.RequiresDecryption(), false); - testing::Mock::VerifyAndClearExpectations(child_node_.get()); -} - -TEST_F(AudioDecoderPipelineNodeTests, TestDecoderDelegateCalls) { - AudioDecoderPipelineNode test_node(child_node_.get()); - auto* node_as_delegate = - static_cast(&test_node); - EXPECT_CALL(*child_node_, SetDelegate(&test_node)); - test_node.SetDelegate(parent_delegate_.get()); - testing::Mock::VerifyAndClearExpectations(child_node_.get()); - - // OnPushBufferComplete. - EXPECT_CALL( - *parent_delegate_, - OnPushBufferComplete(CmaBackend::Decoder::BufferStatus::kBufferSuccess)); - node_as_delegate->OnPushBufferComplete( - CmaBackend::Decoder::BufferStatus::kBufferSuccess); - testing::Mock::VerifyAndClearExpectations(parent_delegate_.get()); - EXPECT_CALL( - *parent_delegate_, - OnPushBufferComplete(CmaBackend::Decoder::BufferStatus::kBufferFailed)); - node_as_delegate->OnPushBufferComplete( - CmaBackend::Decoder::BufferStatus::kBufferFailed); - - // OnEndOfStream. - EXPECT_CALL(*parent_delegate_, OnEndOfStream()); - node_as_delegate->OnEndOfStream(); - testing::Mock::VerifyAndClearExpectations(parent_delegate_.get()); - - // OnDecoderError. - EXPECT_CALL(*parent_delegate_, OnDecoderError()); - node_as_delegate->OnDecoderError(); - testing::Mock::VerifyAndClearExpectations(parent_delegate_.get()); - - // OnKeyStatusChanged. - std::string key = "foobar"; - CastKeyStatus key_status = CastKeyStatus::KEY_STATUS_EXPIRED; - uint32_t system_code = 42; - EXPECT_CALL(*parent_delegate_, - OnKeyStatusChanged(key, key_status, system_code)); - node_as_delegate->OnKeyStatusChanged(key, key_status, system_code); - testing::Mock::VerifyAndClearExpectations(parent_delegate_.get()); - - // OnVideoResolutionChanged. - Size size(12, 27); - EXPECT_CALL(*parent_delegate_, OnVideoResolutionChanged(testing::_)); - node_as_delegate->OnVideoResolutionChanged(size); - testing::Mock::VerifyAndClearExpectations(parent_delegate_.get()); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/buffer_id_manager.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/buffer_id_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,188 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/buffer_id_manager.h" - -#include -#include - -#include "base/functional/callback.h" -#include "base/rand_util.h" -#include "base/time/time.h" -#include "chromecast/media/api/monotonic_clock.h" -#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { -namespace { - -// Mask to apply to a uint64_t to get a BufferId. -constexpr uint64_t kBufferIdMask = (uint64_t{1} << 63) - 1; - -// A "large" time difference is a difference in audio synchronization which may -// be perceived by the human ear. -constexpr int64_t kLargeTimeDifference = - base::Time::kMicrosecondsPerMillisecond; - -// Calculates whether the difference between two microsecond-based timestamps is -// large. -bool IsLargeTimeDifference(int64_t timestamp1, int64_t timestamp2) { - return std::abs(timestamp1 - timestamp2) >= kLargeTimeDifference; -} - -} // namespace - -BufferIdManager::BufferIdQueue::BufferIdQueue() { - next_id_ = 0; -} - -BufferIdManager::BufferId BufferIdManager::BufferIdQueue::Front() const { - return static_cast(next_id_ & kBufferIdMask); -} - -BufferIdManager::BufferId BufferIdManager::BufferIdQueue::Pop() { - BufferIdManager::BufferId id = Front(); - next_id_++; - return id; -} - -BufferIdManager::BufferInfo::BufferInfo(BufferId buffer_id, int64_t pts) - : id(buffer_id), pts_timestamp_micros(pts) {} - -BufferIdManager::Client::~Client() = default; - -BufferIdManager::BufferIdManager(CmaBackend::AudioDecoder* audio_decoder, - Client* client, - std::unique_ptr clock) - : clock_(std::move(clock)), - client_(client), - audio_decoder_(audio_decoder), - weak_factory_(this) { - DCHECK(clock_); - DCHECK(client_); - DCHECK(audio_decoder_); -} - -BufferIdManager::BufferIdManager(CmaBackend::AudioDecoder* audio_decoder, - Client* client) - : BufferIdManager(audio_decoder, client, MonotonicClock::Create()) {} - -BufferIdManager::~BufferIdManager() = default; - -BufferIdManager::TargetBufferInfo -BufferIdManager::GetCurrentlyProcessingBufferInfo() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - // If no data has finished playing, just return the next ID to play. - if (!most_recently_played_buffer_.has_value()) { - BufferId id = buffer_infos_.empty() ? buffer_id_queue_.Front() - : buffer_infos_.front().id; - return TargetBufferInfo{id, clock_->Now()}; - } - - // Else, return the most recently played buffer. - return TargetBufferInfo{ - most_recently_played_buffer_.value().id, - most_recently_played_buffer_.value().expected_playout_timestamp_micros}; -} - -BufferIdManager::BufferId BufferIdManager::AssignBufferId( - const CastDecoderBuffer& buffer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - UpdateAndGetCurrentlyProcessingBufferInfo(); - int64_t additional_playback_time = 0; - if (!buffer_infos_.empty()) { - additional_playback_time = - buffer.timestamp() - buffer_infos_.back().pts_timestamp_micros; - } else if (most_recently_played_buffer_.has_value()) { - additional_playback_time = - buffer.timestamp() - - most_recently_played_buffer_.value().pts_timestamp_micros; - } - - buffer_infos_.emplace(buffer_id_queue_.Front(), buffer.timestamp()); - pending_playback_time_in_microseconds_ += additional_playback_time; - return buffer_id_queue_.Pop(); -} - -BufferIdManager::TargetBufferInfo -BufferIdManager::UpdateAndGetCurrentlyProcessingBufferInfo() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - const auto rendering_delay = audio_decoder_->GetRenderingDelay(); - - // Special case meaning that the Rendering Delay is unavailable. - if (rendering_delay.timestamp_microseconds == - std::numeric_limits::min()) { - return GetCurrentlyProcessingBufferInfo(); - } - - // Pop buffer infos from the queue until only not-yet-played-out frames - // remain. - const int64_t delay_timestamp = rendering_delay.timestamp_microseconds; - const int64_t delay_in_microseconds = rendering_delay.delay_microseconds; - DCHECK_GE(delay_in_microseconds, 0); - - // When no buffers have played out yet, store the currently playing buffer's - // info. - if (!most_recently_played_buffer_.has_value() && !buffer_infos_.empty()) { - // Use a large expected playout time to guarantee an OnTimestampUpdateNeeded - // call occurs. - most_recently_played_buffer_ = BufferPlayoutInfo{ - buffer_infos_.front().id, buffer_infos_.front().pts_timestamp_micros, - std::numeric_limits::max()}; - } - - for (; delay_in_microseconds <= pending_playback_time_in_microseconds_ && - !buffer_infos_.empty(); - buffer_infos_.pop()) { - const BufferInfo& queue_front = buffer_infos_.front(); - DCHECK_GE(queue_front.id, 0); - DCHECK_GE(queue_front.pts_timestamp_micros, 0); - - // Update |pending_playback_time_in_microseconds_|. - BufferPlayoutInfo& most_recently_played_buffer = - most_recently_played_buffer_.value(); - DCHECK_GE(most_recently_played_buffer.id, 0); - DCHECK_GE(most_recently_played_buffer.pts_timestamp_micros, 0); - DCHECK_GE(most_recently_played_buffer.expected_playout_timestamp_micros, 0); - - int64_t change_in_playback_time = - queue_front.pts_timestamp_micros - - most_recently_played_buffer.pts_timestamp_micros; - DCHECK_GE(change_in_playback_time, 0); - pending_playback_time_in_microseconds_ -= change_in_playback_time; - - // Update |most_recently_played_buffer_|. - most_recently_played_buffer.id = queue_front.id; - most_recently_played_buffer.pts_timestamp_micros = - queue_front.pts_timestamp_micros; - most_recently_played_buffer.expected_playout_timestamp_micros += - change_in_playback_time; - } - - // Check if the currently playing buffer has a playback time different from - // what is expected, and update the client if the difference is too large. - const int64_t last_playout_timestamp = delay_timestamp + - delay_in_microseconds - - pending_playback_time_in_microseconds_; - if (most_recently_played_buffer_.has_value() && - IsLargeTimeDifference(most_recently_played_buffer_.value() - .expected_playout_timestamp_micros, - last_playout_timestamp)) { - most_recently_played_buffer_.value().expected_playout_timestamp_micros = - last_playout_timestamp; - client_->OnTimestampUpdateNeeded( - {most_recently_played_buffer_.value().id, last_playout_timestamp}); - } - - return GetCurrentlyProcessingBufferInfo(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/buffer_id_manager.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/buffer_id_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,174 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_BUFFER_ID_MANAGER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_BUFFER_ID_MANAGER_H_ - -#include -#include -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h" - -namespace chromecast { -namespace media { - -class CastDecoderBuffer; -class MonotonicClock; - -// This class is responsible for assigning the IDs for PushBuffer commands sent -// over the CastRuntimeAudioChannel. Each PushBuffer command is expected to have -// an increasing BufferId (with the exception of wrap-around of large integers), -// to be used for audio synchronization between playback in the runtime and any -// further processing or work done on the other side of the -// MultizoneAudioDecoderProxy gRPC Channel. -// -// This class does NOT attempt to track the association between a given -// PushBuffer and its ID. Instead, it tracks the playback timestamp (PTS) -// associated with each frame. By determining the change between the PTS for any -// two adjacent frames, this class can keep a running tally of the total -// playback time that has been pushed to the underlying AudioDecoder's queue. -// Then the playing buffer ID can then be approximated by using the -// GetRenderingDelay() function provided by CmaBackend::AudioDecoder, which -// gives the total amount of time of playback data currently pending in the -// AudioDecoder's internal queue. -// -// Additionally, if the underlying decoder has a "large" change in rendering -// delay (meaning one that may be perceptible to the human ear) with respect to -// what is expected based on the above calculations, the client provided to the -// instance upon creation is used to inform the caller of this change. -class BufferIdManager { - public: - using BufferId = int64_t; - - // Timing information about a buffer to be targeted for playback changes. - struct TargetBufferInfo { - // The ID associated with the target buffer. - BufferId buffer_id = 0; - - // The wall time in microseconds at which the target buffer is expected to - // play, as returned by MonotonicClock::Now(). - int64_t timestamp_micros = 0; - }; - - // Observer responsible for informing the caller when unexpected buffer - // related events occur. - class Client { - public: - // Called when a timestamp update is needed, based on the processing rate of - // buffered data. - // NOTE: Pass-by-value is used here to save a copy through copy-elision. - virtual void OnTimestampUpdateNeeded(TargetBufferInfo buffer) = 0; - - protected: - virtual ~Client(); - }; - - // |audio_decoder| and |client| are expected to remain valid for the lifetime - // of this instance. - BufferIdManager(CmaBackend::AudioDecoder* audio_decoder, Client* client); - BufferIdManager(const BufferIdManager& other) = delete; - BufferIdManager(BufferIdManager&& other) = delete; - - ~BufferIdManager(); - - BufferIdManager& operator=(const BufferIdManager& other) = delete; - BufferIdManager& operator=(BufferIdManager&& other) = delete; - - // Assigns the BufferId to use with the buffer for which it is called. This - // value is used to keep a running tally of the expected pts at which a given - // buffer will play, compared to when it is rendered. - BufferId AssignBufferId(const CastDecoderBuffer& buffer); - - // Returns TargetBufferInfo associated with the APPROXIMATE BufferId - // being rendered by the underlying CmaBackend at this time. Note that, - // although this is not exact, the human ear cannot perceive variation on - // the level introduced by this slight mismatch. - TargetBufferInfo GetCurrentlyProcessingBufferInfo() const; - - // Uses the provided AudioDecoder to calculate approximately how many buffers - // are remaining in the PushBuffer queue, removes all buffers expected to - // have already played out. This ensures that |buffer_infos_| size does not - // grow in an unbounded fashion. Returns TargetBufferInfo associated with the - // APPROXIMATE BufferId being rendered by the underlying CmaBackend at this - // time, as above. - TargetBufferInfo UpdateAndGetCurrentlyProcessingBufferInfo(); - - private: - friend class BufferIdManagerTest; - - // A wrapper around the buffer ID that acts for users like a queue. - class BufferIdQueue { - public: - BufferIdQueue(); - - BufferIdManager::BufferId Front() const; - BufferIdManager::BufferId Pop(); - - private: - // The next id to use, initialized to a random number upon creation. - // NOTE: A uint64_t is used rather than an int64_t to allow for buffer - // overflow and wrap-around-to-zero without crashing the runtime. - uint64_t next_id_; - }; - - // The information stored about each buffer upon an AssignBufferId() call. - struct BufferInfo { - // NOTE: Ctor added to support vector::emplace calls. - BufferInfo(BufferId buffer_id, int64_t pts); - - // The ID of the current buffer. - BufferId id = -1; - - // The PTS of the associated PushBuffer's data in microseconds, as defined - // in DecoderBufferBase. - int64_t pts_timestamp_micros = -1; - }; - - // The union of all information from both TargetBufferInfo and BufferInfo. - // Used only to allow for more readable code when storing information about - // the most recently played buffer. - struct BufferPlayoutInfo { - // The ID associated with the target buffer. - BufferId id = -1; - - // The PTS of the associated PushBuffer's data in microseconds, as defined - // in DecoderBufferBase. - int64_t pts_timestamp_micros = -1; - - // The wall time in microseconds at which the target buffer is EXPECTED to - // play, as understood by callers of this object's public methods. - int64_t expected_playout_timestamp_micros = -1; - }; - - // To be used for testing. - BufferIdManager(CmaBackend::AudioDecoder* audio_decoder, - Client* client, - std::unique_ptr clock); - - // The total playback time of all buffers currently in |buffer_infos|. - int64_t pending_playback_time_in_microseconds_ = 0; - - // Information about the most recently played buffer. - mutable std::optional most_recently_played_buffer_; - - BufferIdQueue buffer_id_queue_; - std::queue buffer_infos_; - std::unique_ptr clock_; - - Client* const client_; - CmaBackend::AudioDecoder* const audio_decoder_; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_BUFFER_ID_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/buffer_id_manager_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/buffer_id_manager_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/buffer_id_manager_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,258 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/buffer_id_manager.h" - -#include - -#include "base/memory/ptr_util.h" -#include "base/memory/scoped_refptr.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/monotonic_clock.h" -#include "chromecast/media/api/test/mock_cma_backend.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using testing::_; -using testing::Mock; -using testing::Return; - -ACTION_P(CompareBufferInfos, expected) { - const BufferIdManager::TargetBufferInfo& actual = arg0; - EXPECT_EQ(actual.buffer_id, expected.buffer_id); - EXPECT_EQ(actual.timestamp_micros, expected.timestamp_micros); -} - -class MockClock : public MonotonicClock { - public: - ~MockClock() override = default; - - MOCK_CONST_METHOD0(Now, int64_t()); -}; - -class MockBufferIdManagerClient : public BufferIdManager::Client { - public: - MOCK_METHOD1(OnTimestampUpdateNeeded, - void(BufferIdManager::TargetBufferInfo)); -}; - -} // namespace - -class BufferIdManagerTest : public testing::Test { - public: - BufferIdManagerTest() { - default_config_.bytes_per_channel = 100; - default_config_.channel_number = 20; - default_config_.samples_per_second = 5000; - - auto clock = std::make_unique>(); - clock_ = clock.get(); - id_manager_ = base::WrapUnique( - new BufferIdManager(&audio_decoder_, &client_, std::move(clock))); - } - ~BufferIdManagerTest() override = default; - - protected: - BufferIdManager::BufferId AssignBufferId(int64_t rendering_delay, - int64_t timestamp, - int64_t pts) { - EXPECT_CALL(audio_decoder_, GetRenderingDelay()) - .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( - rendering_delay, timestamp))); - auto buffer = base::MakeRefCounted(1); - buffer->set_timestamp(base::Microseconds(pts)); - auto result = id_manager_->AssignBufferId(*buffer); - Mock::VerifyAndClearExpectations(&audio_decoder_); - return result; - } - - BufferIdManager::TargetBufferInfo GetCurrentlyProcessingBufferInfo( - int64_t rendering_delay, - int64_t timestamp, - BufferIdManager::BufferId target_buffer) { - auto buffer_info = id_manager_->GetCurrentlyProcessingBufferInfo(); - EXPECT_EQ(buffer_info.buffer_id, target_buffer); - EXPECT_EQ(buffer_info.timestamp_micros, timestamp); - Mock::VerifyAndClearExpectations(&audio_decoder_); - return buffer_info; - } - - testing::StrictMock audio_decoder_; - testing::StrictMock client_; - MockClock* clock_; - std::unique_ptr id_manager_; - - AudioConfig default_config_; -}; - -TEST_F(BufferIdManagerTest, TestDelayedFrames) { - // Push 3 new buffers. - EXPECT_CALL(*clock_, Now()).Times(3).WillRepeatedly(Return(0)); - BufferIdManager::BufferId i = - AssignBufferId(0, std::numeric_limits::min(), 30); - ASSERT_GE(i, 0); - - BufferIdManager::BufferId j = - AssignBufferId(0, std::numeric_limits::min(), 70); - EXPECT_EQ(i + 1, j); - - BufferIdManager::BufferId k = - AssignBufferId(0, std::numeric_limits::min(), 120); - EXPECT_EQ(j + 1, k); - Mock::VerifyAndClearExpectations(clock_); - - // Call UpdateAndGetCurrentlyProcessingBufferInfo() pulling no buffers off the - // queue. - EXPECT_CALL(*clock_, Now()).WillOnce(Return(0)); - GetCurrentlyProcessingBufferInfo(100, 0, i); - Mock::VerifyAndClearExpectations(clock_); - - int64_t rendering_delay = 100; - int64_t renderer_timestamp = 0; - int64_t returned_timestamp = 10; - - EXPECT_CALL(client_, OnTimestampUpdateNeeded(_)) - .WillOnce(testing::WithArgs<0>(CompareBufferInfos( - BufferIdManager::TargetBufferInfo{i, returned_timestamp}))); - EXPECT_CALL(audio_decoder_, GetRenderingDelay()) - .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( - rendering_delay, renderer_timestamp))); - auto buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); - EXPECT_EQ(buffer_info.buffer_id, i); - EXPECT_EQ(buffer_info.timestamp_micros, returned_timestamp); - Mock::VerifyAndClearExpectations(&audio_decoder_); - Mock::VerifyAndClearExpectations(&client_); - - // No buffers should be pulled off when calling - // GetCurrentlyProcessingBufferInfo() regardless of timestamp change. - rendering_delay = 80; - GetCurrentlyProcessingBufferInfo(rendering_delay, returned_timestamp, i); - Mock::VerifyAndClearExpectations(clock_); - - // Pull the first buffer off the queue, and expect no callback because there's - // been no rendering clock changes. - renderer_timestamp = 20; - returned_timestamp = 50; - - EXPECT_CALL(audio_decoder_, GetRenderingDelay()) - .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( - rendering_delay, renderer_timestamp))); - buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); - EXPECT_EQ(buffer_info.buffer_id, j); - EXPECT_EQ(buffer_info.timestamp_micros, returned_timestamp); - Mock::VerifyAndClearExpectations(&audio_decoder_); - - // Pull the last buffer off the queue - rendering_delay = 30; - GetCurrentlyProcessingBufferInfo(rendering_delay, returned_timestamp, j); - - renderer_timestamp = 70; - returned_timestamp = 100; - EXPECT_CALL(audio_decoder_, GetRenderingDelay()) - .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( - rendering_delay, renderer_timestamp))); - buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); - EXPECT_EQ(buffer_info.buffer_id, k); - EXPECT_EQ(buffer_info.timestamp_micros, returned_timestamp); - Mock::VerifyAndClearExpectations(&audio_decoder_); - - // When no buffer is remaining in the queue, return the id of the last - // processed. - rendering_delay = 0; - GetCurrentlyProcessingBufferInfo(rendering_delay, returned_timestamp, k); - - renderer_timestamp = 100; - returned_timestamp = 100; - EXPECT_CALL(audio_decoder_, GetRenderingDelay()) - .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( - rendering_delay, renderer_timestamp))); - buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); - EXPECT_EQ(buffer_info.buffer_id, k); - EXPECT_EQ(buffer_info.timestamp_micros, returned_timestamp); -} - -TEST_F(BufferIdManagerTest, TestUpdateTimestamp) { - auto buffer = base::MakeRefCounted(1); - - // Push a new buffer. - int64_t rendering_delay = 0; - int64_t pts = 0; - EXPECT_CALL(*clock_, Now()).WillOnce(Return(0)); - BufferIdManager::BufferId i = - AssignBufferId(0, std::numeric_limits::min(), pts); - EXPECT_GE(i, 0); - Mock::VerifyAndClearExpectations(clock_); - - // Push a second buffer, with the first one still pending. - rendering_delay = 5; - int64_t renderer_timestamp = 20; - pts = 10; - EXPECT_CALL(client_, OnTimestampUpdateNeeded(_)).Times(1); - AssignBufferId(rendering_delay, renderer_timestamp, pts); - Mock::VerifyAndClearExpectations(&client_); - - // When only 5 microseconds left in the queue, the first pushed buffer is - // removed. - rendering_delay = 15; - renderer_timestamp = 30; - pts = 20; - AssignBufferId(rendering_delay, renderer_timestamp, pts); - Mock::VerifyAndClearExpectations(&client_); - - // When a big change is detected, a client callback is sent. With only one - // element in the queue, the rendering delay retrieved from the underlying - // renderer is treated as exact. - rendering_delay = 5; - renderer_timestamp = 30000; - pts = 40; - EXPECT_CALL(client_, OnTimestampUpdateNeeded(_)) - .WillOnce(testing::WithArgs<0>( - CompareBufferInfos(BufferIdManager::TargetBufferInfo{ - i + 2, renderer_timestamp + rendering_delay}))); - AssignBufferId(rendering_delay, renderer_timestamp, pts); - Mock::VerifyAndClearExpectations(&client_); - - // Push more buffers with none falling off the queue. No client callback - // should be sent. - rendering_delay = 15; - renderer_timestamp += 1; - pts += 10; - AssignBufferId(rendering_delay, renderer_timestamp, pts); - - rendering_delay = 25; - renderer_timestamp += 1; - pts += 10; - AssignBufferId(rendering_delay, renderer_timestamp, pts); - - rendering_delay = 35; - renderer_timestamp += 1; - pts += 10; - auto last_buffer_id = - AssignBufferId(rendering_delay, renderer_timestamp, pts); - - // During the next iteration, if multiple buffers are removed from the queue - // when a timestamp update is needed, only update for the last one. - rendering_delay = 5; - renderer_timestamp = 1500000; - EXPECT_CALL(client_, OnTimestampUpdateNeeded(_)) - .WillOnce(testing::WithArgs<0>( - CompareBufferInfos(BufferIdManager::TargetBufferInfo{ - last_buffer_id, renderer_timestamp + rendering_delay}))); - EXPECT_CALL(audio_decoder_, GetRenderingDelay()) - .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( - rendering_delay, renderer_timestamp))); - auto buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); - EXPECT_EQ(buffer_info.buffer_id, last_buffer_id); - EXPECT_EQ(buffer_info.timestamp_micros, renderer_timestamp + rendering_delay); - Mock::VerifyAndClearExpectations(&audio_decoder_); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h" - -namespace chromecast { -namespace media { - -CastRuntimeAudioChannelBroker::~CastRuntimeAudioChannelBroker() = default; - -CastRuntimeAudioChannelBroker::Handler::~Handler() = default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,134 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CAST_RUNTIME_AUDIO_CHANNEL_BROKER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CAST_RUNTIME_AUDIO_CHANNEL_BROKER_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "third_party/cast_core/public/src/proto/runtime/cast_audio_channel_service.pb.h" -#include "third_party/protobuf/src/google/protobuf/duration.pb.h" - -namespace chromecast { - -class TaskRunner; - -namespace media { -// Exposes the CastAudioDecoderChannel RPC client with a callback-based API. -// -// This class defines a thin abstraction on top of direct gRPC calls, with the -// intention of avoiding any dependency at higher layers on a specific gRPC -// implementation (e.g. gRPC Manager, vanilla gRPC< etc). Objects, enums, and -// values defined in |cast_audio_decoder_service.proto| will be exposed to -// layers above this class, but the specifics of any gRPC Implementation will -// not. -// -// NOTE: Implementations of this interface make NO assumptions either about the -// thread on which calls are made OR on which callbacks in |Handler| are called. -// Any such requirements must be enforced at higher layers. -class CastRuntimeAudioChannelBroker { - public: - using CastAudioDecoderMode = cast::media::CastAudioDecoderMode; - using TimestampInfo = cast::media::TimestampInfo; - - // The valid response types for a gRPC Call. - enum class StatusCode { - kOk = 0, - kCancelled = 1, - kUnknown = 2, - kInvalidArgument = 3, - kDeadlineExceeded = 4, - kNotFound = 5, - kAlreadyExists = 6, - kPermissionDenied = 7, - kUnauthenticated = 16, - kResourceExhausted = 8, - kFailedPrecondition = 9, - kAborted = 10, - kOutOfRange = 11, - kUnimplemented = 12, - kInternal = 13, - kUnavailable = 14, - kDataLoss = 15, - kDoNotUse = -1, - }; - - // Callbacks associated with RPC communication done by gRPC. - // - // The thread on which these callbacks are called is intentionally unspecified - // by this interface. It is the responsibility of the caller to "jump" to - // specific threads as required. - class Handler { - public: - using MediaTime = cast::media::MediaTime; - using PipelineState = cast::media::PipelineState; - using PushBufferRequest = cast::media::PushBufferRequest; - - virtual ~Handler(); - - // Returns a PushBufferRequest to be sent across the |PushBuffer| RPC. May - // only be called if |HasBufferedData()| is true. - virtual std::optional GetBufferedData() = 0; - virtual bool HasBufferedData() = 0; - - // Handlers for the responses of the messages defined in - // cast_audio_decoder_service.proto. - // - // Called when a |Initialize| RPC call completes. In the case of a - // successful call, |status| will be kOK. - virtual void HandleInitializeResponse(StatusCode status) = 0; - - // Called when a |GetMediaTime| RPC call completes. If |status| is kOK, then - // |state| is the current pipeline state. Else, the call failed and |state| - // is undefined. - virtual void HandleStateChangeResponse(PipelineState state, - StatusCode status) = 0; - - // Called when a |SetVolume| RPC call completes. In the case of a - // successful call, |status| will be kOK. - virtual void HandleSetVolumeResponse(StatusCode status) = 0; - - // Called when a |SetPlayback| RPC call completes. In the case of a - // successful call, |status| will be kOK. - virtual void HandleSetPlaybackResponse(StatusCode status) = 0; - - // Called when a |PushBuffer| RPC call completes. If |status| is kOK, then - // |decoded_bytes| is the number of bytes which have been decoded so far. - // Else, the RPC call failed and |decoded_byes| is undefined. - virtual void HandlePushBufferResponse(int64_t decoded_bytes, - StatusCode status) = 0; - - // Called when a |GetMediaTime| RPC call completes. If |status| is kOK, then - // |time| is a valid non-empty MediaTime object. Else, |time| may be empty. - virtual void HandleGetMediaTimeResponse(std::optional time, - StatusCode status) = 0; - }; - - static std::unique_ptr Create( - TaskRunner* task_runner, - Handler* handler); - - virtual ~CastRuntimeAudioChannelBroker(); - - // Calls into the underlying RPC. - virtual void InitializeAsync(const std::string& cast_session_id, - CastAudioDecoderMode decoder_mode) = 0; - virtual void SetVolumeAsync(float multiplier) = 0; - virtual void SetPlaybackAsync(double playback_rate) = 0; - virtual void GetMediaTimeAsync() = 0; - - // Calls to StateChangeRequest RPC. - virtual void StartAsync(int64_t pts_micros, TimestampInfo timestamp_info) = 0; - virtual void StopAsync() = 0; - virtual void PauseAsync() = 0; - virtual void ResumeAsync(TimestampInfo timestamp_info) = 0; - virtual void UpdateTimestampAsync(TimestampInfo timestamp_info) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CAST_RUNTIME_AUDIO_CHANNEL_BROKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_manager.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_manager.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CAST_RUNTIME_AUDIO_CHANNEL_ENDPOINT_MANAGER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CAST_RUNTIME_AUDIO_CHANNEL_ENDPOINT_MANAGER_H_ - -#include - -namespace chromecast { -namespace media { - -// Provides a global accessor for the endpoint to which the -// CastMediaAudioChannel should connect. -class CastRuntimeAudioChannelEndpointManager { - public: - // Returns the singleton instance of this class. - static CastRuntimeAudioChannelEndpointManager* Get(); - - // Returns the endpoint as described above. - virtual const std::string& GetAudioChannelEndpoint() = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CAST_RUNTIME_AUDIO_CHANNEL_ENDPOINT_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_simple.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_simple.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_simple.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_simple.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_endpoint_manager.h" - -#include "base/notreached.h" - -namespace chromecast { -namespace media { - -// static -CastRuntimeAudioChannelEndpointManager* -CastRuntimeAudioChannelEndpointManager::Get() { - NOTIMPLEMENTED(); - return nullptr; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cma_backend_proxy.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cma_backend_proxy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,156 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/cma_backend_proxy.h" - -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/notreached.h" -#include "chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.h" -#include "chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { - -CmaBackendProxy::CmaBackendProxy(const MediaPipelineDeviceParams& params, - std::unique_ptr delegated_pipeline) - : CmaBackendProxy(base::BindOnce(&CmaBackendProxy::CreateAudioDecoderProxy, - base::Unretained(this), - params), - std::move(delegated_pipeline)) {} - -CmaBackendProxy::CmaBackendProxy( - CmaBackendProxy::AudioDecoderFactoryCB audio_decoder_factory, - std::unique_ptr delegated_pipeline) - : delegated_pipeline_(std::move(delegated_pipeline)), - audio_decoder_factory_(std::move(audio_decoder_factory)) { - DCHECK(delegated_pipeline_); - DCHECK(audio_decoder_factory_); -} - -CmaBackendProxy::~CmaBackendProxy() = default; - -CmaBackend::AudioDecoder* CmaBackendProxy::CreateAudioDecoder() { - DCHECK(!audio_decoder_); - DCHECK(audio_decoder_factory_); - audio_decoder_ = std::move(audio_decoder_factory_).Run(); - return audio_decoder_.get(); -} - -CmaBackend::VideoDecoder* CmaBackendProxy::CreateVideoDecoder() { - has_video_decoder_ = true; - return delegated_pipeline_->CreateVideoDecoder(); -} - -bool CmaBackendProxy::Initialize() { - if (audio_decoder_) { - audio_decoder_->Initialize(); - } - - if (audio_decoder_ || has_video_decoder_) { - return delegated_pipeline_->Initialize(); - } else { - return true; - } -} - -bool CmaBackendProxy::Start(int64_t start_pts) { - if (audio_decoder_) { - audio_decoder_->Start(start_pts); - } - - if (audio_decoder_ || has_video_decoder_) { - return delegated_pipeline_->Start(start_pts); - } else { - return true; - } -} - -void CmaBackendProxy::Stop() { - if (has_video_decoder_ || audio_decoder_) { - delegated_pipeline_->Stop(); - } - - if (audio_decoder_) { - audio_decoder_->Stop(); - } -} - -bool CmaBackendProxy::Pause() { - if (audio_decoder_) { - audio_decoder_->Pause(); - } - - if (audio_decoder_ || has_video_decoder_) { - return delegated_pipeline_->Pause(); - } else { - return true; - } -} - -bool CmaBackendProxy::Resume() { - if (audio_decoder_) { - audio_decoder_->Resume(); - } - - if (audio_decoder_ || has_video_decoder_) { - return delegated_pipeline_->Resume(); - } else { - return true; - } -} - -int64_t CmaBackendProxy::GetCurrentPts() { - return delegated_pipeline_->GetCurrentPts(); -} - -bool CmaBackendProxy::SetPlaybackRate(float rate) { - if (audio_decoder_) { - audio_decoder_->SetPlaybackRate(rate); - } - - if (audio_decoder_ || has_video_decoder_) { - return delegated_pipeline_->SetPlaybackRate(rate); - } else { - return true; - } -} - -void CmaBackendProxy::LogicalPause() { - if (has_video_decoder_ || audio_decoder_) { - delegated_pipeline_->LogicalPause(); - } - - if (audio_decoder_) { - audio_decoder_->LogicalPause(); - } -} - -void CmaBackendProxy::LogicalResume() { - if (has_video_decoder_ || audio_decoder_) { - delegated_pipeline_->LogicalResume(); - } - - if (audio_decoder_) { - audio_decoder_->LogicalResume(); - } -} - -std::unique_ptr -CmaBackendProxy::CreateAudioDecoderProxy( - const MediaPipelineDeviceParams& params) { - CmaBackend::AudioDecoder* downstream_decoder = - delegated_pipeline_->CreateAudioDecoder(); - auto buffer_extension = std::make_unique( - params.task_runner, downstream_decoder); - return std::make_unique( - params, std::move(buffer_extension)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cma_backend_proxy.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cma_backend_proxy.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_BACKEND_PROXY_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_BACKEND_PROXY_H_ - -#include - -#include - -#include "base/functional/callback.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy.h" - -namespace chromecast { -namespace media { - -struct MediaPipelineDeviceParams; - -// This class is used to intercept audio data and control messages being sent to -// the local CmaBackend and forward it to a remote instance prior to local -// processing in the underlying CmaBackend. -// -// NOTE: By design, this class does NOT handle a/v sync drift between -// |audio_decoder_| and |delegated_pipeline_|. -class CmaBackendProxy : public CmaBackend { - public: - using AudioDecoderFactoryCB = - base::OnceCallback()>; - - // Creates a new CmaBackendProxy such that all video processing is delegated - // to |delegated_video_pipeline|. - CmaBackendProxy(const MediaPipelineDeviceParams& params, - std::unique_ptr delegated_video_pipeline); - - CmaBackendProxy(const CmaBackendProxy&) = delete; - CmaBackendProxy& operator=(const CmaBackendProxy&) = delete; - - ~CmaBackendProxy() override; - - // MediaPipelineBackend implementation: - // - // NOTE: Each of these calls must forward the call both to the gRPC Pipe (if - // the audio decoder exists) and to the local audio decoder (if either audio - // or video decoding is occuring). - CmaBackend::AudioDecoder* CreateAudioDecoder() override; - CmaBackend::VideoDecoder* CreateVideoDecoder() override; - bool Initialize() override; - bool Start(int64_t start_pts) override; - void Stop() override; - bool Pause() override; - bool Resume() override; - int64_t GetCurrentPts() override; - bool SetPlaybackRate(float rate) override; - void LogicalPause() override; - void LogicalResume() override; - - private: - friend class CmaBackendProxyTest; - - // Creates a new CmaBackendProxy such that all video processing is delegated - // to |delegated_pipeline| and all audio processing is delegated to a - // new MultizoneAudioDecoderProxy created by |audio_decoder_factory|. - CmaBackendProxy(AudioDecoderFactoryCB audio_decoder_factory, - std::unique_ptr delegated_pipeline); - - // Helper to create the AudioDecoder instance, used with base::bind. - std::unique_ptr CreateAudioDecoderProxy( - const MediaPipelineDeviceParams& params); - - // The audio decoder to which audio operations should be delegated. - std::unique_ptr audio_decoder_; - - // The CMA Backend to which all video decoding is delegated. - std::unique_ptr delegated_pipeline_; - - // Determines whether a video decoder is being used. If not, calls should not - // be delegated to the |delegated_pipeline_|, as it may not behave as - // expected when neither the audio or video decoders are initialized. - bool has_video_decoder_ = false; - - // The factory to use to populate the |audio_decoder_| object when needed. - AudioDecoderFactoryCB audio_decoder_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_BACKEND_PROXY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cma_backend_proxy_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cma_backend_proxy_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_backend_proxy_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,239 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/cma_backend_proxy.h" - -#include "base/functional/bind.h" -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/api/test/mock_cma_backend.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::Return; -using testing::StrictMock; - -namespace chromecast { -namespace media { -namespace { - -class MockMultizoneAudioDecoderProxy : public MultizoneAudioDecoderProxy { - public: - MockMultizoneAudioDecoderProxy() - : MultizoneAudioDecoderProxy(&audio_decoder_) {} - ~MockMultizoneAudioDecoderProxy() override = default; - - MOCK_METHOD0(Initialize, void()); - MOCK_METHOD1(Start, void(int64_t)); - MOCK_METHOD0(Stop, void()); - MOCK_METHOD0(Pause, void()); - MOCK_METHOD0(Resume, void()); - MOCK_CONST_METHOD0(GetCurrentPts, int64_t()); - MOCK_METHOD1(SetPlaybackRate, void(float rate)); - MOCK_METHOD0(LogicalPause, void()); - MOCK_METHOD0(LogicalResume, void()); - MOCK_METHOD1(SetDelegate, void(Delegate*)); - MOCK_METHOD1(PushBuffer, BufferStatus(scoped_refptr)); - MOCK_METHOD1(SetConfig, bool(const AudioConfig&)); - MOCK_METHOD1(SetVolume, bool(float)); - MOCK_METHOD0(GetRenderingDelay, RenderingDelay()); - MOCK_METHOD1(GetStatistics, void(Statistics*)); - MOCK_METHOD0(RequiresDecryption, bool()); - - private: - // Used only for the ctor parameter. - MockCmaBackend::AudioDecoder audio_decoder_; -}; - -} // namespace - -class CmaBackendProxyTest : public testing::Test { - public: - CmaBackendProxyTest() { - auto delegated_video_backend = - std::make_unique>(); - auto audio_decoder = - std::make_unique>(); - - delegated_backend_ = delegated_video_backend.get(); - audio_decoder_ = audio_decoder.get(); - - CmaBackendProxy::AudioDecoderFactoryCB factory = base::BindOnce( - [](std::unique_ptr ptr) { return ptr; }, - std::move(audio_decoder)); - CmaBackendProxy* proxy = new CmaBackendProxy( - std::move(factory), std::move(delegated_video_backend)); - backend_.reset(proxy); - } - - protected: - void CreateVideoDecoder() { - EXPECT_CALL(*delegated_backend_, CreateVideoDecoder()).Times(1); - backend_->CreateVideoDecoder(); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - } - - std::unique_ptr backend_; - MockCmaBackend* delegated_backend_; - MockMultizoneAudioDecoderProxy* audio_decoder_; -}; - -TEST_F(CmaBackendProxyTest, Initialize) { - EXPECT_TRUE(backend_->Initialize()); - - CreateVideoDecoder(); - - EXPECT_CALL(*delegated_backend_, Initialize()) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - EXPECT_TRUE(backend_->Initialize()); - EXPECT_FALSE(backend_->Initialize()); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - - ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); - EXPECT_CALL(*audio_decoder_, Initialize()).Times(2); - EXPECT_CALL(*delegated_backend_, Initialize()) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - - EXPECT_TRUE(backend_->Initialize()); - EXPECT_FALSE(backend_->Initialize()); -} - -TEST_F(CmaBackendProxyTest, Start) { - constexpr float kStartPts = 42; - EXPECT_TRUE(backend_->Start(kStartPts)); - - CreateVideoDecoder(); - - EXPECT_CALL(*delegated_backend_, Start(kStartPts)) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - EXPECT_TRUE(backend_->Start(kStartPts)); - EXPECT_FALSE(backend_->Start(kStartPts)); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - - ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); - EXPECT_CALL(*audio_decoder_, Start(kStartPts)).Times(2); - EXPECT_CALL(*delegated_backend_, Start(kStartPts)) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - - EXPECT_TRUE(backend_->Start(kStartPts)); - EXPECT_FALSE(backend_->Start(kStartPts)); -} - -TEST_F(CmaBackendProxyTest, Stop) { - backend_->Stop(); - - CreateVideoDecoder(); - - EXPECT_CALL(*delegated_backend_, Stop()); - backend_->Stop(); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - - ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); - EXPECT_CALL(*audio_decoder_, Stop()); - EXPECT_CALL(*delegated_backend_, Stop()); - backend_->Stop(); -} - -TEST_F(CmaBackendProxyTest, Pause) { - EXPECT_TRUE(backend_->Pause()); - - CreateVideoDecoder(); - - EXPECT_CALL(*delegated_backend_, Pause()) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - EXPECT_TRUE(backend_->Pause()); - EXPECT_FALSE(backend_->Pause()); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - - ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); - EXPECT_CALL(*audio_decoder_, Pause()).Times(2); - EXPECT_CALL(*delegated_backend_, Pause()) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - - EXPECT_TRUE(backend_->Pause()); - EXPECT_FALSE(backend_->Pause()); -} - -TEST_F(CmaBackendProxyTest, Resume) { - EXPECT_TRUE(backend_->Resume()); - - CreateVideoDecoder(); - - EXPECT_CALL(*delegated_backend_, Resume()) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - EXPECT_TRUE(backend_->Resume()); - EXPECT_FALSE(backend_->Resume()); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - - ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); - EXPECT_CALL(*audio_decoder_, Resume()).Times(2); - EXPECT_CALL(*delegated_backend_, Resume()) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - - EXPECT_TRUE(backend_->Resume()); - EXPECT_FALSE(backend_->Resume()); -} - -TEST_F(CmaBackendProxyTest, SetPlaybackRate) { - constexpr float kSetPlaybackRatePts = 0.5; - EXPECT_TRUE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); - - CreateVideoDecoder(); - - EXPECT_CALL(*delegated_backend_, SetPlaybackRate(kSetPlaybackRatePts)) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - EXPECT_TRUE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); - EXPECT_FALSE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - - ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); - EXPECT_CALL(*audio_decoder_, SetPlaybackRate(kSetPlaybackRatePts)).Times(2); - EXPECT_CALL(*delegated_backend_, SetPlaybackRate(kSetPlaybackRatePts)) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - - EXPECT_TRUE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); - EXPECT_FALSE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); -} - -TEST_F(CmaBackendProxyTest, LogicalPause) { - backend_->LogicalPause(); - - CreateVideoDecoder(); - EXPECT_CALL(*delegated_backend_, LogicalPause()); - backend_->LogicalPause(); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - - ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); - EXPECT_CALL(*audio_decoder_, LogicalPause()); - EXPECT_CALL(*delegated_backend_, LogicalPause()); - backend_->LogicalPause(); -} - -TEST_F(CmaBackendProxyTest, LogicalResume) { - backend_->LogicalResume(); - - CreateVideoDecoder(); - EXPECT_CALL(*delegated_backend_, LogicalResume()); - backend_->LogicalResume(); - testing::Mock::VerifyAndClearExpectations(delegated_backend_); - - ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); - EXPECT_CALL(*audio_decoder_, LogicalResume()); - EXPECT_CALL(*delegated_backend_, LogicalResume()); - backend_->LogicalResume(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cma_proxy_handler.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_proxy_handler.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/cma_proxy_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/cma_proxy_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_PROXY_HANDLER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_PROXY_HANDLER_H_ - -#include "base/memory/ref_counted.h" -#include "chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h" -#include "chromecast/media/cma/backend/proxy/buffer_id_manager.h" - -namespace chromecast { - -class TaskRunner; - -namespace media { - -struct AudioConfig; - -class CmaProxyHandler { - public: - // The mode in which Cast Core should operate. - enum class AudioDecoderOperationMode { - // Both multiroom and audio rendering is enabled. - kAll = 0, - - // Only multiroom is enabled and audio rendering is disabled. This should - // be used if the runtime is taking over responsibility for rendering audio. - kMultiroomOnly = 1, - - // Only audio rendering is enabled and multiroom is disabled. - kAudioOnly = 2 - }; - - // The current state of the remote CMA backend. - enum class PipelineState { - kUninitialized = 0, - kStopped = 1, - kPlaying = 2, - kPaused = 3, - }; - - // Observer for changes on the remote client. - class Client { - public: - virtual ~Client() = default; - - // Called when an error occurs upon calling any gRPC Method. - virtual void OnError() = 0; - - // Called when the Start(), Stop(), Pause(), or Resume() methods - // successfully change the current pipeline state. - virtual void OnPipelineStateChange(PipelineState state) = 0; - - // Called following the successful processing of a batch of PushBuffer - // calls. - virtual void OnBytesDecoded(int64_t decoded_byte_count) = 0; - }; - - virtual ~CmaProxyHandler() = default; - - // Create a new implementation-specific CmaProxyHandler. Each provided - // object must exist for the duration of the created instance's lifetime, and - // all callbacks for |client| will be called on |task_runner|. - static std::unique_ptr Create( - TaskRunner* task_runner, - Client* client, - AudioChannelPushBufferHandler::Client* push_buffer_client); - - // Calls to the corresponding gRPC Methods. These functions may be called from - // any thread. - virtual void Initialize(const std::string& cast_session_id, - AudioDecoderOperationMode decoder_mode) = 0; - virtual void Start( - int64_t start_pts, - const BufferIdManager::TargetBufferInfo& target_buffer) = 0; - virtual void Stop() = 0; - virtual void Pause() = 0; - virtual void Resume( - const BufferIdManager::TargetBufferInfo& target_buffer) = 0; - virtual void SetPlaybackRate(float rate) = 0; - virtual void SetVolume(float multiplier) = 0; - virtual void UpdateTimestamp( - const BufferIdManager::TargetBufferInfo& target_buffer) = 0; - - // Push the provided data or config to a queue, for processing at a later - // point when resources are available. Returns true if the data was - // successfully pushed to the queue and false otherwise. These functions may - // be called from any thread. - // - // NOTES: - // - SetConfig is expected to be called prior to any PushBuffer calls. - // - SetConfig may be called later on as-well, after which time the new config - // will be used for all following PushBuffer calls. - virtual bool SetConfig(const AudioConfig& config) = 0; - virtual CmaBackend::BufferStatus PushBuffer( - scoped_refptr buffer, - BufferIdManager::BufferId buffer_id) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_CMA_PROXY_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,228 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.h" - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/task_runner.h" - -namespace chromecast { -namespace media { -namespace { - -// TODO(b/180725465): Make this a BUILD flag for embedders to specify. -constexpr int kMicrosecondsDataToBuffer = - 5 * base::Time::kMicrosecondsPerSecond; - -} // namespace - -MediaPipelineBufferExtension::PendingCommand::PendingCommand( - scoped_refptr buf) - : buffer(std::move(buf)) {} - -MediaPipelineBufferExtension::PendingCommand::PendingCommand( - const AudioConfig& cfg) - : config(cfg) {} - -MediaPipelineBufferExtension::PendingCommand::PendingCommand( - const PendingCommand& other) = default; -MediaPipelineBufferExtension::PendingCommand::PendingCommand( - PendingCommand&& other) = default; - -MediaPipelineBufferExtension::PendingCommand::~PendingCommand() = default; - -MediaPipelineBufferExtension::PendingCommand& -MediaPipelineBufferExtension::PendingCommand::operator=( - const PendingCommand& other) = default; -MediaPipelineBufferExtension::PendingCommand& -MediaPipelineBufferExtension::PendingCommand::operator=( - PendingCommand&& other) = default; - -MediaPipelineBufferExtension::MediaPipelineBufferExtension( - TaskRunner* task_runner, - CmaBackend::AudioDecoder* delegated_decoder) - : AudioDecoderPipelineNode(delegated_decoder), - task_runner_(task_runner), - weak_factory_(this) { - DCHECK(task_runner_); -} - -MediaPipelineBufferExtension::MediaPipelineBufferExtension( - TaskRunner* task_runner, - std::unique_ptr owned_delegated_decoder) - : MediaPipelineBufferExtension(task_runner, owned_delegated_decoder.get()) { - SetOwnedDecoder(std::move(owned_delegated_decoder)); -} - -MediaPipelineBufferExtension::~MediaPipelineBufferExtension() = default; - -CmaBackend::BufferStatus -MediaPipelineBufferExtension::PushBufferToDelegatedDecoder( - scoped_refptr buffer) { - last_buffer_pts_ = buffer->timestamp(); - return AudioDecoderPipelineNode::PushBuffer(std::move(buffer)); -} - -bool MediaPipelineBufferExtension::IsBufferFull() const { - CheckCalledOnCorrectThread(); - return GetBufferDuration() >= kMicrosecondsDataToBuffer; -} - -bool MediaPipelineBufferExtension::IsBufferEmpty() const { - CheckCalledOnCorrectThread(); - return command_queue_.empty(); -} - -int64_t MediaPipelineBufferExtension::GetBufferDuration() const { - if (IsBufferEmpty()) { - return 0; - } - - DCHECK_GE(last_buffer_pts_, 0); - DCHECK_GE(most_recent_buffer_pts_, last_buffer_pts_); - - return most_recent_buffer_pts_ - last_buffer_pts_; -} - -bool MediaPipelineBufferExtension::IsDelegatedDecoderHealthy() const { - return delegated_decoder_buffer_status_ != BufferStatus::kBufferFailed && - delegated_decoder_set_config_status_; -} - -void MediaPipelineBufferExtension::OnPushBufferComplete(BufferStatus status) { - CheckCalledOnCorrectThread(); - - delegated_decoder_buffer_status_ = status; - - // If the buffer was full and the call failed, inform the caller via callback - // per method contract. - if (status == BufferStatus::kBufferFailed && IsBufferFull()) { - DCHECK(!IsBufferEmpty()); - AudioDecoderPipelineNode::OnPushBufferComplete(status); - return; - } - - // Dequeue and push buffers to the underlying AudioDecoder until a Pending or - // Failure signal is returned. Rather than doing this in a loop, it is done - // by posting sequential tasks to the task runner, to ensure that the current - // thread is not blocked for the duration of this process. - SchedulePushToDecoder(); -} - -bool MediaPipelineBufferExtension::TryPushToDecoder() { - CheckCalledOnCorrectThread(); - - if (IsBufferEmpty()) { - return true; - } - - // Pull the front element off this instance's queue and process it. - const bool is_buffer_full_before_push = IsBufferFull(); - PendingCommand& next_command = command_queue_.front(); - - // Only one of the config or buffer may be set. - DCHECK_NE(next_command.buffer.has_value(), next_command.config.has_value()); - - // If the next command in the queue can be processed, do. Else, return true. - if (next_command.buffer.has_value() && - delegated_decoder_buffer_status_ == BufferStatus::kBufferSuccess) { - delegated_decoder_buffer_status_ = - PushBufferToDelegatedDecoder(std::move(next_command.buffer.value())); - - // If this queue is no longer blocked, inform the caller per method - // contract. - if (is_buffer_full_before_push && !IsBufferFull()) { - AudioDecoderPipelineNode::OnPushBufferComplete( - delegated_decoder_buffer_status_ != BufferStatus::kBufferFailed - ? BufferStatus::kBufferSuccess - : BufferStatus::kBufferFailed); - } - - if (delegated_decoder_buffer_status_ == BufferStatus::kBufferFailed) { - return false; - } - } else if (next_command.config.has_value() && - delegated_decoder_set_config_status_) { - delegated_decoder_set_config_status_ = - AudioDecoderPipelineNode::SetConfig(next_command.config.value()); - if (!delegated_decoder_set_config_status_) { - return false; - } - } else { - return true; - } - - // Pop the processed item from the queue and iterate as needed. - command_queue_.pop(); - if (!IsBufferEmpty()) { - SchedulePushToDecoder(); - } - - return true; -} - -void MediaPipelineBufferExtension::SchedulePushToDecoder() { - auto* task = new TaskRunner::CallbackTask(base::BindOnce( - base::IgnoreResult(&MediaPipelineBufferExtension::TryPushToDecoder), - weak_factory_.GetWeakPtr())); - task_runner_->PostTask(task, 0); -} - -bool MediaPipelineBufferExtension::TryProcessCommand(PendingCommand command) { - // If the most recent call was a failure, inform the user. - if (!IsDelegatedDecoderHealthy()) { - return false; - } - - // Queue up the item to be processed in the queue. Then, try to push the top - // item of the queue to the underlying decoder. This may or may not be the - // item that was just pushed, leading to two cases: - // - If so, clearly the result of this call provides enough information to - // determine the correct response to the user's call. - // - If not, then this result is true by assumption. But if the push failed, - // then the buffer is now in an unhealthy state and false should be - // returned. - command_queue_.push(std::move(command)); - return TryPushToDecoder(); -} - -CmaBackend::BufferStatus MediaPipelineBufferExtension::PushBuffer( - scoped_refptr buffer) { - CheckCalledOnCorrectThread(); - - if (IsBufferFull()) { - return BufferStatus::kBufferFailed; - } - - most_recent_buffer_pts_ = buffer->timestamp(); - - if (!TryProcessCommand(PendingCommand(std::move(buffer)))) { - return BufferStatus::kBufferFailed; - } - - return IsBufferFull() ? BufferStatus::kBufferPending - : BufferStatus::kBufferSuccess; -} - -bool MediaPipelineBufferExtension::SetConfig(const AudioConfig& config) { - CheckCalledOnCorrectThread(); - return TryProcessCommand(PendingCommand(config)); -} - -CmaBackend::AudioDecoder::RenderingDelay -MediaPipelineBufferExtension::GetRenderingDelay() { - CheckCalledOnCorrectThread(); - - auto delegated_decoder_delay = AudioDecoderPipelineNode::GetRenderingDelay(); - delegated_decoder_delay.delay_microseconds += GetBufferDuration(); - return delegated_decoder_delay; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,126 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MEDIA_PIPELINE_BUFFER_EXTENSION_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MEDIA_PIPELINE_BUFFER_EXTENSION_H_ - -#include -#include -#include - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h" -#include "chromecast/public/media/cast_key_status.h" - -namespace chromecast { - -class TaskRunner; - -namespace media { - -// This class is intended to act as a layer on top of another CmaBackend, -// increasing the number of PushBuffer frames that may be queued up with -// PushBuffer() calls, while delegating all other functionality directly to the -// CmaBackend on top of which it sits. -class MediaPipelineBufferExtension : public AudioDecoderPipelineNode { - public: - // |task_runner| and |delegated_decoder| must persist for the duration of this - // class's lifetime. - MediaPipelineBufferExtension(TaskRunner* task_runner, - CmaBackend::AudioDecoder* delegated_decoder); - // Takes ownership of |owned_delegated_decoder|. - MediaPipelineBufferExtension( - TaskRunner* task_runner, - std::unique_ptr owned_delegated_decoder); - - ~MediaPipelineBufferExtension() override; - - bool IsBufferFull() const; - bool IsBufferEmpty() const; - - // AudioDecoderPipelineNode overrides. - RenderingDelay GetRenderingDelay() override; - BufferStatus PushBuffer(scoped_refptr buffer) override; - bool SetConfig(const AudioConfig& config) override; - - private: - struct PendingCommand { - // NOTE: Ctors needed to support emplace calls. - explicit PendingCommand(scoped_refptr buf); - explicit PendingCommand(const AudioConfig& cfg); - PendingCommand(const PendingCommand& other); - PendingCommand(PendingCommand&& other); - - ~PendingCommand(); - - PendingCommand& operator=(const PendingCommand& other); - PendingCommand& operator=(PendingCommand&& other); - - std::optional> buffer; - std::optional config; - }; - - // AudioDecoderPipelineNode overrides. - void OnPushBufferComplete(BufferStatus status) override; - - // Pushes the provided |buffer| to |delegated_decoder_|. - BufferStatus PushBufferToDelegatedDecoder( - scoped_refptr buffer); - - // Returns the total amount of playback time stored in this instance. - int64_t GetBufferDuration() const; - - // Returns whether the last call to either PushBuffer() or SetConfig() on the - // delegated decoder returned an unhealthy response code. - bool IsDelegatedDecoderHealthy() const; - - // Helper method to try to push the top item in the |command_queue_| to - // |delegated_decoder_|. Returns false if the underlying decoder's operation - // both was called and that call failed, and true in all other cases. - // - // If either there is no data to process or no work that can be done at this - // time, this operation is a no op which returns true. - bool TryPushToDecoder(); - - // Pushes the |command| to |command_queue_| and tries to process it, returning - // whether or not the delegated decoder is in a healthy state following this - // process. - bool TryProcessCommand(PendingCommand command); - - // Schedules the TryPushToDecoder() method to run at a later time on - // |task_runner_|. - void SchedulePushToDecoder(); - - // PushBuffer and SetConfig data which has been queued locally but has not yet - // been processed by the delegated decoder. - std::queue command_queue_; - - // The playback timestamp (PTS) of the last buffer pushed to the underlying - // decoder. - int64_t last_buffer_pts_ = 0; - - // The playback timestamp (PTS) of the most recently supplied by the caller. - int64_t most_recent_buffer_pts_ = 0; - - // Holds the result of the last call to delegated decoder's PushBuffer - // queue for which additional calls are not queued up (as is done by - // PushToDecoderAfterPushBufferComplete()). - BufferStatus delegated_decoder_buffer_status_ = BufferStatus::kBufferSuccess; - - // Holds the result of the last call to delegated decoder's SetConfig method. - bool delegated_decoder_set_config_status_ = true; - - TaskRunner* const task_runner_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MEDIA_PIPELINE_BUFFER_EXTENSION_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,319 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/proxy/media_pipeline_buffer_extension.h" - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/test/test_simple_task_runner.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/api/test/mock_cma_backend.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h" -#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" -#include "chromecast/public/media/cast_key_status.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/stream_id.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -using BufferStatus = CmaBackend::Decoder::BufferStatus; -using testing::_; -using testing::Mock; -using testing::Return; - -class MediaPipelineBufferExtensionTests : public testing::Test { - public: - MediaPipelineBufferExtensionTests() - : task_runner_(new base::TestSimpleTaskRunner()), - chromecast_task_runner_(task_runner_), - decoder_(std::make_unique< - testing::StrictMock>()), - delegate_(std::make_unique< - testing::StrictMock>()), - buffer_(std::make_unique( - &chromecast_task_runner_, - decoder_.get())) { - EXPECT_CALL(*decoder_, SetDelegate(buffer_.get())); - buffer_->SetDelegate(delegate_.get()); - } - - ~MediaPipelineBufferExtensionTests() override = default; - - protected: - bool IsBufferEmpty() { return buffer_->IsBufferEmpty(); } - - void OnDecoderPushBufferComplete(BufferStatus status) { - static_cast(buffer_.get()) - ->OnPushBufferComplete(status); - task_runner_->RunUntilIdle(); - } - - void ValidateRenderingDelay(int64_t delay_offset) { - static constexpr int64_t kDelay = 12345; - static constexpr int64_t kTimestamp = 678910; - static CmaBackend::AudioDecoder::RenderingDelay decoder_delay(kDelay, - kTimestamp); - EXPECT_CALL(*decoder_, GetRenderingDelay()).WillOnce(Return(decoder_delay)); - - auto calculated_delay = buffer_->GetRenderingDelay(); - EXPECT_EQ(calculated_delay.delay_microseconds, kDelay + delay_offset); - EXPECT_EQ(calculated_delay.timestamp_microseconds, kTimestamp); - } - - scoped_refptr CreateBuffer(int64_t pts_increment = 3) { - scoped_refptr buffer( - new CastDecoderBufferImpl(3, StreamId::kPrimary)); - buffer->set_timestamp(base::Microseconds(current_pts_)); - current_pts_ += pts_increment; - return buffer; - } - - AudioConfig CreateConfig() { - AudioConfig config; - config.bytes_per_channel = 17; - config.channel_number = 3; - config.samples_per_second = 42; - return config; - } - - scoped_refptr task_runner_; - TaskRunnerImpl chromecast_task_runner_; - std::unique_ptr decoder_; - std::unique_ptr delegate_; - std::unique_ptr buffer_; - - private: - uint64_t current_pts_ = 0; -}; - -TEST_F(MediaPipelineBufferExtensionTests, TestPushBufferOnSuccess) { - EXPECT_CALL(*decoder_, PushBuffer(_)) - .Times(4) - .WillRepeatedly(Return(BufferStatus::kBufferSuccess)); - - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_TRUE(IsBufferEmpty()); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_TRUE(IsBufferEmpty()); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_TRUE(IsBufferEmpty()); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_TRUE(IsBufferEmpty()); -} - -TEST_F(MediaPipelineBufferExtensionTests, TestPushBufferOnImmediateFailure) { - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferFailed)); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferFailed); -} - -TEST_F(MediaPipelineBufferExtensionTests, TestPushBufferDelayedFailure) { - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - - OnDecoderPushBufferComplete(BufferStatus::kBufferFailed); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferFailed); -} - -TEST_F(MediaPipelineBufferExtensionTests, TestGetRenderingDelay) { - // Calls with no data buffered are returned directly from the decoder. - ValidateRenderingDelay(0); - - EXPECT_TRUE(buffer_->IsBufferEmpty()); - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferSuccess)); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); - ValidateRenderingDelay(0); - Mock::VerifyAndClearExpectations(decoder_.get()); - - // The first push is buffered in the downstream decoder, not the queue. - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); - ValidateRenderingDelay(0); - Mock::VerifyAndClearExpectations(decoder_.get()); - - // Following pushes are stored in the local queue. - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_FALSE(buffer_->IsBufferEmpty()); - ValidateRenderingDelay(3); - - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_FALSE(buffer_->IsBufferEmpty()); - ValidateRenderingDelay(6); - - // When data is removed from the queue, the delay goes down. - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - OnDecoderPushBufferComplete(BufferStatus::kBufferSuccess); - EXPECT_FALSE(buffer_->IsBufferEmpty()); - ValidateRenderingDelay(3); - Mock::VerifyAndClearExpectations(decoder_.get()); - - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - OnDecoderPushBufferComplete(BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); - ValidateRenderingDelay(0); - Mock::VerifyAndClearExpectations(decoder_.get()); - - OnDecoderPushBufferComplete(BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); - ValidateRenderingDelay(0); -} - -TEST_F(MediaPipelineBufferExtensionTests, QueueFillsAndEmptiesCorrectly) { - EXPECT_TRUE(buffer_->IsBufferEmpty()); - - // It should take 1668 pushes for the buffer to completely fill up. - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferSuccess)); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer(3000)), - BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); - EXPECT_FALSE(buffer_->IsBufferFull()); - - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer(3000)), - BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); - EXPECT_FALSE(buffer_->IsBufferFull()); - - for (int i = 0; i < 1666; i++) { - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer(3000)), - BufferStatus::kBufferSuccess); - EXPECT_FALSE(buffer_->IsBufferEmpty()); - EXPECT_FALSE(buffer_->IsBufferFull()); - } - - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer(3000)), - BufferStatus::kBufferPending); - EXPECT_TRUE(buffer_->IsBufferFull()); - - Mock::VerifyAndClearExpectations(buffer_.get()); - - // When one buffer is processed and another added, it's still full. - EXPECT_CALL(*delegate_, OnPushBufferComplete(BufferStatus::kBufferSuccess)); - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - OnDecoderPushBufferComplete(BufferStatus::kBufferSuccess); - EXPECT_FALSE(buffer_->IsBufferFull()); - Mock::VerifyAndClearExpectations(buffer_.get()); - Mock::VerifyAndClearExpectations(delegate_.get()); - - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer(3000)), - BufferStatus::kBufferPending); - EXPECT_TRUE(buffer_->IsBufferFull()); - Mock::VerifyAndClearExpectations(buffer_.get()); - - // All data can successfully be emptied - EXPECT_CALL(*decoder_, PushBuffer(_)) - .Times(1667) - .WillRepeatedly(Return(BufferStatus::kBufferPending)); - - EXPECT_CALL(*delegate_, OnPushBufferComplete(BufferStatus::kBufferSuccess)); - for (int i = 0; i < 1666; i++) { - OnDecoderPushBufferComplete(BufferStatus::kBufferSuccess); - EXPECT_FALSE(buffer_->IsBufferEmpty()); - EXPECT_FALSE(buffer_->IsBufferFull()); - Mock::VerifyAndClearExpectations(delegate_.get()); - } - - OnDecoderPushBufferComplete(BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); - EXPECT_FALSE(buffer_->IsBufferFull()); -} - -TEST_F(MediaPipelineBufferExtensionTests, QueueEmptiesUntilPendingReceived) { - EXPECT_TRUE(buffer_->IsBufferEmpty()); - - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); - EXPECT_FALSE(buffer_->IsBufferFull()); - Mock::VerifyAndClearExpectations(decoder_.get()); - - for (int i = 0; i < 100; i++) { - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), - BufferStatus::kBufferSuccess); - EXPECT_FALSE(buffer_->IsBufferEmpty()); - EXPECT_FALSE(buffer_->IsBufferFull()); - } - - testing::InSequence s; - EXPECT_CALL(*decoder_, PushBuffer(_)) - .Times(50) - .WillRepeatedly(Return(BufferStatus::kBufferSuccess)); - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - OnDecoderPushBufferComplete(BufferStatus::kBufferSuccess); - Mock::VerifyAndClearExpectations(decoder_.get()); - - EXPECT_CALL(*decoder_, PushBuffer(_)) - .Times(49) - .WillRepeatedly(Return(BufferStatus::kBufferSuccess)); - OnDecoderPushBufferComplete(BufferStatus::kBufferSuccess); - EXPECT_TRUE(buffer_->IsBufferEmpty()); -} - -TEST_F(MediaPipelineBufferExtensionTests, TestSetConfigOnSuccess) { - EXPECT_CALL(*decoder_, SetConfig(_)).Times(4).WillRepeatedly(Return(true)); - - EXPECT_TRUE(buffer_->SetConfig(CreateConfig())); - EXPECT_TRUE(IsBufferEmpty()); - EXPECT_TRUE(buffer_->SetConfig(CreateConfig())); - EXPECT_TRUE(IsBufferEmpty()); - EXPECT_TRUE(buffer_->SetConfig(CreateConfig())); - EXPECT_TRUE(IsBufferEmpty()); - EXPECT_TRUE(buffer_->SetConfig(CreateConfig())); - EXPECT_TRUE(IsBufferEmpty()); -} - -TEST_F(MediaPipelineBufferExtensionTests, SetConfigCalledAfterPushBufferStops) { - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferPending)); - EXPECT_CALL(*decoder_, SetConfig(_)).Times(2).WillRepeatedly(Return(true)); - - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_TRUE(IsBufferEmpty()); - EXPECT_TRUE(buffer_->SetConfig(CreateConfig())); - EXPECT_TRUE(IsBufferEmpty()); - EXPECT_TRUE(buffer_->SetConfig(CreateConfig())); - EXPECT_TRUE(IsBufferEmpty()); - - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferSuccess); - EXPECT_FALSE(IsBufferEmpty()); - EXPECT_TRUE(buffer_->SetConfig(CreateConfig())); - EXPECT_FALSE(IsBufferEmpty()); -} - -TEST_F(MediaPipelineBufferExtensionTests, FailedPushBufferBlocksCommands) { - EXPECT_CALL(*decoder_, PushBuffer(_)) - .WillOnce(Return(BufferStatus::kBufferFailed)); - - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferFailed); - EXPECT_FALSE(buffer_->SetConfig(CreateConfig())); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferFailed); -} - -TEST_F(MediaPipelineBufferExtensionTests, FailedSetConfigBlocksCommands) { - EXPECT_CALL(*decoder_, SetConfig(_)).WillOnce(Return(false)); - - EXPECT_FALSE(buffer_->SetConfig(CreateConfig())); - EXPECT_EQ(buffer_->PushBuffer(CreateBuffer()), BufferStatus::kBufferFailed); - EXPECT_FALSE(buffer_->SetConfig(CreateConfig())); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MULTIZONE_AUDIO_DECODER_PROXY_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MULTIZONE_AUDIO_DECODER_PROXY_H_ - -#include "base/functional/callback.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/backend/proxy/audio_decoder_pipeline_node.h" - -namespace chromecast { -namespace media { - -// This class is used to decrypt then proxy audio data to an external -// CmaBackend::AudioDecoder over gRPC. -class MultizoneAudioDecoderProxy : public AudioDecoderPipelineNode { - public: - MultizoneAudioDecoderProxy(CmaBackend::AudioDecoder* decoder) - : AudioDecoderPipelineNode(decoder) {} - ~MultizoneAudioDecoderProxy() override = default; - - virtual void Initialize() = 0; - virtual void Start(int64_t start_pts) = 0; - virtual void Stop() = 0; - virtual void Pause() = 0; - virtual void Resume() = 0; - virtual void SetPlaybackRate(float rate) = 0; - virtual void LogicalPause() = 0; - virtual void LogicalResume() = 0; - virtual int64_t GetCurrentPts() const = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MULTIZONE_AUDIO_DECODER_PROXY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,164 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.h" - -#include "base/notreached.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { - -MultizoneAudioDecoderProxyImpl::MultizoneAudioDecoderProxyImpl( - const MediaPipelineDeviceParams& params, - CmaBackend::AudioDecoder* downstream_decoder) - : MultizoneAudioDecoderProxy(downstream_decoder), - cast_session_id_(params.session_id), - decoder_mode_(CmaProxyHandler::AudioDecoderOperationMode::kMultiroomOnly), - proxy_handler_(CmaProxyHandler::Create(params.task_runner, this, this)), - buffer_id_manager_(this, this) { - DCHECK(proxy_handler_); -} - -MultizoneAudioDecoderProxyImpl::MultizoneAudioDecoderProxyImpl( - const MediaPipelineDeviceParams& params, - std::unique_ptr downstream_decoder) - : MultizoneAudioDecoderProxyImpl(params, downstream_decoder.get()) { - SetOwnedDecoder(std::move(downstream_decoder)); -} - -MultizoneAudioDecoderProxyImpl::~MultizoneAudioDecoderProxyImpl() = default; - -void MultizoneAudioDecoderProxyImpl::Initialize() { - CheckCalledOnCorrectThread(); - proxy_handler_->Initialize(cast_session_id_, decoder_mode_); -} - -void MultizoneAudioDecoderProxyImpl::Start(int64_t start_pts) { - CheckCalledOnCorrectThread(); - proxy_handler_->Start( - start_pts, - buffer_id_manager_.UpdateAndGetCurrentlyProcessingBufferInfo()); -} - -void MultizoneAudioDecoderProxyImpl::Stop() { - CheckCalledOnCorrectThread(); - proxy_handler_->Stop(); -} - -void MultizoneAudioDecoderProxyImpl::Pause() { - CheckCalledOnCorrectThread(); - proxy_handler_->Pause(); -} - -void MultizoneAudioDecoderProxyImpl::Resume() { - CheckCalledOnCorrectThread(); - proxy_handler_->Resume( - buffer_id_manager_.UpdateAndGetCurrentlyProcessingBufferInfo()); -} - -void MultizoneAudioDecoderProxyImpl::SetPlaybackRate(float rate) { - CheckCalledOnCorrectThread(); - proxy_handler_->SetPlaybackRate(rate); -} - -void MultizoneAudioDecoderProxyImpl::LogicalPause() { - CheckCalledOnCorrectThread(); - // There is intentionally no proxy implementation of this method. -} - -void MultizoneAudioDecoderProxyImpl::LogicalResume() { - CheckCalledOnCorrectThread(); - // There is intentionally no proxy implementation of this method. -} - -int64_t MultizoneAudioDecoderProxyImpl::GetCurrentPts() const { - CheckCalledOnCorrectThread(); - NOTREACHED(); -} - -CmaBackend::Decoder::BufferStatus MultizoneAudioDecoderProxyImpl::PushBuffer( - scoped_refptr buffer) { - CheckCalledOnCorrectThread(); - DCHECK(proxy_handler_); - DCHECK(buffer); - - if (pending_push_buffer_.get()) { - return MultizoneAudioDecoderProxy::BufferStatus::kBufferFailed; - } - - // First try to send the buffer over the gRPC. - const auto proxy_result = proxy_handler_->PushBuffer( - buffer, buffer_id_manager_.AssignBufferId(*buffer)); - - // If that succeeds, send the buffer to the downstream decoder. Else, wait for - // a callback to OnProxyPushBufferComplete() by returning kBufferPending, at - // which point the downstream decoder will receive the PushBuffer call. This - // acts as a flow control mechanism for the proxy decoder. - if (proxy_result != BufferStatus::kBufferSuccess) { - pending_push_buffer_ = std::move(buffer); - return proxy_result; - } - - return MultizoneAudioDecoderProxy::PushBuffer(std::move(buffer)); -} - -bool MultizoneAudioDecoderProxyImpl::SetConfig(const AudioConfig& config) { - return proxy_handler_->SetConfig(config) && - MultizoneAudioDecoderProxy::SetConfig(config); -} - -void MultizoneAudioDecoderProxyImpl::GetStatistics(Statistics* statistics) { - DCHECK(statistics); - CheckCalledOnCorrectThread(); - statistics->decoded_bytes = bytes_decoded_; -} - -void MultizoneAudioDecoderProxyImpl::OnError() { - CheckCalledOnCorrectThread(); - NOTREACHED(); -} - -void MultizoneAudioDecoderProxyImpl::OnPipelineStateChange( - CmaProxyHandler::PipelineState state) { - CheckCalledOnCorrectThread(); -} - -void MultizoneAudioDecoderProxyImpl::OnBytesDecoded( - int64_t decoded_byte_count) { - CheckCalledOnCorrectThread(); - bytes_decoded_ = decoded_byte_count; -} - -void MultizoneAudioDecoderProxyImpl::OnTimestampUpdateNeeded( - BufferIdManager::TargetBufferInfo buffer) { - proxy_handler_->UpdateTimestamp(std::move(buffer)); -} - -void MultizoneAudioDecoderProxyImpl::OnAudioChannelPushBufferComplete( - CmaBackend::BufferStatus status) { - // Try to call PushBuffer on the downstream decoder. - if (status != CmaBackend::BufferStatus::kBufferSuccess) { - DCHECK_NE(status, CmaBackend::BufferStatus::kBufferPending); - MultizoneAudioDecoderProxy::OnPushBufferComplete(status); - return; - } - - DCHECK(pending_push_buffer_); - const auto downstream_decoder_result = - MultizoneAudioDecoderProxy::PushBuffer(std::move(pending_push_buffer_)); - pending_push_buffer_.reset(); - - // If it is able to immediately process the result (either as success or - // failure), call OnPushBufferComplete() to signal that the decoder is ready - // to accept more data. Else, wait for the downstream decoder to call it per - // that method's contract. - if (downstream_decoder_result != BufferStatus::kBufferPending) { - MultizoneAudioDecoderProxy::OnPushBufferComplete(downstream_decoder_result); - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,115 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MULTIZONE_AUDIO_DECODER_PROXY_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MULTIZONE_AUDIO_DECODER_PROXY_IMPL_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h" -#include "chromecast/media/cma/backend/proxy/buffer_id_manager.h" -#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" -#include "chromecast/media/cma/backend/proxy/multizone_audio_decoder_proxy.h" - -namespace chromecast { -namespace media { - -struct AudioConfig; -struct MediaPipelineDeviceParams; - -// This class is used to proxy audio data to an external -// CmaBackend::AudioDecoder over gRPC. -class MultizoneAudioDecoderProxyImpl - : public MultizoneAudioDecoderProxy, - public CmaProxyHandler::Client, - public BufferIdManager::Client, - public AudioChannelPushBufferHandler::Client { - public: - // Creates a new MultizoneAudioDecoderProxy, such that in the event of an - // unrecoverable error, |fatal_error_callback| will be called. Fallowing this - // call, this instance will be in an undefined state. - MultizoneAudioDecoderProxyImpl(const MediaPipelineDeviceParams& params, - CmaBackend::AudioDecoder* downstream_decoder); - - MultizoneAudioDecoderProxyImpl( - const MediaPipelineDeviceParams& params, - std::unique_ptr downstream_decoder); - MultizoneAudioDecoderProxyImpl(const MultizoneAudioDecoderProxyImpl& other) = - delete; - - ~MultizoneAudioDecoderProxyImpl() override; - - MultizoneAudioDecoderProxyImpl& operator=( - const MultizoneAudioDecoderProxyImpl& other) = delete; - - // MultizoneAudioDecoderProxy implementation: - // - // Note that the methods implementing of CmaBackend::AudioDecoder (which - // MultizoneAudioDecoderProxy extends) must call both into the downstream - // decoder and into the |proxy_handler_|, so that audio can be processed both - // locally and remotely. The remaining methods should NOT call into the - // downstream CmaBackend, as this is the responsibility of the caller. - void Initialize() override; - void Start(int64_t start_pts) override; - void Stop() override; - void Pause() override; - void Resume() override; - void SetPlaybackRate(float rate) override; - void LogicalPause() override; - void LogicalResume() override; - int64_t GetCurrentPts() const override; - bool SetConfig(const AudioConfig& config) override; - CmaBackend::Decoder::BufferStatus PushBuffer( - scoped_refptr buffer) override; - void GetStatistics(CmaBackend::AudioDecoder::Statistics* statistics) override; - - private: - // CmaProxyHandler::Client overrides: - void OnError() override; - void OnPipelineStateChange(CmaProxyHandler::PipelineState state) override; - void OnBytesDecoded(int64_t decoded_byte_count) override; - - // BufferIdManager::Client overrides: - void OnTimestampUpdateNeeded( - BufferIdManager::TargetBufferInfo buffer) override; - - // AudioChannelPushBufferHandler::Client overrides: - void OnAudioChannelPushBufferComplete( - CmaBackend::BufferStatus status) override; - - // The PTS offset as determined by the receiver of the gRPC endpoint wrapped - // by this class. This value is updated as new PTS values are received over - // the IPC. - int64_t pts_offset_ = std::numeric_limits::min(); - - // Number of bytes decoded so far. - int64_t bytes_decoded_ = 0; - - // Parameters for the Initialize() call captured in the ctor. - const std::string cast_session_id_; - const CmaProxyHandler::AudioDecoderOperationMode decoder_mode_; - - // The buffer which has received kBufferPending from - // |proxy_handler_->PushBuffer()| and has not yet received the - // OnAudioChannelPushBufferComplete callback. Has the following states: - // - Empty when no such callback is expected, and no pending operation is - // ongoing. - // - Set to a valid pointer when such an operation is ongoing. - scoped_refptr pending_push_buffer_; - - // This is the local instance representing the "remote" backend. All above - // public method calls should call into this instance to proxy the call to - // the remote backend. - std::unique_ptr proxy_handler_; - - BufferIdManager buffer_id_manager_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_MULTIZONE_AUDIO_DECODER_PROXY_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/proxy_call_translator.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/proxy_call_translator.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,368 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/proxy_call_translator.h" - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h" -#include "chromecast/media/cma/backend/proxy/push_buffer_queue.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/task_runner.h" -#include "third_party/cast_core/public/src/proto/runtime/cast_audio_channel_service.grpc.pb.h" -#include "third_party/protobuf/src/google/protobuf/util/time_util.h" - -namespace chromecast { -namespace media { -namespace { - -CmaProxyHandler::PipelineState ToClientTypes( - CastRuntimeAudioChannelBroker::Handler::PipelineState state) { - switch (state) { - case CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_UNINITIALIZED: - return CmaProxyHandler::PipelineState::kUninitialized; - case CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_STOPPED: - return CmaProxyHandler::PipelineState::kStopped; - case CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_PLAYING: - return CmaProxyHandler::PipelineState::kPlaying; - case CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_PAUSED: - return CmaProxyHandler::PipelineState::kPaused; - default: - NOTREACHED(); - } -} - -cast::media::AudioConfiguration_AudioCodec ToGrpcTypes(AudioCodec codec) { - switch (codec) { - case kAudioCodecUnknown: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_UNKNOWN; - case kCodecAAC: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_AAC; - case kCodecMP3: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_MP3; - case kCodecPCM: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_PCM; - case kCodecPCM_S16BE: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_PCM_S16BE; - case kCodecVorbis: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_VORBIS; - case kCodecOpus: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_OPUS; - case kCodecEAC3: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_EAC3; - case kCodecAC3: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_AC3; - case kCodecDTS: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_DTS; - case kCodecFLAC: - return cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_FLAC; - case kCodecMpegHAudio: - return cast::media:: - AudioConfiguration_AudioCodec_AUDIO_CODEC_MPEG_H_AUDIO; - default: - NOTREACHED(); - } -} - -cast::media::AudioConfiguration_ChannelLayout ToGrpcTypes( - ChannelLayout channel_layout) { - switch (channel_layout) { - case ChannelLayout::UNSUPPORTED: - return cast::media:: - AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_UNSUPPORTED; - case ChannelLayout::MONO: - return cast::media::AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_MONO; - case ChannelLayout::STEREO: - return cast::media:: - AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_STEREO; - case ChannelLayout::SURROUND_5_1: - return cast::media:: - AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_SURROUND_5_1; - case ChannelLayout::BITSTREAM: - return cast::media:: - AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_BITSTREAM; - case ChannelLayout::DISCRETE: - return cast::media:: - AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_DISCRETE; - default: - NOTREACHED(); - } -} - -cast::media::AudioConfiguration_SampleFormat ToGrpcTypes( - SampleFormat sample_format) { - switch (sample_format) { - case kUnknownSampleFormat: - return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_UNKNOWN; - case kSampleFormatU8: - return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_U8; - case kSampleFormatS16: - return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_S16; - case kSampleFormatS32: - return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_S32; - case kSampleFormatF32: - return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_F32; - case kSampleFormatPlanarS16: - return cast::media:: - AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_S16; - case kSampleFormatPlanarF32: - return cast::media:: - AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_F32; - case kSampleFormatPlanarS32: - return cast::media:: - AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_S32; - case kSampleFormatS24: - return cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_S24; - default: - NOTREACHED(); - } -} - -cast::media::CastAudioDecoderMode ToGrpcTypes( - CmaProxyHandler::AudioDecoderOperationMode operation_mode) { - switch (operation_mode) { - case CmaProxyHandler::AudioDecoderOperationMode::kAll: - return cast::media::CAST_AUDIO_DECODER_MODE_ALL; - case CmaProxyHandler::AudioDecoderOperationMode::kMultiroomOnly: - return cast::media::CAST_AUDIO_DECODER_MODE_MULTIROOM_ONLY; - case CmaProxyHandler::AudioDecoderOperationMode::kAudioOnly: - return cast::media::CAST_AUDIO_DECODER_MODE_AUDIO_ONLY; - } -} - -CastRuntimeAudioChannelBroker::Handler::PushBufferRequest ToGrpcTypes( - scoped_refptr buffer, - BufferIdManager::BufferId buffer_id) { - auto* decode_buffer = new cast::media::AudioDecoderBuffer; - - decode_buffer->set_id(buffer_id); - decode_buffer->set_end_of_stream(buffer->end_of_stream()); - if (!buffer->end_of_stream()) { - decode_buffer->set_pts_micros(buffer->timestamp()); - decode_buffer->set_data(buffer->data(), buffer->data_size()); - } - - CastRuntimeAudioChannelBroker::Handler::PushBufferRequest request; - - // NOTE: This transfers ownership of |decode_buffer| to |request|. - request.set_allocated_buffer(decode_buffer); - - return request; -} - -CastRuntimeAudioChannelBroker::Handler::PushBufferRequest ToGrpcTypes( - const AudioConfig& audio_config) { - auto* audio_config_internal = new cast::media::AudioConfiguration; - audio_config_internal->set_codec(ToGrpcTypes(audio_config.codec)); - audio_config_internal->set_channel_layout( - ToGrpcTypes(audio_config.channel_layout)); - audio_config_internal->set_sample_format( - ToGrpcTypes(audio_config.sample_format)); - audio_config_internal->set_bytes_per_channel(audio_config.bytes_per_channel); - audio_config_internal->set_channel_number(audio_config.channel_number); - audio_config_internal->set_samples_per_second( - audio_config.samples_per_second); - - // NOTE: This copies the data. - audio_config_internal->set_extra_data(audio_config.extra_data.data(), - audio_config.extra_data.size()); - - CastRuntimeAudioChannelBroker::Handler::PushBufferRequest request; - - // NOTE: This transfers ownership of |audio_config_internal| to |request|. - request.set_allocated_audio_config(audio_config_internal); - - return request; -} - -CastRuntimeAudioChannelBroker::TimestampInfo ToGrpcTypes( - const BufferIdManager::TargetBufferInfo& target_buffer) { - CastRuntimeAudioChannelBroker::TimestampInfo ts_info; - ts_info.set_buffer_id(target_buffer.buffer_id); - cast::common::Duration cc_duration; - cc_duration.set_seconds(target_buffer.timestamp_micros / - base::Time::kMicrosecondsPerSecond); - cc_duration.set_nanoseconds( - (target_buffer.timestamp_micros % base::Time::kMicrosecondsPerSecond) * - base::Time::kNanosecondsPerMicrosecond); - *ts_info.mutable_system_timestamp() = std::move(cc_duration); - return ts_info; -} - -} // namespace - -// static -std::unique_ptr CmaProxyHandler::Create( - TaskRunner* task_runner, - Client* client, - AudioChannelPushBufferHandler::Client* push_buffer_client) { - return std::make_unique(task_runner, client, - push_buffer_client); -} - -ProxyCallTranslator::ProxyCallTranslator( - TaskRunner* client_task_runner, - CmaProxyHandler::Client* client, - AudioChannelPushBufferHandler::Client* push_buffer_client) - : ProxyCallTranslator( - client_task_runner, - client, - push_buffer_client, - CastRuntimeAudioChannelBroker::Create(client_task_runner, this)) {} - -ProxyCallTranslator::ProxyCallTranslator( - TaskRunner* client_task_runner, - CmaProxyHandler::Client* client, - AudioChannelPushBufferHandler::Client* push_buffer_client, - std::unique_ptr decoder_channel) - : decoder_channel_(std::move(decoder_channel)), - client_task_runner_(client_task_runner), - client_(client), - push_buffer_handler_(client_task_runner, push_buffer_client), - weak_factory_(this) { - DCHECK(decoder_channel_.get()); - DCHECK(client_task_runner_); - DCHECK(client_); -} - -ProxyCallTranslator::~ProxyCallTranslator() = default; - -void ProxyCallTranslator::Initialize( - const std::string& cast_session_id, - CmaProxyHandler::AudioDecoderOperationMode decoder_mode) { - decoder_channel_->InitializeAsync(cast_session_id, ToGrpcTypes(decoder_mode)); -} - -void ProxyCallTranslator::Start( - int64_t start_pts, - const BufferIdManager::TargetBufferInfo& target_buffer) { - decoder_channel_->StartAsync(start_pts, ToGrpcTypes(target_buffer)); -} - -void ProxyCallTranslator::Stop() { - decoder_channel_->StopAsync(); -} - -void ProxyCallTranslator::Pause() { - decoder_channel_->PauseAsync(); -} - -void ProxyCallTranslator::Resume( - const BufferIdManager::TargetBufferInfo& target_buffer) { - decoder_channel_->ResumeAsync(ToGrpcTypes(target_buffer)); -} - -void ProxyCallTranslator::SetPlaybackRate(float rate) { - decoder_channel_->SetPlaybackAsync(rate); -} - -void ProxyCallTranslator::SetVolume(float multiplier) { - decoder_channel_->SetVolumeAsync(multiplier); -} - -bool ProxyCallTranslator::SetConfig(const AudioConfig& config) { - return push_buffer_handler_.PushBuffer(ToGrpcTypes(config)) != - CmaBackend::BufferStatus::kBufferFailed; -} - -void ProxyCallTranslator::UpdateTimestamp( - const BufferIdManager::TargetBufferInfo& target_buffer) { - decoder_channel_->UpdateTimestampAsync(ToGrpcTypes(target_buffer)); -} - -CmaBackend::BufferStatus ProxyCallTranslator::PushBuffer( - scoped_refptr buffer, - BufferIdManager::BufferId buffer_id) { - return push_buffer_handler_.PushBuffer( - ToGrpcTypes(std::move(buffer), buffer_id)); -} - -std::optional -ProxyCallTranslator::GetBufferedData() { - return push_buffer_handler_.GetBufferedData(); -} - -bool ProxyCallTranslator::HasBufferedData() { - return push_buffer_handler_.HasBufferedData(); -} - -void ProxyCallTranslator::HandleInitializeResponse( - CastRuntimeAudioChannelBroker::StatusCode status) { - HandleError(status); -} - -void ProxyCallTranslator::HandleSetVolumeResponse( - CastRuntimeAudioChannelBroker::StatusCode status) { - HandleError(status); -} - -void ProxyCallTranslator::HandleSetPlaybackResponse( - CastRuntimeAudioChannelBroker::StatusCode status) { - HandleError(status); -} - -void ProxyCallTranslator::HandleStateChangeResponse( - CastRuntimeAudioChannelBroker::Handler::PipelineState state, - CastRuntimeAudioChannelBroker::StatusCode status) { - if (!HandleError(status)) { - return; - } - - auto* task = new TaskRunner::CallbackTask( - base::BindOnce(&ProxyCallTranslator::OnPipelineStateChangeTask, - weak_factory_.GetWeakPtr(), ToClientTypes(state))); - client_task_runner_->PostTask(task, 0); -} - -void ProxyCallTranslator::HandlePushBufferResponse( - int64_t decoded_bytes, - CastRuntimeAudioChannelBroker::StatusCode status) { - if (!HandleError(status)) { - return; - } - - auto* task = new TaskRunner::CallbackTask( - base::BindOnce(&ProxyCallTranslator::OnBytesDecodedTask, - weak_factory_.GetWeakPtr(), decoded_bytes)); - client_task_runner_->PostTask(task, 0); -} - -void ProxyCallTranslator::HandleGetMediaTimeResponse( - std::optional time, - CastRuntimeAudioChannelBroker::StatusCode status) { - NOTREACHED(); -} - -bool ProxyCallTranslator::HandleError( - CastRuntimeAudioChannelBroker::StatusCode status) { - if (status == CastRuntimeAudioChannelBroker::StatusCode::kOk) { - return true; - } - - auto* task = new TaskRunner::CallbackTask(base::BindOnce( - &ProxyCallTranslator::OnErrorTask, weak_factory_.GetWeakPtr())); - client_task_runner_->PostTask(task, 0); - return false; -} - -void ProxyCallTranslator::OnErrorTask() { - client_->OnError(); -} - -void ProxyCallTranslator::OnPipelineStateChangeTask( - CmaProxyHandler::PipelineState state) { - client_->OnPipelineStateChange(state); -} - -void ProxyCallTranslator::OnBytesDecodedTask(int64_t decoded_byte_count) { - client_->OnBytesDecoded(decoded_byte_count); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/proxy_call_translator.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/proxy_call_translator.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,122 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PROXY_CALL_TRANSLATOR_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PROXY_CALL_TRANSLATOR_H_ - -#include -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/backend/proxy/buffer_id_manager.h" -#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h" -#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" -#include "chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h" - -namespace chromecast { - -class TaskRunner; - -namespace media { - -struct AudioConfig; - -// This class is responsible for translating between entities used by the -// client CmaBackend and entities used by the internal gRPC Channel. -// Calls made to all methods of this class may be made from any thread. -class ProxyCallTranslator : public CmaProxyHandler, - public CastRuntimeAudioChannelBroker::Handler { - public: - // Creates a new ProxyCallTranslator. All provided entities must exist for the - // duration of this instance's lifetime. All calls to |client| will be made - // on |client_task_runner|. - ProxyCallTranslator( - TaskRunner* client_task_runner, - CmaProxyHandler::Client* client, - AudioChannelPushBufferHandler::Client* push_buffer_client); - ProxyCallTranslator(const ProxyCallTranslator& other) = delete; - - ~ProxyCallTranslator() override; - - ProxyCallTranslator& operator=(const ProxyCallTranslator& other) = delete; - - // CmaProxyHandler overrides: - void Initialize( - const std::string& cast_session_id, - CmaProxyHandler::AudioDecoderOperationMode decoder_mode) override; - void Start(int64_t start_pts, - const BufferIdManager::TargetBufferInfo& target_buffer) override; - void Stop() override; - void Pause() override; - void Resume(const BufferIdManager::TargetBufferInfo& target_buffer) override; - void SetPlaybackRate(float rate) override; - void SetVolume(float multiplier) override; - void UpdateTimestamp( - const BufferIdManager::TargetBufferInfo& target_buffer) override; - bool SetConfig(const AudioConfig& config) override; - CmaBackend::BufferStatus PushBuffer( - scoped_refptr buffer, - BufferIdManager::BufferId buffer_id) override; - - private: - friend class ProxyCallTranslatorTest; - - using MediaTime = CastRuntimeAudioChannelBroker::Handler::MediaTime; - using PipelineState = CastRuntimeAudioChannelBroker::Handler::PipelineState; - using PushBufferRequest = - CastRuntimeAudioChannelBroker::Handler::PushBufferRequest; - - ProxyCallTranslator( - TaskRunner* client_task_runner, - CmaProxyHandler::Client* client, - AudioChannelPushBufferHandler::Client* push_buffer_client, - std::unique_ptr decoder_channel); - - // CastRuntimeAudioChannelBroker::Handler overrides: - std::optional GetBufferedData() override; - bool HasBufferedData() override; - void HandleInitializeResponse( - CastRuntimeAudioChannelBroker::StatusCode status) override; - void HandleStateChangeResponse( - PipelineState state, - CastRuntimeAudioChannelBroker::StatusCode status) override; - void HandleSetVolumeResponse( - CastRuntimeAudioChannelBroker::StatusCode status) override; - void HandleSetPlaybackResponse( - CastRuntimeAudioChannelBroker::StatusCode status) override; - void HandlePushBufferResponse( - int64_t decoded_bytes, - CastRuntimeAudioChannelBroker::StatusCode status) override; - void HandleGetMediaTimeResponse( - std::optional time, - CastRuntimeAudioChannelBroker::StatusCode status) override; - - // Helper to share error handling code. - bool HandleError(CastRuntimeAudioChannelBroker::StatusCode status); - - // Helpers to simplify use of callbacks for tasks posted to - // |client_task_runner_|. - void OnErrorTask(); - void OnPipelineStateChangeTask(CmaProxyHandler::PipelineState state); - void OnBytesDecodedTask(int64_t decoded_byte_count); - - std::unique_ptr decoder_channel_; - TaskRunner* const client_task_runner_; - CmaProxyHandler::Client* const client_; - - // Handler to queue up PushBuffer and SetConfig calls. - PushBufferPendingHandler push_buffer_handler_; - - // NOTE: All weak_ptrs created from this factory must be dereferenced on - // |client_task_runner_|. Unfortunately, due to the structure of the - // chromecast::TaskRunner class, weak_ptr validation is not guaranteed so this - // assumption cannot be validated outside of the WeakPtr class. - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PROXY_CALL_TRANSLATOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/proxy_call_translator_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/proxy_call_translator_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/proxy_call_translator_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,355 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/proxy_call_translator.h" - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/test/test_simple_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h" -#include "chromecast/media/cma/backend/proxy/cast_runtime_audio_channel_broker.h" -#include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/stream_id.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -ACTION_P(CompareTimestampInfos, buffer_id, timestamp) { - const CastRuntimeAudioChannelBroker::TimestampInfo& result = arg0; - EXPECT_EQ(result.buffer_id(), buffer_id); - const int64_t micros = - result.system_timestamp().seconds() * base::Time::kMicrosecondsPerSecond + - result.system_timestamp().nanoseconds() / - base::Time::kNanosecondsPerMicrosecond; - EXPECT_EQ(micros, timestamp); -} - -class MockTranslatorClient : public CmaProxyHandler::Client { - public: - ~MockTranslatorClient() override = default; - - MOCK_METHOD0(OnError, void()); - MOCK_METHOD1(OnPipelineStateChange, void(CmaProxyHandler::PipelineState)); - MOCK_METHOD1(OnBytesDecoded, void(int64_t)); - MOCK_METHOD2(OnMediaTimeUpdate, void(int64_t, base::TimeTicks)); - MOCK_METHOD0(OnEndOfStream, void()); -}; - -class MockDecoderChannel : public CastRuntimeAudioChannelBroker { - public: - ~MockDecoderChannel() override = default; - - MOCK_METHOD2( - InitializeAsync, - void(const std::string&, - CastRuntimeAudioChannelBroker::CastAudioDecoderMode decoder_mode)); - MOCK_METHOD1(SetVolumeAsync, void(float)); - MOCK_METHOD1(SetPlaybackAsync, void(double)); - MOCK_METHOD0(GetMediaTimeAsync, void()); - MOCK_METHOD2(StartAsync, - void(int64_t, CastRuntimeAudioChannelBroker::TimestampInfo)); - MOCK_METHOD0(StopAsync, void()); - MOCK_METHOD0(PauseAsync, void()); - MOCK_METHOD1(ResumeAsync, void(CastRuntimeAudioChannelBroker::TimestampInfo)); - MOCK_METHOD1(UpdateTimestampAsync, - void(CastRuntimeAudioChannelBroker::TimestampInfo)); -}; - -class MockPushBufferHandler : public AudioChannelPushBufferHandler::Client { - public: - ~MockPushBufferHandler() override = default; - - MOCK_METHOD1(OnAudioChannelPushBufferComplete, - void(CmaBackend::BufferStatus)); -}; - -} // namespace - -class ProxyCallTranslatorTest : public testing::Test { - public: - ProxyCallTranslatorTest() - : task_runner_(new base::TestSimpleTaskRunner()), - chromecast_task_runner_(task_runner_), - decoder_channel_not_owned_( - std::make_unique>()), - decoder_channel_(decoder_channel_not_owned_.get()), - translator_(&chromecast_task_runner_, - &translator_client_, - &push_buffer_handler_, - std::move(decoder_channel_not_owned_)), - translator_as_handler_( - static_cast( - &translator_)) {} - - ~ProxyCallTranslatorTest() override = default; - - protected: - scoped_refptr task_runner_; - TaskRunnerImpl chromecast_task_runner_; - testing::StrictMock translator_client_; - std::unique_ptr> - decoder_channel_not_owned_; - testing::StrictMock* decoder_channel_; - testing::StrictMock push_buffer_handler_; - - ProxyCallTranslator translator_; - CastRuntimeAudioChannelBroker::Handler* translator_as_handler_; - - const CastRuntimeAudioChannelBroker::StatusCode failure_status_ = - CastRuntimeAudioChannelBroker::StatusCode::kUnknown; - const CastRuntimeAudioChannelBroker::StatusCode success_status_ = - CastRuntimeAudioChannelBroker::StatusCode::kOk; -}; - -TEST_F(ProxyCallTranslatorTest, TestExternalInitialize) { - std::string session_id = "foo"; - EXPECT_CALL( - *decoder_channel_, - InitializeAsync(session_id, cast::media::CAST_AUDIO_DECODER_MODE_ALL)); - translator_.Initialize(session_id, - CmaProxyHandler::AudioDecoderOperationMode::kAll); - - session_id = "bar"; - EXPECT_CALL( - *decoder_channel_, - InitializeAsync(session_id, - cast::media::CAST_AUDIO_DECODER_MODE_MULTIROOM_ONLY)); - translator_.Initialize( - session_id, CmaProxyHandler::AudioDecoderOperationMode::kMultiroomOnly); - - session_id = "foobar"; - EXPECT_CALL(*decoder_channel_, - InitializeAsync(session_id, - cast::media::CAST_AUDIO_DECODER_MODE_AUDIO_ONLY)); - translator_.Initialize( - session_id, CmaProxyHandler::AudioDecoderOperationMode::kAudioOnly); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalStart) { - constexpr int64_t start_pts = 42; - BufferIdManager::TargetBufferInfo target_buffer_info; - static constexpr int64_t timestamp = 112358; - static constexpr BufferIdManager::BufferId buffer_id = 12481516; - target_buffer_info.buffer_id = buffer_id; - target_buffer_info.timestamp_micros = timestamp; - - // TODO(rwkeane): Validate the duration in the StartAsync call. - EXPECT_CALL(*decoder_channel_, StartAsync(start_pts, testing::_)) - .WillOnce( - testing::WithArgs<1>(CompareTimestampInfos(buffer_id, timestamp))); - translator_.Start(start_pts, target_buffer_info); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalStop) { - EXPECT_CALL(*decoder_channel_, StopAsync()); - translator_.Stop(); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalPause) { - EXPECT_CALL(*decoder_channel_, PauseAsync()); - translator_.Pause(); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalResume) { - BufferIdManager::TargetBufferInfo target_buffer_info; - static constexpr int64_t timestamp = 112358; - static constexpr BufferIdManager::BufferId buffer_id = 12481516; - target_buffer_info.buffer_id = buffer_id; - target_buffer_info.timestamp_micros = timestamp; - - EXPECT_CALL(*decoder_channel_, ResumeAsync(testing::_)) - .WillOnce( - testing::WithArgs<0>(CompareTimestampInfos(buffer_id, timestamp))); - translator_.Resume(target_buffer_info); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalUpdateTimestamp) { - BufferIdManager::TargetBufferInfo target_buffer_info; - static constexpr int timestamp = 112358; - static constexpr int buffer_id = 12481516; - target_buffer_info.buffer_id = buffer_id; - target_buffer_info.timestamp_micros = timestamp; - - EXPECT_CALL(*decoder_channel_, UpdateTimestampAsync(testing::_)) - .WillOnce( - testing::WithArgs<0>(CompareTimestampInfos(buffer_id, timestamp))); - translator_.UpdateTimestamp(target_buffer_info); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalSetPlaybackRate) { - constexpr float rate = 42; - EXPECT_CALL(*decoder_channel_, SetPlaybackAsync(rate)); - translator_.SetPlaybackRate(rate); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalSetVolume) { - constexpr float multiplier = 42; - EXPECT_CALL(*decoder_channel_, SetVolumeAsync(multiplier)); - translator_.SetVolume(multiplier); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalPushBuffer) { - scoped_refptr buffer( - new CastDecoderBufferImpl(3, StreamId::kPrimary)); - buffer->writable_data()[0] = 1; - buffer->writable_data()[1] = 2; - buffer->writable_data()[2] = 3; - EXPECT_EQ(translator_.PushBuffer(buffer, 1), - CmaBackend::BufferStatus::kBufferSuccess); - - EXPECT_EQ(translator_.PushBuffer(CastDecoderBufferImpl::CreateEOSBuffer(), 2), - CmaBackend::BufferStatus::kBufferSuccess); - - ASSERT_TRUE(translator_as_handler_->HasBufferedData()); - auto result = translator_as_handler_->GetBufferedData(); - ASSERT_TRUE(result.has_value()); - EXPECT_FALSE(result.value().has_audio_config()); - ASSERT_TRUE(result.value().has_buffer()); - EXPECT_EQ(result.value().buffer().id(), 1); - EXPECT_FALSE(result.value().buffer().end_of_stream()); - EXPECT_EQ(result.value().buffer().data().size(), size_t{3}); - EXPECT_EQ(result.value().buffer().data()[0], 1); - EXPECT_EQ(result.value().buffer().data()[1], 2); - EXPECT_EQ(result.value().buffer().data()[2], 3); - - ASSERT_TRUE(translator_as_handler_->HasBufferedData()); - result = translator_as_handler_->GetBufferedData(); - ASSERT_TRUE(result.has_value()); - EXPECT_FALSE(result.value().has_audio_config()); - ASSERT_TRUE(result.value().has_buffer()); - EXPECT_EQ(result.value().buffer().id(), 2); - EXPECT_TRUE(result.value().buffer().end_of_stream()); - EXPECT_EQ(result.value().buffer().data().size(), size_t{0}); -} - -TEST_F(ProxyCallTranslatorTest, TestExternalSetConfig) { - AudioConfig config; - config.codec = AudioCodec::kCodecPCM; - config.channel_layout = ChannelLayout::SURROUND_5_1; - config.sample_format = SampleFormat::kSampleFormatPlanarS16; - config.bytes_per_channel = 42; - config.channel_number = 5; - config.samples_per_second = 5000; - config.extra_data = {1, 2, 3}; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - - EXPECT_TRUE(translator_.SetConfig(config)); - - ASSERT_TRUE(translator_as_handler_->HasBufferedData()); - auto result = translator_as_handler_->GetBufferedData(); - ASSERT_TRUE(result.has_value()); - EXPECT_FALSE(result.value().has_buffer()); - ASSERT_TRUE(result.value().has_audio_config()); - EXPECT_EQ(result.value().audio_config().codec(), - cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_PCM); - EXPECT_EQ(result.value().audio_config().channel_layout(), - cast::media:: - AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_SURROUND_5_1); - EXPECT_EQ( - result.value().audio_config().sample_format(), - cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_S16); - EXPECT_EQ(result.value().audio_config().bytes_per_channel(), - config.bytes_per_channel); - EXPECT_EQ(result.value().audio_config().channel_number(), - config.channel_number); - EXPECT_EQ(result.value().audio_config().samples_per_second(), - config.samples_per_second); - EXPECT_EQ(result.value().audio_config().extra_data().size(), - config.extra_data.size()); - EXPECT_EQ(result.value().audio_config().extra_data()[0], - config.extra_data[0]); - EXPECT_EQ(result.value().audio_config().extra_data()[1], - config.extra_data[1]); - EXPECT_EQ(result.value().audio_config().extra_data()[2], - config.extra_data[2]); -} - -TEST_F(ProxyCallTranslatorTest, TestInternalHandleInitializeFailure) { - EXPECT_CALL(translator_client_, OnError()); - translator_as_handler_->HandleInitializeResponse(failure_status_); - task_runner_->RunPendingTasks(); -} - -TEST_F(ProxyCallTranslatorTest, TestHandleStateChangeFailure) { - EXPECT_CALL(translator_client_, OnError()); - translator_as_handler_->HandleStateChangeResponse( - CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_UNINITIALIZED, - failure_status_); - task_runner_->RunPendingTasks(); -} - -TEST_F(ProxyCallTranslatorTest, TestHandleSetVolumeFailure) { - EXPECT_CALL(translator_client_, OnError()); - translator_as_handler_->HandleSetVolumeResponse(failure_status_); - task_runner_->RunPendingTasks(); -} - -TEST_F(ProxyCallTranslatorTest, TesSetPlaybackFailure) { - EXPECT_CALL(translator_client_, OnError()); - translator_as_handler_->HandleSetPlaybackResponse(failure_status_); - task_runner_->RunPendingTasks(); -} - -TEST_F(ProxyCallTranslatorTest, TestPushBufferFailure) { - EXPECT_CALL(translator_client_, OnError()); - translator_as_handler_->HandlePushBufferResponse(42, failure_status_); - task_runner_->RunPendingTasks(); -} - -TEST_F(ProxyCallTranslatorTest, TestStateChangeSuccess) { - EXPECT_CALL( - translator_client_, - OnPipelineStateChange(CmaProxyHandler::PipelineState::kUninitialized)); - translator_as_handler_->HandleStateChangeResponse( - CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_UNINITIALIZED, - success_status_); - task_runner_->RunPendingTasks(); - - EXPECT_CALL(translator_client_, - OnPipelineStateChange(CmaProxyHandler::PipelineState::kStopped)); - translator_as_handler_->HandleStateChangeResponse( - CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_STOPPED, - success_status_); - task_runner_->RunPendingTasks(); - - EXPECT_CALL(translator_client_, - OnPipelineStateChange(CmaProxyHandler::PipelineState::kPlaying)); - translator_as_handler_->HandleStateChangeResponse( - CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_PLAYING, - success_status_); - task_runner_->RunPendingTasks(); - - EXPECT_CALL(translator_client_, - OnPipelineStateChange(CmaProxyHandler::PipelineState::kPaused)); - translator_as_handler_->HandleStateChangeResponse( - CastRuntimeAudioChannelBroker::Handler::PipelineState:: - PIPELINE_STATE_PAUSED, - success_status_); - task_runner_->RunPendingTasks(); -} - -TEST_F(ProxyCallTranslatorTest, TestPushBufferSuccess) { - EXPECT_CALL(translator_client_, OnBytesDecoded(42)); - translator_as_handler_->HandlePushBufferResponse(42, success_status_); - task_runner_->RunPendingTasks(); - - EXPECT_CALL(translator_client_, OnBytesDecoded(112358)); - translator_as_handler_->HandlePushBufferResponse(112358, success_status_); - task_runner_->RunPendingTasks(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,131 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h" - -#include - -#include "base/functional/callback.h" -#include "chromecast/media/cma/backend/proxy/push_buffer_queue.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/task_runner.h" - -namespace chromecast { -namespace media { -namespace { - -constexpr uint64_t kDelayBetweenDataPushAttemptsInMs = 10; - -} // namespace - -PushBufferPendingHandler::PushBufferPendingHandler( - TaskRunner* task_runner, - AudioChannelPushBufferHandler::Client* client) - : PushBufferPendingHandler(task_runner, - client, - std::make_unique()) {} - -PushBufferPendingHandler::PushBufferPendingHandler( - TaskRunner* task_runner, - AudioChannelPushBufferHandler::Client* client, - std::unique_ptr handler) - : delegated_handler_(std::move(handler)), - client_(client), - task_runner_(task_runner), - weak_factory_(this) { - DCHECK(delegated_handler_.get()); - DCHECK(client_); - DCHECK(task_runner_); -} - -PushBufferPendingHandler::~PushBufferPendingHandler() = default; - -CmaBackend::BufferStatus PushBufferPendingHandler::PushBuffer( - const PushBufferRequest& request) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - // Try and push the data to |delegated_handler_|. - if (!IsCallPending()) { - auto delegated_result = delegated_handler_->PushBuffer(request); - if (delegated_result != CmaBackend::BufferStatus::kBufferFailed) { - return delegated_result; - } - } - - // Store the request to be processed later, and schedule that processing if it - // isn't scheduled already. - const bool had_data = IsCallPending(); - - if (request.has_buffer()) { - DCHECK(!has_push_buffer_queued_); - has_push_buffer_queued_ = true; - } - - pushed_data_.push(std::move(request)); - - if (!had_data) { - ScheduleDataPush(); - } - - return CmaBackend::BufferStatus::kBufferPending; -} - -bool PushBufferPendingHandler::HasBufferedData() const { - // The pending data is only considered by the producer sequence, so this - // consumer sequence call does not consider it. - return delegated_handler_->HasBufferedData(); -} - -std::optional -PushBufferPendingHandler::GetBufferedData() { - // The pending data is only considered by the producer sequence, so this - // consumer sequence call does not consider it. - return delegated_handler_->GetBufferedData(); -} - -bool PushBufferPendingHandler::IsCallPending() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - return !pushed_data_.empty(); -} - -void PushBufferPendingHandler::TryPushPendingData() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - // Process as much - for (auto push_result = CmaBackend::BufferStatus::kBufferSuccess; - push_result == CmaBackend::BufferStatus::kBufferSuccess && - IsCallPending();) { - push_result = delegated_handler_->PushBuffer(pushed_data_.front()); - - if (push_result != CmaBackend::BufferStatus::kBufferFailed) { - // If we removed the buffer containing data from a PushBuffer() call, - // update the associated variable. - if (pushed_data_.front().has_buffer()) { - DCHECK(has_push_buffer_queued_); - has_push_buffer_queued_ = false; - } - - // If we didn't fail, pop the front element. - pushed_data_.pop(); - } - } - - if (IsCallPending()) { - ScheduleDataPush(); - } else { - client_->OnAudioChannelPushBufferComplete( - CmaBackend::BufferStatus::kBufferSuccess); - } -} - -void PushBufferPendingHandler::ScheduleDataPush() { - auto* task = new TaskRunner::CallbackTask( - base::BindOnce(&PushBufferPendingHandler::TryPushPendingData, - weak_factory_.GetWeakPtr())); - task_runner_->PostTask(task, kDelayBetweenDataPushAttemptsInMs); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_PENDING_HANDLER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_PENDING_HANDLER_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h" -#include "chromecast/media/cma/backend/proxy/buffer_id_manager.h" - -namespace chromecast { - -class TaskRunner; - -namespace media { - -// Utility to queue up PushBuffer() and SetConfig() calls to be made -// asynchronously at a later time, when a synchronous call is not possible. -// -// Per the CmaBackend::Decoder::PushBuffer() method signature, an implementing -// class must continue to accept new buffers until returning the kBufferPending -// response, which then acts as a flow control mechanism. In some -// implementations of AudioChannelPushBufferHandler, kBufferPending is not a -// possible response code, so this class acts as a utility to add that -// functionality. Upon a failed PushBuffer call to the delegated instance, -// this class will call back asynchronously, either resulting in a successful -// push or retrying again at a later time. -// -// This class stores: -// - All AudioConfigs set while the underlying AudioChannelPushBufferHandler is -// blocked. -// - A single PushBuffer call associated with the kBufferPending return value. -// Once any data is stored, it queues up a task on the task runner to try to -// call the associated function at a later time. -class PushBufferPendingHandler : public AudioChannelPushBufferHandler { - public: - // |task_runner| and |client| must persist for the lifetime of this instance. - PushBufferPendingHandler(TaskRunner* task_runner, - AudioChannelPushBufferHandler::Client* client); - ~PushBufferPendingHandler() override; - - // Returns whether or not this instance contains any data waiting to be sent - // at a later point. - bool IsCallPending() const; - - // AudioChannelPushBufferHandler overrides. - // - // Note that the pending data is considered only for the PushBuffer() call, as - // it is only understood by the PRODUCER sequence. The CONSUMER sequence is - // not aware of its existence, so the remaining methods will not consider it. - CmaBackend::BufferStatus PushBuffer( - const PushBufferRequest& request) override; - bool HasBufferedData() const override; - std::optional GetBufferedData() override; - - private: - friend class PushBufferPendingHandlerTest; - - PushBufferPendingHandler( - TaskRunner* task_runner, - AudioChannelPushBufferHandler::Client* client, - std::unique_ptr handler); - - // Attempts to push any pending data to |client_|, scheduling another call to - // itself if any further pending data remains. - void TryPushPendingData(); - - // Schedules a call to TryPushPendingData() in the future. - void ScheduleDataPush(); - - // The AudioChannelPushBufferHandler to which calls to this instance's methods - // should be delegated. - std::unique_ptr delegated_handler_; - - // Client to use for callbacks. - AudioChannelPushBufferHandler::Client* client_; - - // All data which has been pushed to this instance and not yet processed by - // |delegated_handler_|. - std::queue pushed_data_; - - // Signifies whether there is a buffer containing data from a PushBuffer() - // call in the queue (of which there may only be one). - bool has_push_buffer_queued_ = false; - - TaskRunner* const task_runner_; - - SEQUENCE_CHECKER(sequence_checker_); - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_PENDING_HANDLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_pending_handler_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_pending_handler_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_pending_handler_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,258 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/proxy/push_buffer_pending_handler.h" - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "base/test/test_simple_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h" -#include "chromecast/public/media/decoder_config.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using testing::_; -using testing::DoAll; -using testing::Return; -using testing::WithArgs; - -ACTION_P(ComparePushBuffers, expected) { - const AudioChannelPushBufferHandler::PushBufferRequest& result = arg0; - - ASSERT_EQ(expected.has_buffer(), result.has_buffer()); - ASSERT_EQ(expected.has_audio_config(), result.has_audio_config()); - - if (expected.has_buffer()) { - EXPECT_EQ(expected.buffer().pts_micros(), result.buffer().pts_micros()); - EXPECT_EQ(expected.buffer().data(), result.buffer().data()); - EXPECT_EQ(expected.buffer().end_of_stream(), - result.buffer().end_of_stream()); - EXPECT_EQ(expected.buffer().id(), result.buffer().id()); - } - - if (expected.has_audio_config()) { - EXPECT_EQ(expected.audio_config().codec(), result.audio_config().codec()); - EXPECT_EQ(expected.audio_config().channel_layout(), - result.audio_config().channel_layout()); - EXPECT_EQ(expected.audio_config().sample_format(), - result.audio_config().sample_format()); - EXPECT_EQ(expected.audio_config().bytes_per_channel(), - result.audio_config().bytes_per_channel()); - EXPECT_EQ(expected.audio_config().channel_number(), - result.audio_config().channel_number()); - EXPECT_EQ(expected.audio_config().samples_per_second(), - result.audio_config().samples_per_second()); - EXPECT_EQ(expected.audio_config().extra_data(), - result.audio_config().extra_data()); - } -} - -class MockClient : public AudioChannelPushBufferHandler::Client { - public: - ~MockClient() override = default; - - MOCK_METHOD1(OnAudioChannelPushBufferComplete, - void(CmaBackend::BufferStatus)); -}; - -class MockHandler : public AudioChannelPushBufferHandler { - public: - ~MockHandler() override = default; - - MOCK_METHOD1(PushBuffer, CmaBackend::BufferStatus(const PushBufferRequest&)); - MOCK_CONST_METHOD0(HasBufferedData, bool()); - MOCK_METHOD0(GetBufferedData, std::optional()); -}; - -} // namespace - -class PushBufferPendingHandlerTest : public testing::Test { - public: - PushBufferPendingHandlerTest() - : task_runner_(new base::TestSimpleTaskRunner()), - chromecast_task_runner_(task_runner_), - handler_temp_storage( - std::make_unique>()), - handler_(handler_temp_storage.get()), - push_buffer_helper_(&chromecast_task_runner_, - &client_, - std::move(handler_temp_storage)) { - buffer_.mutable_buffer()->set_pts_micros(3); - buffer_.mutable_buffer()->set_id(42); - - second_buffer_.mutable_buffer()->set_pts_micros(7); - second_buffer_.mutable_buffer()->set_id(24); - - config_before_.mutable_audio_config()->set_channel_number(42); - - config_after_.mutable_audio_config()->set_channel_number(124815); - } - - ~PushBufferPendingHandlerTest() override = default; - - protected: - scoped_refptr task_runner_; - TaskRunnerImpl chromecast_task_runner_; - testing::StrictMock client_; - std::unique_ptr> handler_temp_storage; - testing::StrictMock* handler_; - PushBufferPendingHandler push_buffer_helper_; - - AudioChannelPushBufferHandler::PushBufferRequest buffer_; - AudioChannelPushBufferHandler::PushBufferRequest second_buffer_; - AudioChannelPushBufferHandler::PushBufferRequest config_before_; - AudioChannelPushBufferHandler::PushBufferRequest config_after_; -}; - -TEST_F(PushBufferPendingHandlerTest, PushBufferPassesThroughCorrectly) { - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(buffer_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))); - - EXPECT_EQ(push_buffer_helper_.PushBuffer(buffer_), - CmaBackend::BufferStatus::kBufferSuccess); - EXPECT_FALSE(push_buffer_helper_.IsCallPending()); - - task_runner_->RunUntilIdle(); -} - -TEST_F(PushBufferPendingHandlerTest, CallsPassThroughCorrectly) { - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferFailed))); - EXPECT_EQ(push_buffer_helper_.PushBuffer(config_before_), - CmaBackend::BufferStatus::kBufferPending); - EXPECT_EQ(push_buffer_helper_.PushBuffer(buffer_), - CmaBackend::BufferStatus::kBufferPending); - EXPECT_EQ(push_buffer_helper_.PushBuffer(config_after_), - CmaBackend::BufferStatus::kBufferPending); - - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(buffer_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferFailed))); - task_runner_->RunPendingTasks(); - - EXPECT_EQ(push_buffer_helper_.PushBuffer(second_buffer_), - CmaBackend::BufferStatus::kBufferPending); - EXPECT_CALL(client_, OnAudioChannelPushBufferComplete( - CmaBackend::BufferStatus::kBufferSuccess)); - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(second_buffer_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))); - task_runner_->RunUntilIdle(); -} - -TEST_F(PushBufferPendingHandlerTest, CallsContinueTryingUntilSuccessful) { - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferFailed))); - EXPECT_EQ(push_buffer_helper_.PushBuffer(config_before_), - CmaBackend::BufferStatus::kBufferPending); - EXPECT_EQ(push_buffer_helper_.PushBuffer(buffer_), - CmaBackend::BufferStatus::kBufferPending); - EXPECT_EQ(push_buffer_helper_.PushBuffer(config_after_), - CmaBackend::BufferStatus::kBufferPending); - - EXPECT_CALL(client_, OnAudioChannelPushBufferComplete( - CmaBackend::BufferStatus::kBufferSuccess)); - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(buffer_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(buffer_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(buffer_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(buffer_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferFailed))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))); - task_runner_->RunUntilIdle(); -} - -TEST_F(PushBufferPendingHandlerTest, - CallingSetConfigMultipleTimesBeforePushWorks) { - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferFailed))); - - EXPECT_EQ(push_buffer_helper_.PushBuffer(config_before_), - CmaBackend::BufferStatus::kBufferPending); - EXPECT_EQ(push_buffer_helper_.PushBuffer(config_after_), - CmaBackend::BufferStatus::kBufferPending); - - EXPECT_TRUE(push_buffer_helper_.IsCallPending()); - - EXPECT_CALL(client_, OnAudioChannelPushBufferComplete( - CmaBackend::BufferStatus::kBufferSuccess)); - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))); - task_runner_->RunUntilIdle(); - - EXPECT_FALSE(push_buffer_helper_.IsCallPending()); -} - -TEST_F(PushBufferPendingHandlerTest, - CallingSetConfigMultipleTimesAfterPushWorks) { - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(buffer_)), - Return(CmaBackend::BufferStatus::kBufferFailed))); - - EXPECT_EQ(push_buffer_helper_.PushBuffer(buffer_), - CmaBackend::BufferStatus::kBufferPending); - EXPECT_EQ(push_buffer_helper_.PushBuffer(config_before_), - CmaBackend::BufferStatus::kBufferPending); - EXPECT_EQ(push_buffer_helper_.PushBuffer(config_after_), - CmaBackend::BufferStatus::kBufferPending); - - EXPECT_CALL(client_, OnAudioChannelPushBufferComplete( - CmaBackend::BufferStatus::kBufferSuccess)); - EXPECT_CALL(*handler_, PushBuffer(_)) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(buffer_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_before_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))) - .WillOnce(DoAll(WithArgs<0>(ComparePushBuffers(config_after_)), - Return(CmaBackend::BufferStatus::kBufferSuccess))); - - task_runner_->RunUntilIdle(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_queue.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_queue.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,277 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/push_buffer_queue.h" - -#include - -#include "base/notreached.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "third_party/protobuf/src/google/protobuf/util/delimited_message_util.h" - -namespace chromecast { -namespace media { -namespace { - -// The number of consecutive failed read attempts before the buffer is -// determined to be in an invalid state. -int kMaximumFailedReadAttempts = 10; - -// The maximum size of a read/write window used by the underlying buffer. This -// is the maximum size of the array which will be cached for upcoming use. -// size_t type is used here to simplify comparison logic later on. -size_t kWindowSizeBytes = 32; - -} // namespace - -// static -constexpr size_t PushBufferQueue::kBufferSizeBytes; - -PushBufferQueue::PushBufferQueue() - : producer_handler_(this), - consumer_handler_(this), - consumer_stream_(std::in_place, &consumer_handler_), - protobuf_consumer_stream_(std::in_place, &consumer_stream_.value(), 1), - producer_stream_(std::in_place, &producer_handler_) { - DETACH_FROM_SEQUENCE(producer_sequence_checker_); - DETACH_FROM_SEQUENCE(consumer_sequence_checker_); -} - -PushBufferQueue::~PushBufferQueue() = default; - -CmaBackend::BufferStatus PushBufferQueue::PushBuffer( - const PushBufferRequest& request) { - auto success = PushBufferImpl(request); - if (success) { - producer_handler_.ApplyNewBytesWritten(); - } - - return success ? CmaBackend::BufferStatus::kBufferSuccess - : CmaBackend::BufferStatus::kBufferFailed; -} - -bool PushBufferQueue::PushBufferImpl(const PushBufferRequest& request) { - DCHECK_CALLED_ON_VALID_SEQUENCE(producer_sequence_checker_); - - bytes_written_during_current_write_ = 0; - - // NOTE: This method is used instead of SerializeDelimitedToZeroCopyStream() - // due to bugs in the method's implementation. See b/173477672. - DCHECK(producer_stream_.has_value()); - bool success = google::protobuf::util::SerializeDelimitedToOstream( - request, &producer_stream_.value()); - - if (success) { - producer_handler_.overflow(); - } else { - // Now the stream is in a bad state, so recreate it. This should only occur - // when the entire |buffer_| is full at time of writing. - bytes_written_during_current_write_ = 0; - producer_handler_.overflow(); - producer_stream_ = std::nullopt; - producer_stream_.emplace(&producer_handler_); - } - - return success; -} - -bool PushBufferQueue::HasBufferedData() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(consumer_sequence_checker_); - return !is_in_invalid_state_ && GetAvailableyByteCount() != size_t{0}; -} - -std::optional -PushBufferQueue::GetBufferedData() { - auto result = GetBufferedDataImpl(); - if (result.has_value()) { - consumer_handler_.ApplyNewBytesRead(); - } - - return result; -} - -std::optional -PushBufferQueue::GetBufferedDataImpl() { - DCHECK_CALLED_ON_VALID_SEQUENCE(consumer_sequence_checker_); - DCHECK(HasBufferedData()); - - bytes_read_during_current_read_ = 0; - PushBufferRequest request; - - DCHECK(protobuf_consumer_stream_.has_value()); - bool succeeded = google::protobuf::util::ParseDelimitedFromZeroCopyStream( - &request, &protobuf_consumer_stream_.value(), nullptr /* clean_eof */); - - // This case will only occur in one of the following cases: - // - Reading a PushBuffer at the same time it is being written. - // - An error occurs while reading from the stream (specifically, a PushBuffer - // was serialized incorrectly). - // The former case is not expected to occur, but is handled to be safe. - // The latter case is only expected if the buffer is written to when not - // enough space is available to handle the new write. - if (!succeeded) { - consecuitive_read_failures_++; - if (+consecuitive_read_failures_ > kMaximumFailedReadAttempts) { - // This means that data was probably serialized incorrectly. - is_in_invalid_state_ = true; - } - - // Reset the read pointers so that future reads re-read the old data. - bytes_read_during_current_read_ = 0; - consumer_handler_.ResetReadPointers(); - - // If |!succeeded|, the streams have ended up in an unexpected state and - // need to be recreated. - protobuf_consumer_stream_ = std::nullopt; - consumer_stream_ = std::nullopt; - consumer_stream_.emplace(&consumer_handler_); - protobuf_consumer_stream_.emplace(&consumer_stream_.value(), 1); - - return std::nullopt; - } - - consecuitive_read_failures_ = 0; - - return request; -} - -int PushBufferQueue::GetAvailableyByteCount() const { - const int total_bytes_read = - bytes_read_so_far_.load(std::memory_order_relaxed) + - consumer_handler_.GetReadOffset(); - const int total_bytes_written = - bytes_written_so_far_.load(std::memory_order_relaxed); - return total_bytes_written - total_bytes_read; -} - -PushBufferQueue::ProducerHandler::ProducerHandler(PushBufferQueue* queue) - : queue_(queue) { - DCHECK(queue_); -} - -PushBufferQueue::ProducerHandler::~ProducerHandler() = default; - -int PushBufferQueue::ProducerHandler::overflow(int ch) { - // Get the number of bytes read and written so far. - const size_t current_read_bytes = - queue_->bytes_read_so_far_.load(std::memory_order_acquire); - const int currently_written_bytes = UpdateBytesWritten(); - DCHECK_GE(static_cast(currently_written_bytes), current_read_bytes); - - // Calculates the current size of the buffer. - const size_t bytes_currently_used = - currently_written_bytes - current_read_bytes; - DCHECK_LE(bytes_currently_used, kBufferSizeBytes); - - // Calculates the number of bytes that should be included in the next write - // window, which is the least of: - // - |kWindowSizeBytes| - // - The number that can be written before wrapping around to the beginning of - // the underlying array, - // - The number of bytes available before the current read pointer. - const size_t current_write_index = currently_written_bytes % kBufferSizeBytes; - const size_t available_writable_bytes = - std::min(kBufferSizeBytes - current_write_index, - current_read_bytes + kBufferSizeBytes - currently_written_bytes); - const size_t new_window_size = - std::min(kWindowSizeBytes, available_writable_bytes); - - // If there is no writable area, then return a special value per method - // contact. - if (new_window_size == 0) { - setp(epptr(), epptr()); - return std::char_traits::eof(); - } - - // Update the pointers that determine the writable area and write the given - // value |ch| if one was given. - setp(&queue_->buffer_[current_write_index], - &queue_->buffer_[current_write_index + new_window_size]); - const bool should_write_ch = (ch != std::char_traits::eof()); - if (should_write_ch) { - sputc(static_cast(ch)); - } - return 1; // This can be any value except std::char_traits::eof(). -} - -void PushBufferQueue::ProducerHandler::ApplyNewBytesWritten() { - queue_->bytes_written_so_far_.fetch_add( - queue_->bytes_written_during_current_write_, std::memory_order_relaxed); - queue_->bytes_written_during_current_write_ = 0; -} - -size_t PushBufferQueue::ProducerHandler::UpdateBytesWritten() { - const int change_in_write_count = pptr() - pbase(); - DCHECK_GE(change_in_write_count, 0); - queue_->bytes_written_during_current_write_ += change_in_write_count; - return queue_->bytes_written_so_far_.load(std::memory_order_relaxed) + - queue_->bytes_written_during_current_write_; -} - -PushBufferQueue::ConsumerHandler::ConsumerHandler(PushBufferQueue* queue) - : queue_(queue) { - DCHECK(queue_); -} - -PushBufferQueue::ConsumerHandler::~ConsumerHandler() = default; - -int PushBufferQueue::ConsumerHandler::underflow() { - // Get the written and read bytes. - const size_t currently_written_bytes = - queue_->bytes_written_so_far_.load(std::memory_order_acquire); - const size_t current_read_bytes = UpdateBytesRead(); - DCHECK_GE(currently_written_bytes, current_read_bytes); - - // Stop reading at either the end of the array or the current write index, - // whichever is sooner. While there may be more data wrapped around after the - // end of the array, that can be handled as part of the next underflow() call. - const size_t avail = currently_written_bytes - current_read_bytes; - const size_t begin = current_read_bytes % kBufferSizeBytes; - const size_t end = std::min(begin + avail, kBufferSizeBytes); - const size_t new_window_size = std::min(end - begin, kWindowSizeBytes); - - // This means that there are no bytes left to read. Return a special value per - // method contract. - if (new_window_size == 0) { - return std::char_traits::eof(); - } - - // Otherwise, there is still readable data. Update the readable window and - // return the current character per method contact. Because - // std::char_traits::eof() is a special return code, cast to a uint to - // avoid all negative results (EOF is guaranteed to be negative by the stl). - DCHECK_LE(current_read_bytes + new_window_size, currently_written_bytes); - setg(&queue_->buffer_[begin], &queue_->buffer_[begin], - &queue_->buffer_[begin + new_window_size]); - return static_cast(queue_->buffer_[begin]); -} - -void PushBufferQueue::ConsumerHandler::ResetReadPointers() { - const size_t begin = - queue_->bytes_read_so_far_.load(std::memory_order_relaxed) % - kBufferSizeBytes; - setg(&queue_->buffer_[begin], &queue_->buffer_[begin], - &queue_->buffer_[begin]); -} - -void PushBufferQueue::ConsumerHandler::ApplyNewBytesRead() { - queue_->bytes_read_so_far_.fetch_add(queue_->bytes_read_during_current_read_, - std::memory_order_relaxed); - queue_->bytes_read_during_current_read_ = 0; -} - -size_t PushBufferQueue::ConsumerHandler::UpdateBytesRead() { - const int change_in_read_count = GetReadOffset(); - DCHECK_GE(change_in_read_count, 0); - queue_->bytes_read_during_current_read_ += change_in_read_count; - return queue_->bytes_read_so_far_.load(std::memory_order_relaxed) + - queue_->bytes_read_during_current_read_; -} - -int PushBufferQueue::ConsumerHandler::GetReadOffset() const { - return gptr() - eback(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_queue.h chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_queue.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,184 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_QUEUE_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_QUEUE_H_ - -#include -#include -#include -#include - -#include "base/sequence_checker.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/backend/proxy/audio_channel_push_buffer_handler.h" -#include "third_party/cast_core/public/src/proto/runtime/cast_audio_channel_service.pb.h" -#include "third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.h" - -namespace chromecast { -namespace media { - -struct AudioConfig; - -// This class is responsible for buffering both DecoderBuffer and AudioConfig -// data, which are pushed together over gRPC using the PushData() API call. -// Two sequences are expected to simultaneously access this object: -// - A PRODUCER sequence, which will push new data in. -// - A CONSUMER sequence which will pull this data back out of the data -// structure. -// -// This is achieved through serializing this protobuf into bytes, then storing -// these bytes in a lockless FIFO. -class PushBufferQueue : public AudioChannelPushBufferHandler { - public: - // The amount of space to allocate in the buffer. - static constexpr size_t kBufferSizeBytes = 0x01 << 12; // 4 kB. - - PushBufferQueue(); - PushBufferQueue(const PushBufferQueue& other) = delete; - - ~PushBufferQueue() override; - - PushBufferQueue& operator=(const PushBufferQueue& other) = delete; - - // AudioChannelPushBufferHandler overrides. - CmaBackend::BufferStatus PushBuffer( - const PushBufferRequest& request) override; - bool HasBufferedData() const override; - std::optional GetBufferedData() override; - - private: - // These classes exist for the following 2 reasons: - // 1) Readability. Separating of the Read and Write methods is simpler - // 2) Thread safety guarantees. The stl provides no guarantees of thread - // safety within a single instance of std::basic_streambuf, even - // though there should be no overlap between the resources used by both. - // In an ideal world, this functionality could all live in the - // |PushBufferQueue| class. - // - // The approach used by basic_streambuf is to maintain a 'window' on the data - // from which it reads/writes. When the window runs out, underflow() or read - // or overflow() for write is called to get the next window. - // These allow this class to be used as a thread-safe circular read/write - // buffer by input and output streams, as required for use with protobuf - // serialization and deserialization utilities. - // - // Methods in |ProducerHandler| may only be called from the PRODUCER. - class ProducerHandler : public std::basic_streambuf { - public: - explicit ProducerHandler(PushBufferQueue* queue); - ~ProducerHandler() override; - - // std::basic_streambuf overrides: - int overflow(int ch = std::char_traits::eof()) override; - - // Stores the new value of |bytes_written_so_far_| following a successful - // write. - void ApplyNewBytesWritten(); - - private: - // Updates |bytes_written_during_current_write_| and returns the total - // number of bytes written including these new bytes. - size_t UpdateBytesWritten(); - - PushBufferQueue* const queue_; - }; - - // Methods in |ConsumerHandler| may only be called from the CONSUMER. - class ConsumerHandler : public std::basic_streambuf { - public: - explicit ConsumerHandler(PushBufferQueue* queue); - ~ConsumerHandler() override; - - // std::basic_streambuf overrides: - int underflow() override; - - // Returns the number of bytes that have been read so far but not accounted - // for by |queue_->bytes_read_so_far_|. - int GetReadOffset() const; - - // Resets the get area for this streambuf to start at the location pointed - // to by |bytes_read_so_far_| and configures the stream to call underflow() - // during its next read. - void ResetReadPointers(); - - // Stores the new value of |bytes_read_so_far_| following a successful read. - void ApplyNewBytesRead(); - - private: - // Updates |bytes_read_during_current_read_| and returns the total number of - // bytes read including these new bytes. - size_t UpdateBytesRead(); - - PushBufferQueue* const queue_; - }; - - // Friend declaration is needed to test some edge cases that can be hit when - // simultaneous reads and writes are ongoing. - friend class PushBufferQueueTests; - - // Give access to helper types. - friend class ProducerHandler; - friend class ConsumerHandler; - - // Gets the number of buffered bytes. May only be called from the CONSUMER. - int GetAvailableyByteCount() const; - - // Helper methods to be used for test hooks. - bool PushBufferImpl(const PushBufferRequest& request); - std::optional GetBufferedDataImpl(); - - // Buffer where serialized PushBufferRequest data is stored. - char buffer_[kBufferSizeBytes]; - - // Total number of bytes read or written by completed operations so far. - // Atomics are used both to ensure that read and write operations are atomic - // on all systems and to ensure that different values for these values aren't - // loaded from each CPU's physical cache. Size_t types are used intentionally - // to allow for wrap-around. - std::atomic_size_t bytes_read_so_far_{0}; - std::atomic_size_t bytes_written_so_far_{0}; - - // The number of bytes read during the current GetBufferedData() call. This is - // necessary due to internal details of how an IstreamInputStream handles - // end-of-stream conditions. May only be accessed or modified by the - // CONSUMER. - int bytes_read_during_current_read_ = 0; - - // The number of bytes written during the current PushBuffer call. This helps - // to prevent reads of PushBuffer instances currently being written. May only - // be accessed by the PRODUCER. - int bytes_written_during_current_write_ = 0; - - // Tracks whether this buffer is in a valid state for further reads to occur. - // May only be used by the CONSUMER. - int consecuitive_read_failures_ = 0; - bool is_in_invalid_state_ = false; - - // Helpers for keeping CONSUMER and PRODUCER sequences independent. - ProducerHandler producer_handler_; - ConsumerHandler consumer_handler_; - - // Sequence checkers for thread safety validation: - SEQUENCE_CHECKER(producer_sequence_checker_); - SEQUENCE_CHECKER(consumer_sequence_checker_); - - // Input streams backed by this instance. They must be optional so that they - // can be re-created following a failed read. These should only be used by the - // CONSUMER. - std::optional consumer_stream_; - std::optional - protobuf_consumer_stream_; - - // Output stream backed by this instance. This must be optional so it can be - // re-created following a failed write. It should only be used by the - // PRODUCER. - std::optional producer_stream_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_PROXY_PUSH_BUFFER_QUEUE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_queue_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/proxy/push_buffer_queue_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/proxy/push_buffer_queue_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,343 +0,0 @@ -// 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 "chromecast/media/cma/backend/proxy/push_buffer_queue.h" - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/threading/thread.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/cast_core/public/src/proto/runtime/cast_audio_channel_service.grpc.pb.h" - -namespace chromecast { -namespace media { - -class PushBufferQueueTests : public testing::Test { - public: - PushBufferQueueTests() - : first_audio_buffer_(CreateAudioBufferRequest(0, false, 1, 2, 255)), - second_audio_buffer_(CreateAudioBufferRequest(2, false, 6, 4, 2, 0)), - third_audio_buffer_( - CreateAudioBufferRequest(4, true, 0, 1, 1, 2, 3, 5, 8)), - fourth_audio_buffer_( - CreateAudioBufferRequest(42, true, 4, 8, 15, 16, 23, 42)), - fifth_audio_buffer_(CreateAudioBufferRequest(1, false)) { - std::vector extra_data{0, 1, 7, 127, 255}; - - auto* config = new cast::media::AudioConfiguration; - config->set_codec( - cast::media::AudioConfiguration_AudioCodec_AUDIO_CODEC_MP3); - config->set_channel_layout( - cast::media:: - AudioConfiguration_ChannelLayout_CHANNEL_LAYOUT_SURROUND_5_1); - config->set_sample_format( - cast::media::AudioConfiguration_SampleFormat_SAMPLE_FORMAT_PLANAR_S32); - config->set_bytes_per_channel(42); - config->set_channel_number(-1); - config->set_samples_per_second(112358); - config->set_extra_data(extra_data.data(), extra_data.size()); - - first_audio_config_.set_allocated_audio_config(config); - } - - void ReadData(const std::string& name, - const PushBufferQueue::PushBufferRequest& target_buffer) { - ASSERT_TRUE(queue_.HasBufferedData()) << name; - std::optional get = queue_.GetBufferedData(); - ASSERT_TRUE(get.has_value()) << name; - CheckEqual("first", get.value(), target_buffer); - } - - protected: - using PushBufferRequest = PushBufferQueue::PushBufferRequest; - using AudioDecoderBuffer = cast::media::AudioDecoderBuffer; - - template - static PushBufferRequest CreateAudioBufferRequest(int64_t pts_micros, - bool end_of_stream, - TData... data) { - return CreateAudioBufferRequest( - pts_micros, end_of_stream, - std::vector{static_cast(data)...}); - } - - static PushBufferRequest CreateAudioBufferRequest( - int64_t pts_micros, - bool end_of_stream, - std::vector data_vector) { - PushBufferRequest request; - auto* audio_buffer = new AudioDecoderBuffer; - audio_buffer->set_pts_micros(pts_micros); - audio_buffer->set_end_of_stream(end_of_stream); - audio_buffer->set_data(data_vector.data(), data_vector.size()); - - request.set_allocated_buffer(audio_buffer); - return request; - } - - void CheckEqual(const std::string& name, - const PushBufferRequest& first, - const PushBufferRequest& second) { - std::string failure_str = "failed on " + std::move(name); - - ASSERT_EQ(first.has_buffer(), second.has_buffer()) << failure_str; - ASSERT_EQ(first.has_audio_config(), second.has_audio_config()) - << failure_str; - - if (first.has_buffer()) { - EXPECT_EQ(first.buffer().pts_micros(), second.buffer().pts_micros()) - << failure_str; - EXPECT_EQ(first.buffer().end_of_stream(), second.buffer().end_of_stream()) - << failure_str; - EXPECT_EQ(first.buffer().data(), second.buffer().data()) << failure_str; - } - - if (first.has_audio_config()) { - EXPECT_EQ(first.audio_config().codec(), second.audio_config().codec()) - << failure_str; - EXPECT_EQ(first.audio_config().channel_layout(), - second.audio_config().channel_layout()) - << failure_str; - EXPECT_EQ(first.audio_config().sample_format(), - second.audio_config().sample_format()) - << failure_str; - EXPECT_EQ(first.audio_config().bytes_per_channel(), - second.audio_config().bytes_per_channel()) - << failure_str; - EXPECT_EQ(first.audio_config().channel_number(), - second.audio_config().channel_number()) - << failure_str; - EXPECT_EQ(first.audio_config().samples_per_second(), - second.audio_config().samples_per_second()) - << failure_str; - EXPECT_EQ(first.audio_config().extra_data(), - second.audio_config().extra_data()) - << failure_str; - } - } - - void UpdateBufferWriteStreamPositions() { - queue_.producer_handler_.overflow(); - queue_.producer_handler_.ApplyNewBytesWritten(); - } - - std::string GetIterationName(int iteration_id) { - std::stringstream ss; - ss << "iteration " << iteration_id; - return ss.str(); - } - - bool StartPushBuffer(const PushBufferRequest& request) { - return queue_.PushBufferImpl(request); - } - - std::optional StartGetBufferedData() { - return queue_.GetBufferedDataImpl(); - } - - void FinishPushBuffer() { queue_.producer_handler_.ApplyNewBytesWritten(); } - - void FinishGetBufferedData() { queue_.consumer_handler_.ApplyNewBytesRead(); } - - std::istream* consumer_stream() { return &queue_.consumer_stream_.value(); } - std::ostream* producer_stream() { return &queue_.producer_stream_.value(); } - - size_t available_bytes() { return queue_.GetAvailableyByteCount(); } - - PushBufferQueue queue_; - - // Some test data - PushBufferRequest first_audio_buffer_; - PushBufferRequest second_audio_buffer_; - PushBufferRequest third_audio_buffer_; - PushBufferRequest fourth_audio_buffer_; - PushBufferRequest fifth_audio_buffer_; - PushBufferRequest first_audio_config_; -}; - -TEST_F(PushBufferQueueTests, TestPushOrdering) { - EXPECT_FALSE(queue_.HasBufferedData()); - - queue_.PushBuffer(first_audio_buffer_); - queue_.PushBuffer(second_audio_buffer_); - queue_.PushBuffer(first_audio_config_); - queue_.PushBuffer(third_audio_buffer_); - - ReadData("first", first_audio_buffer_); - ReadData("second", second_audio_buffer_); - - queue_.PushBuffer(fourth_audio_buffer_); - - ReadData("config", first_audio_config_); - ReadData("third", third_audio_buffer_); - ReadData("fourth", fourth_audio_buffer_); - - EXPECT_FALSE(queue_.HasBufferedData()); - queue_.PushBuffer(fifth_audio_buffer_); - - ReadData("fifth", fifth_audio_buffer_); - - EXPECT_FALSE(queue_.HasBufferedData()); -} - -TEST_F(PushBufferQueueTests, TestPushLargeBuffer) { - std::vector data; - for (int i = 0; i < 256; i++) { - data.push_back(i); - } - - auto buffer = CreateAudioBufferRequest(0, false, data); - - queue_.PushBuffer(buffer); - - ReadData("big buffer", buffer); -} - -TEST_F(PushBufferQueueTests, TestWrapAround) { - auto first_buffer = CreateAudioBufferRequest(0, false, 0, 1); - queue_.PushBuffer(first_buffer); - - for (size_t i = 1; i < PushBufferQueue::kBufferSizeBytes * 3; i++) { - const std::string name = GetIterationName(i); - const uint8_t previous_id = (i - 1) % 256; - const uint8_t current_id = i % 256; - const uint8_t next_id = (i + 1) % 256; - auto buffer = CreateAudioBufferRequest( - 0, false, std::vector{current_id, next_id}); - auto old_buffer = CreateAudioBufferRequest( - 0, false, std::vector{previous_id, current_id}); - - // Make sure the length is 6. 7 is prime, so guaranteed to hit all possible - // positions in |buffer_| when an extra bit is used for the size. - std::string serialized_str; - buffer.SerializeToString(&serialized_str); - ASSERT_EQ(serialized_str.size(), size_t{6}) << name; - - ASSERT_TRUE(queue_.HasBufferedData()) << name; - ASSERT_EQ(queue_.PushBuffer(buffer), - CmaBackend::BufferStatus::kBufferSuccess) - << name; - - ReadData(name, old_buffer); - } -} - -TEST_F(PushBufferQueueTests, TestWriteEntireBuffer) { - for (size_t i = 0; i < (PushBufferQueue::kBufferSizeBytes >> 3); i++) { - auto buffer = CreateAudioBufferRequest(0, false, 0, 1, 2); - - // Make sure the length is 8 after serialization (with the extra length - // bit). - std::string serialized_str; - buffer.SerializeToString(&serialized_str); - ASSERT_EQ(serialized_str.size(), size_t{7}); - ASSERT_EQ(queue_.PushBuffer(buffer), - CmaBackend::BufferStatus::kBufferSuccess) - << GetIterationName(i); - } - - auto failing_buffer = CreateAudioBufferRequest(0, false); - EXPECT_EQ(queue_.PushBuffer(failing_buffer), - CmaBackend::BufferStatus::kBufferFailed); - - for (size_t i = 0; i < (PushBufferQueue::kBufferSizeBytes >> 3); i++) { - auto buffer = CreateAudioBufferRequest(0, false, 0, 1, 2); - ReadData(GetIterationName(i), buffer); - } - - // Make sure writing still works after the failed write above. - EXPECT_FALSE(queue_.HasBufferedData()); - queue_.PushBuffer(first_audio_buffer_); - - ReadData("first", first_audio_buffer_); - - EXPECT_FALSE(queue_.HasBufferedData()); -} - -TEST_F(PushBufferQueueTests, TestReadingFromPartialWrite) { - std::string serialized_str; - first_audio_buffer_.SerializeToString(&serialized_str); - char size = static_cast(serialized_str.size()); - ASSERT_GT(size, 2); - - *producer_stream() << size << serialized_str[0] << serialized_str[1]; - UpdateBufferWriteStreamPositions(); - - ASSERT_TRUE(queue_.HasBufferedData()); - std::optional pulled_buffer = queue_.GetBufferedData(); - EXPECT_FALSE(pulled_buffer.has_value()); - EXPECT_TRUE(queue_.HasBufferedData()); - - for (size_t i = 2; i < serialized_str.size(); i++) { - *producer_stream() << serialized_str[i]; - } - UpdateBufferWriteStreamPositions(); - - ASSERT_TRUE(queue_.HasBufferedData()); - pulled_buffer = queue_.GetBufferedData(); - ASSERT_TRUE(pulled_buffer.has_value()); - CheckEqual("buffer", pulled_buffer.value(), first_audio_buffer_); -} - -TEST_F(PushBufferQueueTests, InterleaveProduceAndConsume) { - EXPECT_FALSE(queue_.HasBufferedData()); - - EXPECT_TRUE(StartPushBuffer(first_audio_buffer_)); - EXPECT_FALSE(queue_.HasBufferedData()); - - FinishPushBuffer(); - - ReadData("first", first_audio_buffer_); - - ASSERT_TRUE(StartPushBuffer(second_audio_buffer_)); - - FinishGetBufferedData(); - - EXPECT_FALSE(queue_.HasBufferedData()); - - FinishPushBuffer(); - - ReadData("second", second_audio_buffer_); - - EXPECT_FALSE(queue_.HasBufferedData()); -} - -TEST_F(PushBufferQueueTests, TestMultithreaded) { - queue_.PushBuffer(first_audio_buffer_); - queue_.PushBuffer(second_audio_buffer_); - - base::Thread consumer_thread("Consumer Thread"); - consumer_thread.StartAndWaitForTesting(); - { - auto task_runner = consumer_thread.task_runner(); - auto this_ptr = base::Unretained(this); - task_runner->PostTask( - FROM_HERE, base::BindOnce(&PushBufferQueueTests::ReadData, this_ptr, - "first", first_audio_buffer_)); - - task_runner->PostTask( - FROM_HERE, base::BindOnce(&PushBufferQueueTests::ReadData, this_ptr, - "second", second_audio_buffer_)); - - queue_.PushBuffer(third_audio_buffer_); - queue_.PushBuffer(fourth_audio_buffer_); - task_runner->PostTask( - FROM_HERE, base::BindOnce(&PushBufferQueueTests::ReadData, this_ptr, - "third", third_audio_buffer_)); - task_runner->PostTask( - FROM_HERE, base::BindOnce(&PushBufferQueueTests::ReadData, this_ptr, - "fourth", fourth_audio_buffer_)); - } - - consumer_thread.FlushForTesting(); - consumer_thread.Stop(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/saved_volumes.cc chromium-132.0.6834.159/chromecast/media/cma/backend/saved_volumes.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/saved_volumes.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/saved_volumes.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,99 +0,0 @@ -// 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 "chromecast/media/cma/backend/saved_volumes.h" - -#include - -#include "base/json/json_file_value_serializer.h" -#include "base/logging.h" -#include "base/values.h" -#include "chromecast/media/cma/backend/cast_audio_json.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr float kDefaultMediaDbFS = -25.0f; -constexpr float kDefaultAlarmDbFS = -20.0f; -constexpr float kDefaultCommunicationDbFS = -25.0f; - -constexpr char kKeyMediaDbFS[] = "dbfs.media"; -constexpr char kKeyAlarmDbFS[] = "dbfs.alarm"; -constexpr char kKeyCommunicationDbFS[] = "dbfs.communication"; -constexpr char kKeyDefaultVolume[] = "default_volume"; - -std::string ContentTypeToDbFSKey(AudioContentType type) { - switch (type) { - case AudioContentType::kAlarm: - return kKeyAlarmDbFS; - case AudioContentType::kCommunication: - return kKeyCommunicationDbFS; - default: - return kKeyMediaDbFS; - } -} - -} // namespace - -base::flat_map LoadSavedVolumes( - const base::FilePath& storage_path) { - auto types = {AudioContentType::kMedia, AudioContentType::kAlarm, - AudioContentType::kCommunication}; - base::flat_map volumes; - - volumes[AudioContentType::kMedia] = kDefaultMediaDbFS; - volumes[AudioContentType::kAlarm] = kDefaultAlarmDbFS; - volumes[AudioContentType::kCommunication] = kDefaultCommunicationDbFS; - - JSONFileValueDeserializer deserializer(storage_path); - auto stored_data = deserializer.Deserialize(nullptr, nullptr); - if (stored_data && stored_data->is_dict()) { - const auto& stored_data_dict = stored_data->GetDict(); - for (auto type : types) { - auto v = - stored_data_dict.FindDoubleByDottedPath(ContentTypeToDbFSKey(type)); - if (v) { - volumes[type] = v.value(); - } - } - return volumes; - } - - LOG(INFO) << "No saved volumes found"; - // If saved_volumes does not exist, use per-device default if it exists. - auto path = media::CastAudioJson::GetFilePath(); - JSONFileValueDeserializer cast_audio_deserializer(path); - auto cast_audio_config = - cast_audio_deserializer.Deserialize(nullptr, nullptr); - if (!cast_audio_config || !cast_audio_config->is_dict()) { - LOG(INFO) << "Invalid JSON from " << path; - return volumes; - } - - const auto& cast_audio_config_dict = cast_audio_config->GetDict(); - - const base::Value::Dict* default_volume_dict = - cast_audio_config_dict.FindDict(kKeyDefaultVolume); - if (!default_volume_dict) { - LOG(INFO) << "No default volumes specified in " << path; - return volumes; - } - - for (auto type : types) { - std::string key = ContentTypeToDbFSKey(type); - auto v = default_volume_dict->FindDoubleByDottedPath(key); - if (v) { - LOG(INFO) << "Using default volume for " << key << " of " << v.value(); - volumes[type] = v.value(); - } else { - LOG(INFO) << "No default volume for " << key; - } - } - return volumes; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/saved_volumes.h chromium-132.0.6834.159/chromecast/media/cma/backend/saved_volumes.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/saved_volumes.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/saved_volumes.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_SAVED_VOLUMES_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_SAVED_VOLUMES_H_ - -#include "base/containers/flat_map.h" -#include "base/files/file_path.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -// Returns the saved volume in dBFS for each stream type loaded from persistent -// storage, or the appropriate default volume if there was no saved volume. -base::flat_map LoadSavedVolumes( - const base::FilePath& storage_path); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_SAVED_VOLUMES_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/system_volume_control.h chromium-132.0.6834.159/chromecast/media/cma/backend/system_volume_control.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/system_volume_control.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/system_volume_control.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_SYSTEM_VOLUME_CONTROL_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_SYSTEM_VOLUME_CONTROL_H_ - -#include - -namespace chromecast { -namespace media { - -// Handles setting the volume and mute state on the appropriate system mixer -// elements (based on command-line args); also detects changes to the mute state -// or volume and informs a delegate. -// Must be created on an IO thread, and all methods must be called on that -// thread. -class SystemVolumeControl { - public: - class Delegate { - public: - // Called whenever the system volume or mute state have changed. - // Unfortunately it is not possible in all cases to differentiate between - // a volume change and a mute change, so the two events must be combined. - virtual void OnSystemVolumeOrMuteChange(float new_volume, - bool new_mute) = 0; - - protected: - virtual ~Delegate() = default; - }; - - static std::unique_ptr Create(Delegate* delegate); - - SystemVolumeControl() = default; - - SystemVolumeControl(const SystemVolumeControl&) = delete; - SystemVolumeControl& operator=(const SystemVolumeControl&) = delete; - - virtual ~SystemVolumeControl() = default; - - // Returns the value that you would get if you called GetVolume() after - // SetVolume(volume). - virtual float GetRoundtripVolume(float volume) = 0; - - // Returns the volume level for given |db_volume|. - virtual float DbToVolumeLevel(float db_volume) = 0; - - // Returns the volume in dB for given |level|. - virtual float VolumeLevelToDb(float level) = 0; - - // Returns the current system volume (0 <= volume <= 1). - virtual float GetVolume() = 0; - - // Sets the system volume to |level| (0 <= level <= 1). - virtual void SetVolume(float level) = 0; - - // Returns |true| if system is currently muted. - virtual bool IsMuted() = 0; - - // Sets the system mute state to |muted|. - virtual void SetMuted(bool muted) = 0; - - // Sets the system power save state to |power_save_on|. - virtual void SetPowerSave(bool power_save_on) = 0; - - // Sets the volume limit to be applied to the system volume. - virtual void SetLimit(float limit) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_SYSTEM_VOLUME_CONTROL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/video/av_sync_video.cc chromium-132.0.6834.159/chromecast/media/cma/backend/video/av_sync_video.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/video/av_sync_video.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/video/av_sync_video.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,278 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/video/av_sync_video.h" - -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/time/time.h" -#include "chromecast/base/statistics/weighted_moving_linear_regression.h" -#include "chromecast/media/audio/rate_adjuster.h" -#include "chromecast/media/cma/backend/audio_decoder_for_mixer.h" -#include "chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h" -#include "chromecast/media/cma/backend/video_decoder_for_mixer.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr base::TimeDelta kLinearRegressionWindow = base::Seconds(20); - -// Time interval between AV sync upkeeps. -constexpr base::TimeDelta kAvSyncUpkeepInterval = base::Milliseconds(16); - -// Threshold where the audio and video PTS are far enough apart such that we -// want to do a hard correction. -constexpr base::TimeDelta kMaxAptsError = base::Milliseconds(50); - -// Minimum samples of video PTS before we start doing A/V sync. -const int kMinVideoPtsSamples = 60; - -// This is the threshold for which we consider the rate of playback variation -// to be valid. If we measure a rate of playback variation worse than this, we -// consider the linear regression measurement invalid, we flush the linear -// regression and let AvSync collect samples all over again. -const double kExpectedSlopeVariance = 0.005; - -// We don't AV sync content with frame rate less than this. This low framerate -// indicates that the content happens to be audio-centric, with a dummy video -// stream. -const int kAvSyncFpsThreshold = 10; - -// Maximum correction rate for absolute sync offset. -const double kMaxOffsetCorrection = 2.5e-4; - -// Maximum A/V sync offset that we allow without correction. Note that we still -// correct the audio playback rate to match video (to prevent the offset from -// growing) even when the offset is lower than this value. -const int64_t kMaxIgnoredOffset = 500; - -} // namespace - -std::unique_ptr AvSync::Create( - MediaPipelineBackendForMixer* const backend) { - return std::make_unique(backend); -} - -AvSyncVideo::AvSyncVideo(MediaPipelineBackendForMixer* const backend) - : backend_(backend) { - DCHECK(backend_); -} - -AvSyncVideo::~AvSyncVideo() = default; - -void AvSyncVideo::NotifyStart(int64_t timestamp, int64_t pts) { - LOG(INFO) << __func__; - playback_start_timestamp_ = backend_->MonotonicClockNow(); - current_media_playback_rate_ = 1.0; - current_audio_clock_rate_ = 1.0; - backend_->video_decoder()->SetPlaybackRate(current_media_playback_rate_); - - StartAvSync(); -} - -void AvSyncVideo::NotifyStop() { - LOG(INFO) << __func__; - StopAvSync(); -} - -void AvSyncVideo::NotifyPause() { - LOG(INFO) << __func__; - StopAvSync(); - playback_start_timestamp_ = INT64_MAX; -} - -void AvSyncVideo::NotifyResume() { - LOG(INFO) << __func__; - playback_start_timestamp_ = backend_->MonotonicClockNow(); - StartAvSync(); -} - -void AvSyncVideo::NotifyPlaybackRateChange(float rate) { - DCHECK(backend_->video_decoder()); - DCHECK(backend_->audio_decoder()); - - current_media_playback_rate_ = rate; - backend_->video_decoder()->SetPlaybackRate(current_media_playback_rate_); - - FlushAudioPts(); - FlushVideoPts(); - - LOG(INFO) << __func__ - << " current_media_playback_rate_=" << current_media_playback_rate_ - << " current_audio_clock_rate_=" << current_audio_clock_rate_; -} - -void AvSyncVideo::StartAvSync() { - FlushAudioPts(); - FlushVideoPts(); - - upkeep_av_sync_timer_.Start(FROM_HERE, kAvSyncUpkeepInterval, this, - &AvSyncVideo::UpkeepAvSync); -} - -void AvSyncVideo::StopAvSync() { - upkeep_av_sync_timer_.Stop(); - audio_rate_adjuster_.reset(); -} - -void AvSyncVideo::UpkeepAvSync() { - if (!backend_->video_decoder() || !backend_->audio_decoder()) { - return; - } - - if (!VptsUpkeep()) { - return; - } - - int64_t new_raw_apts = 0; - int64_t new_apts_timestamp = 0; - if (!backend_->audio_decoder()->GetTimestampedPts(&new_apts_timestamp, - &new_raw_apts) || - new_apts_timestamp <= playback_start_timestamp_ || - new_raw_apts == last_apts_value_) { - return; - } - last_apts_value_ = new_raw_apts; - - DCHECK(video_pts_); - - int64_t desired_apts_timestamp; - double vpts_slope; - double error; - if (video_pts_->EstimateSlope(&vpts_slope, &error) && - std::abs(vpts_slope - 1.0 / current_media_playback_rate_) > - kExpectedSlopeVariance) { - // VPTS slope is bad. This can be because the video is actually playing out - // at the wrong rate (eg when video playback can't keep up and is too slow), - // or could be due to bad VPTS data (eg after resume, from old timestamps - // before pause). We assume the most recent VPTS sample is OK (so far this - // has always been true) and check if we need to do a hard correction to - // account for cases where the video is actually playing at the wrong rate - // before flushing the VPTS regression. - LOG(ERROR) << "Calculated bad vpts_slope " << vpts_slope - << " corresponding to playback rate =~ " << (1.0 / vpts_slope) - << ". Expected playback rate = " << current_media_playback_rate_; - - int64_t last_vpts = video_pts_->samples().back().x; - int64_t last_vpts_timestamp = video_pts_->samples().back().y; - desired_apts_timestamp = - last_vpts_timestamp + - (new_raw_apts - last_vpts) / current_media_playback_rate_; - FlushVideoPts(); - } else if (!video_pts_->EstimateY(new_raw_apts, &desired_apts_timestamp, - &error)) { - LOG(INFO) << "Failed to estimate desired APTS timestamp"; - return; - } - - // If error is positive, the audio is playing later than it should be. - int64_t apts_timestamp_error = new_apts_timestamp - desired_apts_timestamp; - if (std::abs(apts_timestamp_error) > kMaxAptsError.InMicroseconds() || - new_apts_timestamp < last_apts_timestamp_) { - if (new_apts_timestamp < last_apts_timestamp_) { - LOG(INFO) << "Audio timestamp moved backward"; - } - LOG(INFO) << "Hard correction; APTS = " << new_raw_apts - << ", ts = " << new_apts_timestamp - << ", desired = " << desired_apts_timestamp - << ", error = " << apts_timestamp_error; - HardCorrection(new_raw_apts, desired_apts_timestamp); - return; - } - if (video_pts_) { - // Only do audio rate upkeep if the VPTS data was OK (ie, no bad slope). - DCHECK(audio_rate_adjuster_); - audio_rate_adjuster_->AddError(apts_timestamp_error, new_apts_timestamp); - } -} - -bool AvSyncVideo::VptsUpkeep() { - if (!video_pts_) { - video_pts_ = std::make_unique( - kLinearRegressionWindow.InMicroseconds()); - } - - int64_t new_raw_vpts = 0; - int64_t new_vpts_timestamp = 0; - if (backend_->video_decoder()->GetCurrentPts(&new_vpts_timestamp, - &new_raw_vpts) && - new_vpts_timestamp > playback_start_timestamp_ && - new_raw_vpts != last_vpts_value_) { - video_pts_->AddSample(new_raw_vpts, new_vpts_timestamp, 1.0); - last_vpts_value_ = new_raw_vpts; - } - - if (video_pts_->num_samples() < kMinVideoPtsSamples) { - return false; - } - - return (GetVideoFrameRate() >= kAvSyncFpsThreshold); -} - -int AvSyncVideo::GetVideoFrameRate() { - DCHECK(video_pts_); - DCHECK_GE(video_pts_->num_samples(), 2u); - int64_t duration = - video_pts_->samples().back().x - video_pts_->samples().front().x; - return std::round(static_cast(video_pts_->num_samples()) * 1000000 / - duration); -} - -void AvSyncVideo::HardCorrection(int64_t apts, int64_t desired_apts_timestamp) { - backend_->audio_decoder()->RestartPlaybackAt(apts, desired_apts_timestamp); - FlushAudioPts(); -} - -double AvSyncVideo::ChangeAudioRate(double desired_clock_rate, - double error_slope, - double current_error) { - double effective_new_rate = - backend_->audio_decoder()->SetAvSyncPlaybackRate(desired_clock_rate); - current_audio_clock_rate_ = effective_new_rate; - LOG(INFO) << "Update audio clock rate to " << effective_new_rate - << "; wanted " << desired_clock_rate - << ", error slope = " << error_slope - << ", smoothed error = " << current_error; - - double vpts_slope; - double e; - if (video_pts_->EstimateSlope(&vpts_slope, &e)) { - LOG(INFO) << "VPTS slope = " << vpts_slope << "; playback rate =~ " - << (1.0 / vpts_slope); - } - return effective_new_rate; -} - -void AvSyncVideo::FlushAudioPts() { - last_apts_timestamp_ = INT64_MIN; - // Don't reset last_apts_value_, since we still want to ignore that value for - // the new linear regression since it may be invalid. - - RateAdjuster::Config config; - config.linear_regression_window = kLinearRegressionWindow; - config.max_ignored_current_error = kMaxIgnoredOffset; - config.max_current_error_correction = kMaxOffsetCorrection; - // Only change the clock rate if the desired rate is > 30 ppm different. - // Reasoning: 30 ppm means that leaving the clock rate unchanged will add at - // most 30 microseconds of additional error before the next clock rate check. - config.min_rate_change = 3.0e-5; - audio_rate_adjuster_ = std::make_unique( - config, - base::BindRepeating(&AvSyncVideo::ChangeAudioRate, - base::Unretained(this)), - current_audio_clock_rate_); -} - -void AvSyncVideo::FlushVideoPts() { - video_pts_.reset(); - // Don't reset last_vpts_value_, since we still want to ignore that value for - // the new linear regression since it may be invalid. -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/video/av_sync_video.h chromium-132.0.6834.159/chromecast/media/cma/backend/video/av_sync_video.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/video/av_sync_video.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/video/av_sync_video.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_AV_SYNC_VIDEO_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_AV_SYNC_VIDEO_H_ - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "base/timer/timer.h" -#include "chromecast/media/cma/backend/av_sync.h" - -namespace chromecast { -class WeightedMovingLinearRegression; - -namespace media { -class MediaPipelineBackendForMixer; -class RateAdjuster; - -class AvSyncVideo : public AvSync { - public: - explicit AvSyncVideo(MediaPipelineBackendForMixer* const backend); - - AvSyncVideo(const AvSyncVideo&) = delete; - AvSyncVideo& operator=(const AvSyncVideo&) = delete; - - ~AvSyncVideo() override; - - // AvSync implementation: - void NotifyStart(int64_t timestamp, int64_t pts) override; - void NotifyStop() override; - void NotifyPause() override; - void NotifyResume() override; - void NotifyPlaybackRateChange(float rate) override; - - private: - void StartAvSync(); - void StopAvSync(); - - void UpkeepAvSync(); - bool VptsUpkeep(); - int GetVideoFrameRate(); - - void HardCorrection(int64_t apts, int64_t desired_apts_timestamp); - double ChangeAudioRate(double desired_clock_rate, - double error_slope, - double current_error); - - void FlushAudioPts(); - void FlushVideoPts(); - - MediaPipelineBackendForMixer* const backend_; - - base::RepeatingTimer upkeep_av_sync_timer_; - - std::unique_ptr apts_error_; - std::unique_ptr video_pts_; - std::unique_ptr audio_rate_adjuster_; - - // This is the audio playback rate propagated from SetPlaybackRate, which is - // exposed to the user to speed up or slow down their playback. - double current_media_playback_rate_ = 1.0; - - // This is the small playback rate change done to maintain AV sync. - double current_audio_clock_rate_ = 1.0; - - int64_t playback_start_timestamp_ = INT64_MAX; - - int64_t last_vpts_value_ = INT64_MIN; - - int64_t last_apts_value_ = INT64_MIN; - int64_t last_apts_timestamp_ = INT64_MIN; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_AV_SYNC_VIDEO_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/video/cast_media_shlib_common.cc chromium-132.0.6834.159/chromecast/media/cma/backend/video/cast_media_shlib_common.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/video/cast_media_shlib_common.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/video/cast_media_shlib_common.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/public/media/media_capabilities_shlib.h" - -namespace chromecast { -namespace media { - -bool MediaCapabilitiesShlib::IsSupportedAudioConfig(const AudioConfig& config) { - switch (config.codec) { - case kCodecPCM: - case kCodecPCM_S16BE: - case kCodecAAC: - case kCodecMP3: - case kCodecVorbis: - return true; - default: - break; - } - return false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/video/cast_media_shlib_default.cc chromium-132.0.6834.159/chromecast/media/cma/backend/video/cast_media_shlib_default.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/video/cast_media_shlib_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/video/cast_media_shlib_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/public/cast_media_shlib.h" - -#include "chromecast/media/cma/backend/media_pipeline_backend_for_mixer.h" - -namespace chromecast { -namespace media { - -MediaPipelineBackend* CastMediaShlib::CreateMediaPipelineBackend( - const MediaPipelineDeviceParams& params) { - return new MediaPipelineBackendForMixer(params); -} - -bool CastMediaShlib::SupportsMediaClockRateChange() { - return false; -} - -double CastMediaShlib::GetMediaClockRate() { - return 0.0; -} - -double CastMediaShlib::MediaClockRatePrecision() { - return 0.0; -} - -void CastMediaShlib::MediaClockRateRange(double* minimum_rate, - double* maximum_rate) { - *minimum_rate = 0.0; - *maximum_rate = 1.0; -} - -bool CastMediaShlib::SetMediaClockRate(double new_rate) { - return false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/video_decoder_for_mixer.h chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_for_mixer.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/video_decoder_for_mixer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_for_mixer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,125 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_DECODER_FOR_MIXER_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_DECODER_FOR_MIXER_H_ - -#include - -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { - -// This class represents a video decoder that exposes additional functionality -// that allows a caller to control the rate and state of the video playback -// with enough granularity to be able to sync it to the audio. -// -// The default implementation of this is in VideoDecoderNull. On no-video -// platforms, that implementation is used. -// -// On video platforms that need to use the mixer, you may override this class -// and link in an implementation of VideoDecoderForMixer::Create. -class VideoDecoderForMixer : public MediaPipelineBackend::VideoDecoder { - public: - class Observer { - public: - // Notifies the observer that the video playback is ready to start. After - // this is called, SetPts may be reliably called to start playback at the - // desired time. - virtual void VideoReadyToPlay() = 0; - - protected: - virtual ~Observer() {} - }; - - static std::unique_ptr Create( - const MediaPipelineDeviceParams& params); - - // On some platforms, graphics needs to be initialized before this component - // will function appropriately in tests. Add the initialization here if - // necessary. - static void InitializeGraphicsForTesting(); - - ~VideoDecoderForMixer() override {} - - // Initializes the VideoDecoderForMixer. Called after allocation and before - // Start is called. Gives the implementation a chance to initialize any - // resources. - virtual bool Initialize() = 0; - - // Sets the observer to be notified when the video is ready to play. - virtual void SetObserver(Observer* observer) = 0; - - // When called, playback is expected to start from |start_pts|. - // - // start_pts: the pts to start playing at. - // need_avsync: deprecated. Don't use or implement. - // TODO(almasrymina): remove deprecated. - virtual bool Start(int64_t start_pts, bool need_avsync) = 0; - - // Stop playback. - virtual void Stop() = 0; - - // Pause playback. The video decoder must retain its playback rate after - // resume. - virtual bool Pause() = 0; - - // Resume playback. The video decoder must resume playback at the same - // playback rate prior to pausing. - virtual bool Resume() = 0; - - // Returns the current video PTS. This will typically be the pts of the last - // video frame displayed. - virtual bool GetCurrentPts(int64_t* timestamp, int64_t* pts) const = 0; - - // Set the playback rate. This is used to sync the audio to the video. This - // call will change the rate of play of video in the following manner: - // - // rate = 1.0 -> 1 second of video pts is played for each 1 second of - // wallclock time. - // rate = 1.5 -> 1.5 seconds of video pts is played for each 1 second of - // wallclock time. - // etc. - virtual bool SetPlaybackRate(float rate) = 0; - - // Sets the current pts to the provided value. If |pts| is greater than the - // current pts, all video frames in between will be dropped. If |pts| is less - // than the current pts, all video frames in this pts range will be repeated. - // Implementation is encouraged to smooth out this transition, such that - // minimal jitter in the video is shown, but that is not necessary. - virtual bool SetPts(int64_t timestamp, int64_t pts) = 0; - - // Returns number of frames dropped since the last call to Start(). This is - // used to estimate video playback smoothness. - // This is different from VideoDecoder::Statistics::dropped_frames. That - // value is the number of *decoded* dropped frames. The value returned here - // must be the total number of dropped frames, whether the frames have been - // decoded or not. - virtual int64_t GetDroppedFrames() = 0; - - // Returns number of frames repeated since the last call to Start(). This is - // used to estimate video playback smoothness. Note that repeated frames could - // be due to changes in the rate of playback, setting the PTS, or simply due - // to frame rate conversion. This number should be the sum of all of these - // factors. - // - // For example, if the current OutputRefreshRate is 60hz, and the current - // content frame rate is 24fps, it is expected to repeat 36fps. - virtual int64_t GetRepeatedFrames() = 0; - - // Returns the output refresh rate on this platform, in mHz (millihertz). On - // display devices, this will be the display refresh rate. On HDMI devices, - // this will be the refresh rate of the HDMI connection. - virtual int64_t GetOutputRefreshRate() = 0; - - // Returns the current content refresh rate in mHz (millihertz). - virtual int64_t GetCurrentContentRefreshRate() = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_DECODER_FOR_MIXER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/video_decoder_null.cc chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_null.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/video_decoder_null.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_null.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/video_decoder_null.h" - -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/public/media/cast_decoder_buffer.h" - -namespace chromecast { -namespace media { - -std::unique_ptr VideoDecoderForMixer::Create( - const MediaPipelineDeviceParams& params) { - return std::make_unique(); -} - -void VideoDecoderForMixer::InitializeGraphicsForTesting() { - // No initialization required -} - -VideoDecoderNull::VideoDecoderNull() - : delegate_(nullptr), weak_factory_(this) {} - -VideoDecoderNull::~VideoDecoderNull() {} - -void VideoDecoderNull::SetDelegate(Delegate* delegate) { - DCHECK(delegate); - delegate_ = delegate; -} - -MediaPipelineBackend::BufferStatus VideoDecoderNull::PushBuffer( - CastDecoderBuffer* buffer) { - DCHECK(delegate_); - DCHECK(buffer); - if (buffer->end_of_stream()) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&VideoDecoderNull::OnEndOfStream, - weak_factory_.GetWeakPtr())); - } - return MediaPipelineBackend::kBufferSuccess; -} - -void VideoDecoderNull::GetStatistics(Statistics* statistics) {} - -bool VideoDecoderNull::SetConfig(const VideoConfig& config) { - return true; -} - -void VideoDecoderNull::OnEndOfStream() { - delegate_->OnEndOfStream(); -} - -bool VideoDecoderNull::Initialize() { - return true; -} - -void VideoDecoderNull::SetObserver(VideoDecoderForMixer::Observer* observer) { - DCHECK(observer); - observer_ = observer; -} - -bool VideoDecoderNull::Start(int64_t start_pts, bool need_avsync) { - if (observer_) { - observer_->VideoReadyToPlay(); - } - return true; -} - -void VideoDecoderNull::Stop() {} - -bool VideoDecoderNull::Pause() { - return true; -} - -bool VideoDecoderNull::Resume() { - return true; -} - -bool VideoDecoderNull::GetCurrentPts(int64_t* timestamp, int64_t* pts) const { - return false; -} - -bool VideoDecoderNull::SetPlaybackRate(float rate) { - return true; -} - -bool VideoDecoderNull::SetPts(int64_t timestamp, int64_t pts) { - return true; -} - -int64_t VideoDecoderNull::GetDroppedFrames() { - return 0; -} - -int64_t VideoDecoderNull::GetRepeatedFrames() { - return 0; -} - -int64_t VideoDecoderNull::GetOutputRefreshRate() { - return 0; -} - -int64_t VideoDecoderNull::GetCurrentContentRefreshRate() { - return 0; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/video_decoder_null.h chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_null.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/video_decoder_null.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/video_decoder_null.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_DECODER_NULL_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_DECODER_NULL_H_ - -#include - -#include "base/memory/weak_ptr.h" -#include "chromecast/media/cma/backend/video_decoder_for_mixer.h" - -namespace chromecast { -namespace media { - -class VideoDecoderNull : public VideoDecoderForMixer { - public: - VideoDecoderNull(); - - VideoDecoderNull(const VideoDecoderNull&) = delete; - VideoDecoderNull& operator=(const VideoDecoderNull&) = delete; - - ~VideoDecoderNull() override; - - // MediaPipelineBackend::VideoDecoder implementation: - void SetDelegate(Delegate* delegate) override; - MediaPipelineBackend::BufferStatus PushBuffer( - CastDecoderBuffer* buffer) override; - void GetStatistics(Statistics* statistics) override; - bool SetConfig(const VideoConfig& config) override; - - bool Initialize() override; - void SetObserver(VideoDecoderForMixer::Observer* observer) override; - bool Start(int64_t start_pts, bool need_avsync) override; - void Stop() override; - bool Pause() override; - bool Resume() override; - bool GetCurrentPts(int64_t* timestamp, int64_t* pts) const override; - bool SetPlaybackRate(float rate) override; - bool SetPts(int64_t timestamp, int64_t pts) override; - int64_t GetDroppedFrames() override; - int64_t GetRepeatedFrames() override; - int64_t GetOutputRefreshRate() override; - int64_t GetCurrentContentRefreshRate() override; - - private: - void OnEndOfStream(); - - Delegate* delegate_; - Observer* observer_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_VIDEO_DECODER_NULL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/volume_control.cc chromium-132.0.6834.159/chromecast/media/cma/backend/volume_control.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/volume_control.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/volume_control.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,452 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/public/volume_control.h" - -#include -#include -#include -#include -#include -#include - -#include "base/containers/contains.h" -#include "base/containers/flat_map.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/files/important_file_writer.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/json/json_writer.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/message_loop/message_pump_type.h" -#include "base/no_destructor.h" -#include "base/synchronization/lock.h" -#include "base/synchronization/waitable_event.h" -#include "base/threading/thread.h" -#include "base/time/time.h" -#include "base/values.h" -#include "chromecast/media/audio/mixer_service/control_connection.h" -#include "chromecast/media/cma/backend/audio_buildflags.h" -#include "chromecast/media/cma/backend/saved_volumes.h" -#include "chromecast/media/cma/backend/system_volume_control.h" -#include "chromecast/media/cma/backend/volume_map.h" - -#if BUILDFLAG(MIXER_IN_CAST_SHELL) -#include "chromecast/media/cma/backend/mixer/stream_mixer.h" // nogncheck -#endif - -namespace chromecast { -namespace media { - -namespace { - -#if !BUILDFLAG(SYSTEM_OWNS_VOLUME) -constexpr float kMinDbFS = -120.0f; -#endif - -constexpr char kKeyMediaDbFS[] = "dbfs.media"; -constexpr char kKeyAlarmDbFS[] = "dbfs.alarm"; -constexpr char kKeyCommunicationDbFS[] = "dbfs.communication"; - -#if !BUILDFLAG(SYSTEM_OWNS_VOLUME) -float DbFsToScale(float db) { - if (db <= kMinDbFS) { - return 0.0f; - } - return std::pow(10, db / 20); -} -#endif - -std::string ContentTypeToDbFSPath(AudioContentType type) { - switch (type) { - case AudioContentType::kAlarm: - return kKeyAlarmDbFS; - case AudioContentType::kCommunication: - return kKeyCommunicationDbFS; - default: - return kKeyMediaDbFS; - } -} - -class VolumeControlInternal : public SystemVolumeControl::Delegate { - public: - VolumeControlInternal() - : thread_("VolumeControl"), - initialize_complete_event_( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED) { - // Load volume map to check that the config file is correct. - VolumeControl::VolumeToDbFS(0.0f); - - storage_path_ = base::GetHomeDir().Append("saved_volumes"); - base::flat_map saved_volumes = - LoadSavedVolumes(storage_path_); - for (auto type : {AudioContentType::kMedia, AudioContentType::kAlarm, - AudioContentType::kCommunication}) { - stored_values_.SetByDottedPath(ContentTypeToDbFSPath(type), - saved_volumes[type]); - } - - base::Thread::Options options; - options.message_pump_type = base::MessagePumpType::IO; - thread_.StartWithOptions(std::move(options)); - - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlInternal::InitializeOnThread, - base::Unretained(this))); - initialize_complete_event_.Wait(); - } - - VolumeControlInternal(const VolumeControlInternal&) = delete; - VolumeControlInternal& operator=(const VolumeControlInternal&) = delete; - - ~VolumeControlInternal() override = default; - - void AddVolumeObserver(VolumeObserver* observer) { - base::AutoLock lock(observer_lock_); - volume_observers_.push_back(observer); - } - - void RemoveVolumeObserver(VolumeObserver* observer) { - base::AutoLock lock(observer_lock_); - volume_observers_.erase(std::remove(volume_observers_.begin(), - volume_observers_.end(), observer), - volume_observers_.end()); - } - - float GetVolume(AudioContentType type) { - base::AutoLock lock(volume_lock_); - return volumes_[type]; - } - - void SetVolume(VolumeChangeSource source, - AudioContentType type, - float level) { - if (type == AudioContentType::kOther) { - DLOG(ERROR) << "Can't set volume for content type kOther"; - return; - } - - level = std::clamp(level, 0.0f, 1.0f); - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlInternal::SetVolumeOnThread, - base::Unretained(this), source, type, level, - false /* from_system */)); - } - - void SetVolumeMultiplier(AudioContentType type, float multiplier) { - if (type == AudioContentType::kOther) { - DLOG(ERROR) << "Can't set volume multiplier for content type kOther"; - return; - } - -#if BUILDFLAG(SYSTEM_OWNS_VOLUME) - LOG(INFO) << "Ignore global volume multiplier since volume is externally " - << "controlled"; -#else - thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&VolumeControlInternal::SetVolumeMultiplierOnThread, - base::Unretained(this), type, multiplier)); -#endif - } - - bool IsMuted(AudioContentType type) { - base::AutoLock lock(volume_lock_); - return muted_[type]; - } - - void SetMuted(VolumeChangeSource source, AudioContentType type, bool muted) { - if (type == AudioContentType::kOther) { - DLOG(ERROR) << "Can't set mute state for content type kOther"; - return; - } - - thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VolumeControlInternal::SetMutedOnThread, - base::Unretained(this), source, type, muted, - false /* from_system */)); - } - - void SetOutputLimit(AudioContentType type, float limit) { - if (type == AudioContentType::kOther) { - DLOG(ERROR) << "Can't set output limit for content type kOther"; - return; - } - - thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&VolumeControlInternal::SetOutputLimitOnThread, - base::Unretained(this), type, limit)); - } - - void SetPowerSaveMode(bool power_save_on) { - thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&VolumeControlInternal::SetPowerSaveModeOnThread, - base::Unretained(this), power_save_on)); - } - - private: - void InitializeOnThread() { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - system_volume_control_ = SystemVolumeControl::Create(this); - mixer_ = std::make_unique(); - mixer_->Connect(); - - saved_volumes_writer_ = std::make_unique( - storage_path_, thread_.task_runner(), base::Seconds(1)); - - for (auto type : {AudioContentType::kMedia, AudioContentType::kAlarm, - AudioContentType::kCommunication}) { - std::optional dbfs = - stored_values_.FindDouble(ContentTypeToDbFSPath(type)); - CHECK(dbfs); - volumes_[type] = VolumeControl::DbFSToVolume(*dbfs); - volume_multipliers_[type] = 1.0f; - -#if BUILDFLAG(SYSTEM_OWNS_VOLUME) - // ALSA owns volume; our internal mixer should not apply any scaling - // multiplier. - mixer_->SetVolume(type, 1.0f); -#else - mixer_->SetVolume(type, DbFsToScale(*dbfs)); -#endif - - // Note that mute state is not persisted across reboots. - muted_[type] = false; - mixer_->SetMuted(type, false); - } - -#if BUILDFLAG(SYSTEM_OWNS_VOLUME) - // Read the current volume and mute state from the ALSA mixer element(s). - volumes_[AudioContentType::kMedia] = system_volume_control_->GetVolume(); - muted_[AudioContentType::kMedia] = system_volume_control_->IsMuted(); -#else - // Make sure the ALSA mixer element correctly reflects the current volume - // state. - system_volume_control_->SetVolume(volumes_[AudioContentType::kMedia]); - system_volume_control_->SetMuted(false); -#endif - - volumes_[AudioContentType::kOther] = 1.0; - muted_[AudioContentType::kOther] = false; - - initialize_complete_event_.Signal(); - } - - void SetVolumeOnThread(VolumeChangeSource source, - AudioContentType type, - float level, - bool from_system) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - DCHECK_NE(AudioContentType::kOther, type); - DCHECK(!from_system || type == AudioContentType::kMedia); - DCHECK(base::Contains(volume_multipliers_, type)); - - { - base::AutoLock lock(volume_lock_); - if (from_system && system_volume_control_->GetRoundtripVolume( - volumes_[AudioContentType::kMedia]) == level) { - return; - } - if (level == volumes_[type]) { - return; - } - volumes_[type] = level; - } - - float dbfs = VolumeControl::VolumeToDbFS(level); -#if !BUILDFLAG(SYSTEM_OWNS_VOLUME) - mixer_->SetVolume(type, DbFsToScale(dbfs) * volume_multipliers_[type]); -#endif - - if (!from_system && type == AudioContentType::kMedia) { - system_volume_control_->SetVolume(level); - } - - { - base::AutoLock lock(observer_lock_); - for (VolumeObserver* observer : volume_observers_) { - observer->OnVolumeChange(source, type, level); - } - } - - stored_values_.SetByDottedPath(ContentTypeToDbFSPath(type), dbfs); - std::string output_js; - base::JSONWriter::Write(stored_values_, &output_js); - saved_volumes_writer_->WriteNow(std::move(output_js)); - } - - void SetVolumeMultiplierOnThread(AudioContentType type, float multiplier) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - DCHECK_NE(AudioContentType::kOther, type); -#if BUILDFLAG(SYSTEM_OWNS_VOLUME) - NOTREACHED(); -#else - volume_multipliers_[type] = multiplier; - float scale = - DbFsToScale(VolumeControl::VolumeToDbFS(volumes_[type])) * multiplier; - mixer_->SetVolume(type, scale); -#endif - } - - void SetMutedOnThread(VolumeChangeSource source, - AudioContentType type, - bool muted, - bool from_system) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - DCHECK_NE(AudioContentType::kOther, type); - - { - base::AutoLock lock(volume_lock_); - if (muted == muted_[type]) { - return; - } - muted_[type] = muted; - } - -#if !BUILDFLAG(SYSTEM_OWNS_VOLUME) - mixer_->SetMuted(type, muted); -#endif - - if (!from_system && type == AudioContentType::kMedia) { - system_volume_control_->SetMuted(muted); - } - - { - base::AutoLock lock(observer_lock_); - for (VolumeObserver* observer : volume_observers_) { - observer->OnMuteChange(source, type, muted); - } - } - } - - void SetOutputLimitOnThread(AudioContentType type, float limit) { - if (type == AudioContentType::kOther) { - DLOG(ERROR) << "Can't set output limit for content type kOther"; - return; - } - -#if !BUILDFLAG(SYSTEM_OWNS_VOLUME) - limit = std::clamp(limit, 0.0f, 1.0f); - mixer_->SetVolumeLimit(type, - DbFsToScale(VolumeControl::VolumeToDbFS(limit))); - - if (type == AudioContentType::kMedia) { - system_volume_control_->SetLimit(limit); - } -#endif - } - - void SetPowerSaveModeOnThread(bool power_save_on) { - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - system_volume_control_->SetPowerSave(power_save_on); - } - - // SystemVolumeControl::Delegate implementation: - void OnSystemVolumeOrMuteChange(float new_volume, bool new_mute) override { - LOG(INFO) << "System volume/mute change, new volume = " << new_volume - << ", new mute = " << new_mute; - DCHECK(thread_.task_runner()->BelongsToCurrentThread()); - SetVolumeOnThread(VolumeChangeSource::kUser, AudioContentType::kMedia, - new_volume, true /* from_system */); - SetMutedOnThread(VolumeChangeSource::kUser, AudioContentType::kMedia, - new_mute, true /* from_system */); - } - - base::FilePath storage_path_; - base::Value::Dict stored_values_; - - base::Lock volume_lock_; - base::flat_map volumes_; - base::flat_map volume_multipliers_; - base::flat_map muted_; - - base::Lock observer_lock_; - std::vector volume_observers_; - - base::Thread thread_; - base::WaitableEvent initialize_complete_event_; - - std::unique_ptr system_volume_control_; - std::unique_ptr mixer_; - std::unique_ptr saved_volumes_writer_; -}; - -VolumeControlInternal& GetVolumeControl() { - static base::NoDestructor g_volume_control; - return *g_volume_control; -} - -} // namespace - -// static -void VolumeControl::Initialize(const std::vector& argv) { -#if BUILDFLAG(MIXER_IN_CAST_SHELL) - static base::NoDestructor g_mixer; -#endif - GetVolumeControl(); -} - -// static -void VolumeControl::Finalize() { - // Nothing to do. -} - -// static -void VolumeControl::AddVolumeObserver(VolumeObserver* observer) { - GetVolumeControl().AddVolumeObserver(observer); -} - -// static -void VolumeControl::RemoveVolumeObserver(VolumeObserver* observer) { - GetVolumeControl().RemoveVolumeObserver(observer); -} - -// static -float VolumeControl::GetVolume(AudioContentType type) { - return GetVolumeControl().GetVolume(type); -} - -// static -void VolumeControl::SetVolume(VolumeChangeSource source, - AudioContentType type, - float level) { - GetVolumeControl().SetVolume(source, type, level); -} - -// static -void VolumeControl::SetVolumeMultiplier(AudioContentType type, - float multiplier) { - GetVolumeControl().SetVolumeMultiplier(type, multiplier); -} - -// static -bool VolumeControl::IsMuted(AudioContentType type) { - return GetVolumeControl().IsMuted(type); -} - -// static -void VolumeControl::SetMuted(VolumeChangeSource source, - AudioContentType type, - bool muted) { - GetVolumeControl().SetMuted(source, type, muted); -} - -// static -void VolumeControl::SetOutputLimit(AudioContentType type, float limit) { - GetVolumeControl().SetOutputLimit(type, limit); -} - -// static -void VolumeControl::SetPowerSaveMode(bool power_save_on) { - GetVolumeControl().SetPowerSaveMode(power_save_on); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/volume_map.cc chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/volume_map.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,162 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/volume_map.h" - -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/no_destructor.h" -#include "base/values.h" -#include "chromecast/media/cma/backend/cast_audio_json.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -namespace { - -constexpr char kKeyVolumeMap[] = "volume_map"; -constexpr char kKeyLevel[] = "level"; -constexpr char kKeyDb[] = "db"; -constexpr float kMinDbFS = -120.0f; - -VolumeMap& GetVolumeMap() { - static base::NoDestructor volume_map; - return *volume_map; -} - -} // namespace - -VolumeMap::VolumeMap() - : VolumeMap(std::make_unique()) {} - -VolumeMap::VolumeMap(std::unique_ptr config_provider) - : config_provider_(std::move(config_provider)) { - DCHECK(config_provider_); - // base::Unretained is safe because VolumeMap outlives |config_provider_|. - config_provider_->SetTuningChangedCallback( - base::BindRepeating(&VolumeMap::LoadVolumeMap, base::Unretained(this))); - LoadFromFile(); -} - -VolumeMap::~VolumeMap() = default; - -void VolumeMap::LoadFromFile() { - LoadVolumeMap(config_provider_->GetCastAudioConfig()); -} - -void VolumeMap::LoadVolumeMap( - std::optional cast_audio_config) { - if (!cast_audio_config) { - LOG(WARNING) << "No cast audio config found; using default volume map."; - UseDefaultVolumeMap(); - return; - } - - const base::Value::List* volume_map_list = - cast_audio_config->FindList(kKeyVolumeMap); - if (!volume_map_list) { - LOG(WARNING) << "No volume map found; using default volume map."; - UseDefaultVolumeMap(); - return; - } - - double prev_level = -1.0; - std::vector new_map; - - for (const auto& value : *volume_map_list) { - const base::Value::Dict& volume_map_entry = value.GetDict(); - - std::optional level = volume_map_entry.FindDouble(kKeyLevel); - CHECK(level); - CHECK_GE(*level, 0.0); - CHECK_LE(*level, 1.0); - CHECK_GT(*level, prev_level); - prev_level = *level; - - std::optional db = volume_map_entry.FindDouble(kKeyDb); - CHECK(db); - CHECK_LE(*db, 0.0); - - new_map.push_back({static_cast(*level), static_cast(*db)}); - } - - if (new_map.empty()) { - LOG(FATAL) << "No entries in volume map."; - } - - if (new_map[0].level > 0.0) { - new_map.insert(new_map.begin(), {0.0, kMinDbFS}); - } - - if (new_map.rbegin()->level < 1.0) { - new_map.push_back({1.0, 0.0}); - } - base::AutoLock lock(lock_); - volume_map_ = std::move(new_map); -} - -float VolumeMap::VolumeToDbFS(float volume) { - base::AutoLock lock(lock_); - if (volume <= volume_map_[0].level) { - return volume_map_[0].db; - } - for (size_t i = 1; i < volume_map_.size(); ++i) { - if (volume < volume_map_[i].level) { - const float x_range = volume_map_[i].level - volume_map_[i - 1].level; - const float y_range = volume_map_[i].db - volume_map_[i - 1].db; - const float x_pos = volume - volume_map_[i - 1].level; - - return volume_map_[i - 1].db + x_pos * y_range / x_range; - } - } - return volume_map_[volume_map_.size() - 1].db; -} - -float VolumeMap::DbFSToVolume(float db) { - base::AutoLock lock(lock_); - if (db <= volume_map_[0].db) { - return volume_map_[0].level; - } - for (size_t i = 1; i < volume_map_.size(); ++i) { - if (db < volume_map_[i].db) { - const float x_range = volume_map_[i].db - volume_map_[i - 1].db; - const float y_range = volume_map_[i].level - volume_map_[i - 1].level; - const float x_pos = db - volume_map_[i - 1].db; - - return volume_map_[i - 1].level + x_pos * y_range / x_range; - } - } - return volume_map_[volume_map_.size() - 1].level; -} - -void VolumeMap::UseDefaultVolumeMap() { - std::vector new_map = {{0.0f, kMinDbFS}, - {0.01f, -58.0f}, - {0.090909f, -48.0f}, - {0.818182f, -8.0f}, - {1.0f, 0.0f}}; - base::AutoLock lock(lock_); - volume_map_ = std::move(new_map); -} - -// static -float VolumeControl::VolumeToDbFS(float volume) { - return GetVolumeMap().VolumeToDbFS(volume); -} - -// static -float VolumeControl::DbFSToVolume(float db) { - return GetVolumeMap().DbFSToVolume(db); -} - -// static -void VolumeMap::Reload() { - return GetVolumeMap().LoadFromFile(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/volume_map.h chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map.h --- chromium-132.0.6834.110/chromecast/media/cma/backend/volume_map.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BACKEND_VOLUME_MAP_H_ -#define CHROMECAST_MEDIA_CMA_BACKEND_VOLUME_MAP_H_ - -#include -#include - -#include "base/synchronization/lock.h" -#include "chromecast/media/cma/backend/cast_audio_json.h" - -namespace base { -class Value; -} // namespace base - -namespace chromecast { -namespace media { - -class VolumeMap { - public: - VolumeMap(); - - static void Reload(); - - // For testing. - VolumeMap(std::unique_ptr config_provider); - - VolumeMap(const VolumeMap&) = delete; - VolumeMap& operator=(const VolumeMap&) = delete; - - ~VolumeMap(); - - float VolumeToDbFS(float volume); - - float DbFSToVolume(float db); - - void LoadVolumeMap(std::optional cast_audio_config); - - private: - struct LevelToDb { - float level; - float db; - }; - - void LoadFromFile(); - void UseDefaultVolumeMap(); - - // |volume_map_| must be accessed with |lock_|. - base::Lock lock_; - std::vector volume_map_; - - std::unique_ptr config_provider_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BACKEND_VOLUME_MAP_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/backend/volume_map_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/backend/volume_map_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/backend/volume_map_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,95 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/backend/volume_map.h" - -#include - -#include "base/check.h" -#include "base/test/values_test_util.h" -#include "chromecast/media/cma/backend/cast_audio_json.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -const float kEpsilon = 0.0001; -const char* kNewVolumeMap = R"json({"volume_map": [ - {"level":0.0, "db":-120.0}, - {"level":0.5, "db":-10.0}, - {"level":1.0, "db":0.0} - ]} -)json"; - -class TestFileProvider : public CastAudioJsonProvider { - public: - TestFileProvider(const std::string& file_contents) - : file_contents_(file_contents) {} - - TestFileProvider(const TestFileProvider&) = delete; - TestFileProvider& operator=(const TestFileProvider&) = delete; - - ~TestFileProvider() override = default; - - void CallTuningChangedCallback(const std::string& new_config) { - DCHECK(callback_); - callback_.Run(base::test::ParseJsonDict(new_config)); - } - - private: - std::optional GetCastAudioConfig() override { - return base::test::ParseJsonDict(file_contents_); - } - - void SetTuningChangedCallback(TuningChangedCallback callback) override { - callback_ = std::move(callback); - } - - const std::string file_contents_; - TuningChangedCallback callback_; -}; - -TEST(VolumeMapTest, UsesDefaultMapIfConfigEmpty) { - VolumeMap volume_map(std::make_unique("{}")); - EXPECT_NEAR(-58.0f, volume_map.VolumeToDbFS(0.01f), kEpsilon); - EXPECT_NEAR(-48.0f, volume_map.VolumeToDbFS(1.0 / 11.0), kEpsilon); - EXPECT_NEAR(-8.0f, volume_map.VolumeToDbFS(9.0 / 11.0), kEpsilon); - EXPECT_NEAR(-0.0f, volume_map.VolumeToDbFS(1.0f), kEpsilon); - - EXPECT_NEAR(0.01, volume_map.DbFSToVolume(-58.0), kEpsilon); - EXPECT_NEAR(1.0 / 11.0, volume_map.DbFSToVolume(-48.0), kEpsilon); - EXPECT_NEAR(9.0 / 11.0, volume_map.DbFSToVolume(-8.0), kEpsilon); - EXPECT_NEAR(1.0, volume_map.DbFSToVolume(0.0), kEpsilon); -} - -TEST(VolumeMapTest, LoadsInitialConfig) { - VolumeMap volume_map(std::make_unique(kNewVolumeMap)); - EXPECT_NEAR(-10.0f, volume_map.VolumeToDbFS(0.5), kEpsilon); -} - -TEST(VolumeMapTest, VolumeToDbFSInterpolates) { - VolumeMap volume_map(std::make_unique(kNewVolumeMap)); - EXPECT_NEAR((-120.0 - 10.0) / 2, volume_map.VolumeToDbFS(0.25f), kEpsilon); - EXPECT_NEAR((-10.0 - 0.0) / 2, volume_map.VolumeToDbFS(0.75f), kEpsilon); -} - -TEST(VolumeMapTest, DbFSToVolumeInterpolates) { - VolumeMap volume_map(std::make_unique(kNewVolumeMap)); - EXPECT_NEAR(0.25f, volume_map.DbFSToVolume((-120.0 - 10.0) / 2), kEpsilon); - EXPECT_NEAR(0.75f, volume_map.DbFSToVolume((-10.0 - 0.0) / 2), kEpsilon); -} - -TEST(VolumeMapTest, LoadsNewMapWhenFileChanges) { - auto provider = std::make_unique("{}"); - TestFileProvider* provider_ptr = provider.get(); - VolumeMap volume_map(std::move(provider)); - - provider_ptr->CallTuningChangedCallback(kNewVolumeMap); - EXPECT_NEAR(-10.0f, volume_map.VolumeToDbFS(0.5), kEpsilon); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/balanced_media_task_runner_factory.cc chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_factory.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/balanced_media_task_runner_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,253 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/balanced_media_task_runner_factory.h" - -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/cma/base/media_task_runner.h" -#include "media/base/timestamp_constants.h" - -namespace chromecast { -namespace media { - -// MediaTaskRunnerWithNotification - -// Media task runner which also behaves as a media task runner observer. -class MediaTaskRunnerWithNotification : public MediaTaskRunner { - public: - // Wraps a MediaTaskRunner so that a third party can: - // - be notified when a PostMediaTask is performed on this media task runner. - // |new_task_cb| is invoked in that case. - // - monitor the lifetime of the media task runner, i.e. check when the media - // task runner is not needed anymore. - // |shutdown_cb| is invoked in that case. - MediaTaskRunnerWithNotification( - const scoped_refptr& media_task_runner, - base::RepeatingClosure new_task_cb, - base::OnceClosure shutdown_cb); - - MediaTaskRunnerWithNotification(const MediaTaskRunnerWithNotification&) = - delete; - MediaTaskRunnerWithNotification& operator=( - const MediaTaskRunnerWithNotification&) = delete; - - // MediaTaskRunner implementation. - bool PostMediaTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta timestamp) override; - - private: - ~MediaTaskRunnerWithNotification() override; - - scoped_refptr const media_task_runner_; - - const base::RepeatingClosure new_task_cb_; - base::OnceClosure shutdown_cb_; -}; - -MediaTaskRunnerWithNotification::MediaTaskRunnerWithNotification( - const scoped_refptr& media_task_runner, - base::RepeatingClosure new_task_cb, - base::OnceClosure shutdown_cb) - : media_task_runner_(media_task_runner), - new_task_cb_(std::move(new_task_cb)), - shutdown_cb_(std::move(shutdown_cb)) {} - -MediaTaskRunnerWithNotification::~MediaTaskRunnerWithNotification() { - std::move(shutdown_cb_).Run(); -} - -bool MediaTaskRunnerWithNotification::PostMediaTask( - const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta timestamp) { - bool may_run_in_future = - media_task_runner_->PostMediaTask(from_here, std::move(task), timestamp); - if (may_run_in_future) - new_task_cb_.Run(); - return may_run_in_future; -} - -// BalancedMediaTaskRunner - -// Run media tasks whose timestamp is less or equal to a max timestamp. -// -// Restrictions of BalancedMediaTaskRunner: -// - Can have at most one task in the queue. -// - Tasks should be given by increasing timestamps. -class BalancedMediaTaskRunner - : public MediaTaskRunner { - public: - explicit BalancedMediaTaskRunner( - const scoped_refptr& task_runner); - - BalancedMediaTaskRunner(const BalancedMediaTaskRunner&) = delete; - BalancedMediaTaskRunner& operator=(const BalancedMediaTaskRunner&) = delete; - - // Schedule tasks whose timestamp is less than or equal to |max_timestamp|. - void ScheduleWork(base::TimeDelta max_timestamp); - - // Return the timestamp of the last media task. - // Return ::media::kNoTimestamp if no media task has been posted. - base::TimeDelta GetMediaTimestamp() const; - - // MediaTaskRunner implementation. - bool PostMediaTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta timestamp) override; - - private: - ~BalancedMediaTaskRunner() override; - - scoped_refptr const task_runner_; - - // Protects the following variables. - mutable base::Lock lock_; - - // Possible pending media task. - base::Location from_here_; - base::OnceClosure pending_task_; - - // Timestamp of the last posted task. - // Is initialized to ::media::kNoTimestamp. - base::TimeDelta last_timestamp_; -}; - -BalancedMediaTaskRunner::BalancedMediaTaskRunner( - const scoped_refptr& task_runner) - : task_runner_(task_runner), last_timestamp_(::media::kNoTimestamp) {} - -BalancedMediaTaskRunner::~BalancedMediaTaskRunner() { -} - -void BalancedMediaTaskRunner::ScheduleWork(base::TimeDelta max_media_time) { - base::OnceClosure task; - { - base::AutoLock auto_lock(lock_); - if (pending_task_.is_null()) - return; - - if (last_timestamp_ != ::media::kNoTimestamp && - last_timestamp_ >= max_media_time) { - return; - } - - task = std::move(pending_task_); - } - task_runner_->PostTask(from_here_, std::move(task)); -} - -base::TimeDelta BalancedMediaTaskRunner::GetMediaTimestamp() const { - base::AutoLock auto_lock(lock_); - return last_timestamp_; -} - -bool BalancedMediaTaskRunner::PostMediaTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta timestamp) { - DCHECK(!task.is_null()); - - // Pass through for a task with no timestamp. - if (timestamp == ::media::kNoTimestamp) { - return task_runner_->PostTask(from_here, std::move(task)); - } - - base::AutoLock auto_lock(lock_); - - // Timestamps must be in order. - // Any task that does not meet that condition is simply discarded. - if (last_timestamp_ != ::media::kNoTimestamp && timestamp < last_timestamp_) { - return false; - } - - // Only support one pending task at a time. - DCHECK(pending_task_.is_null()); - from_here_ = from_here; - pending_task_ = std::move(task); - last_timestamp_ = timestamp; - - return true; -} - -BalancedMediaTaskRunnerFactory::BalancedMediaTaskRunnerFactory( - base::TimeDelta max_delta) - : max_delta_(max_delta) { -} - -BalancedMediaTaskRunnerFactory::~BalancedMediaTaskRunnerFactory() { -} - -scoped_refptr -BalancedMediaTaskRunnerFactory::CreateMediaTaskRunner( - const scoped_refptr& task_runner) { - scoped_refptr media_task_runner( - new BalancedMediaTaskRunner(task_runner)); - scoped_refptr media_task_runner_wrapper( - new MediaTaskRunnerWithNotification( - media_task_runner, - base::BindRepeating(&BalancedMediaTaskRunnerFactory::OnNewTask, this), - base::BindOnce( - &BalancedMediaTaskRunnerFactory::UnregisterMediaTaskRunner, this, - media_task_runner))); - base::AutoLock auto_lock(lock_); - // Note that |media_task_runner| is inserted here and - // not |media_task_runner_wrapper|. Otherwise, we would always have one - // ref on |media_task_runner_wrapper| and would never get the release - // notification. - // When |media_task_runner_wrapper| is going away, - // BalancedMediaTaskRunnerFactory will receive a notification and will in - // turn remove |media_task_runner|. - task_runners_.insert(media_task_runner); - return media_task_runner_wrapper; -} - -void BalancedMediaTaskRunnerFactory::OnNewTask() { - typedef - std::multimap > - TaskRunnerMap; - TaskRunnerMap runnable_task_runner; - - base::AutoLock auto_lock(lock_); - - // Get the minimum timestamp among all streams. - for (MediaTaskRunnerSet::const_iterator it = task_runners_.begin(); - it != task_runners_.end(); ++it) { - base::TimeDelta timestamp((*it)->GetMediaTimestamp()); - if (timestamp == ::media::kNoTimestamp) - continue; - runnable_task_runner.insert( - std::pair >( - timestamp, *it)); - } - - // If there is no media task, just returns. - if (runnable_task_runner.empty()) - return; - - // Run tasks which meet the balancing criteria. - base::TimeDelta min_timestamp(runnable_task_runner.begin()->first); - base::TimeDelta max_timestamp = min_timestamp + max_delta_; - for (TaskRunnerMap::iterator it = runnable_task_runner.begin(); - it != runnable_task_runner.end(); ++it) { - (*it).second->ScheduleWork(max_timestamp); - } -} - -void BalancedMediaTaskRunnerFactory::UnregisterMediaTaskRunner( - const scoped_refptr& media_task_runner) { - { - base::AutoLock auto_lock(lock_); - task_runners_.erase(media_task_runner); - } - // After removing one of the task runners some of the other task runners might - // need to be waken up, if they are no longer blocked by the balancing - // restrictions with the old stream. - OnNewTask(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/balanced_media_task_runner_factory.h chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_factory.h --- chromium-132.0.6834.110/chromecast/media/cma/base/balanced_media_task_runner_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_BALANCED_MEDIA_TASK_RUNNER_FACTORY_H_ -#define CHROMECAST_MEDIA_CMA_BASE_BALANCED_MEDIA_TASK_RUNNER_FACTORY_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "base/synchronization/lock.h" -#include "base/time/time.h" - -namespace base { -class SingleThreadTaskRunner; -} - -namespace chromecast { -namespace media { -class BalancedMediaTaskRunner; -class MediaTaskRunner; - -// BalancedMediaTaskRunnerFactory - -// Create media tasks runners that are loosely synchronized between each other. -// For two tasks T1 and T2 with timestamps ts1 and ts2, the scheduler ensures -// T2 is not scheduled before T1 if ts2 > ts1 + |max_delta|. -class BalancedMediaTaskRunnerFactory - : public base::RefCountedThreadSafe { - public: - explicit BalancedMediaTaskRunnerFactory(base::TimeDelta max_delta); - - BalancedMediaTaskRunnerFactory(const BalancedMediaTaskRunnerFactory&) = - delete; - BalancedMediaTaskRunnerFactory& operator=( - const BalancedMediaTaskRunnerFactory&) = delete; - - // Creates a media task runner using |task_runner| as the underlying - // regular task runner. - // Restriction on the returned media task runner: - // - can only schedule only one media task at a time. - // - timestamps of tasks posted on that task runner must be increasing. - scoped_refptr CreateMediaTaskRunner( - const scoped_refptr& task_runner); - - private: - typedef std::set > MediaTaskRunnerSet; - - friend class base::RefCountedThreadSafe; - virtual ~BalancedMediaTaskRunnerFactory(); - - // Invoked when one of the registered media task runners received a new media - // task. - void OnNewTask(); - - // Unregister a media task runner. - void UnregisterMediaTaskRunner( - const scoped_refptr& media_task_runner); - - // Maximum timestamp deviation between tasks from the registered task runners. - const base::TimeDelta max_delta_; - - // Task runners created by the factory that have not been unregistered yet. - base::Lock lock_; - MediaTaskRunnerSet task_runners_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_BALANCED_MEDIA_TASK_RUNNER_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/balanced_media_task_runner_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/balanced_media_task_runner_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/balanced_media_task_runner_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,297 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "base/task/current_thread.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "base/time/time.h" -#include "chromecast/media/cma/base/balanced_media_task_runner_factory.h" -#include "chromecast/media/cma/base/media_task_runner.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { - -struct MediaTaskRunnerTestContext { - MediaTaskRunnerTestContext(); - ~MediaTaskRunnerTestContext(); - - scoped_refptr media_task_runner; - - bool is_pending_task; - - std::vector task_timestamp_list; - - size_t task_index; - base::TimeDelta max_timestamp; -}; - -MediaTaskRunnerTestContext::MediaTaskRunnerTestContext() { -} - -MediaTaskRunnerTestContext::~MediaTaskRunnerTestContext() { -} - -} // namespace - -class BalancedMediaTaskRunnerTest : public testing::Test { - public: - BalancedMediaTaskRunnerTest(); - - BalancedMediaTaskRunnerTest(const BalancedMediaTaskRunnerTest&) = delete; - BalancedMediaTaskRunnerTest& operator=(const BalancedMediaTaskRunnerTest&) = - delete; - - ~BalancedMediaTaskRunnerTest() override; - - void SetupTest(base::TimeDelta max_delta, - const std::vector >& timestamps_in_ms, - const std::vector& pattern, - const std::vector& expected_task_timestamps_ms); - void ProcessAllTasks(); - - protected: - // Expected task order based on their timestamps. - std::list expected_task_timestamps_; - - private: - void ScheduleTask(); - void Task(size_t task_runner_id, base::TimeDelta timestamp); - - void OnTestTimeout(); - - scoped_refptr media_task_runner_factory_; - - // Schedule first a task on media task runner #scheduling_pattern[0] - // then a task on media task runner #scheduling_pattern[1] and so on. - // Wrap around when reaching the end of the pattern. - std::vector scheduling_pattern_; - size_t pattern_index_; - - // For each media task runner, keep a track of which task has already been - // scheduled. - std::vector contexts_; - - base::OnceClosure quit_closure_; -}; - -BalancedMediaTaskRunnerTest::BalancedMediaTaskRunnerTest() { -} - -BalancedMediaTaskRunnerTest::~BalancedMediaTaskRunnerTest() { -} - -void BalancedMediaTaskRunnerTest::SetupTest( - base::TimeDelta max_delta, - const std::vector >& timestamps_in_ms, - const std::vector& pattern, - const std::vector& expected_task_timestamps_ms) { - media_task_runner_factory_ = new BalancedMediaTaskRunnerFactory(max_delta); - - scheduling_pattern_ = pattern; - pattern_index_ = 0; - - // Setup each task runner. - size_t n = timestamps_in_ms.size(); - contexts_.resize(n); - for (size_t k = 0; k < n; k++) { - contexts_[k].media_task_runner = - media_task_runner_factory_->CreateMediaTaskRunner( - base::SingleThreadTaskRunner::GetCurrentDefault()); - contexts_[k].is_pending_task = false; - contexts_[k].task_index = 0; - contexts_[k].task_timestamp_list.resize( - timestamps_in_ms[k].size()); - for (size_t i = 0; i < timestamps_in_ms[k].size(); i++) { - contexts_[k].task_timestamp_list[i] = - base::Milliseconds(timestamps_in_ms[k][i]); - } - } - - // Expected task order (for tasks that are actually run). - for (size_t k = 0; k < expected_task_timestamps_ms.size(); k++) { - expected_task_timestamps_.push_back( - base::Milliseconds(expected_task_timestamps_ms[k])); - } -} - -void BalancedMediaTaskRunnerTest::ProcessAllTasks() { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&BalancedMediaTaskRunnerTest::OnTestTimeout, - base::Unretained(this)), - base::Seconds(5)); - ScheduleTask(); - base::RunLoop loop; - quit_closure_ = loop.QuitWhenIdleClosure(); - loop.Run(); -} - -void BalancedMediaTaskRunnerTest::ScheduleTask() { - bool has_task = false; - for (size_t k = 0; k < contexts_.size(); k++) { - if (contexts_[k].task_index < contexts_[k].task_timestamp_list.size()) - has_task = true; - } - if (!has_task) { - std::move(quit_closure_).Run(); - return; - } - - size_t next_pattern_index = - (pattern_index_ + 1) % scheduling_pattern_.size(); - - size_t task_runner_id = scheduling_pattern_[pattern_index_]; - MediaTaskRunnerTestContext& context = contexts_[task_runner_id]; - - // Check whether all tasks have been scheduled for that task runner - // or if there is already one pending task. - if (context.task_index >= context.task_timestamp_list.size() || - context.is_pending_task) { - pattern_index_ = next_pattern_index; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&BalancedMediaTaskRunnerTest::ScheduleTask, - base::Unretained(this))); - return; - } - - bool expected_may_run = false; - if (context.task_timestamp_list[context.task_index] >= - context.max_timestamp) { - expected_may_run = true; - context.max_timestamp = context.task_timestamp_list[context.task_index]; - } - - bool may_run = context.media_task_runner->PostMediaTask( - FROM_HERE, - base::BindOnce(&BalancedMediaTaskRunnerTest::Task, base::Unretained(this), - task_runner_id, - context.task_timestamp_list[context.task_index]), - context.task_timestamp_list[context.task_index]); - EXPECT_EQ(may_run, expected_may_run); - - if (may_run) - context.is_pending_task = true; - - context.task_index++; - pattern_index_ = next_pattern_index; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&BalancedMediaTaskRunnerTest::ScheduleTask, - base::Unretained(this))); -} - -void BalancedMediaTaskRunnerTest::Task( - size_t task_runner_id, base::TimeDelta timestamp) { - ASSERT_FALSE(expected_task_timestamps_.empty()); - EXPECT_EQ(timestamp, expected_task_timestamps_.front()); - expected_task_timestamps_.pop_front(); - - contexts_[task_runner_id].is_pending_task = false; - - // Release task runner if the task has ended - // otherwise, the task runner may may block other streams - auto& context = contexts_[task_runner_id]; - if (context.task_index >= context.task_timestamp_list.size()) { - context.media_task_runner = nullptr; - } -} - -void BalancedMediaTaskRunnerTest::OnTestTimeout() { - ADD_FAILURE() << "Test timed out"; - std::move(quit_closure_).Run(); -} - -TEST_F(BalancedMediaTaskRunnerTest, OneTaskRunner) { - base::test::SingleThreadTaskEnvironment task_environment; - - // Timestamps of tasks for the single task runner. - int timestamps0_ms[] = {0, 10, 20, 30, 40, 30, 50, 60, 20, 30, 70}; - std::vector > timestamps_ms(1); - timestamps_ms[0] = std::vector( - timestamps0_ms, timestamps0_ms + std::size(timestamps0_ms)); - - // Scheduling pattern. - std::vector scheduling_pattern(1); - scheduling_pattern[0] = 0; - - // Expected results. - int expected_timestamps[] = {0, 10, 20, 30, 40, 50, 60, 70}; - std::vector expected_timestamps_ms( - std::vector(expected_timestamps, - expected_timestamps + std::size(expected_timestamps))); - - SetupTest(base::Milliseconds(30), timestamps_ms, scheduling_pattern, - expected_timestamps_ms); - ProcessAllTasks(); - EXPECT_TRUE(expected_task_timestamps_.empty()); -} - -TEST_F(BalancedMediaTaskRunnerTest, TwoTaskRunnerUnbalanced) { - base::test::SingleThreadTaskEnvironment task_environment; - - // Timestamps of tasks for the 2 task runners. - int timestamps0_ms[] = {0, 10, 20, 30, 40, 30, 50, 60, 20, 30, 70}; - int timestamps1_ms[] = {5, 15, 25, 35, 45, 35, 55, 65, 25, 35, 75}; - std::vector > timestamps_ms(2); - timestamps_ms[0] = std::vector( - timestamps0_ms, timestamps0_ms + std::size(timestamps0_ms)); - timestamps_ms[1] = std::vector( - timestamps1_ms, timestamps1_ms + std::size(timestamps1_ms)); - - // Scheduling pattern. - size_t pattern[] = {1, 0, 0, 0, 0}; - std::vector scheduling_pattern = - std::vector(pattern, pattern + std::size(pattern)); - - // Expected results. - int expected_timestamps[] = { - 5, 0, 10, 20, 30, 15, 40, 25, 50, 35, 60, 45, 70, 55, 65, 75 }; - std::vector expected_timestamps_ms( - std::vector(expected_timestamps, - expected_timestamps + std::size(expected_timestamps))); - - SetupTest(base::Milliseconds(30), timestamps_ms, scheduling_pattern, - expected_timestamps_ms); - ProcessAllTasks(); - EXPECT_TRUE(expected_task_timestamps_.empty()); -} - -TEST_F(BalancedMediaTaskRunnerTest, TwoStreamsOfDifferentLength) { - base::test::SingleThreadTaskEnvironment task_environment; - - std::vector> timestamps = { - // One longer stream and one shorter stream. - // The longer stream runs first, then the shorter stream begins. - // After shorter stream ends, it shouldn't block the longer one. - {0, 20, 40, 60, 80, 100, 120, 140, 160}, - {51, 61, 71, 81}, - }; - - std::vector expected_timestamps = { - 0, 20, 40, 60, 51, 80, 61, 71, 81, 100, 120, 140, 160}; - - std::vector scheduling_pattern = { - 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0}; - - SetupTest(base::Milliseconds(30), timestamps, scheduling_pattern, - expected_timestamps); - ProcessAllTasks(); - EXPECT_TRUE(expected_task_timestamps_.empty()); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_controller.cc chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_controller.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,246 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/buffering_controller.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/media/cma/base/buffering_state.h" -#include "media/base/timestamp_constants.h" - -namespace chromecast { -namespace media { - -namespace { - -// Maximum time for buffering before we error out the stream. -constexpr base::TimeDelta kBufferingTimeout = base::Minutes(1); - -} // namespace - -BufferingController::BufferingController( - const scoped_refptr& config, - const BufferingNotificationCB& buffering_notification_cb) - : config_(config), - buffering_notification_cb_(buffering_notification_cb), - is_buffering_(false), - begin_buffering_time_(base::Time()), - last_buffer_end_time_(base::Time()), - initial_buffering_(true), - buffering_timeout_exceeded_(false), - weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); - thread_checker_.DetachFromThread(); - LOG(INFO) << __FUNCTION__ - << " High threshold: " << config_->high_level().InMilliseconds() - << "ms Low threshold: " << config_->low_level().InMilliseconds() - << "ms"; -} - -BufferingController::~BufferingController() { - // Some weak pointers might possibly be invalidated here. - DCHECK(thread_checker_.CalledOnValidThread()); -} - -void BufferingController::UpdateHighLevelThreshold( - base::TimeDelta high_level_threshold) { - // Can only decrease the high level threshold. - if (high_level_threshold > config_->high_level()) - return; - LOG(INFO) << "High buffer threshold: " - << high_level_threshold.InMilliseconds() << "ms"; - config_->set_high_level(high_level_threshold); - - // Make sure the low level threshold is somewhat consistent. - // Currently, we set it to one third of the high level threshold: - // this value could be adjusted in the future. - base::TimeDelta low_level_threshold = high_level_threshold / 3; - if (low_level_threshold <= config_->low_level()) { - LOG(INFO) << "Low buffer threshold: " - << low_level_threshold.InMilliseconds() << "ms"; - config_->set_low_level(low_level_threshold); - } - - // Signal all the streams the config has changed. - for (StreamList::iterator it = stream_list_.begin(); - it != stream_list_.end(); ++it) { - (*it)->OnConfigChanged(); - } - - // Once all the streams have been notified, the buffering state must be - // updated (no notification is received from the streams). - OnBufferingStateChanged(false, false); -} - -scoped_refptr BufferingController::AddStream( - const std::string& stream_id) { - DCHECK(thread_checker_.CalledOnValidThread()); - - // Add a new stream to the list of streams being monitored. - scoped_refptr buffering_state(new BufferingState( - stream_id, config_, - base::BindRepeating(&BufferingController::OnBufferingStateChanged, - weak_this_, false, false), - base::BindRepeating(&BufferingController::UpdateHighLevelThreshold, - weak_this_))); - stream_list_.push_back(buffering_state); - - // Update the state and force a notification to the streams. - // TODO(damienv): Should this be a PostTask ? - OnBufferingStateChanged(true, false); - - return buffering_state; -} - -void BufferingController::SetMediaTime(base::TimeDelta time) { - for (StreamList::iterator it = stream_list_.begin(); - it != stream_list_.end(); ++it) { - (*it)->SetMediaTime(time); - } -} - -base::TimeDelta BufferingController::GetMaxRenderingTime() const { - base::TimeDelta max_rendering_time(::media::kNoTimestamp); - for (StreamList::const_iterator it = stream_list_.begin(); - it != stream_list_.end(); ++it) { - base::TimeDelta max_stream_rendering_time = - (*it)->GetMaxRenderingTime(); - if (max_stream_rendering_time == ::media::kNoTimestamp) - return ::media::kNoTimestamp; - if (max_rendering_time == ::media::kNoTimestamp || - max_stream_rendering_time < max_rendering_time) { - max_rendering_time = max_stream_rendering_time; - } - } - return max_rendering_time; -} - -void BufferingController::Reset() { - DCHECK(thread_checker_.CalledOnValidThread()); - - is_buffering_ = false; - initial_buffering_ = true; - buffering_timeout_exceeded_ = false; - buffering_timer_.Stop(); - stream_list_.clear(); -} - -void BufferingController::OnBufferingStateChanged( - bool force_notification, bool buffering_timeout) { - DCHECK(thread_checker_.CalledOnValidThread()); - - // Log the state of each stream. - DumpState(); - - bool is_low_buffering = IsLowBufferLevel(); - bool is_high_buffering = !is_low_buffering; - if (!buffering_timeout) { - // Hysteresis: - // - to leave buffering, not only should we leave the low buffer level state - // but we should go to the high buffer level state (medium is not enough). - is_high_buffering = IsHighBufferLevel(); - } - - bool is_buffering_prv = is_buffering_; - if (is_buffering_) { - if (is_high_buffering) - is_buffering_ = false; - } else { - if (is_low_buffering) - is_buffering_ = true; - } - - // Start buffering. - if (is_buffering_ && !is_buffering_prv) { - begin_buffering_time_ = base::Time::Now(); - buffering_timer_.Start(FROM_HERE, kBufferingTimeout, this, - &BufferingController::BufferingTimeoutExceeded); - } - - // End buffering. - if (is_buffering_prv && !is_buffering_) { - base::Time current_time = base::Time::Now(); - base::TimeDelta buffering_user_time = current_time - begin_buffering_time_; - chromecast::metrics::CastMetricsHelper* metrics_helper = - chromecast::metrics::CastMetricsHelper::GetInstance(); - LOG(INFO) << "Buffering took: " << buffering_user_time.InMilliseconds() - << "ms"; - chromecast::metrics::CastMetricsHelper::BufferingType buffering_type = - initial_buffering_ ? - chromecast::metrics::CastMetricsHelper::kInitialBuffering : - chromecast::metrics::CastMetricsHelper::kBufferingAfterUnderrun; - metrics_helper->LogTimeToBufferAv(buffering_type, buffering_user_time); - - if (!initial_buffering_) { - base::TimeDelta time_between_buffering = - begin_buffering_time_ - last_buffer_end_time_; - LOG(INFO) << "Time since last buffering event: " - << time_between_buffering.InMilliseconds() << "ms"; - metrics_helper->RecordApplicationEventWithValue( - "Cast.Platform.PlayTimeBeforeAutoPause", - time_between_buffering.InMilliseconds()); - metrics_helper->RecordApplicationEventWithValue( - "Cast.Platform.AutoPauseTime", buffering_user_time.InMilliseconds()); - } - // Only the first buffering report is considered "initial buffering". - last_buffer_end_time_ = current_time; - initial_buffering_ = false; - buffering_timer_.Stop(); - } - - // Don't notify any buffering change if the timeout was exceeded, to avoid - // user surprise if playback resumes after extremely long buffering. - if (!buffering_timeout_exceeded_ && - (is_buffering_prv != is_buffering_ || force_notification)) - buffering_notification_cb_.Run(is_buffering_); -} - -void BufferingController::BufferingTimeoutExceeded() { - LOG(INFO) << __FUNCTION__; - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( - "Cast.Platform.BufferingTimeoutExceeded"); - buffering_timeout_exceeded_ = true; -} - -bool BufferingController::IsHighBufferLevel() { - if (stream_list_.empty()) - return true; - - bool is_high_buffering = true; - for (StreamList::iterator it = stream_list_.begin(); - it != stream_list_.end(); ++it) { - BufferingState::State stream_state = (*it)->GetState(); - is_high_buffering = is_high_buffering && - ((stream_state == BufferingState::kHighLevel) || - (stream_state == BufferingState::kEosReached)); - } - return is_high_buffering; -} - -bool BufferingController::IsLowBufferLevel() { - if (stream_list_.empty()) - return false; - - for (StreamList::iterator it = stream_list_.begin(); - it != stream_list_.end(); ++it) { - BufferingState::State stream_state = (*it)->GetState(); - if (stream_state == BufferingState::kLowLevel) - return true; - } - - return false; -} - -void BufferingController::DumpState() const { - for (StreamList::const_iterator it = stream_list_.begin(); - it != stream_list_.end(); ++it) { - LOG(INFO) << (*it)->ToString(); - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_controller.h chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller.h --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_controller.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,117 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_BUFFERING_CONTROLLER_H_ -#define CHROMECAST_MEDIA_CMA_BASE_BUFFERING_CONTROLLER_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "base/timer/timer.h" - -namespace chromecast { -namespace media { -class BufferingConfig; -class BufferingState; - -class BufferingController { - public: - typedef base::RepeatingCallback BufferingNotificationCB; - - // Creates a buffering controller where the conditions to trigger rebuffering - // are given by |config|. The whole point of the buffering controller is to - // derive a single buffering state from the buffering state of various - // streams. - // |buffering_notification_cb| is a callback invoked to inform about possible - // changes of the buffering state. - BufferingController( - const scoped_refptr& config, - const BufferingNotificationCB& buffering_notification_cb); - - BufferingController(const BufferingController&) = delete; - BufferingController& operator=(const BufferingController&) = delete; - - ~BufferingController(); - - // Creates a buffering state for one stream. This state is added to the list - // of streams monitored by the buffering controller. - scoped_refptr AddStream(const std::string& stream_id); - - // Sets the playback time. - void SetMediaTime(base::TimeDelta time); - - // Returns the maximum media time available for rendering. - // Return kNoTimestamp if unknown. - base::TimeDelta GetMaxRenderingTime() const; - - // Returns whether there is an active buffering phase. - bool IsBuffering() const { return is_buffering_; } - - // Resets the buffering controller. This includes removing all the streams - // that were previously added. - void Reset(); - - private: - // Invoked each time the buffering state of one of the streams has changed. - // If |force_notification| is set, |buffering_notification_cb_| is invoked - // regardless whether the buffering state has changed or not. - // If |buffering_timeout| is set, then the condition to leave the buffering - // state is relaxed (we don't want to wait more). - void OnBufferingStateChanged(bool force_notification, - bool buffering_timeout); - void BufferingTimeoutExceeded(); - - // Updates the high buffer level threshold to |high_level_threshold| - // if needed. - // This condition is triggered when one of the stream reached its maximum - // capacity. In that case, to avoid possible race condition (the buffering - // controller waits for more data to come but the buffer is to small to - // accomodate additional data), the thresholds in |config_| are adjusted - // accordingly. - void UpdateHighLevelThreshold(base::TimeDelta high_level_threshold); - - // Determines the overall buffer level based on the buffer level of each - // stream. - bool IsHighBufferLevel(); - bool IsLowBufferLevel(); - - // Logs the state of the buffering controller. - void DumpState() const; - - base::ThreadChecker thread_checker_; - - // Settings used to determine when to start/stop buffering. - scoped_refptr config_; - - // Callback invoked each time there is a change of the buffering state. - BufferingNotificationCB buffering_notification_cb_; - - // State of the buffering controller. - bool is_buffering_; - - // Start time of a re-buffering phase. - base::Time begin_buffering_time_; - base::Time last_buffer_end_time_; - bool initial_buffering_; - - bool buffering_timeout_exceeded_; - base::OneShotTimer buffering_timer_; - - // Buffering level for each individual stream. - typedef std::list > StreamList; - StreamList stream_list_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_BUFFERING_CONTROLLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_controller_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_controller_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_controller_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,115 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/buffering_controller.h" - -#include - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "chromecast/media/cma/base/buffering_state.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { - -class MockBufferingControllerClient { - public: - MOCK_METHOD1(OnBufferingNotification, void(bool is_buffering)); -}; - -} // namespace - -class BufferingControllerTest : public testing::Test { - public: - BufferingControllerTest(); - - base::test::TaskEnvironment task_environment_; - std::unique_ptr buffering_controller_; - - MockBufferingControllerClient client_; - - // Buffer level under the low level threshold. - base::TimeDelta d1_; - - // Buffer level between the low and the high level. - base::TimeDelta d2_; - - // Buffer level above the high level. - base::TimeDelta d3_; -}; - -BufferingControllerTest::BufferingControllerTest() { - base::TimeDelta low_level_threshold(base::Milliseconds(2000)); - base::TimeDelta high_level_threshold(base::Milliseconds(6000)); - - d1_ = low_level_threshold - base::Milliseconds(50); - d2_ = (low_level_threshold + high_level_threshold) / 2; - d3_ = high_level_threshold + base::Milliseconds(50); - - scoped_refptr buffering_config( - new BufferingConfig(low_level_threshold, high_level_threshold)); - buffering_controller_.reset(new BufferingController( - buffering_config, - base::BindRepeating( - &MockBufferingControllerClient::OnBufferingNotification, - base::Unretained(&client_)))); -} - -TEST_F(BufferingControllerTest, OneStream_Typical) { - EXPECT_CALL(client_, OnBufferingNotification(true)).Times(1); - scoped_refptr buffering_state = - buffering_controller_->AddStream("test"); - buffering_state->SetMediaTime(base::TimeDelta()); - - // Simulate pre-buffering. - buffering_state->SetBufferedTime(d2_); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kMediumLevel); - - EXPECT_CALL(client_, OnBufferingNotification(false)).Times(1); - buffering_state->SetBufferedTime(d3_); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kHighLevel); - - // Simulate some fluctuations of the buffering level. - buffering_state->SetBufferedTime(d2_); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kMediumLevel); - - // Simulate an underrun. - EXPECT_CALL(client_, OnBufferingNotification(true)).Times(1); - buffering_state->SetBufferedTime(d1_); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kLowLevel); - - EXPECT_CALL(client_, OnBufferingNotification(false)).Times(1); - buffering_state->SetBufferedTime(d3_); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kHighLevel); - - // Simulate the end of stream. - buffering_state->NotifyEos(); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kEosReached); - - buffering_state->SetBufferedTime(d2_); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kEosReached); - - buffering_state->SetBufferedTime(d1_); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kEosReached); -} - -TEST_F(BufferingControllerTest, OneStream_LeaveBufferingOnEos) { - EXPECT_CALL(client_, OnBufferingNotification(true)).Times(1); - scoped_refptr buffering_state = - buffering_controller_->AddStream("test"); - buffering_state->SetMediaTime(base::TimeDelta()); - - EXPECT_CALL(client_, OnBufferingNotification(false)).Times(1); - buffering_state->NotifyEos(); - EXPECT_EQ(buffering_state->GetState(), BufferingState::kEosReached); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_defs.cc chromium-132.0.6834.159/chromecast/media/cma/base/buffering_defs.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_defs.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_defs.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/buffering_defs.h" - -namespace chromecast { -namespace media { - -// TODO(servolk): Find a way to compute those values dynamically, based on -// input stream parameters. These sizes need to allow enough data to be buffered -// to reach high memory threshold of the buffering controller (see -// kHighBufferThresholdMediaSource/kHighBufferThresholdURL being used in media -// pipeline initialization in MediaPipelineImpl::Initialize). Otherwise CMA IPC -// might deadlock (playback is kept paused by buffering_controller since we have -// less than |high_threshold| of data buffered, media DecoderBuffers are kept -// alive holding on to the IPC shared memory and CMA IPC is stuck since it -// reached the buffer limit and can't send more data to the browser process). -const size_t kAppAudioBufferSize = 256 * 1024; -const size_t kAppVideoBufferSize = 4 * 1024 * 1024; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_defs.h chromium-132.0.6834.159/chromecast/media/cma/base/buffering_defs.h --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_defs.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_defs.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_BUFFERING_DEFS_H_ -#define CHROMECAST_MEDIA_CMA_BASE_BUFFERING_DEFS_H_ - -#include - -namespace chromecast { -namespace media { - -extern const size_t kAppAudioBufferSize; -extern const size_t kAppVideoBufferSize; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_BUFFERING_DEFS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_frame_provider.cc chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_frame_provider.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,142 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/buffering_frame_provider.h" - -#include - -#include "base/functional/bind.h" -#include "base/task/bind_post_task.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/base/buffering_state.h" - -namespace chromecast { -namespace media { - -BufferingFrameProvider::BufferWithConfig::BufferWithConfig( - const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) - : buffer_(buffer), - audio_config_(audio_config), - video_config_(video_config) { -} - -BufferingFrameProvider::BufferWithConfig::BufferWithConfig( - const BufferWithConfig& other) = default; - -BufferingFrameProvider::BufferWithConfig::~BufferWithConfig() { -} - -BufferingFrameProvider::BufferingFrameProvider( - std::unique_ptr coded_frame_provider, - size_t max_buffer_size, - size_t max_frame_size, - const FrameBufferedCB& frame_buffered_cb) - : coded_frame_provider_(std::move(coded_frame_provider)), - is_pending_request_(false), - is_eos_(false), - total_buffer_size_(0), - max_buffer_size_(max_buffer_size), - max_frame_size_(max_frame_size), - frame_buffered_cb_(frame_buffered_cb), - weak_factory_(this) { - DCHECK_LE(max_frame_size, max_buffer_size); - weak_this_ = weak_factory_.GetWeakPtr(); - thread_checker_.DetachFromThread(); -} - -BufferingFrameProvider::~BufferingFrameProvider() { - // Required since some weak pointers might be released in the destructor. - DCHECK(thread_checker_.CalledOnValidThread()); -} - -void BufferingFrameProvider::Read(ReadCB read_cb) { - DCHECK(thread_checker_.CalledOnValidThread()); - - DCHECK(!read_cb.is_null()); - read_cb_ = std::move(read_cb); - - CompleteReadIfNeeded(); - - RequestBufferIfNeeded(); -} - -void BufferingFrameProvider::Flush(base::OnceClosure flush_cb) { - DCHECK(thread_checker_.CalledOnValidThread()); - - // Invalidate all the buffers that belong to this media timeline. - // This is needed since, even though |coded_frame_provider_| is flushed later - // in this function, there might be a pending task holding onto a buffer. - weak_factory_.InvalidateWeakPtrs(); - - // Create a new valid weak pointer that is used for the next media timeline. - weak_this_ = weak_factory_.GetWeakPtr(); - - is_pending_request_ = false; - is_eos_ = false; - buffer_list_.clear(); - total_buffer_size_ = 0; - read_cb_.Reset(); - coded_frame_provider_->Flush(std::move(flush_cb)); -} - -void BufferingFrameProvider::OnNewBuffer( - const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) { - is_pending_request_ = false; - buffer_list_.push_back( - BufferWithConfig(buffer, audio_config, video_config)); - - if (buffer->end_of_stream()) { - is_eos_ = true; - } else { - total_buffer_size_ += buffer->data_size(); - } - - if (!frame_buffered_cb_.is_null()) { - // If the next upcoming frame is possibly filling the whole buffer, - // then the buffer is considered as having reached its max capacity. - bool max_capacity_flag = - (total_buffer_size_ + max_frame_size_ >= max_buffer_size_); - frame_buffered_cb_.Run(buffer, max_capacity_flag); - } - - RequestBufferIfNeeded(); - - CompleteReadIfNeeded(); -} - -void BufferingFrameProvider::RequestBufferIfNeeded() { - if (is_pending_request_) - return; - - if (is_eos_ || total_buffer_size_ >= max_buffer_size_) - return; - - is_pending_request_ = true; - coded_frame_provider_->Read(base::BindPostTaskToCurrentDefault( - base::BindOnce(&BufferingFrameProvider::OnNewBuffer, weak_this_))); -} - -void BufferingFrameProvider::CompleteReadIfNeeded() { - if (read_cb_.is_null()) - return; - - if (buffer_list_.empty()) - return; - - BufferWithConfig buffer_with_config(buffer_list_.front()); - buffer_list_.pop_front(); - if (!buffer_with_config.buffer()->end_of_stream()) - total_buffer_size_ -= buffer_with_config.buffer()->data_size(); - - std::move(read_cb_).Run(buffer_with_config.buffer(), - buffer_with_config.audio_config(), - buffer_with_config.video_config()); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_frame_provider.h chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider.h --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_frame_provider.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,123 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_BUFFERING_FRAME_PROVIDER_H_ -#define CHROMECAST_MEDIA_CMA_BASE_BUFFERING_FRAME_PROVIDER_H_ - -#include - -#include -#include - -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "chromecast/media/cma/base/coded_frame_provider.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/video_decoder_config.h" - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -// BufferingFrameProvider - -// Fetch some data from another CodedFrameProvider up to a certain size limit. -class BufferingFrameProvider : public CodedFrameProvider { - public: - typedef base::RepeatingCallback&, - bool)> - FrameBufferedCB; - - // Creates a frame provider that buffers coded frames up to the - // |max_buffer_size| limit (given as a number of bytes). - // |max_frame_size| corresponds to an upper bound of the expected frame size. - // Each time a frame is buffered, |frame_buffered_cb| is invoked with the - // last frame buffered. The second parameter of the callback indicates - // whether the maximum capacity has been reached, i.e. whether the next frame - // size might overflow the buffer: |total_buffer_size_| + next_frame_size - // might be greater than |max_buffer_size|. - // Note: takes ownership of |coded_frame_provider|. - BufferingFrameProvider( - std::unique_ptr coded_frame_provider, - size_t max_buffer_size, - size_t max_frame_size, - const FrameBufferedCB& frame_buffered_cb); - - BufferingFrameProvider(const BufferingFrameProvider&) = delete; - BufferingFrameProvider& operator=(const BufferingFrameProvider&) = delete; - - ~BufferingFrameProvider() override; - - // CodedFrameProvider implementation. - void Read(ReadCB read_cb) override; - void Flush(base::OnceClosure flush_cb) override; - - private: - class BufferWithConfig { - public: - BufferWithConfig( - const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config); - BufferWithConfig(const BufferWithConfig& other); - ~BufferWithConfig(); - - const scoped_refptr& buffer() const { return buffer_; } - const ::media::AudioDecoderConfig& audio_config() const { - return audio_config_; - } - const ::media::VideoDecoderConfig& video_config() const { - return video_config_; - } - - private: - scoped_refptr buffer_; - ::media::AudioDecoderConfig audio_config_; - ::media::VideoDecoderConfig video_config_; - }; - - void OnNewBuffer(const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config); - void RequestBufferIfNeeded(); - void CompleteReadIfNeeded(); - - base::ThreadChecker thread_checker_; - - // Frame provider the buffering frame provider fetches data from. - std::unique_ptr coded_frame_provider_; - - // Indicates whether there is a pending read request on - // |coded_frame_provider_|. - bool is_pending_request_; - - // Indicates whether the end of stream has been reached. - bool is_eos_; - - std::list buffer_list_; - - // Size in bytes of audio/video buffers in |buffer_list_|. - size_t total_buffer_size_; - - // Max amount of data to buffer. - // i.e. this is the maximum size of buffers in |buffer_list_|. - const size_t max_buffer_size_; - - // Maximum expected frame size. - const size_t max_frame_size_; - - // Callback invoked each time there is a new frame buffered. - FrameBufferedCB frame_buffered_cb_; - - // Pending read callback. - ReadCB read_cb_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_BUFFERING_FRAME_PROVIDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_frame_provider_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_frame_provider_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_frame_provider_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,196 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/buffering_frame_provider.h" - -#include - -#include -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "base/task/current_thread.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "base/time/time.h" -#include "chromecast/media/cma/test/frame_generator_for_test.h" -#include "chromecast/media/cma/test/mock_frame_consumer.h" -#include "chromecast/media/cma/test/mock_frame_provider.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/decoder_buffer.h" -#include "media/base/video_decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -class BufferingFrameProviderTest : public testing::Test { - public: - BufferingFrameProviderTest(); - - BufferingFrameProviderTest(const BufferingFrameProviderTest&) = delete; - BufferingFrameProviderTest& operator=(const BufferingFrameProviderTest&) = - delete; - - ~BufferingFrameProviderTest() override; - - // Setup the test. - void Configure( - size_t frame_count, - const std::vector& provider_delayed_pattern, - const std::vector& consumer_delayed_pattern); - - // Start the test. - void Start(); - - // Run the RunLoop and process messages - void Run(); - - protected: - std::unique_ptr buffering_frame_provider_; - std::unique_ptr frame_consumer_; - - private: - void OnTestTimeout(); - void OnTestCompleted(); - - base::OnceClosure quit_closure_; -}; - -BufferingFrameProviderTest::BufferingFrameProviderTest() { -} - -BufferingFrameProviderTest::~BufferingFrameProviderTest() { -} -void BufferingFrameProviderTest::Run() { - base::RunLoop loop; - quit_closure_ = loop.QuitWhenIdleClosure(); - loop.Run(); -} -void BufferingFrameProviderTest::Configure( - size_t frame_count, - const std::vector& provider_delayed_pattern, - const std::vector& consumer_delayed_pattern) { - DCHECK_GE(frame_count, 1u); - - // Frame generation on the producer and consumer side. - std::vector frame_specs(frame_count); - for (size_t k = 0; k < frame_specs.size() - 1; k++) { - frame_specs[k].has_config = (k == 0); - frame_specs[k].timestamp = base::Milliseconds(40) * k; - frame_specs[k].size = 512; - frame_specs[k].has_decrypt_config = ((k % 3) == 0); - } - frame_specs.back().is_eos = true; - - std::unique_ptr frame_generator_provider( - new FrameGeneratorForTest(frame_specs)); - std::unique_ptr frame_generator_consumer( - new FrameGeneratorForTest(frame_specs)); - - std::unique_ptr frame_provider(new MockFrameProvider()); - frame_provider->Configure(provider_delayed_pattern, - std::move(frame_generator_provider)); - - size_t max_frame_size = 10 * 1024; - size_t buffer_size = 10 * max_frame_size; - buffering_frame_provider_.reset(new BufferingFrameProvider( - std::unique_ptr(frame_provider.release()), - buffer_size, max_frame_size, BufferingFrameProvider::FrameBufferedCB())); - - frame_consumer_.reset( - new MockFrameConsumer(buffering_frame_provider_.get())); - frame_consumer_->Configure(consumer_delayed_pattern, false, - std::move(frame_generator_consumer)); -} - -void BufferingFrameProviderTest::Start() { - frame_consumer_->Start(base::BindOnce( - &BufferingFrameProviderTest::OnTestCompleted, base::Unretained(this))); -} - -void BufferingFrameProviderTest::OnTestTimeout() { - ADD_FAILURE() << "Test timed out"; - std::move(quit_closure_).Run(); -} - -void BufferingFrameProviderTest::OnTestCompleted() { - std::move(quit_closure_).Run(); -} - -TEST_F(BufferingFrameProviderTest, FastProviderSlowConsumer) { - bool provider_delayed_pattern[] = { false }; - bool consumer_delayed_pattern[] = { true }; - - const size_t frame_count = 100u; - Configure(frame_count, - std::vector( - provider_delayed_pattern, - provider_delayed_pattern + std::size(provider_delayed_pattern)), - std::vector(consumer_delayed_pattern, - consumer_delayed_pattern + - std::size(consumer_delayed_pattern))); - - base::test::SingleThreadTaskEnvironment task_environment; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&BufferingFrameProviderTest::Start, - base::Unretained(this))); - Run(); -} - -TEST_F(BufferingFrameProviderTest, SlowProviderFastConsumer) { - bool provider_delayed_pattern[] = { true }; - bool consumer_delayed_pattern[] = { false }; - - const size_t frame_count = 100u; - Configure(frame_count, - std::vector( - provider_delayed_pattern, - provider_delayed_pattern + std::size(provider_delayed_pattern)), - std::vector(consumer_delayed_pattern, - consumer_delayed_pattern + - std::size(consumer_delayed_pattern))); - - base::test::SingleThreadTaskEnvironment task_environment; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&BufferingFrameProviderTest::Start, - base::Unretained(this))); - Run(); -} - -TEST_F(BufferingFrameProviderTest, SlowFastProducerConsumer) { - // Lengths are prime between each other so we can test a lot of combinations. - bool provider_delayed_pattern[] = { - true, true, true, true, true, - false, false, false, false - }; - bool consumer_delayed_pattern[] = { - true, true, true, true, true, true, true, - false, false, false, false, false, false, false - }; - - const size_t frame_count = 100u; - Configure(frame_count, - std::vector( - provider_delayed_pattern, - provider_delayed_pattern + std::size(provider_delayed_pattern)), - std::vector(consumer_delayed_pattern, - consumer_delayed_pattern + - std::size(consumer_delayed_pattern))); - - base::test::SingleThreadTaskEnvironment task_environment; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&BufferingFrameProviderTest::Start, - base::Unretained(this))); - Run(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_state.cc chromium-132.0.6834.159/chromecast/media/cma/base/buffering_state.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_state.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_state.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/buffering_state.h" - -#include - -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "media/base/timestamp_constants.h" - -namespace chromecast { -namespace media { - -BufferingConfig::BufferingConfig( - base::TimeDelta low_level_threshold, - base::TimeDelta high_level_threshold) - : low_level_threshold_(low_level_threshold), - high_level_threshold_(high_level_threshold) { -} - -BufferingConfig::~BufferingConfig() { -} - -BufferingState::BufferingState(const std::string& stream_id, - const scoped_refptr& config, - const base::RepeatingClosure& state_changed_cb, - const HighLevelBufferCB& high_level_buffer_cb) - : stream_id_(stream_id), - config_(config), - state_changed_cb_(state_changed_cb), - high_level_buffer_cb_(high_level_buffer_cb), - state_(kLowLevel), - media_time_(::media::kNoTimestamp), - max_rendering_time_(::media::kNoTimestamp), - buffered_time_(::media::kNoTimestamp) {} - -BufferingState::~BufferingState() { -} - -void BufferingState::OnConfigChanged() { - state_ = GetBufferLevelState(); -} - -void BufferingState::SetMediaTime(base::TimeDelta media_time) { - media_time_ = media_time; - switch (state_) { - case kLowLevel: - case kMediumLevel: - case kHighLevel: - UpdateState(GetBufferLevelState()); - break; - case kEosReached: - break; - } -} - -void BufferingState::SetMaxRenderingTime(base::TimeDelta max_rendering_time) { - max_rendering_time_ = max_rendering_time; -} - -base::TimeDelta BufferingState::GetMaxRenderingTime() const { - return max_rendering_time_; -} - -void BufferingState::SetBufferedTime(base::TimeDelta buffered_time) { - buffered_time_ = buffered_time; - switch (state_) { - case kLowLevel: - case kMediumLevel: - case kHighLevel: - UpdateState(GetBufferLevelState()); - break; - case kEosReached: - break; - } -} - -void BufferingState::NotifyEos() { - UpdateState(kEosReached); -} - -void BufferingState::NotifyMaxCapacity(base::TimeDelta buffered_time) { - if (media_time_ == ::media::kNoTimestamp || - buffered_time == ::media::kNoTimestamp) { - LOG(WARNING) << "Max capacity with no timestamp"; - return; - } - base::TimeDelta buffer_duration = buffered_time - media_time_; - if (buffer_duration < config_->high_level()) - high_level_buffer_cb_.Run(buffer_duration); -} - -static const char* StateToString(BufferingState::State state) { - switch (state) { - case BufferingState::kLowLevel: - return "kLowLevel"; - case BufferingState::kMediumLevel: - return "kMediumLevel"; - case BufferingState::kHighLevel: - return "kHighLevel"; - case BufferingState::kEosReached: - return "kEosReached"; - default: - NOTREACHED(); - } -} - -static std::string TimeDeltaToString(const base::TimeDelta& t) { - if (t == ::media::kNoTimestamp) - return "kNoTimestamp"; - return base::NumberToString(t.InSecondsF()); -} - -std::string BufferingState::ToString() const { - std::ostringstream s; - s << stream_id_ << " state=" << StateToString(state_) - << " media_time=" << TimeDeltaToString(media_time_) - << " buffered_time=" << TimeDeltaToString(buffered_time_); - return s.str(); -} - -BufferingState::State BufferingState::GetBufferLevelState() const { - if (media_time_ == ::media::kNoTimestamp || - buffered_time_ == ::media::kNoTimestamp) { - return kLowLevel; - } - - base::TimeDelta buffer_duration = buffered_time_ - media_time_; - if (buffer_duration <= config_->low_level()) - return kLowLevel; - if (buffer_duration >= config_->high_level()) - return kHighLevel; - return kMediumLevel; -} - -void BufferingState::UpdateState(State new_state) { - if (new_state == state_) - return; - - state_ = new_state; - if (!state_changed_cb_.is_null()) - state_changed_cb_.Run(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/buffering_state.h chromium-132.0.6834.159/chromecast/media/cma/base/buffering_state.h --- chromium-132.0.6834.110/chromecast/media/cma/base/buffering_state.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/buffering_state.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,141 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_BUFFERING_STATE_H_ -#define CHROMECAST_MEDIA_CMA_BASE_BUFFERING_STATE_H_ - -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/time/time.h" - -namespace chromecast { -namespace media { - -class BufferingConfig : public base::RefCountedThreadSafe { - public: - BufferingConfig(base::TimeDelta low_level_threshold, - base::TimeDelta high_level_threshold); - - BufferingConfig(const BufferingConfig&) = delete; - BufferingConfig& operator=(const BufferingConfig&) = delete; - - base::TimeDelta low_level() const { return low_level_threshold_; } - base::TimeDelta high_level() const { return high_level_threshold_; } - - void set_low_level(base::TimeDelta low_level) { - low_level_threshold_ = low_level; - } - void set_high_level(base::TimeDelta high_level) { - high_level_threshold_ = high_level; - } - - private: - friend class base::RefCountedThreadSafe; - virtual ~BufferingConfig(); - - base::TimeDelta low_level_threshold_; - base::TimeDelta high_level_threshold_; -}; - -class BufferingState - : public base::RefCountedThreadSafe { - public: - typedef base::RepeatingCallback HighLevelBufferCB; - - enum State { - kLowLevel, - kMediumLevel, - kHighLevel, - kEosReached, - }; - - // Creates a new buffering state. The initial state is |kLowLevel|. - // |state_changed_cb| is used to notify about possible state changes. - // |high_level_buffer_cb| is used to adjust the high buffer threshold - // when the underlying buffer is not large enough to accomodate - // the current high buffer level. - BufferingState(const std::string& stream_id, - const scoped_refptr& config, - const base::RepeatingClosure& state_changed_cb, - const HighLevelBufferCB& high_level_buffer_cb); - - BufferingState(const BufferingState&) = delete; - BufferingState& operator=(const BufferingState&) = delete; - - // Returns the buffering state. - State GetState() const { return state_; } - - // Invoked when the buffering configuration has changed. - // Based on the new configuration, the buffering state might change. - // However, |state_changed_cb_| is not triggered in that case. - void OnConfigChanged(); - - // Sets the current rendering time for this stream. - void SetMediaTime(base::TimeDelta media_time); - - // Sets/gets the maximum rendering media time for this stream. - // The maximum rendering time is always lower than the buffered time. - void SetMaxRenderingTime(base::TimeDelta max_rendering_time); - base::TimeDelta GetMaxRenderingTime() const; - - // Sets the buffered time. - void SetBufferedTime(base::TimeDelta buffered_time); - - // Notifies the buffering state that all the frames for this stream have been - // buffered, i.e. the end of stream has been reached. - void NotifyEos(); - - // Notifies the buffering state the underlying buffer has reached - // its maximum capacity. - // The maximum frame timestamp in the buffer is given by |buffered_time|. - // Note: this timestamp can be different from the one provided through - // SetBufferedTime since SetBufferedTime takes the timestamp of a playable - // frame which is not necessarily the case here (e.g. missing key id). - void NotifyMaxCapacity(base::TimeDelta buffered_time); - - // Buffering state as a human readable string, for debugging. - std::string ToString() const; - - private: - friend class base::RefCountedThreadSafe; - virtual ~BufferingState(); - - // Returns the state solely based on the buffered time. - State GetBufferLevelState() const; - - // Updates the state to |new_state|. - void UpdateState(State new_state); - - std::string const stream_id_; - scoped_refptr const config_; - - // Callback invoked each time there is a change of state. - base::RepeatingClosure state_changed_cb_; - - // Callback invoked to adjust the high buffer level. - HighLevelBufferCB high_level_buffer_cb_; - - // State. - State state_; - - // Playback media time. - // Equal to kNoTimestamp when not known. - base::TimeDelta media_time_; - - // Maximum rendering media time. - // This corresponds to the timestamp of the last frame sent to the hardware - // decoder/renderer. - base::TimeDelta max_rendering_time_; - - // Buffered media time. - // Equal to kNoTimestamp when not known. - base::TimeDelta buffered_time_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_BUFFERING_STATE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/cast_decrypt_config_impl.cc chromium-132.0.6834.159/chromecast/media/cma/base/cast_decrypt_config_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/cast_decrypt_config_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/cast_decrypt_config_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// 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 "chromecast/media/cma/base/cast_decrypt_config_impl.h" - -namespace chromecast { -namespace media { - -CastDecryptConfigImpl::CastDecryptConfigImpl( - std::string key_id, - std::string iv, - const EncryptionPattern& pattern, - std::vector subsamples, - EncryptionScheme encryption_scheme) - : key_id_(std::move(key_id)), - iv_(std::move(iv)), - pattern_(pattern), - subsamples_(std::move(subsamples)), - encryption_scheme_(encryption_scheme) {} - -CastDecryptConfigImpl::~CastDecryptConfigImpl() {} - -const std::string& CastDecryptConfigImpl::key_id() const { - return key_id_; -} - -const std::string& CastDecryptConfigImpl::iv() const { - return iv_; -} - -const EncryptionPattern& CastDecryptConfigImpl::pattern() const { - return pattern_; -} - -const std::vector& CastDecryptConfigImpl::subsamples() const { - return subsamples_; -} - -EncryptionScheme CastDecryptConfigImpl::encryption_scheme() const { - return encryption_scheme_; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/cast_decrypt_config_impl.h chromium-132.0.6834.159/chromecast/media/cma/base/cast_decrypt_config_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/base/cast_decrypt_config_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/cast_decrypt_config_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_CAST_DECRYPT_CONFIG_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_BASE_CAST_DECRYPT_CONFIG_IMPL_H_ - -#include "chromecast/public/media/cast_decrypt_config.h" - -namespace chromecast { -namespace media { - -// Contains all information that a decryptor needs to decrypt a media sample. -class CastDecryptConfigImpl : public CastDecryptConfig { - public: - CastDecryptConfigImpl(std::string key_id, - std::string iv, - const EncryptionPattern& pattern, - std::vector subsamples, - EncryptionScheme encryption_scheme); - ~CastDecryptConfigImpl() override; - - const std::string& key_id() const override; - const std::string& iv() const override; - const EncryptionPattern& pattern() const override; - const std::vector& subsamples() const override; - EncryptionScheme encryption_scheme() const override; - - private: - std::string key_id_; - std::string iv_; - const EncryptionPattern pattern_; - std::vector subsamples_; - EncryptionScheme encryption_scheme_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_CAST_DECRYPT_CONFIG_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/coded_frame_provider.cc chromium-132.0.6834.159/chromecast/media/cma/base/coded_frame_provider.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/coded_frame_provider.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/coded_frame_provider.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/coded_frame_provider.h" - -namespace chromecast { -namespace media { - -CodedFrameProvider::CodedFrameProvider() { -} - -CodedFrameProvider::~CodedFrameProvider() { -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/coded_frame_provider.h chromium-132.0.6834.159/chromecast/media/cma/base/coded_frame_provider.h --- chromium-132.0.6834.110/chromecast/media/cma/base/coded_frame_provider.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/coded_frame_provider.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_CODED_FRAME_PROVIDER_H_ -#define CHROMECAST_MEDIA_CMA_BASE_CODED_FRAME_PROVIDER_H_ - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" - -namespace media { -class AudioDecoderConfig; -class VideoDecoderConfig; -} - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -class CodedFrameProvider { - public: - typedef base::OnceCallback&, - const ::media::AudioDecoderConfig&, - const ::media::VideoDecoderConfig&)> - ReadCB; - - CodedFrameProvider(); - - CodedFrameProvider(const CodedFrameProvider&) = delete; - CodedFrameProvider& operator=(const CodedFrameProvider&) = delete; - - virtual ~CodedFrameProvider(); - - // Request a coded frame which is provided asynchronously through callback - // |read_cb|. - // If the frame is associated with a new video/audio configuration, - // these configurations are returned as part of the |read_cb| callback. - // Invoking the |read_cb| callback with invalid audio/video configurations - // means the configurations have not changed. - virtual void Read(ReadCB read_cb) = 0; - - // Flush the coded frames held by the frame provider. - // Invoke callback |flush_cb| when completed. - // Note: any pending read is cancelled, meaning that any pending |read_cb| - // callback will not be invoked. - // TODO(alokp): Delete this function once CmaRenderer is deprecated. - virtual void Flush(base::OnceClosure flush_cb) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_CODED_FRAME_PROVIDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/decoder_buffer_adapter.cc chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/decoder_buffer_adapter.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,110 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" - -#include "base/notreached.h" -#include "chromecast/media/cma/base/cast_decrypt_config_impl.h" -#include "chromecast/public/media/cast_decrypt_config.h" -#include "media/base/decoder_buffer.h" - -namespace chromecast { -namespace media { - -namespace { - -// Converts a chromium EncryptionScheme to a cast one. -EncryptionScheme ToEncryptionScheme(::media::EncryptionScheme scheme) { - switch (scheme) { - case ::media::EncryptionScheme::kUnencrypted: - return EncryptionScheme::kUnencrypted; - case ::media::EncryptionScheme::kCenc: - return EncryptionScheme::kAesCtr; - case ::media::EncryptionScheme::kCbcs: - return EncryptionScheme::kAesCbc; - default: - NOTREACHED(); - } -} - -} // namespace - -DecoderBufferAdapter::DecoderBufferAdapter( - const scoped_refptr<::media::DecoderBuffer>& buffer) - : DecoderBufferAdapter(kPrimary, buffer) {} - -DecoderBufferAdapter::DecoderBufferAdapter( - StreamId stream_id, - const scoped_refptr<::media::DecoderBuffer>& buffer) - : stream_id_(stream_id), buffer_(buffer) { - DCHECK(buffer_); - - const ::media::DecryptConfig* decrypt_config = - buffer_->end_of_stream() ? nullptr : buffer_->decrypt_config(); - if (decrypt_config) { - std::vector subsamples; - for (const auto& sample : decrypt_config->subsamples()) { - subsamples.emplace_back(sample.clear_bytes, sample.cypher_bytes); - } - if (subsamples.empty()) { - // DecryptConfig may contain 0 subsamples if all content is encrypted. - // Map this case to a single fully-encrypted "subsample" for more - // consistent backend handling. - subsamples.emplace_back(0, buffer_->size()); - } - - EncryptionPattern pattern; - if (decrypt_config->encryption_pattern()) { - pattern = EncryptionPattern( - decrypt_config->encryption_pattern()->crypt_byte_block(), - decrypt_config->encryption_pattern()->skip_byte_block()); - } - - decrypt_config_.reset(new CastDecryptConfigImpl( - decrypt_config->key_id(), decrypt_config->iv(), pattern, - std::move(subsamples), - ToEncryptionScheme(decrypt_config->encryption_scheme()))); - } -} - -DecoderBufferAdapter::~DecoderBufferAdapter() {} - -StreamId DecoderBufferAdapter::stream_id() const { - return stream_id_; -} - -int64_t DecoderBufferAdapter::timestamp() const { - return buffer_->timestamp().InMicroseconds(); -} - -void DecoderBufferAdapter::set_timestamp(base::TimeDelta timestamp) { - buffer_->set_timestamp(timestamp); -} - -const uint8_t* DecoderBufferAdapter::data() const { - return buffer_->data(); -} - -uint8_t* DecoderBufferAdapter::writable_data() const { - return buffer_->writable_data(); -} - -size_t DecoderBufferAdapter::data_size() const { - return buffer_->size(); -} - -const CastDecryptConfig* DecoderBufferAdapter::decrypt_config() const { - return decrypt_config_.get(); -} - -bool DecoderBufferAdapter::end_of_stream() const { - return buffer_->end_of_stream(); -} - -bool DecoderBufferAdapter::is_key_frame() const { - return buffer_->is_key_frame(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/decoder_buffer_adapter.h chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter.h --- chromium-132.0.6834.110/chromecast/media/cma/base/decoder_buffer_adapter.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_DECODER_BUFFER_ADAPTER_H_ -#define CHROMECAST_MEDIA_CMA_BASE_DECODER_BUFFER_ADAPTER_H_ - -#include -#include - -#include - -#include "chromecast/media/api/decoder_buffer_base.h" - -namespace media { -class DecoderBuffer; -} - -namespace chromecast { -namespace media { - -// DecoderBufferAdapter wraps a ::media::DecoderBuffer -// into a DecoderBufferBase. -class DecoderBufferAdapter : public DecoderBufferBase { - public: - // Using explicit constructor without providing stream Id will set it to - // kPrimary by default. - explicit DecoderBufferAdapter( - const scoped_refptr<::media::DecoderBuffer>& buffer); - DecoderBufferAdapter(StreamId stream_id, - const scoped_refptr<::media::DecoderBuffer>& buffer); - - DecoderBufferAdapter(const DecoderBufferAdapter&) = delete; - DecoderBufferAdapter& operator=(const DecoderBufferAdapter&) = delete; - - // DecoderBufferBase implementation: - StreamId stream_id() const override; - int64_t timestamp() const override; - void set_timestamp(base::TimeDelta timestamp) override; - const uint8_t* data() const override; - uint8_t* writable_data() const override; - size_t data_size() const override; - const CastDecryptConfig* decrypt_config() const override; - bool end_of_stream() const override; - bool is_key_frame() const override; - - private: - ~DecoderBufferAdapter() override; - - StreamId stream_id_; - scoped_refptr<::media::DecoderBuffer> const buffer_; - std::unique_ptr decrypt_config_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_DECODER_BUFFER_ADAPTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/decoder_buffer_adapter_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/decoder_buffer_adapter_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/decoder_buffer_adapter_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,192 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" - -#include "base/memory/scoped_refptr.h" -#include "chromecast/public/media/cast_decrypt_config.h" -#include "media/base/decoder_buffer.h" -#include "media/base/decrypt_config.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::NotNull; - -constexpr uint8_t kBufferData[] = "hello"; -constexpr size_t kBufferDataSize = std::size(kBufferData); -constexpr int64_t kBufferTimestampUs = 31; -// This has to be DecryptConfig::kDecryptionKeySize=16 bytes. -constexpr char kIv[] = "0123456789ABCDEF"; - -scoped_refptr<::media::DecoderBuffer> MakeDecoderBuffer() { - scoped_refptr<::media::DecoderBuffer> buffer = - ::media::DecoderBuffer::CopyFrom(kBufferData); - buffer->set_timestamp(base::Microseconds(kBufferTimestampUs)); - return buffer; -} - -TEST(DecoderBufferAdapterTest, Default) { - scoped_refptr<::media::DecoderBuffer> buffer = MakeDecoderBuffer(); - scoped_refptr buffer_adapter( - new DecoderBufferAdapter(buffer)); - - EXPECT_EQ(kPrimary, buffer_adapter->stream_id()); - EXPECT_EQ(kBufferTimestampUs, buffer_adapter->timestamp()); - EXPECT_EQ(0, memcmp(buffer_adapter->data(), kBufferData, kBufferDataSize)); - EXPECT_EQ(kBufferDataSize, buffer_adapter->data_size()); - EXPECT_EQ(nullptr, buffer_adapter->decrypt_config()); - EXPECT_FALSE(buffer_adapter->end_of_stream()); -} - -TEST(DecoderBufferAdapterTest, Secondary) { - scoped_refptr buffer_adapter( - new DecoderBufferAdapter(kSecondary, MakeDecoderBuffer())); - EXPECT_EQ(kSecondary, buffer_adapter->stream_id()); -} - -TEST(DecoderBufferAdapterTest, Timestamp) { - scoped_refptr buffer_adapter( - new DecoderBufferAdapter(MakeDecoderBuffer())); - EXPECT_EQ(kBufferTimestampUs, buffer_adapter->timestamp()); - - const int64_t kTestTimestampUs = 62; - buffer_adapter->set_timestamp(base::Microseconds(kTestTimestampUs)); - EXPECT_EQ(kTestTimestampUs, buffer_adapter->timestamp()); -} - -TEST(DecoderBufferAdapterTest, Data) { - scoped_refptr buffer_adapter( - new DecoderBufferAdapter(MakeDecoderBuffer())); - EXPECT_EQ(0, memcmp(buffer_adapter->data(), kBufferData, kBufferDataSize)); - EXPECT_EQ(kBufferDataSize, buffer_adapter->data_size()); - - const uint8_t kTestBufferData[] = "world"; - const size_t kTestBufferDataSize = std::size(kTestBufferData); - memcpy(buffer_adapter->writable_data(), kTestBufferData, kTestBufferDataSize); - EXPECT_EQ( - 0, memcmp(buffer_adapter->data(), kTestBufferData, kTestBufferDataSize)); - EXPECT_EQ(kTestBufferDataSize, buffer_adapter->data_size()); -} - -TEST(DecoderBufferAdapterTest, DecryptConfig) { - const std::string kKeyId("foo-key"); - const std::string kIV("0123456789abcdef"); - - // No DecryptConfig. - { - scoped_refptr<::media::DecoderBuffer> buffer = MakeDecoderBuffer(); - EXPECT_EQ(nullptr, buffer->decrypt_config()); - scoped_refptr buffer_adapter( - new DecoderBufferAdapter(buffer)); - // DecoderBufferAdapter ignores the decrypt config. - EXPECT_EQ(nullptr, buffer_adapter->decrypt_config()); - } - - // Empty subsamples. - { - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCencConfig(kKeyId, kIV, {}); - EXPECT_TRUE(decrypt_config); - - scoped_refptr<::media::DecoderBuffer> buffer = MakeDecoderBuffer(); - buffer->set_decrypt_config(std::move(decrypt_config)); - scoped_refptr buffer_adapter( - new DecoderBufferAdapter(buffer)); - const CastDecryptConfig* cast_decrypt_config = - buffer_adapter->decrypt_config(); - EXPECT_NE(nullptr, cast_decrypt_config); - EXPECT_EQ(kKeyId, cast_decrypt_config->key_id()); - EXPECT_EQ(kIV, cast_decrypt_config->iv()); - // DecoderBufferAdapter creates a single fully-encrypted subsample. - EXPECT_EQ(1u, cast_decrypt_config->subsamples().size()); - EXPECT_EQ(0u, cast_decrypt_config->subsamples()[0].clear_bytes); - EXPECT_EQ(kBufferDataSize, - cast_decrypt_config->subsamples()[0].cypher_bytes); - } - - // Regular DecryptConfig with non-empty subsamples. - { - uint32_t kClearBytes[] = {10, 15}; - uint32_t kCypherBytes[] = {5, 7}; - std::vector<::media::SubsampleEntry> subsamples; - subsamples.emplace_back(kClearBytes[0], kCypherBytes[0]); - subsamples.emplace_back(kClearBytes[1], kCypherBytes[1]); - - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCencConfig(kKeyId, kIV, subsamples); - EXPECT_TRUE(decrypt_config); - - scoped_refptr<::media::DecoderBuffer> buffer = MakeDecoderBuffer(); - buffer->set_decrypt_config(std::move(decrypt_config)); - scoped_refptr buffer_adapter( - new DecoderBufferAdapter(buffer)); - const CastDecryptConfig* cast_decrypt_config = - buffer_adapter->decrypt_config(); - EXPECT_NE(nullptr, cast_decrypt_config); - EXPECT_EQ(kKeyId, cast_decrypt_config->key_id()); - EXPECT_EQ(kIV, cast_decrypt_config->iv()); - // DecoderBufferAdapter copies all subsamples. - EXPECT_EQ(2u, cast_decrypt_config->subsamples().size()); - EXPECT_EQ(kClearBytes[0], cast_decrypt_config->subsamples()[0].clear_bytes); - EXPECT_EQ(kCypherBytes[0], - cast_decrypt_config->subsamples()[0].cypher_bytes); - EXPECT_EQ(kClearBytes[1], cast_decrypt_config->subsamples()[1].clear_bytes); - EXPECT_EQ(kCypherBytes[1], - cast_decrypt_config->subsamples()[1].cypher_bytes); - } -} - -TEST(DecoderBufferAdapterTest, EndOfStream) { - scoped_refptr buffer_adapter( - new DecoderBufferAdapter(::media::DecoderBuffer::CreateEOSBuffer())); - EXPECT_TRUE(buffer_adapter->end_of_stream()); - EXPECT_EQ(nullptr, buffer_adapter->decrypt_config()); -} - -TEST(DecoderBufferAdapterTest, SetsEncryptionSchemeOfCencDecryptConfig) { - scoped_refptr<::media::DecoderBuffer> buffer = MakeDecoderBuffer(); - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCencConfig("key_id", kIv, - /*subsamples=*/{}); - buffer->set_decrypt_config(std::move(decrypt_config)); - - auto buffer_adapter = base::MakeRefCounted(buffer); - ASSERT_THAT(buffer_adapter->decrypt_config(), NotNull()); - EXPECT_EQ(buffer_adapter->decrypt_config()->encryption_scheme(), - EncryptionScheme::kAesCtr); -} - -TEST(DecoderBufferAdapterTest, SetsEncryptionSchemeOfCbcsDecryptConfig) { - scoped_refptr<::media::DecoderBuffer> buffer = MakeDecoderBuffer(); - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCbcsConfig( - "key_id", kIv, - /*subsamples=*/{}, - /*encryption_pattern=*/std::nullopt); - buffer->set_decrypt_config(std::move(decrypt_config)); - - auto buffer_adapter = base::MakeRefCounted(buffer); - ASSERT_THAT(buffer_adapter->decrypt_config(), NotNull()); - EXPECT_EQ(buffer_adapter->decrypt_config()->encryption_scheme(), - EncryptionScheme::kAesCbc); -} - -TEST(DecoderBufferAdapterTest, HandlesIsKeyFrame) { - scoped_refptr<::media::DecoderBuffer> buffer = MakeDecoderBuffer(); - auto buffer_adapter = base::MakeRefCounted(buffer); - - buffer->set_is_key_frame(true); - EXPECT_TRUE(buffer_adapter->is_key_frame()); - - buffer->set_is_key_frame(false); - EXPECT_FALSE(buffer_adapter->is_key_frame()); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/decoder_config_adapter.cc chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/decoder_config_adapter.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,387 +0,0 @@ -// 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 "chromecast/media/cma/base/decoder_config_adapter.h" - -#include "base/logging.h" -#include "build/build_config.h" -#include "chromecast/media/base/media_codec_support.h" -#include "media/base/channel_layout.h" -#include "media/base/encryption_pattern.h" -#include "media/base/encryption_scheme.h" -#include "ui/gfx/hdr_metadata.h" - -namespace chromecast { -namespace media { - -namespace { - -// Converts ::media::AudioCodec to chromecast::media::AudioCodec. Any unknown or -// unsupported codec will be converted to chromecast::media::kCodecUnknown. -AudioCodec ToAudioCodec(const ::media::AudioCodec audio_codec) { - switch (audio_codec) { - case ::media::AudioCodec::kAAC: - return kCodecAAC; - case ::media::AudioCodec::kMP3: - return kCodecMP3; - case ::media::AudioCodec::kPCM: - return kCodecPCM; - case ::media::AudioCodec::kPCM_S16BE: - return kCodecPCM_S16BE; - case ::media::AudioCodec::kVorbis: - return kCodecVorbis; - case ::media::AudioCodec::kOpus: - return kCodecOpus; - case ::media::AudioCodec::kFLAC: - return kCodecFLAC; - case ::media::AudioCodec::kEAC3: - return kCodecEAC3; - case ::media::AudioCodec::kAC3: - return kCodecAC3; - case ::media::AudioCodec::kMpegHAudio: - return kCodecMpegHAudio; - case ::media::AudioCodec::kDTS: - return kCodecDTS; - case ::media::AudioCodec::kDTSXP2: - return kCodecDTSXP2; - case ::media::AudioCodec::kDTSE: - return kCodecDTSE; - default: - LOG(ERROR) << "Unsupported audio codec " << audio_codec; - } - return kAudioCodecUnknown; -} - -SampleFormat ToSampleFormat(const ::media::SampleFormat sample_format) { - switch (sample_format) { - case ::media::kUnknownSampleFormat: - case ::media::kSampleFormatAc3: - case ::media::kSampleFormatEac3: - case ::media::kSampleFormatDts: - case ::media::kSampleFormatDtsxP2: - case ::media::kSampleFormatMpegHAudio: - case ::media::kSampleFormatIECDts: - case ::media::kSampleFormatDtse: - return kUnknownSampleFormat; - case ::media::kSampleFormatU8: - return kSampleFormatU8; - case ::media::kSampleFormatS16: - return kSampleFormatS16; - case ::media::kSampleFormatS24: - return kSampleFormatS24; - case ::media::kSampleFormatS32: - return kSampleFormatS32; - case ::media::kSampleFormatF32: - return kSampleFormatF32; - case ::media::kSampleFormatPlanarU8: - return kSampleFormatPlanarU8; - case ::media::kSampleFormatPlanarS16: - return kSampleFormatPlanarS16; - case ::media::kSampleFormatPlanarF32: - return kSampleFormatPlanarF32; - case ::media::kSampleFormatPlanarS32: - return kSampleFormatPlanarS32; - } - NOTREACHED(); -} - -::media::SampleFormat ToMediaSampleFormat(const SampleFormat sample_format) { - switch (sample_format) { - case kUnknownSampleFormat: - return ::media::kUnknownSampleFormat; - case kSampleFormatU8: - return ::media::kSampleFormatU8; - case kSampleFormatS16: - return ::media::kSampleFormatS16; - case kSampleFormatS24: - return ::media::kSampleFormatS24; - case kSampleFormatS32: - return ::media::kSampleFormatS32; - case kSampleFormatF32: - return ::media::kSampleFormatF32; - case kSampleFormatPlanarU8: - return ::media::kSampleFormatPlanarU8; - case kSampleFormatPlanarS16: - return ::media::kSampleFormatPlanarS16; - case kSampleFormatPlanarF32: - return ::media::kSampleFormatPlanarF32; - case kSampleFormatPlanarS32: - return ::media::kSampleFormatPlanarS32; - default: - NOTREACHED(); - } -} - -::media::AudioCodec ToMediaAudioCodec( - const chromecast::media::AudioCodec codec) { - switch (codec) { - case kAudioCodecUnknown: - return ::media::AudioCodec::kUnknown; - case kCodecAAC: - return ::media::AudioCodec::kAAC; - case kCodecMP3: - return ::media::AudioCodec::kMP3; - case kCodecPCM: - return ::media::AudioCodec::kPCM; - case kCodecPCM_S16BE: - return ::media::AudioCodec::kPCM_S16BE; - case kCodecVorbis: - return ::media::AudioCodec::kVorbis; - case kCodecOpus: - return ::media::AudioCodec::kOpus; - case kCodecFLAC: - return ::media::AudioCodec::kFLAC; - case kCodecEAC3: - return ::media::AudioCodec::kEAC3; - case kCodecAC3: - return ::media::AudioCodec::kAC3; - case kCodecMpegHAudio: - return ::media::AudioCodec::kMpegHAudio; - case kCodecDTS: - return ::media::AudioCodec::kDTS; - case kCodecDTSXP2: - return ::media::AudioCodec::kDTSXP2; - case kCodecDTSE: - return ::media::AudioCodec::kDTSE; - default: - return ::media::AudioCodec::kUnknown; - } -} - -EncryptionScheme ToEncryptionScheme(::media::EncryptionScheme scheme) { - switch (scheme) { - case ::media::EncryptionScheme::kUnencrypted: - return EncryptionScheme::kUnencrypted; - case ::media::EncryptionScheme::kCenc: - return EncryptionScheme::kAesCtr; - case ::media::EncryptionScheme::kCbcs: - return EncryptionScheme::kAesCbc; - default: - NOTREACHED(); - } -} - -::media::EncryptionScheme ToMediaEncryptionScheme(EncryptionScheme scheme) { - switch (scheme) { - case EncryptionScheme::kUnencrypted: - return ::media::EncryptionScheme::kUnencrypted; - case EncryptionScheme::kAesCtr: - return ::media::EncryptionScheme::kCenc; - case EncryptionScheme::kAesCbc: - return ::media::EncryptionScheme::kCbcs; - default: - NOTREACHED(); - } -} - -} // namespace - -// static -ChannelLayout DecoderConfigAdapter::ToChannelLayout( - ::media::ChannelLayout channel_layout) { - switch (channel_layout) { - case ::media::ChannelLayout::CHANNEL_LAYOUT_UNSUPPORTED: - return ChannelLayout::UNSUPPORTED; - case ::media::ChannelLayout::CHANNEL_LAYOUT_MONO: - return ChannelLayout::MONO; - case ::media::ChannelLayout::CHANNEL_LAYOUT_STEREO: - return ChannelLayout::STEREO; - case ::media::ChannelLayout::CHANNEL_LAYOUT_5_1: - case ::media::ChannelLayout::CHANNEL_LAYOUT_5_1_BACK: - return ChannelLayout::SURROUND_5_1; - case ::media::ChannelLayout::CHANNEL_LAYOUT_BITSTREAM: - return ChannelLayout::BITSTREAM; - case ::media::ChannelLayout::CHANNEL_LAYOUT_DISCRETE: - return ChannelLayout::DISCRETE; - - default: - NOTREACHED(); - } -} - -// static -::media::ChannelLayout DecoderConfigAdapter::ToMediaChannelLayout( - ChannelLayout channel_layout) { - switch (channel_layout) { - case ChannelLayout::UNSUPPORTED: - return ::media::ChannelLayout::CHANNEL_LAYOUT_UNSUPPORTED; - case ChannelLayout::MONO: - return ::media::ChannelLayout::CHANNEL_LAYOUT_MONO; - case ChannelLayout::STEREO: - return ::media::ChannelLayout::CHANNEL_LAYOUT_STEREO; - case ChannelLayout::SURROUND_5_1: - return ::media::ChannelLayout::CHANNEL_LAYOUT_5_1; - case ChannelLayout::BITSTREAM: - return ::media::ChannelLayout::CHANNEL_LAYOUT_BITSTREAM; - case ChannelLayout::DISCRETE: - return ::media::ChannelLayout::CHANNEL_LAYOUT_DISCRETE; - - default: - NOTREACHED(); - } -} - -// static -AudioConfig DecoderConfigAdapter::ToCastAudioConfig( - StreamId id, - const ::media::AudioDecoderConfig& config) { - AudioConfig audio_config; - if (!config.IsValidConfig()) { - return audio_config; - } - - audio_config.id = id; - audio_config.codec = ToAudioCodec(config.codec()); - audio_config.sample_format = ToSampleFormat(config.sample_format()); - audio_config.bytes_per_channel = config.bytes_per_channel(); - audio_config.channel_layout = ToChannelLayout(config.channel_layout()); - audio_config.channel_number = config.channels(); - audio_config.samples_per_second = config.samples_per_second(); - audio_config.extra_data = config.extra_data(); - audio_config.encryption_scheme = - ToEncryptionScheme(config.encryption_scheme()); - -#if BUILDFLAG(IS_ANDROID) - // On Android, Chromium's mp4 parser adds extra data for AAC, but we don't - // need this with CMA. - if (audio_config.codec == kCodecAAC) { - audio_config.extra_data.clear(); - } -#endif // BUILDFLAG(IS_ANDROID) - - return audio_config; -} - -// static -::media::AudioDecoderConfig DecoderConfigAdapter::ToMediaAudioDecoderConfig( - const AudioConfig& config) { - ::media::AudioDecoderConfig audio_decoder_config( - ToMediaAudioCodec(config.codec), - ToMediaSampleFormat(config.sample_format), - ToMediaChannelLayout(config.channel_layout), config.samples_per_second, - config.extra_data, ToMediaEncryptionScheme(config.encryption_scheme)); - if (config.channel_layout == ChannelLayout::DISCRETE) { - audio_decoder_config.SetChannelsForDiscrete(config.channel_number); - } - return audio_decoder_config; -} - -// static -#define STATIC_ASSERT_MATCHING_ENUM(chromium_name, chromecast_name) \ - static_assert(static_cast(::media::VideoColorSpace::chromium_name) == \ - static_cast(::chromecast::media::chromecast_name), \ - "mismatching status enum values: " #chromium_name) - -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::BT709, PrimaryID::BT709); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::UNSPECIFIED, PrimaryID::UNSPECIFIED); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::BT470M, PrimaryID::BT470M); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::BT470BG, PrimaryID::BT470BG); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::SMPTE170M, PrimaryID::SMPTE170M); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::SMPTE240M, PrimaryID::SMPTE240M); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::FILM, PrimaryID::FILM); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::BT2020, PrimaryID::BT2020); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::SMPTEST428_1, PrimaryID::SMPTEST428_1); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::SMPTEST431_2, PrimaryID::SMPTEST431_2); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::SMPTEST432_1, PrimaryID::SMPTEST432_1); -STATIC_ASSERT_MATCHING_ENUM(PrimaryID::EBU_3213_E, PrimaryID::EBU_3213_E); - -STATIC_ASSERT_MATCHING_ENUM(TransferID::BT709, TransferID::BT709); -STATIC_ASSERT_MATCHING_ENUM(TransferID::UNSPECIFIED, TransferID::UNSPECIFIED); -STATIC_ASSERT_MATCHING_ENUM(TransferID::GAMMA22, TransferID::GAMMA22); -STATIC_ASSERT_MATCHING_ENUM(TransferID::GAMMA28, TransferID::GAMMA28); -STATIC_ASSERT_MATCHING_ENUM(TransferID::SMPTE170M, TransferID::SMPTE170M); -STATIC_ASSERT_MATCHING_ENUM(TransferID::SMPTE240M, TransferID::SMPTE240M); -STATIC_ASSERT_MATCHING_ENUM(TransferID::LINEAR, TransferID::LINEAR); -STATIC_ASSERT_MATCHING_ENUM(TransferID::LOG, TransferID::LOG); -STATIC_ASSERT_MATCHING_ENUM(TransferID::LOG_SQRT, TransferID::LOG_SQRT); -STATIC_ASSERT_MATCHING_ENUM(TransferID::IEC61966_2_4, TransferID::IEC61966_2_4); -STATIC_ASSERT_MATCHING_ENUM(TransferID::BT1361_ECG, TransferID::BT1361_ECG); -STATIC_ASSERT_MATCHING_ENUM(TransferID::IEC61966_2_1, TransferID::IEC61966_2_1); -STATIC_ASSERT_MATCHING_ENUM(TransferID::BT2020_10, TransferID::BT2020_10); -STATIC_ASSERT_MATCHING_ENUM(TransferID::BT2020_12, TransferID::BT2020_12); -STATIC_ASSERT_MATCHING_ENUM(TransferID::SMPTEST2084, TransferID::SMPTEST2084); -STATIC_ASSERT_MATCHING_ENUM(TransferID::SMPTEST428_1, TransferID::SMPTEST428_1); -STATIC_ASSERT_MATCHING_ENUM(TransferID::ARIB_STD_B67, TransferID::ARIB_STD_B67); - -STATIC_ASSERT_MATCHING_ENUM(MatrixID::RGB, MatrixID::RGB); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::BT709, MatrixID::BT709); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::UNSPECIFIED, MatrixID::UNSPECIFIED); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::FCC, MatrixID::FCC); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::BT470BG, MatrixID::BT470BG); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::SMPTE170M, MatrixID::SMPTE170M); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::SMPTE240M, MatrixID::SMPTE240M); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::YCOCG, MatrixID::YCOCG); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::BT2020_NCL, MatrixID::BT2020_NCL); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::BT2020_CL, MatrixID::BT2020_CL); -STATIC_ASSERT_MATCHING_ENUM(MatrixID::YDZDX, MatrixID::YDZDX); - -#define STATIC_ASSERT_MATCHING_ENUM2(chromium_name, chromecast_name) \ - static_assert(static_cast(::gfx::ColorSpace::chromium_name) == \ - static_cast(::chromecast::media::chromecast_name), \ - "mismatching status enum values: " #chromium_name) - -STATIC_ASSERT_MATCHING_ENUM2(RangeID::INVALID, RangeID::INVALID); -STATIC_ASSERT_MATCHING_ENUM2(RangeID::LIMITED, RangeID::LIMITED); -STATIC_ASSERT_MATCHING_ENUM2(RangeID::FULL, RangeID::FULL); -STATIC_ASSERT_MATCHING_ENUM2(RangeID::DERIVED, RangeID::DERIVED); - -VideoConfig DecoderConfigAdapter::ToCastVideoConfig( - StreamId id, - const ::media::VideoDecoderConfig& config) { - VideoConfig video_config; - if (!config.IsValidConfig()) { - return video_config; - } - - video_config.id = id; - video_config.codec = ToCastVideoCodec(config.codec(), config.profile()); - video_config.profile = ToCastVideoProfile(config.profile()); - video_config.codec_profile_level = config.level(); - video_config.extra_data = config.extra_data(); - video_config.encryption_scheme = - ToEncryptionScheme(config.encryption_scheme()); - - video_config.primaries = - static_cast(config.color_space_info().primaries); - video_config.transfer = - static_cast(config.color_space_info().transfer); - video_config.matrix = static_cast(config.color_space_info().matrix); - video_config.range = static_cast(config.color_space_info().range); - - std::optional<::gfx::HDRMetadata> hdr_metadata = config.hdr_metadata(); - if (hdr_metadata) { - video_config.have_hdr_metadata = true; - - if (const auto& cta_861_3 = hdr_metadata->cta_861_3) { - video_config.hdr_metadata.max_content_light_level = - cta_861_3->max_content_light_level; - video_config.hdr_metadata.max_frame_average_light_level = - cta_861_3->max_frame_average_light_level; - } - - if (const auto& mm1 = hdr_metadata->smpte_st_2086) { - auto& mm2 = video_config.hdr_metadata.color_volume_metadata; - mm2.primary_r_chromaticity_x = mm1->primaries.fRX; - mm2.primary_r_chromaticity_y = mm1->primaries.fRY; - mm2.primary_g_chromaticity_x = mm1->primaries.fGX; - mm2.primary_g_chromaticity_y = mm1->primaries.fGY; - mm2.primary_b_chromaticity_x = mm1->primaries.fBX; - mm2.primary_b_chromaticity_y = mm1->primaries.fBY; - mm2.white_point_chromaticity_x = mm1->primaries.fWX; - mm2.white_point_chromaticity_y = mm1->primaries.fWY; - mm2.luminance_max = mm1->luminance_max; - mm2.luminance_min = mm1->luminance_min; - } - } - - const gfx::Size aspect_ratio = - config.aspect_ratio().GetNaturalSize(config.visible_rect()); - video_config.width = aspect_ratio.width(); - video_config.height = aspect_ratio.height(); - - return video_config; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/decoder_config_adapter.h chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter.h --- chromium-132.0.6834.110/chromecast/media/cma/base/decoder_config_adapter.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_DECODER_CONFIG_ADAPTER_H_ -#define CHROMECAST_MEDIA_CMA_BASE_DECODER_CONFIG_ADAPTER_H_ - -#include "chromecast/public/media/decoder_config.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/video_decoder_config.h" - -namespace chromecast { -namespace media { - -class DecoderConfigAdapter { - public: - static ChannelLayout ToChannelLayout(::media::ChannelLayout channel_layout); - static ::media::ChannelLayout ToMediaChannelLayout( - ChannelLayout channel_layout); - - // Converts ::media::AudioDecoderConfig to chromecast::media::AudioConfig. - static AudioConfig ToCastAudioConfig( - StreamId id, - const ::media::AudioDecoderConfig& config); - - // Converts chromecast::media::AudioConfig to ::media::AudioDecoderConfig. - static ::media::AudioDecoderConfig ToMediaAudioDecoderConfig( - const AudioConfig& config); - - // Converts ::media::VideoDecoderConfig to chromecast::media::VideoConfig. - static VideoConfig ToCastVideoConfig( - StreamId id, - const ::media::VideoDecoderConfig& config); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_DECODER_CONFIG_ADAPTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/decoder_config_adapter_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/decoder_config_adapter_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/decoder_config_adapter_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/decoder_config_adapter.h" - -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/stream_id.h" -#include "media/base/media_util.h" -#include "media/base/video_color_space.h" -#include "media/base/video_decoder_config.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -// Returns an initialized ::media::VideoDecoderConfig. -::media::VideoDecoderConfig GetChromiumVideoConfig() { - gfx::Size coded_size(640, 480); - gfx::Rect visible_rect(640, 480); - gfx::Size natural_size(640, 480); - return ::media::VideoDecoderConfig( - ::media::VideoCodec::kH264, ::media::VIDEO_CODEC_PROFILE_UNKNOWN, - ::media::VideoDecoderConfig::AlphaMode::kIsOpaque, - ::media::VideoColorSpace(), ::media::kNoTransformation, coded_size, - visible_rect, natural_size, ::media::EmptyExtraData(), - ::media::EncryptionScheme::kUnencrypted); -} - -TEST(DecoderConfigAdapterTest, PopulatesVideoCodecLevel) { - constexpr uint32_t kCodecLevel = 30ul; - - ::media::VideoDecoderConfig chromium_config = GetChromiumVideoConfig(); - chromium_config.set_level(kCodecLevel); - - VideoConfig cast_config = DecoderConfigAdapter::ToCastVideoConfig( - StreamId::kPrimary, chromium_config); - - EXPECT_EQ(cast_config.codec_profile_level, kCodecLevel); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_adapter.cc chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_adapter.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,181 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/demuxer_stream_adapter.h" - -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/cma/base/balanced_media_task_runner_factory.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/media/cma/base/simple_media_task_runner.h" -#include "media/base/decoder_buffer.h" -#include "media/base/demuxer_stream.h" -#include "media/base/timestamp_constants.h" - -namespace chromecast { -namespace media { - -DemuxerStreamAdapter::DemuxerStreamAdapter( - const scoped_refptr& task_runner, - const scoped_refptr& - media_task_runner_factory, - ::media::DemuxerStream* demuxer_stream) - : task_runner_(task_runner), - media_task_runner_factory_(media_task_runner_factory), - media_task_runner_(new SimpleMediaTaskRunner(task_runner)), - demuxer_stream_(demuxer_stream), - is_pending_read_(false), - is_pending_demuxer_read_(false), - weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); - ResetMediaTaskRunner(); - thread_checker_.DetachFromThread(); -} - -DemuxerStreamAdapter::~DemuxerStreamAdapter() { - // Needed since we use weak pointers: - // weak pointers must be invalidated on the same thread. - DCHECK(thread_checker_.CalledOnValidThread()); -} - -void DemuxerStreamAdapter::Read(ReadCB read_cb) { - DCHECK(thread_checker_.CalledOnValidThread()); - - DCHECK(flush_cb_.is_null()); - - // Support only one read at a time. - DCHECK(!is_pending_read_); - is_pending_read_ = true; - ReadInternal(std::move(read_cb)); -} - -void DemuxerStreamAdapter::ReadInternal(ReadCB read_cb) { - bool may_run_in_future = media_task_runner_->PostMediaTask( - FROM_HERE, - base::BindOnce(&DemuxerStreamAdapter::RequestBuffer, weak_this_, - std::move(read_cb)), - max_pts_); - DCHECK(may_run_in_future); -} - -void DemuxerStreamAdapter::Flush(base::OnceClosure flush_cb) { - DCHECK(thread_checker_.CalledOnValidThread()); - LOG(INFO) << __FUNCTION__; - - // Flush cancels any pending read. - is_pending_read_ = false; - - // Reset the decoder configurations. - audio_config_ = ::media::AudioDecoderConfig(); - video_config_ = ::media::VideoDecoderConfig(); - - // Create a new media task runner for the upcoming media timeline. - ResetMediaTaskRunner(); - - DCHECK(flush_cb_.is_null()); - if (is_pending_demuxer_read_) { - // If there is a pending demuxer read, the implicit contract - // is that the pending read must be completed before invoking the - // flush callback. - flush_cb_ = std::move(flush_cb); - return; - } - - // At this point, there is no more pending demuxer read, - // so all the previous tasks associated with the current timeline - // can be cancelled. - weak_factory_.InvalidateWeakPtrs(); - weak_this_ = weak_factory_.GetWeakPtr(); - - LOG(INFO) << "Flush done"; - std::move(flush_cb).Run(); -} - -void DemuxerStreamAdapter::ResetMediaTaskRunner() { - DCHECK(thread_checker_.CalledOnValidThread()); - - max_pts_ = ::media::kNoTimestamp; - if (media_task_runner_factory_.get()) { - media_task_runner_ = - media_task_runner_factory_->CreateMediaTaskRunner(task_runner_); - } -} - -void DemuxerStreamAdapter::RequestBuffer(ReadCB read_cb) { - DCHECK(thread_checker_.CalledOnValidThread()); - is_pending_demuxer_read_ = true; - demuxer_stream_->Read(1, base::BindPostTaskToCurrentDefault(base::BindOnce( - &DemuxerStreamAdapter::OnNewBuffer, weak_this_, - std::move(read_cb)))); -} - -void DemuxerStreamAdapter::OnNewBuffer( - ReadCB read_cb, - ::media::DemuxerStream::Status status, - ::media::DemuxerStream::DecoderBufferVector input_buffers) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK_LE(input_buffers.size(), 1u) - << "RequestBuffer() only reads a single buffer."; - is_pending_demuxer_read_ = false; - - // Just discard the buffer in the flush stage. - if (!flush_cb_.is_null()) { - LOG(INFO) << "Flush done"; - std::move(flush_cb_).Run(); - return; - } - - if (status == ::media::DemuxerStream::kAborted) { - DCHECK(input_buffers.empty()); - return; - } - - if (status == ::media::DemuxerStream::kConfigChanged) { - DCHECK(input_buffers.empty()); - if (demuxer_stream_->type() == ::media::DemuxerStream::VIDEO) - video_config_ = demuxer_stream_->video_decoder_config(); - if (demuxer_stream_->type() == ::media::DemuxerStream::AUDIO) - audio_config_ = demuxer_stream_->audio_decoder_config(); - - // Got a new config, but we still need to get a frame. - ReadInternal(std::move(read_cb)); - return; - } - - DCHECK_EQ(status, ::media::DemuxerStream::kOk); - scoped_refptr<::media::DecoderBuffer> input = std::move(input_buffers[0]); - - if (input->end_of_stream()) { - // This stream has ended, its media time will stop increasing, but there - // might be other streams that are still playing. Remove the task runner of - // this stream to ensure other streams are not blocked waiting for this one. - ResetMediaTaskRunner(); - } - - // Updates the timestamp used for task scheduling. - if (!input->end_of_stream() && input->timestamp() != ::media::kNoTimestamp && - (max_pts_ == ::media::kNoTimestamp || input->timestamp() > max_pts_)) { - max_pts_ = input->timestamp(); - } - - // Provides the buffer as well as possibly valid audio and video configs. - is_pending_read_ = false; - scoped_refptr buffer( - new DecoderBufferAdapter(std::move(input))); - std::move(read_cb).Run(buffer, audio_config_, video_config_); - - // Back to the default audio/video config: - // an invalid audio/video config means there is no config update. - if (audio_config_.IsValidConfig()) - audio_config_ = ::media::AudioDecoderConfig(); - if (video_config_.IsValidConfig()) - video_config_ = ::media::VideoDecoderConfig(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_adapter.h chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter.h --- chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_adapter.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_DEMUXER_STREAM_ADAPTER_H_ -#define CHROMECAST_MEDIA_CMA_BASE_DEMUXER_STREAM_ADAPTER_H_ - -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "chromecast/media/cma/base/coded_frame_provider.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/demuxer_stream.h" -#include "media/base/video_decoder_config.h" - -namespace base { -class SingleThreadTaskRunner; -} - -namespace media { -class DemuxerStream; -} - -namespace chromecast { -namespace media { -class BalancedMediaTaskRunnerFactory; -class MediaTaskRunner; - -// DemuxerStreamAdapter wraps a DemuxerStream into a CodedFrameProvider. -class DemuxerStreamAdapter : public CodedFrameProvider { - public: - DemuxerStreamAdapter( - const scoped_refptr& task_runner, - const scoped_refptr& - media_task_runner_factory, - ::media::DemuxerStream* demuxer_stream); - - DemuxerStreamAdapter(const DemuxerStreamAdapter&) = delete; - DemuxerStreamAdapter& operator=(const DemuxerStreamAdapter&) = delete; - - ~DemuxerStreamAdapter() override; - - // CodedFrameProvider implementation. - void Read(ReadCB read_cb) override; - void Flush(base::OnceClosure flush_cb) override; - - private: - void ResetMediaTaskRunner(); - - void ReadInternal(ReadCB read_cb); - void RequestBuffer(ReadCB read_cb); - - // Callback invoked from the demuxer stream to signal a buffer is ready. - void OnNewBuffer(ReadCB read_cb, - ::media::DemuxerStream::Status status, - ::media::DemuxerStream::DecoderBufferVector input); - - base::ThreadChecker thread_checker_; - - // Task runner DemuxerStreamAdapter is running on. - scoped_refptr const task_runner_; - - // Media task runner to pace requests to the DemuxerStream. - scoped_refptr const - media_task_runner_factory_; - scoped_refptr media_task_runner_; - base::TimeDelta max_pts_; - - // Frames are provided by |demuxer_stream_|. - ::media::DemuxerStream* const demuxer_stream_; - - // Indicate if there is a pending read. - bool is_pending_read_; - - // Indicate if |demuxer_stream_| has a pending read. - bool is_pending_demuxer_read_; - - // In case of a pending flush operation, this is the callback - // that is invoked when flush is completed. - base::OnceClosure flush_cb_; - - // Audio/video configuration that applies to the next frame. - ::media::AudioDecoderConfig audio_config_; - ::media::VideoDecoderConfig video_config_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_DEMUXER_STREAM_ADAPTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_adapter_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_adapter_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_adapter_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,224 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/demuxer_stream_adapter.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "base/task/current_thread.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/base/balanced_media_task_runner_factory.h" -#include "chromecast/media/cma/base/demuxer_stream_for_test.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/decoder_buffer.h" -#include "media/base/demuxer_stream.h" -#include "media/base/video_decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -class DemuxerStreamAdapterTest : public testing::Test { - public: - DemuxerStreamAdapterTest(); - - DemuxerStreamAdapterTest(const DemuxerStreamAdapterTest&) = delete; - DemuxerStreamAdapterTest& operator=(const DemuxerStreamAdapterTest&) = delete; - - ~DemuxerStreamAdapterTest() override; - - void Initialize(::media::DemuxerStream* demuxer_stream); - void Start(); - void Run(); - - protected: - void OnTestTimeout(); - void OnNewFrame(const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config); - void OnFlushCompleted(); - - // Total number of frames to request. - int total_frames_; - - // Number of demuxer read before issuing an early flush. - int early_flush_idx_; - bool use_post_task_for_flush_; - - // Number of expected read frames. - int total_expected_frames_; - - // Number of frames actually read so far. - int frame_received_count_; - - // List of expected frame indices with decoder config changes. - std::list config_idx_; - - std::unique_ptr demuxer_stream_; - - std::unique_ptr coded_frame_provider_; - - base::OnceClosure quit_closure_; -}; - -DemuxerStreamAdapterTest::DemuxerStreamAdapterTest() - : use_post_task_for_flush_(false) { -} - -DemuxerStreamAdapterTest::~DemuxerStreamAdapterTest() { -} - -void DemuxerStreamAdapterTest::Initialize( - ::media::DemuxerStream* demuxer_stream) { - coded_frame_provider_.reset(new DemuxerStreamAdapter( - base::SingleThreadTaskRunner::GetCurrentDefault(), - scoped_refptr(), demuxer_stream)); -} - -void DemuxerStreamAdapterTest::Run() { - base::RunLoop loop; - quit_closure_ = loop.QuitWhenIdleClosure(); - loop.Run(); -} - -void DemuxerStreamAdapterTest::Start() { - frame_received_count_ = 0; - - // TODO(damienv): currently, test assertions which fail do not trigger the - // exit of the unit test, the message loop is still running. Find a different - // way to exit the unit test. - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&DemuxerStreamAdapterTest::OnTestTimeout, - base::Unretained(this)), - base::Seconds(5)); - - coded_frame_provider_->Read(base::BindOnce( - &DemuxerStreamAdapterTest::OnNewFrame, base::Unretained(this))); -} - -void DemuxerStreamAdapterTest::OnTestTimeout() { - ADD_FAILURE() << "Test timed out"; - std::move(quit_closure_).Run(); -} - -void DemuxerStreamAdapterTest::OnNewFrame( - const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) { - if (video_config.IsValidConfig()) { - ASSERT_GT(config_idx_.size(), 0u); - ASSERT_EQ(frame_received_count_, config_idx_.front()); - config_idx_.pop_front(); - } - - ASSERT_TRUE(buffer.get() != NULL); - ASSERT_EQ(base::Microseconds(buffer->timestamp()), - base::Milliseconds(40 * frame_received_count_)); - frame_received_count_++; - - if (frame_received_count_ >= total_frames_) { - coded_frame_provider_->Flush(base::BindOnce( - &DemuxerStreamAdapterTest::OnFlushCompleted, base::Unretained(this))); - return; - } - - coded_frame_provider_->Read(base::BindOnce( - &DemuxerStreamAdapterTest::OnNewFrame, base::Unretained(this))); - - ASSERT_LE(frame_received_count_, early_flush_idx_); - if (frame_received_count_ == early_flush_idx_) { - base::OnceClosure flush_cb = base::BindOnce( - &DemuxerStreamAdapterTest::OnFlushCompleted, base::Unretained(this)); - if (use_post_task_for_flush_) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&CodedFrameProvider::Flush, - base::Unretained(coded_frame_provider_.get()), - std::move(flush_cb))); - } else { - coded_frame_provider_->Flush(std::move(flush_cb)); - } - return; - } -} - -void DemuxerStreamAdapterTest::OnFlushCompleted() { - ASSERT_EQ(frame_received_count_, total_expected_frames_); - std::move(quit_closure_).Run(); -} - -TEST_F(DemuxerStreamAdapterTest, NoDelay) { - total_frames_ = 10; - early_flush_idx_ = total_frames_; // No early flush. - total_expected_frames_ = 10; - config_idx_.push_back(0); - config_idx_.push_back(5); - - int cycle_count = 1; - int delayed_frame_count = 0; - demuxer_stream_.reset(new DemuxerStreamForTest( - -1, cycle_count, delayed_frame_count, config_idx_)); - - base::test::SingleThreadTaskEnvironment task_environment; - Initialize(demuxer_stream_.get()); - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&DemuxerStreamAdapterTest::Start, base::Unretained(this))); - Run(); -} - -TEST_F(DemuxerStreamAdapterTest, AllDelayed) { - total_frames_ = 10; - early_flush_idx_ = total_frames_; // No early flush. - total_expected_frames_ = 10; - config_idx_.push_back(0); - config_idx_.push_back(5); - - int cycle_count = 1; - int delayed_frame_count = 1; - demuxer_stream_.reset(new DemuxerStreamForTest( - -1, cycle_count, delayed_frame_count, config_idx_)); - - base::test::SingleThreadTaskEnvironment task_environment; - Initialize(demuxer_stream_.get()); - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&DemuxerStreamAdapterTest::Start, base::Unretained(this))); - Run(); -} - -TEST_F(DemuxerStreamAdapterTest, AllDelayedEarlyFlush) { - total_frames_ = 10; - early_flush_idx_ = 5; - use_post_task_for_flush_ = true; - total_expected_frames_ = 5; - config_idx_.push_back(0); - config_idx_.push_back(3); - - int cycle_count = 1; - int delayed_frame_count = 1; - demuxer_stream_.reset(new DemuxerStreamForTest( - -1, cycle_count, delayed_frame_count, config_idx_)); - - base::test::SingleThreadTaskEnvironment task_environment; - Initialize(demuxer_stream_.get()); - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&DemuxerStreamAdapterTest::Start, base::Unretained(this))); - Run(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_for_test.cc chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_for_test.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_for_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_for_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,87 +0,0 @@ -// 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 "chromecast/media/cma/base/demuxer_stream_for_test.h" - -#include "base/task/single_thread_task_runner.h" -#include "base/threading/thread.h" -#include "media/base/media_util.h" - -namespace chromecast { -namespace media { - -DemuxerStreamForTest::DemuxerStreamForTest(int total_frames, - int cycle_count, - int delayed_frame_count, - const std::list& config_idx) - : total_frame_count_(total_frames), - cycle_count_(cycle_count), - delayed_frame_count_(delayed_frame_count), - config_idx_(config_idx), - frame_count_(0) { - DCHECK_LE(delayed_frame_count, cycle_count); -} - -DemuxerStreamForTest::~DemuxerStreamForTest() { -} - -void DemuxerStreamForTest::Read(uint32_t count, ReadCB read_cb) { - DCHECK_EQ(count, 1u) << "DemuxerStreamForTest only reads a single buffer."; - if (!config_idx_.empty() && config_idx_.front() == frame_count_) { - config_idx_.pop_front(); - std::move(read_cb).Run(kConfigChanged, {}); - return; - } - - if ((frame_count_ % cycle_count_) < delayed_frame_count_) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&DemuxerStreamForTest::DoRead, base::Unretained(this), - std::move(read_cb)), - base::Milliseconds(20)); - return; - } - DoRead(std::move(read_cb)); -} - -::media::AudioDecoderConfig DemuxerStreamForTest::audio_decoder_config() { - NOTREACHED() << "DemuxerStreamForTest is a video DemuxerStream"; -} - -::media::VideoDecoderConfig DemuxerStreamForTest::video_decoder_config() { - gfx::Size coded_size(640, 480); - gfx::Rect visible_rect(640, 480); - gfx::Size natural_size(640, 480); - return ::media::VideoDecoderConfig( - ::media::VideoCodec::kH264, ::media::VIDEO_CODEC_PROFILE_UNKNOWN, - ::media::VideoDecoderConfig::AlphaMode::kIsOpaque, - ::media::VideoColorSpace(), ::media::kNoTransformation, coded_size, - visible_rect, natural_size, ::media::EmptyExtraData(), - ::media::EncryptionScheme::kUnencrypted); -} - -::media::DemuxerStream::Type DemuxerStreamForTest::type() const { - return VIDEO; -} - -bool DemuxerStreamForTest::SupportsConfigChanges() { - return true; -} - -void DemuxerStreamForTest::DoRead(ReadCB read_cb) { - if (total_frame_count_ != -1 && frame_count_ >= total_frame_count_) { - // End of stream - std::move(read_cb).Run(kOk, {::media::DecoderBuffer::CreateEOSBuffer()}); - return; - } - - scoped_refptr<::media::DecoderBuffer> buffer(new ::media::DecoderBuffer(16)); - buffer->set_timestamp(frame_count_ * - base::Milliseconds(kDemuxerStreamForTestFrameDuration)); - frame_count_++; - std::move(read_cb).Run(kOk, {std::move(buffer)}); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_for_test.h chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_for_test.h --- chromium-132.0.6834.110/chromecast/media/cma/base/demuxer_stream_for_test.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/demuxer_stream_for_test.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_DEMUXER_STREAM_FOR_TEST_H_ -#define CHROMECAST_MEDIA_CMA_BASE_DEMUXER_STREAM_FOR_TEST_H_ - -#include - -#include "base/functional/bind.h" -#include "chromecast/media/cma/base/demuxer_stream_adapter.h" -#include "media/base/decoder_buffer.h" -#include "media/base/demuxer_stream.h" - -namespace chromecast { -namespace media { - -class DemuxerStreamForTest : public ::media::DemuxerStream { - public: - // Creates a demuxer stream which provides frames either with a delay - // or instantly. - // - |total_frames| is the number of frames to generate before EOS frame. - // -1 means keep generating frames and never produce EOS. - // The scheduling pattern is the following: - // - provides |delayed_frame_count| frames with a delay, - // - then provides the following |cycle_count| - |delayed_frame_count| - // instantly, - // - then provides |delayed_frame_count| frames with a delay, - // - ... and so on. - // Special cases: - // - all frames are delayed: |delayed_frame_count| = |cycle_count| - // - all frames are provided instantly: |delayed_frame_count| = 0 - // |config_idx| is a list of frame index before which there is - // a change of decoder configuration. - DemuxerStreamForTest(int total_frames, - int cycle_count, - int delayed_frame_count, - const std::list& config_idx); - - DemuxerStreamForTest(const DemuxerStreamForTest&) = delete; - DemuxerStreamForTest& operator=(const DemuxerStreamForTest&) = delete; - - ~DemuxerStreamForTest() override; - - // ::media::DemuxerStream implementation. - void Read(uint32_t count, ReadCB read_cb) override; - ::media::AudioDecoderConfig audio_decoder_config() override; - ::media::VideoDecoderConfig video_decoder_config() override; - Type type() const override; - bool SupportsConfigChanges() override; - - // Frame duration - static const int kDemuxerStreamForTestFrameDuration = 40; - - private: - void DoRead(ReadCB read_cb); - - // Demuxer configuration. - int total_frame_count_; - const int cycle_count_; - const int delayed_frame_count_; - std::list config_idx_; - - // Number of frames sent so far. - int frame_count_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_DEMUXER_STREAM_FOR_TEST_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/media_task_runner.cc chromium-132.0.6834.159/chromecast/media/cma/base/media_task_runner.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/media_task_runner.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/media_task_runner.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/base/media_task_runner.h" - -namespace chromecast { -namespace media { - -MediaTaskRunner::MediaTaskRunner() { -} - -MediaTaskRunner::~MediaTaskRunner() { -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/media_task_runner.h chromium-132.0.6834.159/chromecast/media/cma/base/media_task_runner.h --- chromium-132.0.6834.110/chromecast/media/cma/base/media_task_runner.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/media_task_runner.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_MEDIA_TASK_RUNNER_H_ -#define CHROMECAST_MEDIA_CMA_BASE_MEDIA_TASK_RUNNER_H_ - -#include "base/functional/callback.h" -#include "base/location.h" -#include "base/memory/ref_counted.h" -#include "base/time/time.h" - -namespace chromecast { -namespace media { - -class MediaTaskRunner - : public base::RefCountedThreadSafe { - public: - MediaTaskRunner(); - - MediaTaskRunner(const MediaTaskRunner&) = delete; - MediaTaskRunner& operator=(const MediaTaskRunner&) = delete; - - // Post a task with the given media |timestamp|. If |timestamp| is equal to - // |kNoTimestamp|, the task is scheduled right away. - // How the media timestamp is used to schedule the task is an implementation - // detail of derived classes. - // Returns true if the task may be run at some point in the future, and false - // if the task definitely will not be run. - virtual bool PostMediaTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta timestamp) = 0; - - protected: - virtual ~MediaTaskRunner(); - friend class base::RefCountedThreadSafe; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_MEDIA_TASK_RUNNER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/multi_demuxer_stream_adapter_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/base/multi_demuxer_stream_adapter_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/multi_demuxer_stream_adapter_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/multi_demuxer_stream_adapter_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,180 +0,0 @@ -// 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 -#include - -#include "base/functional/bind.h" -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/base/balanced_media_task_runner_factory.h" -#include "chromecast/media/cma/base/demuxer_stream_adapter.h" -#include "chromecast/media/cma/base/demuxer_stream_for_test.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/decoder_buffer.h" -#include "media/base/demuxer_stream.h" -#include "media/base/video_decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -namespace { -// Maximum pts diff between frames -const int kMaxPtsDiffMs = 2000; -} // namespace - -// Test for multiple streams -class MultiDemuxerStreamAdaptersTest : public testing::Test { - public: - MultiDemuxerStreamAdaptersTest(); - - MultiDemuxerStreamAdaptersTest(const MultiDemuxerStreamAdaptersTest&) = - delete; - MultiDemuxerStreamAdaptersTest& operator=( - const MultiDemuxerStreamAdaptersTest&) = delete; - - ~MultiDemuxerStreamAdaptersTest() override; - - void Start(); - void Run(); - - protected: - void OnTestTimeout(); - void OnNewFrame(CodedFrameProvider* frame_provider, - const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config); - - // Number of expected read frames. - int total_expected_frames_; - - // Number of frames actually read so far. - int frame_received_count_; - - // List of expected frame indices with decoder config changes. - std::list config_idx_; - - std::vector> demuxer_streams_; - - std::vector> coded_frame_providers_; - - private: - // exit if all of the streams end - void OnEos(); - - // Number of reading-streams - int running_stream_count_; - - scoped_refptr media_task_runner_factory_; - - base::OnceClosure quit_closure_; -}; - -MultiDemuxerStreamAdaptersTest::MultiDemuxerStreamAdaptersTest() { -} - -MultiDemuxerStreamAdaptersTest::~MultiDemuxerStreamAdaptersTest() { -} -void MultiDemuxerStreamAdaptersTest::Run() { - base::RunLoop loop; - quit_closure_ = loop.QuitWhenIdleClosure(); - loop.Run(); -} -void MultiDemuxerStreamAdaptersTest::Start() { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&MultiDemuxerStreamAdaptersTest::OnTestTimeout, - base::Unretained(this)), - base::Seconds(5)); - - media_task_runner_factory_ = - new BalancedMediaTaskRunnerFactory(base::Milliseconds(kMaxPtsDiffMs)); - - coded_frame_providers_.clear(); - frame_received_count_ = 0; - - for (const auto& stream : demuxer_streams_) { - coded_frame_providers_.push_back(std::make_unique( - base::SingleThreadTaskRunner::GetCurrentDefault(), - media_task_runner_factory_, stream.get())); - } - running_stream_count_ = coded_frame_providers_.size(); - - // read each stream - for (const auto& code_frame_provider : coded_frame_providers_) { - auto read_cb = - base::BindOnce(&MultiDemuxerStreamAdaptersTest::OnNewFrame, - base::Unretained(this), code_frame_provider.get()); - - base::OnceClosure task = base::BindOnce( - &CodedFrameProvider::Read, base::Unretained(code_frame_provider.get()), - std::move(read_cb)); - - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, std::move(task)); - } -} - -void MultiDemuxerStreamAdaptersTest::OnTestTimeout() { - if (running_stream_count_ != 0) { - ADD_FAILURE() << "Test timed out"; - } -} - -void MultiDemuxerStreamAdaptersTest::OnNewFrame( - CodedFrameProvider* frame_provider, - const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) { - if (buffer->end_of_stream()) { - OnEos(); - return; - } - - frame_received_count_++; - auto read_cb = base::BindOnce(&MultiDemuxerStreamAdaptersTest::OnNewFrame, - base::Unretained(this), frame_provider); - frame_provider->Read(std::move(read_cb)); -} - -void MultiDemuxerStreamAdaptersTest::OnEos() { - running_stream_count_--; - ASSERT_GE(running_stream_count_, 0); - if (running_stream_count_ == 0) { - ASSERT_EQ(frame_received_count_, total_expected_frames_); - std::move(quit_closure_).Run(); - } -} - -TEST_F(MultiDemuxerStreamAdaptersTest, EarlyEos) { - // We have more than one streams here. One of them is much shorter than the - // others. When the shortest stream reaches EOS, other streams should still - // run as usually. BalancedTaskRunner should not be blocked. - int frame_count_short = 2; - int frame_count_long = - frame_count_short + - kMaxPtsDiffMs / DemuxerStreamForTest::kDemuxerStreamForTestFrameDuration + - 100; - demuxer_streams_.push_back(std::make_unique( - frame_count_short, 2, 0, config_idx_)); - demuxer_streams_.push_back(std::make_unique( - frame_count_long, 10, 0, config_idx_)); - - total_expected_frames_ = frame_count_short + frame_count_long; - - base::test::SingleThreadTaskEnvironment task_environment; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&MultiDemuxerStreamAdaptersTest::Start, - base::Unretained(this))); - Run(); -} -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/simple_media_task_runner.cc chromium-132.0.6834.159/chromecast/media/cma/base/simple_media_task_runner.cc --- chromium-132.0.6834.110/chromecast/media/cma/base/simple_media_task_runner.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/simple_media_task_runner.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// 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 "chromecast/media/cma/base/simple_media_task_runner.h" - -#include "base/task/single_thread_task_runner.h" - -namespace chromecast { -namespace media { - -SimpleMediaTaskRunner::SimpleMediaTaskRunner( - const scoped_refptr& task_runner) - : task_runner_(task_runner) { -} - -SimpleMediaTaskRunner::~SimpleMediaTaskRunner() { -} - -bool SimpleMediaTaskRunner::PostMediaTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta timestamp) { - return task_runner_->PostTask(from_here, std::move(task)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/base/simple_media_task_runner.h chromium-132.0.6834.159/chromecast/media/cma/base/simple_media_task_runner.h --- chromium-132.0.6834.110/chromecast/media/cma/base/simple_media_task_runner.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/base/simple_media_task_runner.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_BASE_SIMPLE_MEDIA_TASK_RUNNER_H_ -#define CHROMECAST_MEDIA_CMA_BASE_SIMPLE_MEDIA_TASK_RUNNER_H_ - -#include "base/memory/ref_counted.h" -#include "chromecast/media/cma/base/media_task_runner.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -namespace media { - -// This is a light version of task runner which post tasks immediately -// by ignoring the timestamps once receiving the request. -class SimpleMediaTaskRunner : public MediaTaskRunner { - public: - SimpleMediaTaskRunner( - const scoped_refptr& task_runner); - - SimpleMediaTaskRunner(const SimpleMediaTaskRunner&) = delete; - SimpleMediaTaskRunner& operator=(const SimpleMediaTaskRunner&) = delete; - - // MediaTaskRunner implementation. - bool PostMediaTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta timestamp) override; - - private: - ~SimpleMediaTaskRunner() override; - - scoped_refptr const task_runner_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_BASE_SIMPLE_MEDIA_TASK_RUNNER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/decoder/DEPS chromium-132.0.6834.159/chromecast/media/cma/decoder/DEPS --- chromium-132.0.6834.110/chromecast/media/cma/decoder/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/decoder/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -include_rules = [ - "+media/filters", -] diff -Nru chromium-132.0.6834.110/chromecast/media/cma/decoder/cast_audio_decoder.cc chromium-132.0.6834.159/chromecast/media/cma/decoder/cast_audio_decoder.cc --- chromium-132.0.6834.110/chromecast/media/cma/decoder/cast_audio_decoder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/decoder/cast_audio_decoder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,355 +0,0 @@ -// 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 "chromecast/media/api/cast_audio_decoder.h" - -#include -#include -#include -#include -#include -#include - -#include "base/containers/heap_array.h" -#include "base/containers/queue.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/media/cma/decoder/external_audio_decoder_wrapper.h" -#include "chromecast/media/common/base/decoder_config_logging.h" -#include "media/base/audio_buffer.h" -#include "media/base/audio_bus.h" -#include "media/base/cdm_context.h" -#include "media/base/channel_layout.h" -#include "media/base/decoder_buffer.h" -#include "media/base/media_util.h" -#include "media/base/sample_format.h" -#include "media/base/status.h" -#include "media/filters/ffmpeg_audio_decoder.h" - -namespace chromecast { -namespace media { - -namespace { - -// This class wraps the underlying data of a DecoderBufferBase. -// This class does not take the ownership of the data. The DecoderBufferBase -// is still responsible for deleting the data. This class holds a reference -// to the DecoderBufferBase so that it lives longer than this DecoderBuffer. -class DecoderBufferExternalMemory - : public ::media::DecoderBuffer::ExternalMemory { - public: - explicit DecoderBufferExternalMemory(scoped_refptr buffer) - : buffer_(std::move(buffer)) {} - - const base::span Span() const override { - return {buffer_->data(), buffer_->data_size()}; - } - - private: - scoped_refptr buffer_; -}; - -class CastAudioDecoderImpl : public CastAudioDecoder { - public: - CastAudioDecoderImpl(scoped_refptr task_runner, - const media::AudioConfig& config, - OutputFormat output_format) - : task_runner_(std::move(task_runner)), - output_format_(output_format), - weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); - DCHECK(task_runner_); - - input_config_ = config; - input_config_.encryption_scheme = EncryptionScheme::kUnencrypted; - - output_config_ = input_config_; - output_config_.codec = kCodecPCM; - output_config_.sample_format = - (output_format_ == kOutputSigned16 ? kSampleFormatS16 - : kSampleFormatPlanarF32); - - decoder_ = std::make_unique<::media::FFmpegAudioDecoder>(task_runner_, - &media_log_); - decoder_->Initialize( - media::DecoderConfigAdapter::ToMediaAudioDecoderConfig(input_config_), - nullptr, - base::BindRepeating(&CastAudioDecoderImpl::OnInitialized, weak_this_), - base::BindRepeating(&CastAudioDecoderImpl::OnDecoderOutput, weak_this_), - base::NullCallback()); - // Unfortunately there is no result from decoder_->Initialize() until later - // (the pipeline status callback is posted to the task runner). - } - - CastAudioDecoderImpl(const CastAudioDecoderImpl&) = delete; - CastAudioDecoderImpl& operator=(const CastAudioDecoderImpl&) = delete; - - // CastAudioDecoder implementation: - const AudioConfig& GetOutputConfig() const override { return output_config_; } - - void Decode(scoped_refptr data, - DecodeCallback decode_callback) override { - DCHECK(decode_callback); - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - - if (data->decrypt_context() != nullptr || error_) { - if (data->decrypt_context() != nullptr) { - LOG(ERROR) << "Audio decoder doesn't support encrypted stream"; - } - - // Post the task to ensure that |decode_callback| is not called from - // within a call to Decode(). - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&CastAudioDecoderImpl::CallDecodeCallback, - weak_this_, std::move(decode_callback), - kDecodeError, std::move(data))); - } else if (!initialized_ || decode_pending_) { - decode_queue_.push( - std::make_pair(std::move(data), std::move(decode_callback))); - } else { - DecodeNow(std::move(data), std::move(decode_callback)); - } - } - - private: - typedef std::pair, DecodeCallback> - DecodeBufferCallbackPair; - - void CallDecodeCallback(DecodeCallback decode_callback, - Status status, - scoped_refptr data) { - std::move(decode_callback).Run(status, output_config_, std::move(data)); - } - - void DecodeNow(scoped_refptr data, - DecodeCallback decode_callback) { - if (data->end_of_stream()) { - // Post the task to ensure that |decode_callback| is not called from - // within a call to Decode(). - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&CastAudioDecoderImpl::CallDecodeCallback, - weak_this_, std::move(decode_callback), - kDecodeOk, std::move(data))); - return; - } - - // FFmpegAudioDecoder requires a timestamp to be set. - base::TimeDelta timestamp = base::Microseconds(data->timestamp()); - if (timestamp == ::media::kNoTimestamp) { - timestamp = base::TimeDelta(); - data->set_timestamp(timestamp); - } - - decode_pending_ = true; - pending_decode_callback_ = std::move(decode_callback); - - auto media_buffer = ::media::DecoderBuffer::FromExternalMemory( - std::make_unique(std::move(data))); - media_buffer->set_timestamp(timestamp); - - decoder_->Decode(std::move(media_buffer), - base::BindRepeating(&CastAudioDecoderImpl::OnDecodeStatus, - weak_this_, timestamp)); - } - - void OnInitialized(::media::DecoderStatus status) { - DCHECK(!initialized_); - initialized_ = true; - if (status.is_ok()) { - if (!decode_queue_.empty()) { - auto& d = decode_queue_.front(); - DecodeNow(std::move(d.first), std::move(d.second)); - decode_queue_.pop(); - } - return; - } - - error_ = true; - LOG(ERROR) << "Failed to initialize audio decoder"; - LOG(INFO) << "Config:"; - LOG(INFO) << "\tCodec: " << input_config_.codec; - LOG(INFO) << "\tSample format: " << input_config_.sample_format; - LOG(INFO) << "\tChannels: " << input_config_.channel_number; - LOG(INFO) << "\tSample rate: " << input_config_.samples_per_second; - - while (!decode_queue_.empty()) { - auto& d = decode_queue_.front(); - std::move(d.second).Run(kDecodeError, output_config_, std::move(d.first)); - decode_queue_.pop(); - } - } - - void OnDecodeStatus(base::TimeDelta buffer_timestamp, - ::media::DecoderStatus status) { - DCHECK(pending_decode_callback_); - - Status result_status = kDecodeOk; - scoped_refptr decoded; - if (status.is_ok() && !decoded_chunks_.empty()) { - decoded = ConvertDecoded(); - } else { - if (!status.is_ok()) - result_status = kDecodeError; - decoded = base::MakeRefCounted( - output_config_.id, base::MakeRefCounted<::media::DecoderBuffer>(0)); - } - decoded_chunks_.clear(); - decoded->set_timestamp(buffer_timestamp); - base::WeakPtr self = weak_factory_.GetWeakPtr(); - std::move(pending_decode_callback_) - .Run(result_status, output_config_, std::move(decoded)); - if (!self) - return; // Return immediately if the decode callback deleted this. - - // Do not reset decode_pending_ to false until after the callback has - // finished running because the callback may call Decode(). - decode_pending_ = false; - - if (decode_queue_.empty()) - return; - - auto& d = decode_queue_.front(); - // Calling DecodeNow() here does not result in a loop, because - // OnDecodeStatus() is always called asynchronously (guaranteed by the - // AudioDecoder interface). - DecodeNow(std::move(d.first), std::move(d.second)); - decode_queue_.pop(); - } - - void OnDecoderOutput(scoped_refptr<::media::AudioBuffer> decoded) { - if (decoded->sample_rate() != output_config_.samples_per_second) { - LOG(WARNING) << "sample_rate changed to " << decoded->sample_rate() - << " from " << output_config_.samples_per_second; - output_config_.samples_per_second = decoded->sample_rate(); - } - - ChannelLayout decoded_channel_layout = - DecoderConfigAdapter::ToChannelLayout(decoded->channel_layout()); - if (decoded->channel_count() != output_config_.channel_number || - decoded_channel_layout != output_config_.channel_layout) { - LOG(WARNING) << "channel_count changed to " << decoded->channel_count() - << " from " << output_config_.channel_number - << ", channel_layout changed to " - << static_cast(decoded_channel_layout) << " from " - << static_cast(output_config_.channel_layout); - output_config_.channel_number = decoded->channel_count(); - output_config_.channel_layout = - DecoderConfigAdapter::ToChannelLayout(decoded->channel_layout()); - decoded_bus_.reset(); - } - - decoded_chunks_.push_back(std::move(decoded)); - } - - scoped_refptr ConvertDecoded() { - DCHECK(!decoded_chunks_.empty()); - int num_frames = 0; - for (auto& chunk : decoded_chunks_) - num_frames += chunk->frame_count(); - - // Copy decoded data into an AudioBus for conversion. - if (!decoded_bus_ || decoded_bus_->frames() < num_frames) { - decoded_bus_ = ::media::AudioBus::Create(output_config_.channel_number, - num_frames * 2); - } - int bus_frame_offset = 0; - for (auto& chunk : decoded_chunks_) { - chunk->ReadFrames(chunk->frame_count(), 0, bus_frame_offset, - decoded_bus_.get()); - bus_frame_offset += chunk->frame_count(); - } - - return FinishConversion(decoded_bus_.get(), bus_frame_offset); - } - - scoped_refptr FinishConversion( - ::media::AudioBus* bus, - int num_frames) { - int size = - num_frames * bus->channels() * OutputFormatSizeInBytes(output_format_); - auto result = base::MakeRefCounted<::media::DecoderBuffer>(size); - - if (output_format_ == kOutputSigned16) { - bus->ToInterleaved<::media::SignedInt16SampleTypeTraits>( - num_frames, reinterpret_cast(result->writable_data())); - } else if (output_format_ == kOutputPlanarFloat) { - // Data in an AudioBus is already in planar float format; just copy each - // channel into the result buffer in order. - float* ptr = reinterpret_cast(result->writable_data()); - for (int c = 0; c < bus->channels(); ++c) { - std::copy_n(bus->channel(c), num_frames, ptr); - ptr += num_frames; - } - } else { - NOTREACHED(); - } - - result->set_duration( - base::Microseconds(num_frames * base::Time::kMicrosecondsPerSecond / - output_config_.samples_per_second)); - return base::MakeRefCounted(output_config_.id, - result); - } - - ::media::NullMediaLog media_log_; - const scoped_refptr task_runner_; - OutputFormat output_format_; - bool initialized_ = false; - bool error_ = false; - media::AudioConfig input_config_; - media::AudioConfig output_config_; - - std::unique_ptr<::media::AudioDecoder> decoder_; - base::queue decode_queue_; - - bool decode_pending_ = false; - DecodeCallback pending_decode_callback_; - std::vector> decoded_chunks_; - - std::unique_ptr<::media::AudioBus> decoded_bus_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace - -// static -std::unique_ptr CastAudioDecoder::Create( - scoped_refptr task_runner, - const media::AudioConfig& config, - OutputFormat output_format) { - if (ExternalAudioDecoderWrapper::IsSupportedConfig(config)) { - auto external_decoder = std::make_unique( - std::move(task_runner), config, output_format); - if (!external_decoder->initialized()) { - return nullptr; - } - return external_decoder; - } - - return std::make_unique(std::move(task_runner), config, - output_format); -} - -// static -int CastAudioDecoder::OutputFormatSizeInBytes( - CastAudioDecoder::OutputFormat format) { - switch (format) { - case CastAudioDecoder::OutputFormat::kOutputSigned16: - return 2; - case CastAudioDecoder::OutputFormat::kOutputPlanarFloat: - return 4; - } - NOTREACHED(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/decoder/external_audio_decoder_wrapper.cc chromium-132.0.6834.159/chromecast/media/cma/decoder/external_audio_decoder_wrapper.cc --- chromium-132.0.6834.110/chromecast/media/cma/decoder/external_audio_decoder_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/decoder/external_audio_decoder_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,290 +0,0 @@ -// 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 "chromecast/media/cma/decoder/external_audio_decoder_wrapper.h" - -#include -#include - -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/no_destructor.h" -#include "base/scoped_native_library.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_sample_types.h" -#include "media/base/decoder_buffer.h" - -namespace chromecast { -namespace media { - -namespace { - -const char kDefaultExternalDecoderPath[] = "libcast_external_decoder.so"; - -const char kSupportedConfigFunction[] = - "ExternalAudioDecoder_IsSupportedConfig"; -const char kCreateFunction[] = "ExternalAudioDecoder_CreateDecoder"; -const char kDeleteFunction[] = "ExternalAudioDecoder_DeleteDecoder"; - -const size_t kMinConversionBufferSize = 256; - -class ExternalDecoderLib { - public: - ExternalDecoderLib() : lib_(base::FilePath(kDefaultExternalDecoderPath)) { - if (lib_.is_valid()) { - supported_config_func_ = reinterpret_cast( - lib_.GetFunctionPointer(kSupportedConfigFunction)); - create_func_ = reinterpret_cast( - lib_.GetFunctionPointer(kCreateFunction)); - delete_func_ = reinterpret_cast( - lib_.GetFunctionPointer(kDeleteFunction)); - - LOG_IF(ERROR, !supported_config_func_) - << "Missing function: " << kSupportedConfigFunction; - LOG_IF(ERROR, !create_func_) << "Missing function: " << kCreateFunction; - LOG_IF(ERROR, !delete_func_) << "Missing function: " << kDeleteFunction; - } - } - - ExternalDecoderLib(const ExternalDecoderLib&) = delete; - ExternalDecoderLib& operator=(const ExternalDecoderLib&) = delete; - - ~ExternalDecoderLib() = default; - - bool IsSupportedConfig(const AudioConfig& config) { - if (!supported_config_func_ || !create_func_ || !delete_func_) { - return false; - } - - return supported_config_func_(config); - } - - ExternalAudioDecoder* CreateDecoder( - ExternalAudioDecoder::Delegate* delegate, - const chromecast::media::AudioConfig& config) { - if (!create_func_ || !delete_func_) { - return nullptr; - } - - return create_func_(delegate, config); - } - - void DeleteDecoder(ExternalAudioDecoder* decoder) { - DCHECK(delete_func_); - delete_func_(decoder); - } - - private: - using IsSupportedConfigFunction = - decltype(&ExternalAudioDecoder_IsSupportedConfig); - using CreateFunction = decltype(&ExternalAudioDecoder_CreateDecoder); - using DeleteFunction = decltype(&ExternalAudioDecoder_DeleteDecoder); - - base::ScopedNativeLibrary lib_; - IsSupportedConfigFunction supported_config_func_ = nullptr; - CreateFunction create_func_ = nullptr; - DeleteFunction delete_func_ = nullptr; -}; - -ExternalDecoderLib& GetLib() { - static base::NoDestructor g_lib; - return *g_lib; -} - -AudioConfig BuildOutputConfig(const AudioConfig& input_config, - CastAudioDecoder::OutputFormat output_format, - ExternalAudioDecoder* decoder) { - AudioConfig output_config = input_config; - output_config.encryption_scheme = EncryptionScheme::kUnencrypted; - output_config.codec = kCodecPCM; - output_config.sample_format = - (output_format == CastAudioDecoder::kOutputSigned16 - ? kSampleFormatS16 - : kSampleFormatPlanarF32); - output_config.channel_number = decoder->GetNumOutputChannels(); - if (output_config.channel_number <= 0) { - output_config.channel_number = input_config.channel_number; - } - return output_config; -} - -} // namespace - -class ExternalAudioDecoderWrapper::DecodedBuffer : public DecoderBufferBase { - public: - DecodedBuffer(StreamId stream_id, size_t capacity) - : stream_id_(stream_id), - capacity_(capacity), - data_(std::make_unique(capacity_)) {} - - void set_size(size_t size) { - DCHECK_LE(size, capacity_); - size_ = size; - } - - // DecoderBufferBase implementation: - StreamId stream_id() const override { return stream_id_; } - int64_t timestamp() const override { return timestamp_.InMicroseconds(); } - void set_timestamp(base::TimeDelta timestamp) override { - timestamp_ = timestamp; - } - const uint8_t* data() const override { return data_.get(); } - uint8_t* writable_data() const override { return data_.get(); } - size_t data_size() const override { return size_; } - const CastDecryptConfig* decrypt_config() const override { return nullptr; } - bool end_of_stream() const override { return false; } - bool is_key_frame() const override { return false; } - - private: - ~DecodedBuffer() override = default; - - const StreamId stream_id_; - const size_t capacity_; - - const std::unique_ptr data_; - - base::TimeDelta timestamp_; - size_t size_ = 0; -}; - -// static -bool ExternalAudioDecoderWrapper::IsSupportedConfig(const AudioConfig& config) { - return GetLib().IsSupportedConfig(config); -} - -ExternalAudioDecoderWrapper::ExternalAudioDecoderWrapper( - scoped_refptr task_runner, - const AudioConfig& config, - CastAudioDecoder::OutputFormat output_format) - : task_runner_(std::move(task_runner)), - output_format_(output_format), - decoder_(GetLib().CreateDecoder(this, config)), - output_config_(BuildOutputConfig(config, output_format_, decoder_)) {} - -ExternalAudioDecoderWrapper::~ExternalAudioDecoderWrapper() { - if (decoder_) { - GetLib().DeleteDecoder(decoder_); - } -} - -const AudioConfig& ExternalAudioDecoderWrapper::GetOutputConfig() const { - return output_config_; -} - -void ExternalAudioDecoderWrapper::Decode( - scoped_refptr data, - DecodeCallback decode_callback) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - // Post a task, since some callers don't expect a synchronous callback. - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&ExternalAudioDecoderWrapper::DecodeDeferred, - weak_factory_.GetWeakPtr(), std::move(data), - std::move(decode_callback))); -} - -void ExternalAudioDecoderWrapper::DecodeDeferred( - scoped_refptr data, - DecodeCallback decode_callback) { - if (data->end_of_stream()) { - std::move(decode_callback).Run(kDecodeOk, output_config_, std::move(data)); - return; - } - - if (!decoder_ || !decoder_->Decode(*data)) { - std::move(decode_callback).Run(kDecodeError, output_config_, nullptr); - return; - } - - size_t buffer_count = buffers_.size() - pending_buffer_; - scoped_refptr decoded; - if (buffer_count == 0) { - decoded = base::MakeRefCounted(output_config_.id, 0); - } else if (buffer_count == 1) { - decoded = std::move(buffers_.front()); - } else { - size_t size = 0; - for (size_t i = 0; i < buffer_count; ++i) { - size += buffers_[i]->data_size(); - } - - decoded = base::MakeRefCounted(output_config_.id, size); - decoded->set_size(size); - - const size_t frame_size = sizeof(float) * output_config_.channel_number; - size_t total_frames = size / frame_size; - for (int c = 0; c < output_config_.channel_number; ++c) { - uint8_t* dest = - decoded->writable_data() + c * total_frames * sizeof(float); - for (size_t i = 0; i < buffer_count; ++i) { - size_t frames = buffers_[i]->data_size() / frame_size; - void* src = buffers_[i]->writable_data() + c * frames * sizeof(float); - memcpy(dest, src, frames * sizeof(float)); - dest += frames * sizeof(float); - } - } - } - - buffers_.erase(buffers_.begin(), buffers_.begin() + buffer_count); - - if (output_format_ == CastAudioDecoder::kOutputSigned16) { - ConvertToS16(decoded.get()); - } - - decoded->set_timestamp(base::Microseconds(data->timestamp())); - std::move(decode_callback).Run(kDecodeOk, output_config_, std::move(decoded)); -} - -void ExternalAudioDecoderWrapper::ConvertToS16(DecodedBuffer* buffer) { - const int channels = output_config_.channel_number; - const size_t frame_size = sizeof(float) * channels; - const size_t frames = buffer->data_size() / frame_size; - - if (!conversion_buffer_ || - conversion_buffer_->frames() < static_cast(frames) || - conversion_buffer_->channels() != channels) { - conversion_buffer_ = ::media::AudioBus::Create( - channels, std::max(frames * 2, kMinConversionBufferSize)); - } - - const float* src = reinterpret_cast(buffer->data()); - for (int c = 0; c < channels; ++c) { - std::copy_n(src + c * frames, frames, conversion_buffer_->channel(c)); - } - - int16_t* dest = reinterpret_cast(buffer->writable_data()); - conversion_buffer_ - ->ToInterleavedPartial<::media::SignedInt16SampleTypeTraits>(0, frames, - dest); - - buffer->set_size(frames * channels * sizeof(int16_t)); -} - -void* ExternalAudioDecoderWrapper::AllocateBuffer(size_t bytes) { - auto buffer = base::MakeRefCounted(output_config_.id, bytes); - void* ptr = buffer->writable_data(); - buffers_.push_back(std::move(buffer)); - pending_buffer_ = true; - return ptr; -} - -void ExternalAudioDecoderWrapper::OnDecodedBuffer(size_t decoded_size_bytes, - const AudioConfig& config) { - DCHECK(!buffers_.empty()); - size_t frame_size = sizeof(float) * config.channel_number; - DCHECK_EQ(decoded_size_bytes % frame_size, 0u); - - buffers_.back()->set_size(decoded_size_bytes); - output_config_.channel_number = config.channel_number; - output_config_.samples_per_second = config.samples_per_second; - pending_buffer_ = false; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/decoder/external_audio_decoder_wrapper.h chromium-132.0.6834.159/chromecast/media/cma/decoder/external_audio_decoder_wrapper.h --- chromium-132.0.6834.110/chromecast/media/cma/decoder/external_audio_decoder_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/decoder/external_audio_decoder_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_CMA_DECODER_EXTERNAL_AUDIO_DECODER_WRAPPER_H_ -#define CHROMECAST_MEDIA_CMA_DECODER_EXTERNAL_AUDIO_DECODER_WRAPPER_H_ - -#include -#include - -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/media/api/cast_audio_decoder.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/external_audio_decoder.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace media { -class AudioBus; -} - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -// Wrapper API for external (3P) decoder library. -class ExternalAudioDecoderWrapper : public ExternalAudioDecoder::Delegate, - public CastAudioDecoder { - public: - static bool IsSupportedConfig(const AudioConfig& config); - - ExternalAudioDecoderWrapper( - scoped_refptr task_runner, - const AudioConfig& config, - CastAudioDecoder::OutputFormat output_format); - ExternalAudioDecoderWrapper(const ExternalAudioDecoderWrapper&) = delete; - ExternalAudioDecoderWrapper& operator=(const ExternalAudioDecoderWrapper&) = - delete; - ~ExternalAudioDecoderWrapper() override; - - bool initialized() const { return decoder_ != nullptr; } - - private: - class DecodedBuffer; - - // CastAudioDecoder implementation: - const AudioConfig& GetOutputConfig() const override; - void Decode(scoped_refptr data, - DecodeCallback decode_callback) override; - - void DecodeDeferred(scoped_refptr data, - DecodeCallback decode_callback); - void ConvertToS16(DecodedBuffer* buffer); - - // ExternalAudioDecoder::Delegate implementation: - void* AllocateBuffer(size_t bytes) override; - void OnDecodedBuffer(size_t decoded_size_bytes, - const AudioConfig& config) override; - - const scoped_refptr task_runner_; - const CastAudioDecoder::OutputFormat output_format_; - ExternalAudioDecoder* const decoder_; - - AudioConfig output_config_; - std::vector> buffers_; - bool pending_buffer_ = false; - - std::unique_ptr<::media::AudioBus> conversion_buffer_; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_DECODER_EXTERNAL_AUDIO_DECODER_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/audio_pipeline_impl.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_pipeline_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/audio_pipeline_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_pipeline_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,119 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/audio_pipeline_impl.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "chromecast/media/cma/base/buffering_defs.h" -#include "chromecast/media/cma/base/coded_frame_provider.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/media/cma/pipeline/backend_decryptor.h" -#include "chromecast/media/cma/pipeline/cdm_decryptor.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_capabilities_shlib.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "media/base/audio_decoder_config.h" - -namespace chromecast { -namespace media { - -namespace { -const size_t kMaxAudioFrameSize = 32 * 1024; - -} - -AudioPipelineImpl::AudioPipelineImpl(CmaBackend::AudioDecoder* decoder, - AvPipelineClient client) - : AvPipelineImpl(decoder, std::move(client)), audio_decoder_(decoder) { - DCHECK(audio_decoder_); -} - -AudioPipelineImpl::~AudioPipelineImpl() = default; - -::media::PipelineStatus AudioPipelineImpl::Initialize( - const ::media::AudioDecoderConfig& audio_config, - std::unique_ptr frame_provider) { - LOG(INFO) << __FUNCTION__ << " " << audio_config.AsHumanReadableString(); - if (frame_provider) { - SetCodedFrameProvider(std::move(frame_provider), kAppAudioBufferSize, - kMaxAudioFrameSize); - } - - DCHECK(audio_config.IsValidConfig()); - AudioConfig config = - DecoderConfigAdapter::ToCastAudioConfig(kPrimary, audio_config); - encryption_scheme_ = config.encryption_scheme; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - - if (!audio_decoder_->SetConfig(config)) { - return ::media::PIPELINE_ERROR_INITIALIZATION_FAILED; - } - set_state(kFlushed); - return ::media::PIPELINE_OK; -} - -void AudioPipelineImpl::SetVolume(float volume) { - audio_decoder_->SetVolume(volume); -} - -void AudioPipelineImpl::OnUpdateConfig( - StreamId id, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) { - if (audio_config.IsValidConfig()) { - LOG(INFO) << __FUNCTION__ << " id:" << id << " " - << audio_config.AsHumanReadableString(); - - AudioConfig config = - DecoderConfigAdapter::ToCastAudioConfig(id, audio_config); - encryption_scheme_ = config.encryption_scheme; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - bool success = audio_decoder_->SetConfig(config); - if (!success && !client().playback_error_cb.is_null()) - client().playback_error_cb.Run(::media::PIPELINE_ERROR_DECODE); - } -} - -EncryptionScheme AudioPipelineImpl::GetEncryptionScheme(StreamId id) const { - return encryption_scheme_; -} - -std::unique_ptr AudioPipelineImpl::CreateDecryptor() { - if (MediaPipelineBackend::CreateAudioDecryptor) { - DCHECK_NE(encryption_scheme_, EncryptionScheme::kUnencrypted); - LOG(INFO) << __func__ << " Create backend decryptor for audio."; - return std::make_unique(encryption_scheme_); - } - - return std::make_unique(true /* clear_buffer_needed */); -} - -void AudioPipelineImpl::UpdateStatistics() { - if (client().statistics_cb.is_null()) - return; - - // TODO(mbjorge): Give Statistics a default constructor when the - // next system update happens. b/32802298 - CmaBackend::AudioDecoder::Statistics audio_stats = {}; - audio_decoder_->GetStatistics(&audio_stats); - - ::media::PipelineStatistics current_stats; - current_stats.audio_bytes_decoded = audio_stats.decoded_bytes; - - ::media::PipelineStatistics delta_stats; - delta_stats.audio_bytes_decoded = - current_stats.audio_bytes_decoded - previous_stats_.audio_bytes_decoded; - - bytes_decoded_since_last_update_ = delta_stats.audio_bytes_decoded; - previous_stats_ = current_stats; - - client().statistics_cb.Run(delta_stats); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/audio_pipeline_impl.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_pipeline_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/audio_pipeline_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_pipeline_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_AUDIO_PIPELINE_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_AUDIO_PIPELINE_IMPL_H_ - -#include -#include - -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/cma/pipeline/av_pipeline_client.h" -#include "chromecast/media/cma/pipeline/av_pipeline_impl.h" -#include "chromecast/public/media/stream_id.h" -#include "media/base/pipeline_status.h" - -namespace media { -class AudioDecoderConfig; -class VideoDecoderConfig; -} - -namespace chromecast { -namespace media { -class CodedFrameProvider; - -class AudioPipelineImpl : public AvPipelineImpl { - public: - AudioPipelineImpl(CmaBackend::AudioDecoder* decoder, AvPipelineClient client); - - AudioPipelineImpl(const AudioPipelineImpl&) = delete; - AudioPipelineImpl& operator=(const AudioPipelineImpl&) = delete; - - ~AudioPipelineImpl() override; - - ::media::PipelineStatus Initialize( - const ::media::AudioDecoderConfig& config, - std::unique_ptr frame_provider); - - void SetVolume(float volume); - - // AvPipelineImpl implementation: - void UpdateStatistics() override; - - private: - // AvPipelineImpl implementation: - void OnUpdateConfig(StreamId id, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) override; - EncryptionScheme GetEncryptionScheme(StreamId id) const override; - std::unique_ptr CreateDecryptor() override; - - CmaBackend::AudioDecoder* const audio_decoder_; - - EncryptionScheme encryption_scheme_ = EncryptionScheme::kUnencrypted; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_AUDIO_PIPELINE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/audio_video_pipeline_impl_unittest.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_video_pipeline_impl_unittest.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/audio_video_pipeline_impl_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/audio_video_pipeline_impl_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,459 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "chromecast/media/api/test/mock_cma_backend.h" -#include "chromecast/media/base/decrypt_context_impl.h" -#include "chromecast/media/cdm/cast_cdm_context.h" -#include "chromecast/media/cma/pipeline/av_pipeline_client.h" -#include "chromecast/media/cma/pipeline/media_pipeline_impl.h" -#include "chromecast/media/cma/pipeline/video_pipeline_client.h" -#include "chromecast/media/cma/test/frame_generator_for_test.h" -#include "chromecast/media/cma/test/mock_frame_provider.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/callback_registry.h" -#include "media/base/media_util.h" -#include "media/base/video_decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; -using testing::AtLeast; -using testing::Invoke; -using testing::NiceMock; -using testing::Return; -using testing::SaveArg; - -namespace { -// Total number of frames generated by CodedFrameProvider. -// The first frame has config, while the last one is EOS. -const int kNumFrames = 100; -const int kFrameSize = 512; -const int kFrameDurationUs = 40 * 1000; -const int kLastFrameTimestamp = (kNumFrames - 2) * kFrameDurationUs; -} // namespace - -namespace chromecast { -namespace media { - -ACTION_P2(PushBuffer, delegate, buffer_pts) { - if (arg0->end_of_stream()) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&CmaBackend::Decoder::Delegate::OnEndOfStream, - base::Unretained(*delegate))); - } else { - *buffer_pts = arg0->timestamp(); - } - return CmaBackend::BufferStatus::kBufferSuccess; -} - -class CastCdmContextForTest : public CastCdmContext { - public: - CastCdmContextForTest() : license_installed_(false) {} - - CastCdmContextForTest(const CastCdmContextForTest&) = delete; - CastCdmContextForTest& operator=(const CastCdmContextForTest&) = delete; - - void SetLicenseInstalled() { - license_installed_ = true; - event_callbacks_.Notify( - ::media::CdmContext::Event::kHasAdditionalUsableKey); - } - - // CastCdmContext implementation: - std::unique_ptr<::media::CallbackRegistration> RegisterEventCB( - ::media::CdmContext::EventCB event_cb) override { - return event_callbacks_.Register(std::move(event_cb)); - } - - std::unique_ptr GetDecryptContext( - const std::string& key_id, - EncryptionScheme encryption_scheme) override { - if (license_installed_) { - return std::unique_ptr( - new DecryptContextImpl(KEY_SYSTEM_CLEAR_KEY)); - } - return nullptr; - } - - void SetKeyStatus(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override {} - - void SetVideoResolution(int width, int height) override {} - - private: - bool license_installed_; - ::media::CallbackRegistry<::media::CdmContext::EventCB::RunType> - event_callbacks_; -}; - -// Helper class for managing pipeline setup, teardown, feeding data, stop/start -// etc in a simple API for tests to use. -class PipelineHelper { - public: - enum Stream { STREAM_AUDIO, STREAM_VIDEO }; - - PipelineHelper(bool audio, bool video, bool encrypted) - : have_audio_(audio), - have_video_(video), - encrypted_(encrypted), - pipeline_backend_(nullptr), - audio_decoder_delegate_(nullptr), - video_decoder_delegate_(nullptr) {} - - PipelineHelper(const PipelineHelper&) = delete; - PipelineHelper& operator=(const PipelineHelper&) = delete; - - void Setup() { - if (encrypted_) { - cdm_context_.reset(new CastCdmContextForTest()); - } - - auto backend = std::make_unique(); - pipeline_backend_ = backend.get(); - ON_CALL(*pipeline_backend_, SetPlaybackRate(_)).WillByDefault(Return(true)); - ON_CALL(audio_decoder_, SetConfig(_)).WillByDefault(Return(true)); - ON_CALL(audio_decoder_, PushBuffer(_)) - .WillByDefault(PushBuffer(&audio_decoder_delegate_, - &last_push_pts_[STREAM_AUDIO])); - ON_CALL(video_decoder_, SetConfig(_)).WillByDefault(Return(true)); - ON_CALL(video_decoder_, PushBuffer(_)) - .WillByDefault(PushBuffer(&video_decoder_delegate_, - &last_push_pts_[STREAM_VIDEO])); - - media_pipeline_ = std::make_unique(); - media_pipeline_->Initialize(kLoadTypeURL, std::move(backend), - /* is_buffering_enabled */ true); - - if (have_audio_) { - ::media::AudioDecoderConfig audio_config( - ::media::AudioCodec::kMP3, ::media::kSampleFormatS16, - ::media::CHANNEL_LAYOUT_STEREO, 44100, ::media::EmptyExtraData(), - ::media::EncryptionScheme::kUnencrypted); - AvPipelineClient client; - client.eos_cb = base::BindRepeating(&PipelineHelper::OnEos, - base::Unretained(this), STREAM_AUDIO); - EXPECT_CALL(*pipeline_backend_, CreateAudioDecoder()) - .Times(1) - .WillOnce(Return(&audio_decoder_)); - EXPECT_CALL(audio_decoder_, SetDelegate(_)) - .Times(1) - .WillOnce(SaveArg<0>(&audio_decoder_delegate_)); - ::media::PipelineStatus status = media_pipeline_->InitializeAudio( - audio_config, std::move(client), CreateFrameProvider()); - ASSERT_EQ(::media::PIPELINE_OK, status); - } - if (have_video_) { - std::vector<::media::VideoDecoderConfig> video_configs; - video_configs.push_back(::media::VideoDecoderConfig( - ::media::VideoCodec::kH264, ::media::H264PROFILE_MAIN, - ::media::VideoDecoderConfig::AlphaMode::kIsOpaque, - ::media::VideoColorSpace(), ::media::kNoTransformation, - gfx::Size(640, 480), gfx::Rect(0, 0, 640, 480), gfx::Size(640, 480), - ::media::EmptyExtraData(), ::media::EncryptionScheme())); - VideoPipelineClient client; - client.av_pipeline_client.eos_cb = base::BindRepeating( - &PipelineHelper::OnEos, base::Unretained(this), STREAM_VIDEO); - EXPECT_CALL(*pipeline_backend_, CreateVideoDecoder()) - .Times(1) - .WillOnce(Return(&video_decoder_)); - EXPECT_CALL(video_decoder_, SetDelegate(_)) - .Times(1) - .WillOnce(SaveArg<0>(&video_decoder_delegate_)); - ::media::PipelineStatus status = media_pipeline_->InitializeVideo( - video_configs, std::move(client), CreateFrameProvider()); - ASSERT_EQ(::media::PIPELINE_OK, status); - } - } - - void SetPipelineStartExpectations() { - // The pipeline will be paused first, for the initial data buffering. Then - // it will be resumed, once enough data is buffered to start playback. - // When starting media pipeline, GetCurrentPts will be called every - // kTimeUpdateInterval(250ms). - EXPECT_CALL(*pipeline_backend_, GetCurrentPts()).Times(AtLeast(1)); - EXPECT_CALL(*pipeline_backend_, Pause()); - EXPECT_CALL(*pipeline_backend_, SetPlaybackRate(1.0f)); - EXPECT_CALL(*pipeline_backend_, Resume()); - } - - // This is used for the Flush test case, where the pipeline start sequence is - // interrupted by the Flush, and the initial buffering never completes. - void SetPipelineStartFlushExpectations() { - EXPECT_CALL(*pipeline_backend_, GetCurrentPts()); - EXPECT_CALL(*pipeline_backend_, Pause()); - } - void Run() { - base::RunLoop loop; - quit_closure_ = loop.QuitWhenIdleClosure(); - loop.Run(); - } - void Start(base::RepeatingClosure eos_cb) { - eos_cb_ = std::move(eos_cb); - eos_[STREAM_AUDIO] = !media_pipeline_->HasAudio(); - eos_[STREAM_VIDEO] = !media_pipeline_->HasVideo(); - last_push_pts_[STREAM_AUDIO] = std::numeric_limits::min(); - last_push_pts_[STREAM_VIDEO] = std::numeric_limits::min(); - int64_t start_pts = 0; - - EXPECT_CALL(*pipeline_backend_, Initialize()) - .Times(1) - .WillOnce(Return(true)); - EXPECT_CALL(*pipeline_backend_, Start(start_pts)) - .Times(1) - .WillOnce(Return(true)); - - media_pipeline_->StartPlayingFrom(base::Milliseconds(start_pts)); - media_pipeline_->SetPlaybackRate(1.0f); - } - void SetCdm() { media_pipeline_->SetCdm(cdm_context_.get()); } - void Flush(base::OnceClosure flush_cb) { - EXPECT_CALL(*pipeline_backend_, Stop()).Times(1); - media_pipeline_->Flush(std::move(flush_cb)); - } - void Stop() { - media_pipeline_.reset(); - std::move(quit_closure_).Run(); - } - void FlushThenStop() { - base::OnceClosure stop_task = - base::BindOnce(&PipelineHelper::Stop, base::Unretained(this)); - Flush(std::move(stop_task)); - } - void SetCdmLicenseInstalled() { cdm_context_->SetLicenseInstalled(); } - - bool have_audio() const { return have_audio_; } - bool have_video() const { return have_video_; } - int64_t last_push_pts(Stream stream) const { return last_push_pts_[stream]; } - - private: - std::unique_ptr CreateFrameProvider() { - std::vector frame_specs; - frame_specs.resize(kNumFrames); - for (size_t k = 0; k < frame_specs.size() - 1; k++) { - frame_specs[k].has_config = (k == 0); - frame_specs[k].timestamp = base::Microseconds(kFrameDurationUs) * k; - frame_specs[k].size = kFrameSize; - frame_specs[k].has_decrypt_config = encrypted_; - } - frame_specs.back().is_eos = true; - - std::unique_ptr frame_generator( - new FrameGeneratorForTest(frame_specs)); - bool provider_delayed_pattern[] = {false, true}; - std::unique_ptr frame_provider(new MockFrameProvider()); - frame_provider->Configure( - std::vector( - provider_delayed_pattern, - provider_delayed_pattern + std::size(provider_delayed_pattern)), - std::move(frame_generator)); - frame_provider->SetDelayFlush(true); - return std::move(frame_provider); - } - - void OnEos(Stream stream) { - eos_[stream] = true; - if (eos_[STREAM_AUDIO] && eos_[STREAM_VIDEO] && !eos_cb_.is_null()) - eos_cb_.Run(); - } - - bool have_audio_; - bool have_video_; - bool encrypted_; - bool eos_[2]; - int64_t last_push_pts_[2]; - base::RepeatingClosure eos_cb_; - std::unique_ptr cdm_context_; - MockCmaBackend* pipeline_backend_; - NiceMock audio_decoder_; - NiceMock video_decoder_; - CmaBackend::Decoder::Delegate* audio_decoder_delegate_; - CmaBackend::Decoder::Delegate* video_decoder_delegate_; - std::unique_ptr media_pipeline_; - base::OnceClosure quit_closure_; -}; - -using AudioVideoTuple = ::testing::tuple; - -class AudioVideoPipelineImplTest - : public ::testing::TestWithParam { - public: - AudioVideoPipelineImplTest() {} - - AudioVideoPipelineImplTest(const AudioVideoPipelineImplTest&) = delete; - AudioVideoPipelineImplTest& operator=(const AudioVideoPipelineImplTest&) = - delete; - - protected: - void SetUp() override { - pipeline_helper_.reset(new PipelineHelper( - ::testing::get<0>(GetParam()), ::testing::get<1>(GetParam()), false)); - pipeline_helper_->Setup(); - } - - base::test::TaskEnvironment task_environment_; - std::unique_ptr pipeline_helper_; -}; - -static void VerifyPlay(PipelineHelper* pipeline_helper) { - // The decoders must have received the last frame. - if (pipeline_helper->have_audio()) - EXPECT_EQ(kLastFrameTimestamp, - pipeline_helper->last_push_pts(PipelineHelper::STREAM_AUDIO)); - if (pipeline_helper->have_video()) - EXPECT_EQ(kLastFrameTimestamp, - pipeline_helper->last_push_pts(PipelineHelper::STREAM_VIDEO)); - - pipeline_helper->Stop(); -} - -TEST_P(AudioVideoPipelineImplTest, Play) { - base::RepeatingClosure verify_task = base::BindRepeating( - &VerifyPlay, base::Unretained(pipeline_helper_.get())); - pipeline_helper_->SetPipelineStartExpectations(); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::Start, - base::Unretained(pipeline_helper_.get()), - std::move(verify_task))); - pipeline_helper_->Run(); -} - -static void VerifyFlush(PipelineHelper* pipeline_helper) { - // The decoders must not have received any frame. - if (pipeline_helper->have_audio()) - EXPECT_LT(pipeline_helper->last_push_pts(PipelineHelper::STREAM_AUDIO), 0); - if (pipeline_helper->have_video()) - EXPECT_LT(pipeline_helper->last_push_pts(PipelineHelper::STREAM_VIDEO), 0); - - pipeline_helper->Stop(); -} - -static void VerifyNotReached() { - EXPECT_TRUE(false); -} - -TEST_P(AudioVideoPipelineImplTest, Flush) { - base::OnceClosure verify_task = - base::BindOnce(&VerifyFlush, base::Unretained(pipeline_helper_.get())); - pipeline_helper_->SetPipelineStartFlushExpectations(); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::Start, - base::Unretained(pipeline_helper_.get()), - base::BindRepeating(&VerifyNotReached))); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::Flush, - base::Unretained(pipeline_helper_.get()), - std::move(verify_task))); - - pipeline_helper_->Run(); -} - -TEST_P(AudioVideoPipelineImplTest, FullCycle) { - base::RepeatingClosure eos_cb = base::BindRepeating( - &PipelineHelper::FlushThenStop, base::Unretained(pipeline_helper_.get())); - - pipeline_helper_->SetPipelineStartExpectations(); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::Start, - base::Unretained(pipeline_helper_.get()), - std::move(eos_cb))); - pipeline_helper_->Run(); -} - -// Test all three types of pipeline: audio-only, video-only, audio-video. -INSTANTIATE_TEST_SUITE_P( - MediaPipelineImplTests, - AudioVideoPipelineImplTest, - ::testing::Values(AudioVideoTuple(true, false), // Audio only. - AudioVideoTuple(false, true), // Video only. - AudioVideoTuple(true, true))); // Audio and Video. - -// These tests verify that the pipeline handles encrypted media playback -// events (in particular, CDM and license installation) correctly. -class EncryptedAVPipelineImplTest : public ::testing::Test { - public: - EncryptedAVPipelineImplTest() {} - - EncryptedAVPipelineImplTest(const EncryptedAVPipelineImplTest&) = delete; - EncryptedAVPipelineImplTest& operator=(const EncryptedAVPipelineImplTest&) = - delete; - - protected: - void SetUp() override { - pipeline_helper_.reset(new PipelineHelper(true, true, true)); - pipeline_helper_->Setup(); - } - - base::test::TaskEnvironment task_environment_; - std::unique_ptr pipeline_helper_; -}; - -// Sets a CDM with license already installed before starting the pipeline. -TEST_F(EncryptedAVPipelineImplTest, SetCdmWithLicenseBeforeStart) { - base::RepeatingClosure verify_task = base::BindRepeating( - &VerifyPlay, base::Unretained(pipeline_helper_.get())); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::SetCdm, - base::Unretained(pipeline_helper_.get()))); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::SetCdmLicenseInstalled, - base::Unretained(pipeline_helper_.get()))); - pipeline_helper_->SetPipelineStartExpectations(); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::Start, - base::Unretained(pipeline_helper_.get()), - std::move(verify_task))); - pipeline_helper_->Run(); -} - -// Start the pipeline, then set a CDM with existing license. -TEST_F(EncryptedAVPipelineImplTest, SetCdmWithLicenseAfterStart) { - base::RepeatingClosure verify_task = base::BindRepeating( - &VerifyPlay, base::Unretained(pipeline_helper_.get())); - pipeline_helper_->SetPipelineStartExpectations(); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::Start, - base::Unretained(pipeline_helper_.get()), - std::move(verify_task))); - - task_environment_.RunUntilIdle(); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::SetCdmLicenseInstalled, - base::Unretained(pipeline_helper_.get()))); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::SetCdm, - base::Unretained(pipeline_helper_.get()))); - pipeline_helper_->Run(); -} - -// Start the pipeline, set a CDM, and then install the license. -TEST_F(EncryptedAVPipelineImplTest, SetCdmAndInstallLicenseAfterStart) { - base::RepeatingClosure verify_task = base::BindRepeating( - &VerifyPlay, base::Unretained(pipeline_helper_.get())); - pipeline_helper_->SetPipelineStartExpectations(); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::Start, - base::Unretained(pipeline_helper_.get()), - std::move(verify_task))); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::SetCdm, - base::Unretained(pipeline_helper_.get()))); - - task_environment_.RunUntilIdle(); - task_environment_.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, base::BindOnce(&PipelineHelper::SetCdmLicenseInstalled, - base::Unretained(pipeline_helper_.get()))); - pipeline_helper_->Run(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/av_pipeline_client.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_client.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/av_pipeline_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/av_pipeline_client.h" - -namespace chromecast { -namespace media { - -AvPipelineClient::AvPipelineClient() { -} - -AvPipelineClient::AvPipelineClient(AvPipelineClient&& other) = default; -AvPipelineClient& AvPipelineClient::operator=(AvPipelineClient&& other) = - default; - -AvPipelineClient::~AvPipelineClient() { -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/av_pipeline_client.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_client.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/av_pipeline_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_AV_PIPELINE_CLIENT_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_AV_PIPELINE_CLIENT_H_ - -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "media/base/pipeline_status.h" -#include "media/base/waiting.h" - -namespace chromecast { -namespace media { - -struct AvPipelineClient { - typedef base::RepeatingCallback< - void(base::TimeDelta, base::TimeDelta, base::TimeTicks)> - TimeUpdateCB; - - AvPipelineClient(); - AvPipelineClient(AvPipelineClient&& other); - AvPipelineClient(const AvPipelineClient& other) = delete; - AvPipelineClient& operator=(AvPipelineClient&& other); - AvPipelineClient& operator=(const AvPipelineClient& other) = delete; - ~AvPipelineClient(); - - // Waiting status notification. - ::media::WaitingCB waiting_cb; - - // End of stream notification. - base::RepeatingClosure eos_cb; - - // Asynchronous playback error notification. - ::media::PipelineStatusCB playback_error_cb; - - // Callback used to report the playback statistics. - ::media::StatisticsCB statistics_cb; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_AV_PIPELINE_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/av_pipeline_impl.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/av_pipeline_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,431 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/av_pipeline_impl.h" - -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/base/decrypt_context_impl.h" -#include "chromecast/media/cdm/cast_cdm_context.h" -#include "chromecast/media/cma/base/buffering_frame_provider.h" -#include "chromecast/media/cma/base/buffering_state.h" -#include "chromecast/media/cma/base/coded_frame_provider.h" -#include "chromecast/media/cma/pipeline/cdm_decryptor.h" -#include "chromecast/media/cma/pipeline/decrypt_util.h" -#include "chromecast/public/media/cast_decrypt_config.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/decrypt_config.h" -#include "media/base/timestamp_constants.h" - -namespace chromecast { -namespace media { - -AvPipelineImpl::AvPipelineImpl(CmaBackend::Decoder* decoder, - AvPipelineClient client) - : bytes_decoded_since_last_update_(0), - decoder_(decoder), - client_(std::move(client)), - state_(kUninitialized), - buffered_time_(::media::kNoTimestamp), - playable_buffered_time_(::media::kNoTimestamp), - enable_feeding_(false), - pending_read_(false), - cast_cdm_context_(nullptr), - weak_factory_(this), - decrypt_weak_factory_(this) { - DCHECK(decoder_); - decoder_->SetDelegate(this); - weak_this_ = weak_factory_.GetWeakPtr(); - thread_checker_.DetachFromThread(); -} - -AvPipelineImpl::~AvPipelineImpl() { - DCHECK(thread_checker_.CalledOnValidThread()); -} - -void AvPipelineImpl::SetCodedFrameProvider( - std::unique_ptr frame_provider, - size_t max_buffer_size, - size_t max_frame_size) { - DCHECK_EQ(state_, kUninitialized); - DCHECK(frame_provider); - - // Wrap the incoming frame provider to add some buffering capabilities. - frame_provider_.reset(new BufferingFrameProvider( - std::move(frame_provider), max_buffer_size, max_frame_size, - base::BindRepeating(&AvPipelineImpl::OnDataBuffered, weak_this_))); -} - -bool AvPipelineImpl::StartPlayingFrom( - base::TimeDelta time, - const scoped_refptr& buffering_state) { - LOG(INFO) << __FUNCTION__ << " t0=" << time.InMilliseconds(); - DCHECK(thread_checker_.CalledOnValidThread()); - - // Reset the pipeline statistics. - previous_stats_ = ::media::PipelineStatistics(); - - if (state_ == kError) { - LOG(INFO) << __FUNCTION__ << " called while in error state"; - return false; - } - DCHECK_EQ(state_, kFlushed); - - // Buffering related initialization. - DCHECK(frame_provider_); - buffering_state_ = buffering_state; - if (buffering_state_.get()) - buffering_state_->SetMediaTime(time); - - // Discard any previously pushed buffer and start feeding the pipeline. - pushed_buffer_ = nullptr; - enable_feeding_ = true; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&AvPipelineImpl::FetchBuffer, weak_this_)); - - set_state(kPlaying); - return true; -} - -void AvPipelineImpl::Flush(base::OnceClosure flush_cb) { - LOG(INFO) << __FUNCTION__; - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(flush_cb_.is_null()); - - if (state_ == kError) { - LOG(INFO) << __FUNCTION__ << " called while in error state"; - return; - } - DCHECK_EQ(state_, kPlaying); - set_state(kFlushing); - - flush_cb_ = std::move(flush_cb); - // Stop feeding the pipeline. - // Do not invalidate |pushed_buffer_| here since the backend may still be - // using it. Invalidate it in StartPlayingFrom on the assumption that - // the backend will be stopped after this function returns. - enable_feeding_ = false; - // Remove any pending buffer. - pending_buffer_ = nullptr; - // Remove any frames left in the frame provider. - pending_read_ = false; - buffered_time_ = ::media::kNoTimestamp; - playable_buffered_time_ = ::media::kNoTimestamp; - non_playable_frames_.clear(); - - // Drop any pending asynchronous decryption, so any pending - // OnBufferDecrypted() callback will not be called. StartPlayingFrom() sets - // enable_feeding_ back to true, so if a pending decryption callback from - // before Stop() is allowed to complete after StartPlayingFrom() is called - // again, it will think everything is fine and try to push a buffer, resulting - // in a double push. - decrypt_weak_factory_.InvalidateWeakPtrs(); - - ready_buffers_ = {}; - - // Reset |decryptor_| to flush buffered frames in |decryptor_|. - decryptor_.reset(); - - frame_provider_->Flush( - base::BindOnce(&AvPipelineImpl::OnFlushDone, weak_this_)); -} - -void AvPipelineImpl::OnFlushDone() { - LOG(INFO) << __FUNCTION__; - DCHECK(thread_checker_.CalledOnValidThread()); - if (state_ == kError) { - // Flush callback is reset on error. - DCHECK(flush_cb_.is_null()); - return; - } - DCHECK_EQ(state_, kFlushing); - set_state(kFlushed); - std::move(flush_cb_).Run(); -} - -void AvPipelineImpl::SetCdm(CastCdmContext* cast_cdm_context) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(cast_cdm_context); - - cast_cdm_context_ = cast_cdm_context; - event_cb_registration_ = cast_cdm_context_->RegisterEventCB( - base::BindRepeating(&AvPipelineImpl::OnCdmStateChanged, weak_this_)); - - // We could be waiting for CDM to provide key (see b/29564232). - OnCdmStateChanged(::media::CdmContext::Event::kHasAdditionalUsableKey); -} - -void AvPipelineImpl::FetchBuffer() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (!enable_feeding_) - return; - - DCHECK(!pending_read_ && !pending_buffer_); - - pending_read_ = true; - frame_provider_->Read( - base::BindOnce(&AvPipelineImpl::OnNewFrame, weak_this_)); -} - -void AvPipelineImpl::OnNewFrame( - const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) { - DCHECK(thread_checker_.CalledOnValidThread()); - pending_read_ = false; - - if (!enable_feeding_) - return; - - if (audio_config.IsValidConfig() || video_config.IsValidConfig()) - OnUpdateConfig(buffer->stream_id(), audio_config, video_config); - - pending_buffer_ = buffer; - ProcessPendingBuffer(); -} - -void AvPipelineImpl::ProcessPendingBuffer() { - if (!enable_feeding_) - return; - - DCHECK(!pushed_buffer_); - - // Break the feeding loop when the end of stream is reached. - if (pending_buffer_->end_of_stream()) { - LOG(INFO) << __FUNCTION__ << ": EOS reached, stopped feeding"; - enable_feeding_ = false; - } - - if (!pending_buffer_->end_of_stream() && - pending_buffer_->decrypt_config()) { - // Verify that CDM has the key ID. - // Should not send the frame if the key ID is not available yet. - std::string key_id(pending_buffer_->decrypt_config()->key_id()); - if (!cast_cdm_context_) { - LOG(INFO) << "No CDM for frame: pts=" << pending_buffer_->timestamp(); - return; - } - - std::unique_ptr decrypt_context = - cast_cdm_context_->GetDecryptContext( - key_id, GetEncryptionScheme(pending_buffer_->stream_id())); - if (!decrypt_context) { - LOG(INFO) << "frame(pts=" << pending_buffer_->timestamp() - << "): waiting for key id " << base::HexEncode(key_id); - if (!client_.waiting_cb.is_null()) - client_.waiting_cb.Run(::media::WaitingReason::kNoDecryptionKey); - return; - } - - DCHECK_NE(decrypt_context->GetKeySystem(), KEY_SYSTEM_NONE); - - if (!decryptor_) { - decryptor_ = CreateStreamDecryptor(decrypt_context->GetKeySystem()); - DCHECK(decryptor_); - decryptor_->Init(base::BindRepeating(&AvPipelineImpl::OnBufferDecrypted, - decrypt_weak_factory_.GetWeakPtr())); - } - - pending_buffer_->set_decrypt_context(std::move(decrypt_context)); - } - - if (decryptor_) { - decryptor_->Decrypt(std::move(pending_buffer_)); - return; - } - - DCHECK(ready_buffers_.empty()); - PushReadyBuffer(std::move(pending_buffer_)); -} - -void AvPipelineImpl::PushAllReadyBuffers() { - if (state_ != kPlaying) - return; - - DCHECK(!ready_buffers_.empty()); - - scoped_refptr ready_buffer = - std::move(ready_buffers_.front()); - ready_buffers_.pop(); - - PushReadyBuffer(std::move(ready_buffer)); -} - -void AvPipelineImpl::PushReadyBuffer(scoped_refptr buffer) { - DCHECK(!pushed_buffer_); - - if (!buffer->end_of_stream() && buffering_state_.get()) { - base::TimeDelta timestamp = base::Microseconds(buffer->timestamp()); - if (timestamp != ::media::kNoTimestamp) - buffering_state_->SetMaxRenderingTime(timestamp); - } - - pushed_buffer_ = std::move(buffer); - - CmaBackend::BufferStatus status = decoder_->PushBuffer(pushed_buffer_); - - if (status != CmaBackend::BufferStatus::kBufferPending) - OnPushBufferComplete(status); -} - -void AvPipelineImpl::OnBufferDecrypted(bool success, - StreamDecryptor::BufferQueue buffers) { - DCHECK(thread_checker_.CalledOnValidThread()); - - if (!success) { - OnDecoderError(); - return; - } - - // Decryptor needs more data. - if (buffers.empty()) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&AvPipelineImpl::FetchBuffer, weak_this_)); - return; - } - - ready_buffers_ = std::move(buffers); - PushAllReadyBuffers(); -} - -void AvPipelineImpl::OnPushBufferComplete(BufferStatus status) { - DCHECK(thread_checker_.CalledOnValidThread()); - - pushed_buffer_ = nullptr; - if (status == CmaBackend::BufferStatus::kBufferFailed) { - LOG(WARNING) << "AvPipelineImpl: PushFrame failed"; - OnDecoderError(); - return; - } - - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - ready_buffers_.empty() - ? base::BindOnce(&AvPipelineImpl::FetchBuffer, weak_this_) - : base::BindOnce(&AvPipelineImpl::PushAllReadyBuffers, weak_this_)); -} - -void AvPipelineImpl::OnEndOfStream() { - if (!client_.eos_cb.is_null()) - client_.eos_cb.Run(); -} - -void AvPipelineImpl::OnDecoderError() { - enable_feeding_ = false; - state_ = kError; - - if (!client_.playback_error_cb.is_null()) - client_.playback_error_cb.Run(::media::PIPELINE_ERROR_COULD_NOT_RENDER); - - if (!flush_cb_.is_null()) - std::move(flush_cb_).Run(); -} - -void AvPipelineImpl::OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) { - LOG(INFO) << __FUNCTION__ << " key_status= " << key_status - << " system_code=" << system_code; - DCHECK(cast_cdm_context_); - cast_cdm_context_->SetKeyStatus(key_id, key_status, system_code); -} - -void AvPipelineImpl::OnVideoResolutionChanged(const Size& size) { - // Ignored here; VideoPipelineImpl overrides this method. -} - -void AvPipelineImpl::OnCdmStateChanged(::media::CdmContext::Event event) { - DCHECK(thread_checker_.CalledOnValidThread()); - - if (event != ::media::CdmContext::Event::kHasAdditionalUsableKey) - return; - - // Update the buffering state if needed. - if (buffering_state_.get()) - UpdatePlayableFrames(); - - // Process the pending buffer in case the CDM now has the frame key id. - if (pending_buffer_) - ProcessPendingBuffer(); -} - -void AvPipelineImpl::OnDataBuffered( - const scoped_refptr& buffer, - bool is_at_max_capacity) { - DCHECK(thread_checker_.CalledOnValidThread()); - - if (!buffering_state_.get()) - return; - - if (!buffer->end_of_stream() && - (buffered_time_ == ::media::kNoTimestamp || - buffered_time_ < base::Microseconds(buffer->timestamp()))) { - buffered_time_ = base::Microseconds(buffer->timestamp()); - } - - if (is_at_max_capacity) - buffering_state_->NotifyMaxCapacity(buffered_time_); - - // No need to update the list of playable frames, - // if we are already blocking on a frame. - bool update_playable_frames = non_playable_frames_.empty(); - non_playable_frames_.push_back(buffer); - if (update_playable_frames) - UpdatePlayableFrames(); -} - -void AvPipelineImpl::UpdatePlayableFrames() { - while (!non_playable_frames_.empty()) { - const scoped_refptr& non_playable_frame = - non_playable_frames_.front(); - - if (non_playable_frame->end_of_stream()) { - buffering_state_->NotifyEos(); - } else { - const CastDecryptConfig* decrypt_config = - non_playable_frame->decrypt_config(); - if (decrypt_config && - !(cast_cdm_context_ && - cast_cdm_context_ - ->GetDecryptContext( - decrypt_config->key_id(), - GetEncryptionScheme(non_playable_frame->stream_id())) - .get())) { - // The frame is still not playable. All the following are thus not - // playable. - break; - } - - if (playable_buffered_time_ == ::media::kNoTimestamp || - playable_buffered_time_ < - base::Microseconds(non_playable_frame->timestamp())) { - playable_buffered_time_ = - base::Microseconds(non_playable_frame->timestamp()); - buffering_state_->SetBufferedTime(playable_buffered_time_); - } - } - - // The frame is playable: remove it from the list of non playable frames. - non_playable_frames_.pop_front(); - } -} - -std::unique_ptr AvPipelineImpl::CreateStreamDecryptor( - CastKeySystem key_system) { - if (key_system == KEY_SYSTEM_CLEAR_KEY) { - // Clear Key only supports clear output. - return std::make_unique(true /* clear_buffer_needed */); - } - - return CreateDecryptor(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/av_pipeline_impl.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/av_pipeline_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/av_pipeline_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,206 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_AV_PIPELINE_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_AV_PIPELINE_IMPL_H_ - -#include -#include - -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/cma/pipeline/av_pipeline_client.h" -#include "chromecast/media/cma/pipeline/stream_decryptor.h" -#include "chromecast/public/media/cast_decrypt_config.h" -#include "chromecast/public/media/stream_id.h" -#include "media/base/callback_registry.h" -#include "media/base/cdm_context.h" -#include "media/base/pipeline_status.h" - -namespace media { -class AudioDecoderConfig; -class VideoDecoderConfig; -} - -namespace chromecast { -namespace media { -class CastCdmContext; -class BufferingFrameProvider; -class BufferingState; -class CodedFrameProvider; -class DecoderBufferBase; - -class AvPipelineImpl : CmaBackend::Decoder::Delegate { - public: - AvPipelineImpl(CmaBackend::Decoder* decoder, AvPipelineClient client); - - AvPipelineImpl(const AvPipelineImpl&) = delete; - AvPipelineImpl& operator=(const AvPipelineImpl&) = delete; - - ~AvPipelineImpl() override; - - void SetCdm(CastCdmContext* cast_cdm_context); - - // Setup the pipeline and ensure samples are available for the given media - // time, then start rendering samples. - bool StartPlayingFrom(base::TimeDelta time, - const scoped_refptr& buffering_state); - void Flush(base::OnceClosure flush_cb); - - virtual void UpdateStatistics() = 0; - - int bytes_decoded_since_last_update() const { - return bytes_decoded_since_last_update_; - } - - protected: - // Pipeline states. - enum State { - kUninitialized, - kPlaying, - kFlushing, - kFlushed, - kError, - }; - - State state() const { return state_; } - void set_state(State state) { state_ = state; } - const AvPipelineClient& client() const { return client_; } - CastCdmContext* cdm_context() const { return cast_cdm_context_; } - - virtual void OnUpdateConfig( - StreamId id, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) = 0; - virtual EncryptionScheme GetEncryptionScheme(StreamId id) const = 0; - - // Create a decoder for decrypt and decode. - virtual std::unique_ptr CreateDecryptor() = 0; - - // Setting the frame provider must be done in the |kUninitialized| state. - void SetCodedFrameProvider(std::unique_ptr frame_provider, - size_t max_buffer_size, - size_t max_frame_size); - - ::media::PipelineStatistics previous_stats_; - int bytes_decoded_since_last_update_; - - private: - void OnFlushDone(); - - // CmaBackend::Decoder::Delegate implementation: - void OnPushBufferComplete(BufferStatus status) override; - void OnEndOfStream() override; - void OnDecoderError() override; - void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override; - void OnVideoResolutionChanged(const Size& size) override; - - void OnBufferDecrypted(bool success, StreamDecryptor::BufferQueue buffers); - - // Feed the pipeline, getting the frames from |frame_provider_|. - void FetchBuffer(); - - // Callback invoked when receiving a new frame from |frame_provider_|. - void OnNewFrame(const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config); - - // Process a pending buffer. - void ProcessPendingBuffer(); - void DoPushBufferCompleteTask(CmaBackend::BufferStatus status); - - // Pushes all the ready buffers to decoder. - void PushAllReadyBuffers(); - - // Pushes one ready buffer to decoder. - void PushReadyBuffer(scoped_refptr buffer); - - // Callbacks when CastCdm updated its state. - void OnCdmStateChanged(::media::CdmContext::Event event); - - // Callback invoked when a media buffer has been buffered by |frame_provider_| - // which is a BufferingFrameProvider. - void OnDataBuffered(const scoped_refptr& buffer, - bool is_at_max_capacity); - void UpdatePlayableFrames(); - - std::unique_ptr CreateStreamDecryptor( - CastKeySystem key_system); - - base::ThreadChecker thread_checker_; - - CmaBackend::Decoder* const decoder_; - AvPipelineClient client_; - - // Callback provided to Flush(). - base::OnceClosure flush_cb_; - - // AV pipeline state. - State state_; - - // Buffering state. - // Can be NULL if there is no buffering strategy. - scoped_refptr buffering_state_; - - // |buffered_time_| is the maximum timestamp of buffered frames. - // |playable_buffered_time_| is the maximum timestamp of buffered and - // playable frames (i.e. the key id is available for those frames). - base::TimeDelta buffered_time_; - base::TimeDelta playable_buffered_time_; - - // List of frames buffered but not playable right away due to a missing - // key id. - std::list > non_playable_frames_; - - // Buffer provider. - std::unique_ptr frame_provider_; - - // Indicate whether the frame fetching process is active. - bool enable_feeding_; - - // Indicate whether there is a pending buffer read. - bool pending_read_; - - // Pending buffer (not pushed to decryptor yet) - scoped_refptr pending_buffer_; - - // Buffers which are ready to be pushed to decoder. - StreamDecryptor::BufferQueue ready_buffers_; - - // Buffer that has been pushed to the device but not processed yet. - scoped_refptr pushed_buffer_; - - // CdmContext, if available. - CastCdmContext* cast_cdm_context_; - - // To keep the CdmContext event callback registered. - std::unique_ptr<::media::CallbackRegistration> event_cb_registration_; - - // Decryptor to get clear buffers. All the buffers (clear or encrypted) will - // be pushed to |decryptor_| before being pushed to |decoder_|. |decryptor_| - // can do nothing if the media backend is able to handle encrypted buffer. - std::unique_ptr decryptor_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; - // Special weak factory used for asynchronous decryption. This allows us to - // cancel pending asynchronous decryption (by invalidating this factory's weak - // ptrs) without affecting other bound callbacks. - base::WeakPtrFactory decrypt_weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_AV_PIPELINE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/backend_decryptor.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/backend_decryptor.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/backend_decryptor.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/backend_decryptor.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/backend_decryptor.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/cma/pipeline/decrypt_util.h" - -namespace chromecast { -namespace media { - -BackendDecryptor::BackendDecryptor(EncryptionScheme scheme) - : decrypt_success_(true), - wait_eos_(false), - task_runner_(new TaskRunnerImpl) { - DCHECK(MediaPipelineBackend::CreateAudioDecryptor); - - task_runner_ = std::make_unique(); - decryptor_ = base::WrapUnique( - MediaPipelineBackend::CreateAudioDecryptor(scheme, task_runner_.get())); - - DCHECK(decryptor_); - decryptor_->SetDelegate(this); -} - -BackendDecryptor::~BackendDecryptor() = default; - -void BackendDecryptor::Init(const DecryptCB& decrypt_cb) { - DCHECK(!decrypt_cb_); - decrypt_cb_ = decrypt_cb; -} - -void BackendDecryptor::Decrypt(scoped_refptr buffer) { - DCHECK(!wait_eos_); - - // Push both clear and encrypted buffers to backend, so that |decryptor_| - // won't be blocked if there are not enough encrypted buffers. EOS buffer is - // also needed so that the last buffer can be flushed. - pending_buffers_.push(buffer); - - if (buffer->end_of_stream()) - wait_eos_ = true; - - MediaPipelineBackend::BufferStatus status = decryptor_->PushBufferForDecrypt( - buffer.get(), - buffer->end_of_stream() ? nullptr : buffer->writable_data()); - - if (status != MediaPipelineBackend::kBufferPending) - OnPushBufferForDecryptComplete(status); -} - -void BackendDecryptor::OnPushBufferForDecryptComplete( - MediaPipelineBackend::BufferStatus status) { - // If the pushed buffer is EOS, the callback should be called when all the - // buffers are decrypted. - if (wait_eos_) - return; - - DCHECK(decrypt_cb_); - decrypt_cb_.Run( - decrypt_success_ && status == MediaPipelineBackend::kBufferSuccess, - std::move(ready_buffers_)); -} - -void BackendDecryptor::OnDecryptComplete(bool success) { - DCHECK(!pending_buffers_.empty()); - - // Cache the success value and return it in OnPushBufferForDecryptComplete. - decrypt_success_ &= success; - - scoped_refptr buffer = std::move(pending_buffers_.front()); - pending_buffers_.pop(); - - ready_buffers_.push(buffer->end_of_stream() || !buffer->decrypt_config() - ? buffer - : base::MakeRefCounted(buffer)); - - if (wait_eos_ && buffer->end_of_stream()) { - // Last frame, all the buffers should be decrypted. - DCHECK(pending_buffers_.empty()); - DCHECK(decrypt_cb_); - LOG(INFO) << "Return all the ready buffers, size = " - << ready_buffers_.size(); - decrypt_cb_.Run(decrypt_success_, std::move(ready_buffers_)); - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/backend_decryptor.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/backend_decryptor.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/backend_decryptor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/backend_decryptor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_BACKEND_DECRYPTOR_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_BACKEND_DECRYPTOR_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/pipeline/stream_decryptor.h" -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -class TaskRunnerImpl; - -namespace media { - -class BackendDecryptor : public StreamDecryptor, - MediaPipelineBackend::AudioDecryptor::Delegate { - public: - explicit BackendDecryptor(EncryptionScheme scheme); - - BackendDecryptor(const BackendDecryptor&) = delete; - BackendDecryptor& operator=(const BackendDecryptor&) = delete; - - ~BackendDecryptor() override; - - // StreamDecryptor implementation: - void Init(const DecryptCB& decrypt_cb) override; - void Decrypt(scoped_refptr buffer) override; - - private: - // MediaPipelineBackend::AudioDecryptor::Delegate implementation: - void OnPushBufferForDecryptComplete( - MediaPipelineBackend::BufferStatus status) override; - void OnDecryptComplete(bool success) override; - - // Pending buffers for decrypt. - BufferQueue pending_buffers_; - - // Buffers that are ready to return to caller. - BufferQueue ready_buffers_; - bool decrypt_success_; - bool wait_eos_; - - // |task_runner_| should have a longer life than |decryptor_|. - std::unique_ptr task_runner_; - std::unique_ptr decryptor_; - - DecryptCB decrypt_cb_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_BACKEND_DECRYPTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/cdm_decryptor.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/cdm_decryptor.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/cdm_decryptor.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/cdm_decryptor.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/cdm_decryptor.h" - -#include "base/functional/bind.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/base/decrypt_context_impl.h" -#include "chromecast/media/cma/pipeline/decrypt_util.h" - -namespace chromecast { -namespace media { - -CdmDecryptor::CdmDecryptor(bool clear_buffer_needed) - : clear_buffer_needed_(clear_buffer_needed), weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); -} - -CdmDecryptor::~CdmDecryptor() = default; - -void CdmDecryptor::Init(const DecryptCB& decrypt_cb) { - DCHECK(!decrypt_cb_); - decrypt_cb_ = decrypt_cb; -} - -void CdmDecryptor::Decrypt(scoped_refptr buffer) { - if (buffer->end_of_stream() || !buffer->decrypt_config()) { - OnResult(std::move(buffer), true); - return; - } - - DecryptContextImpl* decrypt_context = - static_cast(buffer->decrypt_context()); - DCHECK(decrypt_context); - - DecryptContextImpl::OutputType output_type = decrypt_context->GetOutputType(); - if (output_type == DecryptContextImpl::OutputType::kClearRequired || - (clear_buffer_needed_ && - output_type == DecryptContextImpl::OutputType::kClearAllowed)) { - DecryptDecoderBuffer(std::move(buffer), decrypt_context, - base::BindOnce(&CdmDecryptor::OnResult, weak_this_)); - return; - } - - // Media pipeline backend will handle decryption. - OnResult(std::move(buffer), true); -} - -void CdmDecryptor::OnResult(scoped_refptr buffer, - bool success) { - BufferQueue ready_buffers; - ready_buffers.push(buffer); - - DCHECK(decrypt_cb_); - decrypt_cb_.Run(success, std::move(ready_buffers)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/cdm_decryptor.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/cdm_decryptor.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/cdm_decryptor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/cdm_decryptor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_CDM_DECRYPTOR_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_CDM_DECRYPTOR_H_ - -#include "base/memory/weak_ptr.h" -#include "chromecast/media/cma/pipeline/stream_decryptor.h" - -namespace chromecast { -namespace media { - -// StreamDecryptor implemented with CDM decrypt APIs. -class CdmDecryptor : public StreamDecryptor { - public: - explicit CdmDecryptor(bool clear_buffer_needed); - - CdmDecryptor(const CdmDecryptor&) = delete; - CdmDecryptor& operator=(const CdmDecryptor&) = delete; - - ~CdmDecryptor() override; - - // StreamDecryptor implementation: - void Init(const DecryptCB& decrypt_cb) override; - void Decrypt(scoped_refptr buffer) override; - - private: - void OnResult(scoped_refptr buffer, bool success); - - DecryptCB decrypt_cb_; - - const bool clear_buffer_needed_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_CDM_DECRYPTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/decrypt_util.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/decrypt_util.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/decrypt_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/decrypt_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/decrypt_util.h" - -#include -#include - -#include - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "chromecast/media/base/decrypt_context_impl.h" -#include "chromecast/public/media/cast_decrypt_config.h" -#include "media/base/decoder_buffer.h" - -namespace chromecast { -namespace media { -namespace { -void OnBufferDecrypted(scoped_refptr buffer, - BufferDecryptedCB buffer_decrypted_cb, - bool success) { - scoped_refptr out_buffer = - success ? base::MakeRefCounted(buffer) : buffer; - std::move(buffer_decrypted_cb).Run(std::move(out_buffer), success); -} -} // namespace - -DecoderBufferClear::DecoderBufferClear(scoped_refptr buffer) - : buffer_(buffer) {} - -DecoderBufferClear::~DecoderBufferClear() {} - -StreamId DecoderBufferClear::stream_id() const { - return buffer_->stream_id(); -} - -int64_t DecoderBufferClear::timestamp() const { - return buffer_->timestamp(); -} - -void DecoderBufferClear::set_timestamp(base::TimeDelta timestamp) { - buffer_->set_timestamp(timestamp); -} - -const uint8_t* DecoderBufferClear::data() const { - return buffer_->data(); -} - -uint8_t* DecoderBufferClear::writable_data() const { - return buffer_->writable_data(); -} - -size_t DecoderBufferClear::data_size() const { - return buffer_->data_size(); -} - -const CastDecryptConfig* DecoderBufferClear::decrypt_config() const { - // Buffer is clear so no decryption info. - return nullptr; -} - -bool DecoderBufferClear::end_of_stream() const { - return buffer_->end_of_stream(); -} - -bool DecoderBufferClear::is_key_frame() const { - return buffer_->is_key_frame(); -} - -void DecryptDecoderBuffer(scoped_refptr buffer, - DecryptContextImpl* decrypt_ctxt, - BufferDecryptedCB buffer_decrypted_cb) { - decrypt_ctxt->DecryptAsync(buffer.get(), buffer->writable_data(), - 0 /* data_offset */, true /* clear_output */, - base::BindOnce(&OnBufferDecrypted, buffer, - std::move(buffer_decrypted_cb))); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/decrypt_util.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/decrypt_util.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/decrypt_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/decrypt_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_DECRYPT_UTIL_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_DECRYPT_UTIL_H_ - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/decoder_buffer_base.h" - -namespace chromecast { -namespace media { - -class CastDecryptConfig; -class DecryptContextImpl; - -class DecoderBufferClear : public DecoderBufferBase { - public: - explicit DecoderBufferClear(scoped_refptr buffer); - - DecoderBufferClear(const DecoderBufferClear&) = delete; - DecoderBufferClear& operator=(const DecoderBufferClear&) = delete; - - // DecoderBufferBase implementation. - StreamId stream_id() const override; - int64_t timestamp() const override; - void set_timestamp(base::TimeDelta timestamp) override; - const uint8_t* data() const override; - uint8_t* writable_data() const override; - size_t data_size() const override; - const CastDecryptConfig* decrypt_config() const override; - bool end_of_stream() const override; - bool is_key_frame() const override; - - private: - ~DecoderBufferClear() override; - - const scoped_refptr buffer_; -}; - -using BufferDecryptedCB = - base::OnceCallback, bool)>; - -// Create a new buffer which corresponds to the clear version of |buffer|. -// Note: the memory area corresponding to the ES data of the new buffer -// is the same as the ES data of |buffer| (for efficiency). -// After the |buffer_decrypted_cb| is called, |buffer| is left in a inconsistent -// state in the sense it has some decryption info but the ES data is now in -// clear. -void DecryptDecoderBuffer(scoped_refptr buffer, - DecryptContextImpl* decrypt_ctxt, - BufferDecryptedCB buffer_decrypted_cb); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_DECRYPT_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/load_type.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/load_type.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/load_type.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/load_type.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_LOAD_TYPE_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_LOAD_TYPE_H_ - -namespace chromecast { -namespace media { - -enum LoadType { - kLoadTypeURL, - kLoadTypeMediaSource, - kLoadTypeMediaStream, - kLoadTypeCommunication, -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_LOAD_TYPE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_client.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_client.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/media_pipeline_client.h" - -namespace chromecast { -namespace media { - -MediaPipelineClient::MediaPipelineClient() { -} - -MediaPipelineClient::MediaPipelineClient(MediaPipelineClient&& other) = default; - -MediaPipelineClient& MediaPipelineClient::operator=( - MediaPipelineClient&& other) = default; - -MediaPipelineClient::~MediaPipelineClient() { -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_client.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_client.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_CLIENT_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_CLIENT_H_ - -#include "base/functional/callback.h" -#include "base/time/time.h" -#include "media/base/buffering_state.h" -#include "media/base/pipeline_status.h" - -namespace chromecast { -namespace media { - -struct MediaPipelineClient { - typedef base::RepeatingCallback< - void(base::TimeDelta, base::TimeDelta, base::TimeTicks)> - TimeUpdateCB; - - MediaPipelineClient(); - MediaPipelineClient(MediaPipelineClient&& other); - MediaPipelineClient(const MediaPipelineClient& other) = delete; - MediaPipelineClient& operator=(MediaPipelineClient&& other); - MediaPipelineClient& operator=(const MediaPipelineClient& other) = delete; - ~MediaPipelineClient(); - - // Callback used to report a playback error as a ::media::PipelineStatus. - ::media::PipelineStatusCallback error_cb; - - // Callback used to report the latest playback time, - // as well as the maximum time available for rendering. - TimeUpdateCB time_update_cb; - - // Callback used to report the buffering status. - ::media::BufferingStateCB buffering_state_cb; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_impl.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,592 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/media_pipeline_impl.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/default_tick_clock.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/cdm/cast_cdm_context.h" -#include "chromecast/media/cma/base/buffering_controller.h" -#include "chromecast/media/cma/base/buffering_state.h" -#include "chromecast/media/cma/base/coded_frame_provider.h" -#include "chromecast/media/cma/pipeline/audio_pipeline_impl.h" -#include "chromecast/media/cma/pipeline/cma_pipeline_buildflags.h" -#include "chromecast/media/cma/pipeline/media_pipeline_observer.h" -#include "chromecast/media/cma/pipeline/video_pipeline_impl.h" -#include "media/base/timestamp_constants.h" - -namespace chromecast { -namespace media { - -namespace { - -// Buffering parameters when load_type is kLoadTypeUrl. -constexpr base::TimeDelta kLowBufferThresholdURL(base::Milliseconds(2000)); -constexpr base::TimeDelta kHighBufferThresholdURL(base::Milliseconds(6000)); - -// Buffering parameters when load_type is kLoadTypeMediaSource. -constexpr base::TimeDelta kLowBufferThresholdMediaSource(base::Milliseconds(0)); -constexpr base::TimeDelta kHighBufferThresholdMediaSource( - base::Milliseconds(1000)); - -// Interval between two updates of the media time. -constexpr base::TimeDelta kTimeUpdateInterval(base::Milliseconds(250)); - -// Interval between two updates of the statistics is equal to: -// kTimeUpdateInterval * kStatisticsUpdatePeriod. -const int kStatisticsUpdatePeriod = 4; - -// Stall duration threshold that triggers a playback stall event. -constexpr int kPlaybackStallEventThresholdMs = 2500; - -void LogEstimatedBitrate(int decoded_bytes, - base::TimeDelta elapsed_time, - const char* tag, - const char* metric) { - int estimated_bitrate_in_kbps = - 8 * decoded_bytes / elapsed_time.InMilliseconds(); - - if (estimated_bitrate_in_kbps <= 0) - return; - - LOG(INFO) << "Estimated " << tag << " bitrate is " - << estimated_bitrate_in_kbps << " kbps"; - metrics::CastMetricsHelper* metrics_helper = - metrics::CastMetricsHelper::GetInstance(); - metrics_helper->RecordApplicationEventWithValue(metric, - estimated_bitrate_in_kbps); -} - -} // namespace - -struct MediaPipelineImpl::FlushTask { - bool audio_flushed; - bool video_flushed; - base::OnceClosure done_cb; -}; - -MediaPipelineImpl::MediaPipelineImpl() - : cdm_context_(nullptr), - backend_state_(BACKEND_STATE_UNINITIALIZED), - playback_rate_(0), - audio_decoder_(nullptr), - video_decoder_(nullptr), - pending_time_update_task_(false), - last_media_time_(::media::kNoTimestamp), - statistics_rolling_counter_(0), - audio_bytes_for_bitrate_estimation_(0), - video_bytes_for_bitrate_estimation_(0), - playback_stalled_(false), - playback_stalled_notification_sent_(false), - media_time_interpolator_(base::DefaultTickClock::GetInstance()), - weak_factory_(this) { - LOG(INFO) << __FUNCTION__; - weak_this_ = weak_factory_.GetWeakPtr(); - thread_checker_.DetachFromThread(); -} - -MediaPipelineImpl::~MediaPipelineImpl() { - LOG(INFO) << __FUNCTION__; - DCHECK(thread_checker_.CalledOnValidThread()); - - // TODO(b/67112414): Do something better than this. - MediaPipelineObserver::NotifyPipelineDestroyed(this); - - if (backend_state_ != BACKEND_STATE_UNINITIALIZED && - backend_state_ != BACKEND_STATE_INITIALIZED) - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( - "Cast.Platform.Ended"); -} - -void MediaPipelineImpl::Initialize( - LoadType load_type, - std::unique_ptr media_pipeline_backend, - bool is_buffering_enabled) { - LOG(INFO) << __FUNCTION__; - DCHECK(thread_checker_.CalledOnValidThread()); - media_pipeline_backend_ = std::move(media_pipeline_backend); - - if ((load_type == kLoadTypeURL || load_type == kLoadTypeMediaSource) && - is_buffering_enabled) { - base::TimeDelta low_threshold(kLowBufferThresholdURL); - base::TimeDelta high_threshold(kHighBufferThresholdURL); - if (load_type == kLoadTypeMediaSource) { - low_threshold = kLowBufferThresholdMediaSource; - high_threshold = kHighBufferThresholdMediaSource; - } - scoped_refptr buffering_config( - new BufferingConfig(low_threshold, high_threshold)); - buffering_controller_.reset(new BufferingController( - buffering_config, - base::BindRepeating(&MediaPipelineImpl::OnBufferingNotification, - weak_this_))); - } -} - -void MediaPipelineImpl::SetClient(MediaPipelineClient client) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!client.error_cb.is_null()); - DCHECK(!client.buffering_state_cb.is_null()); - client_ = std::move(client); -} - -void MediaPipelineImpl::SetCdm(const base::UnguessableToken* cdm_id) { - LOG(INFO) << __FUNCTION__ - << " cdm_id=" << ::media::CdmContext::CdmIdToString(cdm_id); - DCHECK(thread_checker_.CalledOnValidThread()); - NOTIMPLEMENTED(); - // TODO(gunsch): SetCdm(int) is not implemented. - // One possibility would be a GetCdmByIdCB that's passed in. -} - -void MediaPipelineImpl::SetCdm(CastCdmContext* cdm_context) { - LOG(INFO) << __FUNCTION__; - DCHECK(thread_checker_.CalledOnValidThread()); - cdm_context_ = cdm_context; - if (audio_pipeline_) - audio_pipeline_->SetCdm(cdm_context); - if (video_pipeline_) - video_pipeline_->SetCdm(cdm_context); -} - -::media::PipelineStatus MediaPipelineImpl::InitializeAudio( - const ::media::AudioDecoderConfig& config, - AvPipelineClient client, - std::unique_ptr frame_provider) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!audio_decoder_); - - audio_decoder_ = media_pipeline_backend_->CreateAudioDecoder(); - if (!audio_decoder_) { - return ::media::PIPELINE_ERROR_ABORT; - } - audio_pipeline_ = - std::make_unique(audio_decoder_, std::move(client)); - if (cdm_context_) - audio_pipeline_->SetCdm(cdm_context_); - ::media::PipelineStatus status = - audio_pipeline_->Initialize(config, std::move(frame_provider)); - - if (status.is_ok()) { - // TODO(b/67112414): Do something better than this. - MediaPipelineObserver::NotifyAudioPipelineInitialized(this, config); - } - - return status; -} - -::media::PipelineStatus MediaPipelineImpl::InitializeVideo( - const std::vector<::media::VideoDecoderConfig>& configs, - VideoPipelineClient client, - std::unique_ptr frame_provider) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!video_decoder_); - - video_decoder_ = media_pipeline_backend_->CreateVideoDecoder(); - if (!video_decoder_) { - return ::media::PIPELINE_ERROR_ABORT; - } - video_pipeline_.reset( - new VideoPipelineImpl(video_decoder_, std::move(client))); - if (cdm_context_) - video_pipeline_->SetCdm(cdm_context_); - return video_pipeline_->Initialize(configs, std::move(frame_provider)); -} - -void MediaPipelineImpl::StartPlayingFrom(base::TimeDelta time) { - LOG(INFO) << __FUNCTION__ << " t0=" << time.InMilliseconds(); - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(audio_pipeline_ || video_pipeline_); - DCHECK(!pending_flush_task_); - - // Lazy initialize. - if (backend_state_ == BACKEND_STATE_UNINITIALIZED) { - if (!media_pipeline_backend_->Initialize()) { - OnError(::media::PIPELINE_ERROR_ABORT); - return; - } - backend_state_ = BACKEND_STATE_INITIALIZED; - } - - // Start the backend. - if (!media_pipeline_backend_->Start(time.InMicroseconds())) { - OnError(::media::PIPELINE_ERROR_ABORT); - return; - } - backend_state_ = BACKEND_STATE_PLAYING; - ResetBitrateState(); - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( - "Cast.Platform.Playing"); - - // Enable time updates. - start_media_time_ = time; - last_media_time_ = ::media::kNoTimestamp; - statistics_rolling_counter_ = 0; - if (!pending_time_update_task_) { - pending_time_update_task_ = true; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&MediaPipelineImpl::UpdateMediaTime, weak_this_)); - } - - waiting_for_first_have_enough_data_ = true; - - media_time_interpolator_.SetBounds(time, time, base::TimeTicks::Now()); - media_time_interpolator_.StartInterpolating(); - - // Setup the audio and video pipeline for the new timeline. - if (audio_pipeline_) { - scoped_refptr buffering_state; - if (buffering_controller_) - buffering_state = buffering_controller_->AddStream("audio"); - if (!audio_pipeline_->StartPlayingFrom(time, buffering_state)) { - OnError(::media::PIPELINE_ERROR_ABORT); - return; - } - } - if (video_pipeline_) { - scoped_refptr buffering_state; - if (buffering_controller_) - buffering_state = buffering_controller_->AddStream("video"); - if (!video_pipeline_->StartPlayingFrom(time, buffering_state)) { - OnError(::media::PIPELINE_ERROR_ABORT); - return; - } - } -} - -void MediaPipelineImpl::Flush(base::OnceClosure flush_cb) { - LOG(INFO) << __FUNCTION__; - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK((backend_state_ == BACKEND_STATE_PLAYING) || - (backend_state_ == BACKEND_STATE_PAUSED)); - DCHECK(audio_pipeline_ || video_pipeline_); - DCHECK(!pending_flush_task_); - - media_time_interpolator_.StopInterpolating(); - - buffering_controller_->Reset(); - - // Flush both audio and video pipeline. This will flush the frame - // provider and stop feeding buffers to the backend. - // MediaPipelineImpl::OnFlushDone will stop the backend once flush completes. - pending_flush_task_.reset(new FlushTask); - pending_flush_task_->audio_flushed = !audio_pipeline_; - pending_flush_task_->video_flushed = !video_pipeline_; - pending_flush_task_->done_cb = std::move(flush_cb); - if (audio_pipeline_) { - audio_pipeline_->Flush( - base::BindOnce(&MediaPipelineImpl::OnFlushDone, weak_this_, true)); - } - if (video_pipeline_) { - video_pipeline_->Flush( - base::BindOnce(&MediaPipelineImpl::OnFlushDone, weak_this_, false)); - } -} - -void MediaPipelineImpl::SetPlaybackRate(double rate) { - LOG(INFO) << __FUNCTION__ << " rate=" << rate; - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK((backend_state_ == BACKEND_STATE_PLAYING) || - (backend_state_ == BACKEND_STATE_PAUSED)); - - playback_rate_ = rate; - if (buffering_controller_ && buffering_controller_->IsBuffering()) - return; - - if (rate != 0.0f) { - media_pipeline_backend_->SetPlaybackRate(rate); - media_time_interpolator_.SetPlaybackRate(rate); - if (backend_state_ == BACKEND_STATE_PAUSED) { - media_pipeline_backend_->Resume(); - backend_state_ = BACKEND_STATE_PLAYING; - ResetBitrateState(); - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( - "Cast.Platform.Playing"); - } - } else if (backend_state_ == BACKEND_STATE_PLAYING) { - media_pipeline_backend_->Pause(); - media_time_interpolator_.SetPlaybackRate(0.f); - backend_state_ = BACKEND_STATE_PAUSED; - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( - "Cast.Platform.Pause"); - } -} - -void MediaPipelineImpl::SetVolume(float volume) { - LOG(INFO) << __FUNCTION__ << " vol=" << volume; - DCHECK(thread_checker_.CalledOnValidThread()); - if (audio_pipeline_) - audio_pipeline_->SetVolume(volume); -} - -base::TimeDelta MediaPipelineImpl::GetMediaTime() const { - DCHECK(thread_checker_.CalledOnValidThread()); -#if BUILDFLAG(CMA_USE_ACCURATE_MEDIA_TIME) - base::TimeDelta time = - base::Microseconds(media_pipeline_backend_->GetCurrentPts()); -#else - base::TimeDelta time = last_media_time_; -#endif - return (time == ::media::kNoTimestamp ? start_media_time_ : time); -} - -bool MediaPipelineImpl::HasAudio() const { - DCHECK(thread_checker_.CalledOnValidThread()); - return audio_pipeline_ != nullptr; -} - -bool MediaPipelineImpl::HasVideo() const { - DCHECK(thread_checker_.CalledOnValidThread()); - return video_pipeline_ != nullptr; -} - -void MediaPipelineImpl::OnFlushDone(bool is_audio_stream) { - LOG(INFO) << __FUNCTION__ << " is_audio_stream=" << is_audio_stream; - DCHECK(pending_flush_task_); - - if (is_audio_stream) { - DCHECK(!pending_flush_task_->audio_flushed); - pending_flush_task_->audio_flushed = true; - } else { - DCHECK(!pending_flush_task_->video_flushed); - pending_flush_task_->video_flushed = true; - } - - if (pending_flush_task_->audio_flushed && - pending_flush_task_->video_flushed) { - // Stop the backend, so that the backend won't push their pending buffer, - // which may be invalidated later, to hardware. (b/25342604) - media_pipeline_backend_->Stop(); - backend_state_ = BACKEND_STATE_INITIALIZED; - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( - "Cast.Platform.Ended"); - - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, std::move(pending_flush_task_->done_cb)); - pending_flush_task_.reset(); - } -} - -void MediaPipelineImpl::OnBufferingNotification(bool is_buffering) { - LOG(INFO) << __FUNCTION__ << " is_buffering=" << is_buffering; - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK((backend_state_ == BACKEND_STATE_PLAYING) || - (backend_state_ == BACKEND_STATE_PAUSED)); - DCHECK(buffering_controller_); - DCHECK_EQ(is_buffering, buffering_controller_->IsBuffering()); - - if (waiting_for_first_have_enough_data_) { - waiting_for_first_have_enough_data_ = is_buffering; - } - - if (!waiting_for_first_have_enough_data_ && client_.buffering_state_cb) { - ::media::BufferingState state = is_buffering - ? ::media::BUFFERING_HAVE_NOTHING - : ::media::BUFFERING_HAVE_ENOUGH; - // Reports buffering state to WMPI. WMPI will change HTMLMediaElement ready - // state: - // HAVE_NOTHING -> HAVE_CURRENT_DATA - // HAVE_ENOUGH -> HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA - // DEMUXER_UNDERFLOW is the only possible reason. We pass encoded audio to - // the vendor-specific backend. Our buffering controller only reports a - // buffering state change based on based on the difference between the - // current playout PTS reported by the vendor backed and the most recent - // encoded buffer. - client_.buffering_state_cb.Run(state, ::media::DEMUXER_UNDERFLOW); - } - - if (is_buffering && (backend_state_ == BACKEND_STATE_PLAYING)) { - media_pipeline_backend_->Pause(); - media_time_interpolator_.SetPlaybackRate(0.f); - backend_state_ = BACKEND_STATE_PAUSED; - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( - "Cast.Platform.Pause"); - } else if (!is_buffering && (backend_state_ == BACKEND_STATE_PAUSED)) { - // Once we finish buffering, we need to honour the desired playback rate - // (rather than just resuming). This way, if playback was paused while - // buffering, it will remain paused rather than incorrectly resuming. - SetPlaybackRate(playback_rate_); - } -} - -void MediaPipelineImpl::CheckForPlaybackStall(base::TimeDelta media_time, - base::TimeTicks current_stc) { - DCHECK(media_time != ::media::kNoTimestamp); - - // A playback stall is defined as a scenario where the underlying media - // pipeline has unexpectedly stopped making forward progress. The pipeline is - // NOT stalled if: - // - // 1. Media time is progressing - // 2. The backend is paused - // 3. We are currently buffering (this is captured in a separate event) - if (media_time != last_media_time_ || - backend_state_ != BACKEND_STATE_PLAYING || - (buffering_controller_ && buffering_controller_->IsBuffering())) { - if (playback_stalled_) { - // Transition out of the stalled condition. - base::TimeDelta stall_duration = current_stc - playback_stalled_time_; - LOG(INFO) << "Transitioning out of stalled state. Stall duration was " - << stall_duration.InMilliseconds() << " ms"; - playback_stalled_ = false; - playback_stalled_notification_sent_ = false; - } - return; - } - - // Check to see if this is a new stall condition. - if (!playback_stalled_) { - playback_stalled_ = true; - playback_stalled_time_ = current_stc; - return; - } - - // If we are in an existing stall, check to see if we've been stalled for more - // than 2.5 s. If so, send a single notification of the stall event. - if (!playback_stalled_notification_sent_) { - base::TimeDelta current_stall_duration = - current_stc - playback_stalled_time_; - if (current_stall_duration.InMilliseconds() >= - kPlaybackStallEventThresholdMs) { - LOG(INFO) << "Playback stalled"; - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( - "Cast.Platform.PlaybackStall"); - playback_stalled_notification_sent_ = true; - } - return; - } -} - -void MediaPipelineImpl::UpdateMediaTime() { - pending_time_update_task_ = false; - if ((backend_state_ != BACKEND_STATE_PLAYING) && - (backend_state_ != BACKEND_STATE_PAUSED)) - return; - - if (statistics_rolling_counter_ == 0) { - if (audio_pipeline_) - audio_pipeline_->UpdateStatistics(); - if (video_pipeline_) - video_pipeline_->UpdateStatistics(); - - if (backend_state_ == BACKEND_STATE_PLAYING) { - base::TimeTicks current_time = base::TimeTicks::Now(); - if (audio_pipeline_) - audio_bytes_for_bitrate_estimation_ += - audio_pipeline_->bytes_decoded_since_last_update(); - if (video_pipeline_) - video_bytes_for_bitrate_estimation_ += - video_pipeline_->bytes_decoded_since_last_update(); - elapsed_time_delta_ += current_time - last_sample_time_; - if (elapsed_time_delta_.InMilliseconds() > 5000) { - if (audio_pipeline_) - LogEstimatedBitrate(audio_bytes_for_bitrate_estimation_, - elapsed_time_delta_, "audio", - "Cast.Platform.AudioBitrate"); - if (video_pipeline_) - LogEstimatedBitrate(video_bytes_for_bitrate_estimation_, - elapsed_time_delta_, "video", - "Cast.Platform.VideoBitrate"); - ResetBitrateState(); - } - last_sample_time_ = current_time; - } - } - - statistics_rolling_counter_ = - (statistics_rolling_counter_ + 1) % kStatisticsUpdatePeriod; - - // Wait until the first available timestamp returned from backend, which means - // the actual playback starts. Some of the rest of the logic, mainly media - // time interpolating, expects a valid timestamp as baseline. - base::TimeDelta media_time = - base::Microseconds(media_pipeline_backend_->GetCurrentPts()); - if (media_time == ::media::kNoTimestamp && - (last_media_time_ == ::media::kNoTimestamp || - !media_time_interpolator_.interpolating())) { - pending_time_update_task_ = true; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&MediaPipelineImpl::UpdateMediaTime, weak_this_), - kTimeUpdateInterval); - return; - } - - base::TimeTicks stc = base::TimeTicks::Now(); - - if (media_time == ::media::kNoTimestamp) { - DCHECK(media_time_interpolator_.interpolating()); - media_time = media_time_interpolator_.GetInterpolatedTime(); - - LOG(WARNING) << "Backend returns invalid timestamp. Estimated time is " - << media_time; - } else { - // It's safe to use kInfiniteDuration as upper bound. When pipeline - // rebuffers, time interpolator is also paused, in which case it returns - // the timestamp when pausing it. - media_time_interpolator_.SetBounds(media_time, ::media::kInfiniteDuration, - stc); - } - - CheckForPlaybackStall(media_time, stc); - - base::TimeDelta max_rendering_time = media_time; - if (buffering_controller_) { - buffering_controller_->SetMediaTime(media_time); - - // Receiving the same time twice in a row means playback isn't moving, - // so don't interpolate ahead. - if (media_time != last_media_time_) { - max_rendering_time = buffering_controller_->GetMaxRenderingTime(); - if (max_rendering_time == ::media::kNoTimestamp) - max_rendering_time = media_time; - - // Cap interpolation time to avoid interpolating too far ahead. - max_rendering_time = - std::min(max_rendering_time, media_time + 2 * kTimeUpdateInterval); - } - } - - last_media_time_ = media_time; - if (!client_.time_update_cb.is_null()) - client_.time_update_cb.Run(media_time, max_rendering_time, stc); - - pending_time_update_task_ = true; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&MediaPipelineImpl::UpdateMediaTime, weak_this_), - kTimeUpdateInterval); -} - -void MediaPipelineImpl::OnError(::media::PipelineStatus error) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(error != ::media::PIPELINE_OK) << "PIPELINE_OK is not an error!"; - - metrics::CastMetricsHelper::GetInstance()->RecordApplicationEventWithValue( - "Cast.Platform.Error", error.code()); - - if (!client_.error_cb.is_null()) - std::move(client_.error_cb).Run(error); -} - -void MediaPipelineImpl::ResetBitrateState() { - elapsed_time_delta_ = base::Seconds(0); - audio_bytes_for_bitrate_estimation_ = 0; - video_bytes_for_bitrate_estimation_ = 0; - last_sample_time_ = base::TimeTicks::Now(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_impl.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,143 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_IMPL_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "base/unguessable_token.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/cma/pipeline/load_type.h" -#include "chromecast/media/cma/pipeline/media_pipeline_client.h" -#include "media/base/time_delta_interpolator.h" - -namespace media { -class AudioDecoderConfig; -class VideoDecoderConfig; -} // namespace media - -namespace chromecast { -namespace media { -class AudioPipelineImpl; -class BufferingController; -class CastCdmContext; -class CodedFrameProvider; -class VideoPipelineImpl; -struct AvPipelineClient; -struct VideoPipelineClient; - -class MediaPipelineImpl { - public: - MediaPipelineImpl(); - - MediaPipelineImpl(const MediaPipelineImpl&) = delete; - MediaPipelineImpl& operator=(const MediaPipelineImpl&) = delete; - - ~MediaPipelineImpl(); - - // Initialize the media pipeline: the pipeline is configured based on - // |load_type|. - void Initialize(LoadType load_type, - std::unique_ptr media_pipeline_backend, - bool is_buffering_enabled); - - void SetClient(MediaPipelineClient client); - void SetCdm(const base::UnguessableToken* cdm_id); - - ::media::PipelineStatus InitializeAudio( - const ::media::AudioDecoderConfig& config, - AvPipelineClient client, - std::unique_ptr frame_provider); - ::media::PipelineStatus InitializeVideo( - const std::vector<::media::VideoDecoderConfig>& configs, - VideoPipelineClient client, - std::unique_ptr frame_provider); - void StartPlayingFrom(base::TimeDelta time); - void Flush(base::OnceClosure flush_cb); - void SetPlaybackRate(double playback_rate); - void SetVolume(float volume); - base::TimeDelta GetMediaTime() const; - bool HasAudio() const; - bool HasVideo() const; - - void SetCdm(CastCdmContext* cdm); - - private: - enum BackendState { - BACKEND_STATE_UNINITIALIZED, - BACKEND_STATE_INITIALIZED, - BACKEND_STATE_PLAYING, - BACKEND_STATE_PAUSED - }; - struct FlushTask; - void CheckForPlaybackStall(base::TimeDelta media_time, - base::TimeTicks current_stc); - - void OnFlushDone(bool is_audio_stream); - - // Invoked to notify about a change of buffering state. - void OnBufferingNotification(bool is_buffering); - - void UpdateMediaTime(); - void OnError(::media::PipelineStatus error); - void ResetBitrateState(); - - base::ThreadChecker thread_checker_; - MediaPipelineClient client_; - std::unique_ptr buffering_controller_; - CastCdmContext* cdm_context_; - - // Interface with the underlying hardware media pipeline. - BackendState backend_state_; - // Playback rate set by the upper layer. - // Cached here because CMA pipeline backend does not support rate == 0, - // which is emulated by pausing the backend. - float playback_rate_; - - // Since av pipeline still need to access device components in their - // destructor, it's important to delete them first. - std::unique_ptr media_pipeline_backend_; - CmaBackend::AudioDecoder* audio_decoder_; - CmaBackend::VideoDecoder* video_decoder_; - std::unique_ptr audio_pipeline_; - std::unique_ptr video_pipeline_; - std::unique_ptr pending_flush_task_; - - // The media time is retrieved at regular intervals. - bool pending_time_update_task_; - base::TimeDelta start_media_time_; - base::TimeDelta last_media_time_; - - // Used to make the statistics update period a multiplier of the time update - // period. - int statistics_rolling_counter_; - base::TimeTicks last_sample_time_; - base::TimeDelta elapsed_time_delta_; - int audio_bytes_for_bitrate_estimation_; - int video_bytes_for_bitrate_estimation_; - - // Playback stalled handling. - bool playback_stalled_; - base::TimeTicks playback_stalled_time_; - bool playback_stalled_notification_sent_; - - // It's used to estimate current media time when the timestamp returned by - // backend is invalid. - ::media::TimeDeltaInterpolator media_time_interpolator_; - - bool waiting_for_first_have_enough_data_ = true; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_observer.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_observer.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_observer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_observer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/media_pipeline_observer.h" - -#include - -#include "base/observer_list.h" - -namespace { -base::ObserverList::Unchecked - g_observers; -} // namespace - -namespace chromecast { -namespace media { - -// static -void MediaPipelineObserver::NotifyAudioPipelineInitialized( - MediaPipelineImpl* pipeline, - const ::media::AudioDecoderConfig& config) { - for (auto& observer : g_observers) { - observer.OnAudioPipelineInitialized(pipeline, config); - } -} - -// static -void MediaPipelineObserver::NotifyPipelineDestroyed( - MediaPipelineImpl* pipeline) { - for (auto& observer : g_observers) { - observer.OnPipelineDestroyed(pipeline); - } -} - -// static -void MediaPipelineObserver::AddObserver(MediaPipelineObserver* observer) { - g_observers.AddObserver(observer); -} - -// static -void MediaPipelineObserver::RemoveObserver(MediaPipelineObserver* observer) { - g_observers.RemoveObserver(observer); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_observer.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_observer.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/media_pipeline_observer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/media_pipeline_observer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_OBSERVER_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_OBSERVER_H_ - -namespace media { -class AudioDecoderConfig; -} // namespace media - -namespace chromecast { -namespace media { -class MediaPipelineImpl; - -// Don't use this -class MediaPipelineObserver { - private: - static void NotifyAudioPipelineInitialized( - MediaPipelineImpl* pipeline, - const ::media::AudioDecoderConfig& config); - static void NotifyPipelineDestroyed(MediaPipelineImpl* pipeline); - friend class MediaPipelineImpl; - - public: - virtual void OnAudioPipelineInitialized( - MediaPipelineImpl* pipeline, - const ::media::AudioDecoderConfig& config) = 0; - virtual void OnPipelineDestroyed(MediaPipelineImpl* pipeline) = 0; - - static void AddObserver(MediaPipelineObserver* observer); - static void RemoveObserver(MediaPipelineObserver* observer); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_MEDIA_PIPELINE_OBSERVER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/stream_decryptor.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/stream_decryptor.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/stream_decryptor.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/stream_decryptor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_STREAM_DECRYPTOR_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_STREAM_DECRYPTOR_H_ - -#include - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -// Decryptor to get clear buffers in asynchronous way. All the buffers are -// pushed into decryptor to keep the order of frames. -class StreamDecryptor { - public: - using BufferQueue = std::queue>; - - // Callback for Decrypt. The first argument is true iff Decrypt was - // successful. The second argument contains all the buffers that are ready to - // be pushed to decoder by the time the callback is called. - // If BufferQueue is empty, it means decryptor can't return ready buffer right - // now but it can accept more data. The buffer will be returned together with - // other buffers in a later call to Decrypt. Some of the implementations - // expect more data to keep themselves running. - // Once Decrypt is called with EOS buffer, implementation should decrypt all - // the buffers and return them in one callback. In other words, the total - // number of output buffers should be the same as number of input buffers. - // Caller won't call Decrypt again once EOS is pushed. - using DecryptCB = base::RepeatingCallback; - - virtual ~StreamDecryptor() = default; - - virtual void Init(const DecryptCB& decrypt_cb) = 0; - - // Decrypts |buffer| and returns the clear buffers in DecryptCB. Caller must - // not call Decrypt again until |decrypt_cb| is called. |decrypt_cb| will be - // called once for each call to Decrypt. - virtual void Decrypt(scoped_refptr buffer) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_STREAM_DECRYPTOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/video_pipeline_client.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_client.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/video_pipeline_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/video_pipeline_client.h" - -namespace chromecast { -namespace media { - -VideoPipelineClient::VideoPipelineClient() { -} - -VideoPipelineClient::VideoPipelineClient(VideoPipelineClient&& other) = default; -VideoPipelineClient& VideoPipelineClient::operator=( - VideoPipelineClient&& other) = default; - -VideoPipelineClient::~VideoPipelineClient() { -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/video_pipeline_client.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_client.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/video_pipeline_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_VIDEO_PIPELINE_CLIENT_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_VIDEO_PIPELINE_CLIENT_H_ - -#include "base/functional/callback.h" -#include "chromecast/media/cma/pipeline/av_pipeline_client.h" - -namespace gfx { -class Size; -} - -namespace chromecast { -namespace media { - -struct VideoPipelineClient { - typedef base::RepeatingCallback - NaturalSizeChangedCB; - - VideoPipelineClient(); - VideoPipelineClient(VideoPipelineClient&& other); - VideoPipelineClient(const VideoPipelineClient& other) = delete; - VideoPipelineClient& operator=(VideoPipelineClient&& other); - VideoPipelineClient& operator=(const VideoPipelineClient& other) = delete; - ~VideoPipelineClient(); - - // All the default callbacks. - AvPipelineClient av_pipeline_client; - - // Video resolution change notification. - NaturalSizeChangedCB natural_size_changed_cb; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_VIDEO_PIPELINE_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/video_pipeline_impl.cc chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_impl.cc --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/video_pipeline_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,160 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/pipeline/video_pipeline_impl.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/media/cdm/cast_cdm_context.h" -#include "chromecast/media/cma/base/buffering_defs.h" -#include "chromecast/media/cma/base/coded_frame_provider.h" -#include "chromecast/media/cma/base/decoder_config_adapter.h" -#include "chromecast/media/cma/pipeline/av_pipeline_impl.h" -#include "chromecast/media/cma/pipeline/cdm_decryptor.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/media/decoder_config.h" -#include "media/base/video_decoder_config.h" - -namespace chromecast { -namespace media { - -namespace { -const size_t kMaxVideoFrameSize = 1024 * 1024; -} - -VideoPipelineImpl::VideoPipelineImpl(CmaBackend::VideoDecoder* decoder, - VideoPipelineClient client) - : AvPipelineImpl(decoder, std::move(client.av_pipeline_client)), - video_decoder_(decoder), - natural_size_changed_cb_(client.natural_size_changed_cb) { - DCHECK(video_decoder_); -} - -VideoPipelineImpl::~VideoPipelineImpl() { -} - -::media::PipelineStatus VideoPipelineImpl::Initialize( - const std::vector<::media::VideoDecoderConfig>& configs, - std::unique_ptr frame_provider) { - DCHECK_GT(configs.size(), 0u); - for (const auto& config : configs) { - LOG(INFO) << __FUNCTION__ << " " << config.AsHumanReadableString(); - } - - if (frame_provider) { - SetCodedFrameProvider(std::move(frame_provider), kAppVideoBufferSize, - kMaxVideoFrameSize); - } - - if (configs.empty()) { - return ::media::PIPELINE_ERROR_INITIALIZATION_FAILED; - } - DCHECK_LE(configs.size(), 2U); - DCHECK(configs[0].IsValidConfig()); - encryption_schemes_.resize(configs.size()); - - VideoConfig video_config = - DecoderConfigAdapter::ToCastVideoConfig(kPrimary, configs[0]); - encryption_schemes_[0] = video_config.encryption_scheme; - - VideoConfig secondary_config; - if (configs.size() == 2) { - DCHECK(configs[1].IsValidConfig()); - secondary_config = DecoderConfigAdapter::ToCastVideoConfig(kSecondary, - configs[1]); - video_config.additional_config = &secondary_config; - encryption_schemes_[1] = secondary_config.encryption_scheme; - } - - if (!video_decoder_->SetConfig(video_config)) { - return ::media::PIPELINE_ERROR_INITIALIZATION_FAILED; - } - - set_state(kFlushed); - return ::media::PIPELINE_OK; -} - -void VideoPipelineImpl::OnVideoResolutionChanged(const Size& size) { - if (state() != kPlaying) - return; - - metrics::CastMetricsHelper* metrics_helper = - metrics::CastMetricsHelper::GetInstance(); - int encoded_video_resolution = (size.width << 16) | size.height; - metrics_helper->RecordApplicationEventWithValue( - "Cast.Platform.VideoResolution", encoded_video_resolution); - - if (!natural_size_changed_cb_.is_null()) { - natural_size_changed_cb_.Run(gfx::Size(size.width, size.height)); - } - - CastCdmContext* cdm = cdm_context(); - if (cdm) { - cdm->SetVideoResolution(size.width, size.height); - } -} - -void VideoPipelineImpl::OnUpdateConfig( - StreamId id, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) { - if (video_config.IsValidConfig()) { - LOG(INFO) << __FUNCTION__ << " id:" << id << " " - << video_config.AsHumanReadableString(); - - DCHECK_LT(id, encryption_schemes_.size()); - VideoConfig cast_video_config = - DecoderConfigAdapter::ToCastVideoConfig(id, video_config); - encryption_schemes_[static_cast(id)] = - cast_video_config.encryption_scheme; - - bool success = video_decoder_->SetConfig(cast_video_config); - if (!success && !client().playback_error_cb.is_null()) - client().playback_error_cb.Run(::media::PIPELINE_ERROR_DECODE); - } -} - -EncryptionScheme VideoPipelineImpl::GetEncryptionScheme(StreamId id) const { - DCHECK_LT(id, encryption_schemes_.size()); - return encryption_schemes_[static_cast(id)]; -} - -std::unique_ptr VideoPipelineImpl::CreateDecryptor() { - return std::make_unique(false /* clear_buffer_needed */); -} - -void VideoPipelineImpl::UpdateStatistics() { - if (client().statistics_cb.is_null()) - return; - - // TODO(mbjorge): Give Statistics a default constructor when the - // next system update happens. b/32802298 - CmaBackend::VideoDecoder::Statistics video_stats = {}; - video_decoder_->GetStatistics(&video_stats); - - ::media::PipelineStatistics current_stats; - current_stats.video_bytes_decoded = video_stats.decoded_bytes; - current_stats.video_frames_decoded = video_stats.decoded_frames; - current_stats.video_frames_dropped = video_stats.dropped_frames; - - ::media::PipelineStatistics delta_stats; - delta_stats.video_bytes_decoded = - current_stats.video_bytes_decoded - previous_stats_.video_bytes_decoded; - delta_stats.video_frames_decoded = - current_stats.video_frames_decoded - previous_stats_.video_frames_decoded; - delta_stats.video_frames_dropped = - current_stats.video_frames_dropped - previous_stats_.video_frames_dropped; - - bytes_decoded_since_last_update_ = delta_stats.video_bytes_decoded; - previous_stats_ = current_stats; - - client().statistics_cb.Run(delta_stats); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/pipeline/video_pipeline_impl.h chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_impl.h --- chromium-132.0.6834.110/chromecast/media/cma/pipeline/video_pipeline_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/pipeline/video_pipeline_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_PIPELINE_VIDEO_PIPELINE_IMPL_H_ -#define CHROMECAST_MEDIA_CMA_PIPELINE_VIDEO_PIPELINE_IMPL_H_ - -#include -#include - -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/cma/pipeline/av_pipeline_impl.h" -#include "chromecast/media/cma/pipeline/video_pipeline_client.h" -#include "chromecast/public/media/stream_id.h" -#include "media/base/pipeline_status.h" - -namespace media { -class AudioDecoderConfig; -class VideoDecoderConfig; -} - -namespace chromecast { -struct Size; -namespace media { -class CodedFrameProvider; - -class VideoPipelineImpl : public AvPipelineImpl { - public: - VideoPipelineImpl(CmaBackend::VideoDecoder* decoder, - VideoPipelineClient client); - - VideoPipelineImpl(const VideoPipelineImpl&) = delete; - VideoPipelineImpl& operator=(const VideoPipelineImpl&) = delete; - - ~VideoPipelineImpl() override; - - ::media::PipelineStatus Initialize( - const std::vector<::media::VideoDecoderConfig>& configs, - std::unique_ptr frame_provider); - - // AvPipelineImpl implementation: - void UpdateStatistics() override; - - private: - // AvPipelineImpl implementation: - void OnVideoResolutionChanged(const Size& size) override; - void OnUpdateConfig(StreamId id, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) override; - EncryptionScheme GetEncryptionScheme(StreamId id) const override; - std::unique_ptr CreateDecryptor() override; - - CmaBackend::VideoDecoder* const video_decoder_; - const VideoPipelineClient::NaturalSizeChangedCB natural_size_changed_cb_; - std::vector encryption_schemes_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_PIPELINE_VIDEO_PIPELINE_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/DEPS chromium-132.0.6834.159/chromecast/media/cma/test/DEPS --- chromium-132.0.6834.110/chromecast/media/cma/test/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -include_rules = [ - "+chromecast/common/mojom", - "+media/filters", - "+media/parsers", -] diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/frame_generator_for_test.cc chromium-132.0.6834.159/chromecast/media/cma/test/frame_generator_for_test.cc --- chromium-132.0.6834.110/chromecast/media/cma/test/frame_generator_for_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/frame_generator_for_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/test/frame_generator_for_test.h" - -#include - -#include - -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "media/base/decoder_buffer.h" -#include "media/base/decrypt_config.h" - -namespace chromecast { -namespace media { - -FrameGeneratorForTest::FrameSpec::FrameSpec() - : has_config(false), - is_eos(false), - has_decrypt_config(false), - size(0) { -} - -FrameGeneratorForTest::FrameSpec::~FrameSpec() { -} - -FrameGeneratorForTest::FrameGeneratorForTest( - const std::vector frame_specs) - : frame_specs_(frame_specs), - frame_idx_(0), - total_buffer_size_(0) { -} - -FrameGeneratorForTest::~FrameGeneratorForTest() { -} - -bool FrameGeneratorForTest::HasDecoderConfig() const { - if (frame_idx_ >= frame_specs_.size()) - return false; - - return frame_specs_[frame_idx_].has_config; -} - -scoped_refptr FrameGeneratorForTest::Generate() { - if (frame_idx_ >= frame_specs_.size()) - return scoped_refptr(); - - const FrameSpec& frame_spec = frame_specs_[frame_idx_]; - frame_idx_++; - - if (frame_spec.is_eos) { - return scoped_refptr( - new DecoderBufferAdapter(::media::DecoderBuffer::CreateEOSBuffer())); - } - - scoped_refptr< ::media::DecoderBuffer> buffer( - new ::media::DecoderBuffer(frame_spec.size)); - - // Timestamp. - buffer->set_timestamp(frame_spec.timestamp); - - // Generate the frame data. - for (size_t k = 0; k < frame_spec.size; k++) { - buffer->writable_data()[k] = total_buffer_size_ & 0xff; - total_buffer_size_++; - } - - // Generate the decrypt configuration. - if (frame_spec.has_decrypt_config) { - uint32_t frame_size = buffer->size(); - uint32_t chunk_size = 1; - std::vector< ::media::SubsampleEntry> subsamples; - while (frame_size > 0) { - ::media::SubsampleEntry subsample; - subsample.clear_bytes = chunk_size; - if (subsample.clear_bytes > frame_size) - subsample.clear_bytes = frame_size; - frame_size -= subsample.clear_bytes; - chunk_size <<= 1; - - subsample.cypher_bytes = chunk_size; - if (subsample.cypher_bytes > frame_size) - subsample.cypher_bytes = frame_size; - frame_size -= subsample.cypher_bytes; - chunk_size <<= 1; - - subsamples.push_back(subsample); - } - - char key_id[] = { - 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, - 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf }; - - char iv[] = { - 0x0, 0x2, 0x1, 0x3, 0x5, 0x4, 0x7, 0x6, - 0x9, 0x8, 0xb, 0xa, 0xd, 0xc, 0xf, 0xe }; - - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCencConfig( - std::string(key_id, std::size(key_id)), - std::string(iv, std::size(iv)), subsamples); - buffer->set_decrypt_config(std::move(decrypt_config)); - } - - return scoped_refptr(new DecoderBufferAdapter(buffer)); -} - -size_t FrameGeneratorForTest::RemainingFrameCount() const { - size_t count = frame_specs_.size() - frame_idx_; - return count; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/frame_generator_for_test.h chromium-132.0.6834.159/chromecast/media/cma/test/frame_generator_for_test.h --- chromium-132.0.6834.110/chromecast/media/cma/test/frame_generator_for_test.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/frame_generator_for_test.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_TEST_FRAME_GENERATOR_FOR_TEST_H_ -#define CHROMECAST_MEDIA_CMA_TEST_FRAME_GENERATOR_FOR_TEST_H_ - -#include - -#include - -#include "base/memory/ref_counted.h" -#include "base/time/time.h" - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -class FrameGeneratorForTest { - public: - // Parameters used to generate frames. - struct FrameSpec { - FrameSpec(); - ~FrameSpec(); - - // Indicates whether the frame comes with a new decoder configuration. - bool has_config; - - bool is_eos; - base::TimeDelta timestamp; - bool has_decrypt_config; - size_t size; - }; - - explicit FrameGeneratorForTest(const std::vector frame_specs); - - FrameGeneratorForTest(const FrameGeneratorForTest&) = delete; - FrameGeneratorForTest& operator=(const FrameGeneratorForTest&) = delete; - - ~FrameGeneratorForTest(); - - // Indicates whether the next frame should come with a new decoder config. - bool HasDecoderConfig() const; - - // Generates a frame. - // Returns NULL is there is no frame left to generate. - scoped_refptr Generate(); - - // Number of frames not generated yet. - size_t RemainingFrameCount() const; - - private: - std::vector frame_specs_; - size_t frame_idx_; - - // Total size of A/V buffers generated so far. - size_t total_buffer_size_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_TEST_FRAME_GENERATOR_FOR_TEST_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/frame_segmenter_for_test.cc chromium-132.0.6834.159/chromecast/media/cma/test/frame_segmenter_for_test.cc --- chromium-132.0.6834.110/chromecast/media/cma/test/frame_segmenter_for_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/frame_segmenter_for_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,355 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/test/frame_segmenter_for_test.h" - -#include - -#include "base/compiler_specific.h" -#include "base/containers/span.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/logging.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "media/base/decoder_buffer.h" -#include "media/base/demuxer.h" -#include "media/base/media_tracks.h" -#include "media/base/media_util.h" -#include "media/base/test_helpers.h" -#include "media/filters/ffmpeg_demuxer.h" -#include "media/filters/file_data_source.h" -#include "media/parsers/h264_parser.h" - -namespace chromecast { -namespace media { - -namespace { - -struct AudioFrameHeader { - size_t offset; - size_t frame_size; - int sampling_frequency; -}; - -int mp3_bitrate[] = { - 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0 }; -int mp3_sample_rate[] = { 44100, 48000, 32000, 0 }; - -AudioFrameHeader FindNextMp3Header(const uint8_t* data, size_t data_size) { - bool found = false; - AudioFrameHeader header; - header.frame_size = 0; - if (data_size < 4) - return header; - - for (size_t k = 0; k < data_size - 4 && !found; k++) { - // Mp3 Header: - // syncword: 11111111111 - // Mpeg1: 11 - // Layer3: 01 - if (!(data[k + 0] == 0xff && (data[k + 1] & 0xfe) == 0xfa)) - continue; - - int bitrate_index = (data[k + 2] >> 4); - if (bitrate_index == 0 || bitrate_index == 15) { - // Free size or bad bitrate => not supported. - continue; - } - - int sample_rate_index = (data[k + 2] >> 2) & 0x3; - if (sample_rate_index == 3) - continue; - - size_t frame_size = - ((1152 / 8) * mp3_bitrate[bitrate_index] * 1000) / - mp3_sample_rate[sample_rate_index]; - if (data[k + 2] & 0x2) - frame_size++; - - // Make sure the frame is complete. - if (k + frame_size > data_size) - break; - - if (k + frame_size < data_size - 3 && - !(data[k + frame_size + 0] == 0xff && - (data[k + frame_size + 1] & 0xfe) == 0xfa)) { - continue; - } - - found = true; - header.offset = k; - header.frame_size = frame_size; - header.sampling_frequency = mp3_sample_rate[sample_rate_index]; - } - return header; -} - -} // namespace - -BufferList Mp3SegmenterForTest(const uint8_t* data_ptr, size_t data_size) { - // TODO(crbug.com/40284755): These functions should be based on span. - auto data = UNSAFE_TODO(base::span(data_ptr, data_size)); - BufferList audio_frames; - base::TimeDelta timestamp; - - while (true) { - AudioFrameHeader header = FindNextMp3Header(data.data(), data.size()); - if (header.frame_size == 0) { - break; - } - - scoped_refptr<::media::DecoderBuffer> buffer( - ::media::DecoderBuffer::CopyFrom( - data.subspan(header.offset, header.frame_size))); - data = data.subspan(header.offset + header.frame_size); - buffer->set_timestamp(timestamp); - audio_frames.push_back( - scoped_refptr(new DecoderBufferAdapter(buffer))); - - // 1152 samples in an MP3 frame. - timestamp += base::Microseconds((UINT64_C(1152) * 1000 * 1000) / - header.sampling_frequency); - } - return audio_frames; -} - -struct H264AccessUnit { - H264AccessUnit(); - - size_t offset; - size_t size; - int has_vcl; - int poc; -}; - -H264AccessUnit::H264AccessUnit() - : offset(0), - size(0), - has_vcl(false), - poc(0) { -} - -BufferList H264SegmenterForTest(const uint8_t* data_ptr, size_t data_size) { - // TODO(crbug.com/40284755): These functions should be based on span. - auto data = UNSAFE_TODO(base::span(data_ptr, data_size)); - BufferList video_frames; - std::list access_unit_list; - H264AccessUnit access_unit; - - int prev_pic_order_cnt_lsb = 0; - int pic_order_cnt_msb = 0; - - std::unique_ptr<::media::H264Parser> h264_parser(new ::media::H264Parser()); - h264_parser->SetStream(data_ptr, data_size); - - while (true) { - bool is_eos = false; - ::media::H264NALU nalu; - switch (h264_parser->AdvanceToNextNALU(&nalu)) { - case ::media::H264Parser::kOk: - break; - case ::media::H264Parser::kInvalidStream: - case ::media::H264Parser::kUnsupportedStream: - return video_frames; - case ::media::H264Parser::kEOStream: - is_eos = true; - break; - } - if (is_eos) - break; - - // To get the NALU syncword offset, substract 3 or 4 - // which corresponds to the possible syncword lengths. - size_t nalu_offset = nalu.data - data_ptr; - nalu_offset -= 3; - if (nalu_offset > 0 && data[nalu_offset-1] == 0) - nalu_offset--; - - switch (nalu.nal_unit_type) { - case ::media::H264NALU::kAUD: { - break; - } - case ::media::H264NALU::kSPS: { - int sps_id; - if (h264_parser->ParseSPS(&sps_id) != ::media::H264Parser::kOk) - return video_frames; - if (access_unit.has_vcl) { - access_unit.size = nalu_offset - access_unit.offset; - access_unit_list.push_back(access_unit); - access_unit = H264AccessUnit(); - access_unit.offset = nalu_offset; - } - break; - } - case ::media::H264NALU::kPPS: { - int pps_id; - if (h264_parser->ParsePPS(&pps_id) != ::media::H264Parser::kOk) - return video_frames; - if (access_unit.has_vcl) { - access_unit.size = nalu_offset - access_unit.offset; - access_unit_list.push_back(access_unit); - access_unit = H264AccessUnit(); - access_unit.offset = nalu_offset; - } - break; - } - case ::media::H264NALU::kIDRSlice: - case ::media::H264NALU::kNonIDRSlice: { - ::media::H264SliceHeader shdr; - if (h264_parser->ParseSliceHeader(nalu, &shdr) != - ::media::H264Parser::kOk) { - return video_frames; - } - const ::media::H264PPS* pps = - h264_parser->GetPPS(shdr.pic_parameter_set_id); - if (!pps) - return video_frames; - const ::media::H264SPS* sps = - h264_parser->GetSPS(pps->seq_parameter_set_id); - - // Very simplified way to segment H264. - // This assumes only 1 VCL NALU per access unit. - if (access_unit.has_vcl) { - access_unit.size = nalu_offset - access_unit.offset; - access_unit_list.push_back(access_unit); - access_unit = H264AccessUnit(); - access_unit.offset = nalu_offset; - } - - access_unit.has_vcl = true; - - // Support only explicit POC so far. - if (sps->pic_order_cnt_type != 0) { - LOG(WARNING) << "Unsupported pic_order_cnt_type"; - return video_frames; - } - int diff_pic_order_cnt_lsb = - shdr.pic_order_cnt_lsb - prev_pic_order_cnt_lsb; - int max_pic_order_cnt_lsb = - 1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4); - if (diff_pic_order_cnt_lsb < 0 && - diff_pic_order_cnt_lsb <= -max_pic_order_cnt_lsb / 2) { - pic_order_cnt_msb += max_pic_order_cnt_lsb; - } else if (diff_pic_order_cnt_lsb > 0 && - diff_pic_order_cnt_lsb > max_pic_order_cnt_lsb / 2) { - pic_order_cnt_msb -= max_pic_order_cnt_lsb; - } - access_unit.poc = pic_order_cnt_msb + shdr.pic_order_cnt_lsb; - prev_pic_order_cnt_lsb = shdr.pic_order_cnt_lsb; - break; - } - default: { - } - } - } - - // Emit the last access unit. - if (access_unit.has_vcl) { - access_unit.size = data_size - access_unit.offset; - access_unit_list.push_back(access_unit); - } - - // Create the list of buffers. - // Totally arbitrary decision: assume a delta POC of 1 is 20ms (50Hz field - // rate). - base::TimeDelta poc_duration = base::Milliseconds(20); - for (std::list::iterator it = access_unit_list.begin(); - it != access_unit_list.end(); ++it) { - scoped_refptr<::media::DecoderBuffer> buffer( - ::media::DecoderBuffer::CopyFrom(data.subspan(it->offset, it->size))); - buffer->set_timestamp(it->poc * poc_duration); - video_frames.push_back( - scoped_refptr(new DecoderBufferAdapter(buffer))); - } - - return video_frames; -} - -void OnEncryptedMediaInitData(::media::EmeInitDataType init_data_type, - const std::vector& init_data) { - LOG(FATAL) << "Unexpected test failure: file is encrypted."; -} - -void OnMediaTracksUpdated(std::unique_ptr<::media::MediaTracks> tracks) {} - -void OnNewBuffer(BufferList* buffer_list, - const base::RepeatingClosure& finished_cb, - ::media::DemuxerStream::Status status, - ::media::DemuxerStream::DecoderBufferVector buffers) { - CHECK_EQ(status, ::media::DemuxerStream::kOk); - EXPECT_EQ(buffers.size(), 1u) << "OnNewBuffer only reads a single buffer."; - scoped_refptr<::media::DecoderBuffer> buffer = std::move(buffers[0]); - CHECK(buffer.get()); - CHECK(buffer_list); - buffer_list->push_back(new DecoderBufferAdapter(buffer)); - finished_cb.Run(); -} - -class FakeDemuxerHost : public ::media::DemuxerHost { - public: - // DemuxerHost implementation. - void OnBufferedTimeRangesChanged( - const ::media::Ranges& ranges) override {} - void SetDuration(base::TimeDelta duration) override {} - void OnDemuxerError(::media::PipelineStatus error) override { - LOG(FATAL) << "OnDemuxerError: " << error; - } -}; - -DemuxResult::DemuxResult() { -} - -DemuxResult::DemuxResult(const DemuxResult& other) = default; - -DemuxResult::~DemuxResult() { -} - -DemuxResult FFmpegDemuxForTest(const base::FilePath& filepath, - bool audio) { - FakeDemuxerHost fake_demuxer_host; - ::media::FileDataSource data_source; - CHECK(data_source.Initialize(filepath)); - - ::media::NullMediaLog media_log; - ::media::FFmpegDemuxer demuxer( - base::SingleThreadTaskRunner::GetCurrentDefault(), &data_source, - base::BindRepeating(&OnEncryptedMediaInitData), - base::BindRepeating(&OnMediaTracksUpdated), &media_log, true); - ::media::WaitableMessageLoopEvent init_event; - demuxer.Initialize(&fake_demuxer_host, init_event.GetPipelineStatusCB()); - init_event.RunAndWaitForStatus(::media::PIPELINE_OK); - - auto stream_type = - audio ? ::media::DemuxerStream::AUDIO : ::media::DemuxerStream::VIDEO; - ::media::DemuxerStream* stream = demuxer.GetFirstStream(stream_type); - CHECK(stream); - stream->EnableBitstreamConverter(); - - DemuxResult demux_result; - if (audio) { - demux_result.audio_config = stream->audio_decoder_config(); - } else { - demux_result.video_config = stream->video_decoder_config(); - } - - bool end_of_stream = false; - while (!end_of_stream) { - base::RunLoop run_loop; - stream->Read( - 1, base::BindOnce(&OnNewBuffer, base::Unretained(&demux_result.frames), - run_loop.QuitClosure())); - run_loop.Run(); - CHECK(!demux_result.frames.empty()); - end_of_stream = demux_result.frames.back()->end_of_stream(); - } - - demuxer.Stop(); - return demux_result; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/frame_segmenter_for_test.h chromium-132.0.6834.159/chromecast/media/cma/test/frame_segmenter_for_test.h --- chromium-132.0.6834.110/chromecast/media/cma/test/frame_segmenter_for_test.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/frame_segmenter_for_test.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_TEST_FRAME_SEGMENTER_FOR_TEST_H_ -#define CHROMECAST_MEDIA_CMA_TEST_FRAME_SEGMENTER_FOR_TEST_H_ - -#include -#include - -#include - -#include "base/memory/ref_counted.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/video_decoder_config.h" - -namespace base { -class FilePath; -} - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -typedef std::list > BufferList; - -// Implement some basic frame segmenters good enough for unit tests. -BufferList Mp3SegmenterForTest(const uint8_t* data, size_t data_size); -BufferList H264SegmenterForTest(const uint8_t* data, size_t data_size); - -struct DemuxResult { - DemuxResult(); - DemuxResult(const DemuxResult& other); - ~DemuxResult(); - - ::media::AudioDecoderConfig audio_config; - ::media::VideoDecoderConfig video_config; - BufferList frames; -}; - -DemuxResult FFmpegDemuxForTest(const base::FilePath& filepath, - bool audio); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_TEST_FRAME_SEGMENTER_FOR_TEST_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/mock_frame_consumer.cc chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_consumer.cc --- chromium-132.0.6834.110/chromecast/media/cma/test/mock_frame_consumer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_consumer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,111 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/test/mock_frame_consumer.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/base/coded_frame_provider.h" -#include "chromecast/media/cma/test/frame_generator_for_test.h" -#include "media/base/video_decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -MockFrameConsumer::MockFrameConsumer( - CodedFrameProvider* coded_frame_provider) - : coded_frame_provider_(coded_frame_provider), - pattern_idx_(0), - last_read_aborted_by_flush_(false) { -} - -MockFrameConsumer::~MockFrameConsumer() { -} - -void MockFrameConsumer::Configure( - const std::vector& delayed_task_pattern, - bool last_read_aborted_by_flush, - std::unique_ptr frame_generator) { - delayed_task_pattern_ = delayed_task_pattern; - last_read_aborted_by_flush_ = last_read_aborted_by_flush; - frame_generator_ = std::move(frame_generator); -} - -void MockFrameConsumer::Start(base::OnceClosure done_cb) { - done_cb_ = std::move(done_cb); - - pattern_idx_ = 0; - - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&MockFrameConsumer::ReadFrame, base::Unretained(this))); -} - -void MockFrameConsumer::ReadFrame() { - // Once all the frames have been read, flush the frame provider. - if (frame_generator_->RemainingFrameCount() == 0 && - !last_read_aborted_by_flush_) { - coded_frame_provider_->Flush(base::BindOnce( - &MockFrameConsumer::OnFlushCompleted, base::Unretained(this))); - return; - } - - coded_frame_provider_->Read( - base::BindOnce(&MockFrameConsumer::OnNewFrame, base::Unretained(this))); - - // The last read is right away aborted by a Flush. - if (frame_generator_->RemainingFrameCount() == 0 && - last_read_aborted_by_flush_) { - coded_frame_provider_->Flush(base::BindOnce( - &MockFrameConsumer::OnFlushCompleted, base::Unretained(this))); - return; - } -} - -void MockFrameConsumer::OnNewFrame( - const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config) { - bool ref_has_config = frame_generator_->HasDecoderConfig(); - scoped_refptr ref_buffer = frame_generator_->Generate(); - - ASSERT_TRUE(buffer.get()); - ASSERT_TRUE(ref_buffer.get()); - - EXPECT_EQ(video_config.IsValidConfig(), ref_has_config); - - EXPECT_EQ(buffer->end_of_stream(), ref_buffer->end_of_stream()); - if (!ref_buffer->end_of_stream()) { - EXPECT_EQ(buffer->timestamp(), ref_buffer->timestamp()); - ASSERT_EQ(buffer->data_size(), ref_buffer->data_size()); - for (size_t k = 0; k < ref_buffer->data_size(); k++) - EXPECT_EQ(buffer->data()[k], ref_buffer->data()[k]); - } - - bool delayed = delayed_task_pattern_[pattern_idx_]; - pattern_idx_ = (pattern_idx_ + 1) % delayed_task_pattern_.size(); - - if (delayed) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&MockFrameConsumer::ReadFrame, base::Unretained(this)), - base::Milliseconds(1)); - } else { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, - base::BindOnce(&MockFrameConsumer::ReadFrame, base::Unretained(this))); - } -} - -void MockFrameConsumer::OnFlushCompleted() { - EXPECT_EQ(frame_generator_->RemainingFrameCount(), 0u); - std::move(done_cb_).Run(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/mock_frame_consumer.h chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_consumer.h --- chromium-132.0.6834.110/chromecast/media/cma/test/mock_frame_consumer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_consumer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_TEST_MOCK_FRAME_CONSUMER_H_ -#define CHROMECAST_MEDIA_CMA_TEST_MOCK_FRAME_CONSUMER_H_ - -#include - -#include -#include - -#include "base/functional/callback.h" - -namespace media { -class AudioDecoderConfig; -class VideoDecoderConfig; -} - -namespace chromecast { -namespace media { -class CodedFrameProvider; -class DecoderBufferBase; -class FrameGeneratorForTest; - -class MockFrameConsumer { - public: - explicit MockFrameConsumer(CodedFrameProvider* coded_frame_provider); - - MockFrameConsumer(const MockFrameConsumer&) = delete; - MockFrameConsumer& operator=(const MockFrameConsumer&) = delete; - - ~MockFrameConsumer(); - - void Configure(const std::vector& delayed_task_pattern, - bool last_read_aborted_by_flush, - std::unique_ptr frame_generator); - - // Starts consuming frames. Invoke |done_cb| when all the expected frames - // have been received. - void Start(base::OnceClosure done_cb); - - private: - void ReadFrame(); - void OnNewFrame(const scoped_refptr& buffer, - const ::media::AudioDecoderConfig& audio_config, - const ::media::VideoDecoderConfig& video_config); - - void OnFlushCompleted(); - - CodedFrameProvider* const coded_frame_provider_; - - base::OnceClosure done_cb_; - - // Parameterization of the frame consumer: - // |delayed_task_pattern_| indicates the pattern for fetching frames, - // i.e. after receiving a frame, either fetch a frame right away - // or wait some time before fetching another frame. - // |pattern_idx_| is the current index in the pattern. - // |last_read_aborted_by_flush_| indicates whether the last buffer request - // should be aborted by a Flush. - std::vector delayed_task_pattern_; - size_t pattern_idx_; - bool last_read_aborted_by_flush_; - - // Expected results. - std::unique_ptr frame_generator_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_TEST_MOCK_FRAME_CONSUMER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/mock_frame_provider.cc chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_provider.cc --- chromium-132.0.6834.110/chromecast/media/cma/test/mock_frame_provider.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_provider.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,98 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/cma/test/mock_frame_provider.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/cma/test/frame_generator_for_test.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/decoder_buffer.h" -#include "media/base/media_util.h" -#include "media/base/video_decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/size.h" - -namespace chromecast { -namespace media { - -MockFrameProvider::MockFrameProvider() : delay_flush_(false) { -} - -MockFrameProvider::~MockFrameProvider() { -} - -void MockFrameProvider::Configure( - const std::vector& delayed_task_pattern, - std::unique_ptr frame_generator) { - delayed_task_pattern_ = delayed_task_pattern; - pattern_idx_ = 0; - - frame_generator_ = std::move(frame_generator); -} - -void MockFrameProvider::SetDelayFlush(bool delay_flush) { - delay_flush_ = delay_flush; -} - -void MockFrameProvider::Read(ReadCB read_cb) { - bool delayed = delayed_task_pattern_[pattern_idx_]; - pattern_idx_ = (pattern_idx_ + 1) % delayed_task_pattern_.size(); - - if (delayed) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&MockFrameProvider::DoRead, base::Unretained(this), - std::move(read_cb)), - base::Milliseconds(1)); - } else { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&MockFrameProvider::DoRead, - base::Unretained(this), std::move(read_cb))); - } -} - -void MockFrameProvider::Flush(base::OnceClosure flush_cb) { - if (delay_flush_) { - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, std::move(flush_cb), base::Milliseconds(10)); - } else { - std::move(flush_cb).Run(); - } -} - -void MockFrameProvider::DoRead(ReadCB read_cb) { - bool has_config = frame_generator_->HasDecoderConfig(); - - scoped_refptr buffer(frame_generator_->Generate()); - ASSERT_TRUE(buffer.get()); - - ::media::AudioDecoderConfig audio_config; - ::media::VideoDecoderConfig video_config; - if (has_config) { - gfx::Size coded_size(640, 480); - gfx::Rect visible_rect(640, 480); - gfx::Size natural_size(640, 480); - video_config = ::media::VideoDecoderConfig( - ::media::VideoCodec::kH264, ::media::VIDEO_CODEC_PROFILE_UNKNOWN, - ::media::VideoDecoderConfig::AlphaMode::kIsOpaque, - ::media::VideoColorSpace(), ::media::kNoTransformation, coded_size, - visible_rect, natural_size, ::media::EmptyExtraData(), - ::media::EncryptionScheme::kUnencrypted); - - audio_config = ::media::AudioDecoderConfig( - ::media::AudioCodec::kAAC, ::media::kSampleFormatS16, - ::media::CHANNEL_LAYOUT_STEREO, 44100, ::media::EmptyExtraData(), - ::media::EncryptionScheme::kUnencrypted); - } - - std::move(read_cb).Run(buffer, audio_config, video_config); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/cma/test/mock_frame_provider.h chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_provider.h --- chromium-132.0.6834.110/chromecast/media/cma/test/mock_frame_provider.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/cma/test/mock_frame_provider.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_CMA_TEST_MOCK_FRAME_PROVIDER_H_ -#define CHROMECAST_MEDIA_CMA_TEST_MOCK_FRAME_PROVIDER_H_ - -#include - -#include -#include - -#include "chromecast/media/cma/base/coded_frame_provider.h" - -namespace chromecast { -namespace media { -class FrameGeneratorForTest; - -class MockFrameProvider : public CodedFrameProvider { - public: - MockFrameProvider(); - - MockFrameProvider(const MockFrameProvider&) = delete; - MockFrameProvider& operator=(const MockFrameProvider&) = delete; - - ~MockFrameProvider() override; - - void Configure(const std::vector& delayed_task_pattern, - std::unique_ptr frame_generator); - void SetDelayFlush(bool delay_flush); - - // CodedFrameProvider implementation. - void Read(ReadCB read_cb) override; - void Flush(base::OnceClosure flush_cb) override; - - private: - void DoRead(ReadCB read_cb); - - // Parameterization of the frame provider. - // |delayed_task_pattern_| indicates the pattern for delivering frames, - // i.e. after receiving a Read request, either delivers a frame right away - // or wait some time before delivering the frame. - // |pattern_idx_| is the current index in the pattern. - // |delay_flush_| indicates whether to delay flush cb in Flush. Default is - // false. - std::vector delayed_task_pattern_; - size_t pattern_idx_; - bool delay_flush_; - - std::unique_ptr frame_generator_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_CMA_TEST_MOCK_FRAME_PROVIDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/common/audio_decoder_software_wrapper.cc chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper.cc --- chromium-132.0.6834.110/chromecast/media/common/audio_decoder_software_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,205 +0,0 @@ -// 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 "chromecast/media/common/audio_decoder_software_wrapper.h" - -#include - -#include "base/containers/contains.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/common/base/decoder_config_logging.h" - -namespace chromecast { -namespace media { - -namespace { -const int kMonoChannelCount = 1; -const int kStereoChannelCount = 2; -const int k5_1ChannelCount = 6; - -bool IsChannelLayoutSupported(AudioConfig config) { - if (config.channel_number == kMonoChannelCount || - config.channel_number == kStereoChannelCount) - return true; - - // Only supports 5.1 for Opus. - if (config.channel_number == k5_1ChannelCount && - config.codec == AudioCodec::kCodecOpus) - return true; - - return false; -} - -// Codecs that cannot be decoded on the device and must be passed through. -constexpr media::AudioCodec kPassthroughCodecs[] = { - kCodecEAC3, kCodecAC3, kCodecDTS, kCodecDTSXP2, kCodecMpegHAudio, -}; - -} // namespace - -AudioDecoderSoftwareWrapper::AudioDecoderSoftwareWrapper( - MediaPipelineBackend::AudioDecoder* backend_decoder) - : backend_decoder_(backend_decoder), - delegate_(nullptr), - decoder_error_(false) { - DCHECK(backend_decoder_); - backend_decoder_->SetDelegate(this); -} - -AudioDecoderSoftwareWrapper::~AudioDecoderSoftwareWrapper() {} - -void AudioDecoderSoftwareWrapper::SetDelegate(DecoderDelegate* delegate) { - DCHECK(delegate); - delegate_ = delegate; - if (decoder_error_) { - delegate_->OnDecoderError(); - } -} - -MediaPipelineBackend::BufferStatus AudioDecoderSoftwareWrapper::PushBuffer( - CastDecoderBuffer* buffer) { - DCHECK(buffer); - if (!software_decoder_) - return backend_decoder_->PushBuffer(buffer); - - DecoderBufferBase* buffer_base = static_cast(buffer); - software_decoder_->Decode( - base::WrapRefCounted(buffer_base), - base::BindOnce(&AudioDecoderSoftwareWrapper::OnDecodedBuffer, - base::Unretained(this))); - return MediaPipelineBackend::kBufferPending; -} - -void AudioDecoderSoftwareWrapper::GetStatistics(Statistics* statistics) { - DCHECK(statistics); - return backend_decoder_->GetStatistics(statistics); -} - -bool AudioDecoderSoftwareWrapper::SetConfig(const AudioConfig& config) { - DCHECK(IsValidConfig(config)); - - if (backend_decoder_->SetConfig(config)) { - LOG(INFO) << "Using backend decoder for " << config.codec; - software_decoder_.reset(); - output_config_ = config; - return true; - } - - if (base::Contains(kPassthroughCodecs, config.codec)) { - LOG(INFO) << "Cannot use software decoder for " << config.codec; - return false; - } - - if (!CreateSoftwareDecoder(config)) { - LOG(INFO) << "Failed to create software decoder for " << config.codec; - return false; - } - - LOG(INFO) << "Using software decoder for " << config.codec; - - output_config_ = software_decoder_->GetOutputConfig(); - return backend_decoder_->SetConfig(output_config_); -} - -bool AudioDecoderSoftwareWrapper::SetVolume(float multiplier) { - return backend_decoder_->SetVolume(multiplier); -} - -AudioDecoderSoftwareWrapper::RenderingDelay -AudioDecoderSoftwareWrapper::GetRenderingDelay() { - return backend_decoder_->GetRenderingDelay(); -} - -AudioDecoderSoftwareWrapper::AudioTrackTimestamp -AudioDecoderSoftwareWrapper::GetAudioTrackTimestamp() { - return backend_decoder_->GetAudioTrackTimestamp(); -} - -int AudioDecoderSoftwareWrapper::GetStartThresholdInFrames() { - return backend_decoder_->GetStartThresholdInFrames(); -} - -bool AudioDecoderSoftwareWrapper::IsUsingSoftwareDecoder() { - return software_decoder_.get() != nullptr; -} - -bool AudioDecoderSoftwareWrapper::CreateSoftwareDecoder( - const AudioConfig& config) { - if (!IsChannelLayoutSupported(config)) { - LOG(ERROR) << "Software audio decoding is not supported for channel: " - << config.channel_number << " with codec: " << config.codec; - return false; - } - // TODO(kmackay) Consider using planar float instead. - software_decoder_ = media::CastAudioDecoder::Create( - base::SingleThreadTaskRunner::GetCurrentDefault(), config, - media::CastAudioDecoder::kOutputSigned16); - if (!software_decoder_) { - decoder_error_ = true; - LOG(ERROR) << "Failed to initialize software decoder"; - return false; - } - return true; -} - -void AudioDecoderSoftwareWrapper::OnDecodedBuffer( - CastAudioDecoder::Status status, - const media::AudioConfig& config, - scoped_refptr decoded) { - DCHECK(delegate_); - if (status != CastAudioDecoder::kDecodeOk) { - delegate_->OnPushBufferComplete(MediaPipelineBackend::kBufferFailed); - return; - } - - if (config.samples_per_second != output_config_.samples_per_second) { - // Sample rate of actual stream may differ from the rate reported from the - // container format. - output_config_.samples_per_second = config.samples_per_second; - if (!backend_decoder_->SetConfig(output_config_)) { - LOG(ERROR) << "Failed to set underlying backend to changed sample rate"; - delegate_->OnPushBufferComplete(MediaPipelineBackend::kBufferFailed); - return; - } - } - - pending_pushed_buffer_ = decoded; - MediaPipelineBackend::BufferStatus buffer_status = - backend_decoder_->PushBuffer(pending_pushed_buffer_.get()); - if (buffer_status != MediaPipelineBackend::kBufferPending) - delegate_->OnPushBufferComplete(buffer_status); -} - -void AudioDecoderSoftwareWrapper::OnPushBufferComplete( - MediaPipelineBackend::BufferStatus status) { - DCHECK(delegate_); - delegate_->OnPushBufferComplete(status); -} - -void AudioDecoderSoftwareWrapper::OnEndOfStream() { - DCHECK(delegate_); - delegate_->OnEndOfStream(); -} - -void AudioDecoderSoftwareWrapper::OnDecoderError() { - DCHECK(delegate_); - delegate_->OnDecoderError(); -} - -void AudioDecoderSoftwareWrapper::OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) { - DCHECK(delegate_); - delegate_->OnKeyStatusChanged(key_id, key_status, system_code); -} - -void AudioDecoderSoftwareWrapper::OnVideoResolutionChanged(const Size& size) { - NOTREACHED(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/audio_decoder_software_wrapper.h chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper.h --- chromium-132.0.6834.110/chromecast/media/common/audio_decoder_software_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_COMMON_AUDIO_DECODER_SOFTWARE_WRAPPER_H_ -#define CHROMECAST_MEDIA_COMMON_AUDIO_DECODER_SOFTWARE_WRAPPER_H_ - -#include - -#include -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/cast_audio_decoder.h" -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -namespace media { - -// Provides transparent software decoding if the backend does not support the -// incoming audio config. -class AudioDecoderSoftwareWrapper - : public MediaPipelineBackend::Decoder::Delegate { - public: - using DecoderDelegate = MediaPipelineBackend::Decoder::Delegate; - using RenderingDelay = MediaPipelineBackend::AudioDecoder::RenderingDelay; - using Statistics = MediaPipelineBackend::AudioDecoder::Statistics; - using AudioTrackTimestamp = - MediaPipelineBackend::AudioDecoder::AudioTrackTimestamp; - - AudioDecoderSoftwareWrapper( - MediaPipelineBackend::AudioDecoder* backend_decoder); - - AudioDecoderSoftwareWrapper(const AudioDecoderSoftwareWrapper&) = delete; - AudioDecoderSoftwareWrapper& operator=(const AudioDecoderSoftwareWrapper&) = - delete; - - ~AudioDecoderSoftwareWrapper() override; - - void SetDelegate(DecoderDelegate* delegate); - MediaPipelineBackend::BufferStatus PushBuffer(CastDecoderBuffer* buffer); - void GetStatistics(Statistics* statistics); - bool SetConfig(const AudioConfig& config); - bool SetVolume(float multiplier); - RenderingDelay GetRenderingDelay(); - AudioTrackTimestamp GetAudioTrackTimestamp(); - int GetStartThresholdInFrames(); - bool IsUsingSoftwareDecoder(); - - private: - bool CreateSoftwareDecoder(const AudioConfig& config); - void OnDecodedBuffer(CastAudioDecoder::Status status, - const media::AudioConfig& config, - scoped_refptr decoded); - - // MediaPipelineBackend::Decoder::Delegate implementation: - void OnPushBufferComplete(MediaPipelineBackend::BufferStatus status) override; - void OnEndOfStream() override; - void OnDecoderError() override; - void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override; - void OnVideoResolutionChanged(const Size& size) override; - - MediaPipelineBackend::AudioDecoder* const backend_decoder_; - DecoderDelegate* delegate_; - std::unique_ptr software_decoder_; - AudioConfig output_config_; - scoped_refptr pending_pushed_buffer_; - bool decoder_error_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_COMMON_AUDIO_DECODER_SOFTWARE_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/common/audio_decoder_software_wrapper_unittest.cc chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper_unittest.cc --- chromium-132.0.6834.110/chromecast/media/common/audio_decoder_software_wrapper_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/audio_decoder_software_wrapper_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/audio_decoder_software_wrapper.h" - -#include "base/test/task_environment.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::_; -using ::testing::Field; -using ::testing::Return; - -namespace chromecast { -namespace media { - -namespace { - -class MockAudioDecoder : public MediaPipelineBackend::AudioDecoder { - public: - MockAudioDecoder() { EXPECT_CALL(*this, SetDelegate(_)); } - - MOCK_METHOD1(SetDelegate, void(Delegate*)); - MOCK_METHOD1(PushBuffer, BufferStatus(CastDecoderBuffer*)); - MOCK_METHOD1(SetConfig, bool(const AudioConfig&)); - MOCK_METHOD1(SetVolume, bool(float)); - MOCK_METHOD0(GetRenderingDelay, RenderingDelay()); - MOCK_METHOD1(GetStatistics, void(Statistics*)); - MOCK_METHOD0(GetAudioTrackTimestamp, AudioTrackTimestamp()); - MOCK_METHOD0(GetStartThresholdInFrames, int()); -}; - -} // namespace - -class AudioDecoderSoftwareWrapperTest : public ::testing::Test { - public: - AudioDecoderSoftwareWrapperTest() - : audio_decoder_software_wrapper_(&audio_decoder_) {} - - base::test::TaskEnvironment task_environment_; - MockAudioDecoder audio_decoder_; - AudioDecoderSoftwareWrapper audio_decoder_software_wrapper_; -}; - -TEST_F(AudioDecoderSoftwareWrapperTest, IsUsingSoftwareDecoder) { - AudioConfig audio_config; - audio_config.channel_layout = ChannelLayout::STEREO; - audio_config.sample_format = kSampleFormatS16; - audio_config.bytes_per_channel = 2; - audio_config.channel_number = 2; - audio_config.samples_per_second = 48000; - - EXPECT_CALL(audio_decoder_, SetConfig(Field(&AudioConfig::codec, kCodecPCM))) - .WillRepeatedly(Return(true)); - EXPECT_CALL(audio_decoder_, SetConfig(Field(&AudioConfig::codec, kCodecOpus))) - .WillRepeatedly(Return(false)); - - audio_config.codec = kCodecPCM; - EXPECT_TRUE(audio_decoder_software_wrapper_.SetConfig(audio_config)); - EXPECT_FALSE(audio_decoder_software_wrapper_.IsUsingSoftwareDecoder()); - - audio_config.codec = kCodecOpus; - EXPECT_TRUE(audio_decoder_software_wrapper_.SetConfig(audio_config)); - EXPECT_TRUE(audio_decoder_software_wrapper_.IsUsingSoftwareDecoder()); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/audio_decoder_wrapper.cc chromium-132.0.6834.159/chromecast/media/common/audio_decoder_wrapper.cc --- chromium-132.0.6834.110/chromecast/media/common/audio_decoder_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/audio_decoder_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,248 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/audio_decoder_wrapper.h" - -#include -#include - -#include "base/logging.h" -#include "chromecast/media/api/decoder_buffer_base.h" -#include "chromecast/media/common/media_pipeline_backend_manager.h" -#include "chromecast/public/media/cast_decoder_buffer.h" - -namespace chromecast { -namespace media { - -namespace { - -// This revoked AudioDecoder would behave as one with buffer filled up and -// doesn't advance |statistics| and doesn't change RenderingDelay. -class RevokedAudioDecoderWrapper : public DestructableAudioDecoder { - public: - RevokedAudioDecoderWrapper(RenderingDelay rendering_delay, - Statistics statistics, - AudioTrackTimestamp audio_track_timestamp, - int start_threshold_in_frames, - bool requires_decryption) - : rendering_delay_(rendering_delay), - statistics_(statistics), - audio_track_timestamp_(audio_track_timestamp), - start_threshold_in_frames_(start_threshold_in_frames), - requires_decryption_(requires_decryption) {} - - RevokedAudioDecoderWrapper(const RevokedAudioDecoderWrapper&) = delete; - RevokedAudioDecoderWrapper& operator=(const RevokedAudioDecoderWrapper&) = - delete; - - ~RevokedAudioDecoderWrapper() override = default; - - private: - // DestructableAudioDecoder implementation: - void OnInitialized() override {} - void SetDelegate(Delegate* delegate) override {} - BufferStatus PushBuffer(scoped_refptr buffer) override { - return MediaPipelineBackend::kBufferPending; - } - bool SetConfig(const AudioConfig& config) override { return true; } - bool SetVolume(float multiplier) override { return true; } - RenderingDelay GetRenderingDelay() override { return rendering_delay_; } - void GetStatistics(Statistics* statistics) override { - *statistics = statistics_; - } - AudioTrackTimestamp GetAudioTrackTimestamp() override { - return audio_track_timestamp_; - } - int GetStartThresholdInFrames() override { - return start_threshold_in_frames_; - } - bool RequiresDecryption() override { return requires_decryption_; } - - const RenderingDelay rendering_delay_; - const Statistics statistics_; - const AudioTrackTimestamp audio_track_timestamp_; - const int start_threshold_in_frames_; - const bool requires_decryption_; -}; - -} // namespace - -ActiveAudioDecoderWrapper::ActiveAudioDecoderWrapper( - MediaPipelineBackend::AudioDecoder* backend_decoder, - AudioContentType type, - MediaPipelineBackendManager::BufferDelegate* buffer_delegate) - : decoder_(backend_decoder), - content_type_(type), - buffer_delegate_(buffer_delegate), - initialized_(false), - delegate_active_(false), - stream_volume_multiplier_(1.0f) { - if (buffer_delegate_) { - buffer_delegate_->OnStreamStarted(); - } -} - -ActiveAudioDecoderWrapper::~ActiveAudioDecoderWrapper() { - if (buffer_delegate_) { - buffer_delegate_->OnStreamStopped(); - } -} - -void ActiveAudioDecoderWrapper::OnInitialized() { - initialized_ = true; - if (!delegate_active_) { - decoder_.SetVolume(stream_volume_multiplier_); - } -} - -void ActiveAudioDecoderWrapper::SetDelegate(Delegate* delegate) { - decoder_.SetDelegate(delegate); -} - -CmaBackend::BufferStatus ActiveAudioDecoderWrapper::PushBuffer( - scoped_refptr buffer) { - if (buffer_delegate_ && buffer_delegate_->IsActive()) { - // Mute the decoder, we are sending audio to delegate. - if (!delegate_active_) { - delegate_active_ = true; - decoder_.SetVolume(0.0); - } - buffer_delegate_->OnPushBuffer(buffer.get()); - } else { - // Restore original volume. - if (delegate_active_) { - delegate_active_ = false; - if (!decoder_.SetVolume(stream_volume_multiplier_)) { - LOG(ERROR) << "SetVolume failed"; - } - } - } - - // Retain the buffer. Backend expects pipeline to hold the buffer until - // Decoder::Delegate::OnBufferComplete is called. - // TODO: Release the buffer at a proper time. - pushed_buffer_ = std::move(buffer); - return decoder_.PushBuffer(pushed_buffer_.get()); -} - -bool ActiveAudioDecoderWrapper::SetConfig(const AudioConfig& config) { - if (buffer_delegate_) { - buffer_delegate_->OnSetConfig(config); - } - return decoder_.SetConfig(config); -} - -bool ActiveAudioDecoderWrapper::SetVolume(float multiplier) { - stream_volume_multiplier_ = std::max(0.0f, multiplier); - if (buffer_delegate_) { - buffer_delegate_->OnSetVolume(stream_volume_multiplier_); - } - - if (delegate_active_ || !initialized_) { - return true; - } - return decoder_.SetVolume(stream_volume_multiplier_); -} - -ActiveAudioDecoderWrapper::RenderingDelay -ActiveAudioDecoderWrapper::GetRenderingDelay() { - return decoder_.GetRenderingDelay(); -} - -void ActiveAudioDecoderWrapper::GetStatistics(Statistics* statistics) { - decoder_.GetStatistics(statistics); -} - -ActiveAudioDecoderWrapper::AudioTrackTimestamp -ActiveAudioDecoderWrapper::GetAudioTrackTimestamp() { - return decoder_.GetAudioTrackTimestamp(); -} - -int ActiveAudioDecoderWrapper::GetStartThresholdInFrames() { - return decoder_.GetStartThresholdInFrames(); -} - -bool ActiveAudioDecoderWrapper::RequiresDecryption() { - return (MediaPipelineBackend::AudioDecoder::RequiresDecryption && - MediaPipelineBackend::AudioDecoder::RequiresDecryption()) || - decoder_.IsUsingSoftwareDecoder(); -} - -AudioDecoderWrapper::AudioDecoderWrapper( - MediaPipelineBackend::AudioDecoder* backend_decoder, - AudioContentType type, - MediaPipelineBackendManager::BufferDelegate* buffer_delegate) - : decoder_revoked_(false) { - audio_decoder_ = std::make_unique( - backend_decoder, type, buffer_delegate); -} - -AudioDecoderWrapper::AudioDecoderWrapper(AudioContentType type) - : decoder_revoked_(true) { - audio_decoder_ = std::make_unique( - RenderingDelay(), Statistics(), AudioTrackTimestamp(), - 0 /* start_threshold_in_frames */, false); -} - -AudioDecoderWrapper::~AudioDecoderWrapper() = default; - -void AudioDecoderWrapper::OnInitialized() { - audio_decoder_->OnInitialized(); -} - -void AudioDecoderWrapper::Revoke() { - if (!decoder_revoked_) { - decoder_revoked_ = true; - // Get some current values from audio_decoder_(ActiveAudioDecoderWrapper), - // then replace the audio_decoder_ with a revoked one. - Statistics statistics; - audio_decoder_->GetStatistics(&statistics); - audio_decoder_ = std::make_unique( - audio_decoder_->GetRenderingDelay(), statistics, - audio_decoder_->GetAudioTrackTimestamp(), - audio_decoder_->GetStartThresholdInFrames(), - audio_decoder_->RequiresDecryption()); - } -} - -void AudioDecoderWrapper::SetDelegate(Delegate* delegate) { - audio_decoder_->SetDelegate(delegate); -} - -AudioDecoderWrapper::BufferStatus AudioDecoderWrapper::PushBuffer( - scoped_refptr buffer) { - return audio_decoder_->PushBuffer(buffer); -} - -bool AudioDecoderWrapper::SetConfig(const AudioConfig& config) { - return audio_decoder_->SetConfig(config); -} - -bool AudioDecoderWrapper::SetVolume(float multiplier) { - return audio_decoder_->SetVolume(multiplier); -} - -AudioDecoderWrapper::RenderingDelay AudioDecoderWrapper::GetRenderingDelay() { - return audio_decoder_->GetRenderingDelay(); -} - -void AudioDecoderWrapper::GetStatistics(Statistics* statistics) { - audio_decoder_->GetStatistics(statistics); -} - -AudioDecoderWrapper::AudioTrackTimestamp -AudioDecoderWrapper::GetAudioTrackTimestamp() { - return audio_decoder_->GetAudioTrackTimestamp(); -} - -int AudioDecoderWrapper::GetStartThresholdInFrames() { - return audio_decoder_->GetStartThresholdInFrames(); -} - -bool AudioDecoderWrapper::RequiresDecryption() { - return audio_decoder_->RequiresDecryption(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/audio_decoder_wrapper.h chromium-132.0.6834.159/chromecast/media/common/audio_decoder_wrapper.h --- chromium-132.0.6834.110/chromecast/media/common/audio_decoder_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/audio_decoder_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,107 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_COMMON_AUDIO_DECODER_WRAPPER_H_ -#define CHROMECAST_MEDIA_COMMON_AUDIO_DECODER_WRAPPER_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/common/audio_decoder_software_wrapper.h" -#include "chromecast/media/common/media_pipeline_backend_manager.h" -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -namespace media { - -enum class AudioContentType; - -// Make the destructor of CmaBackend::AudioDecoder() public. -class DestructableAudioDecoder : public CmaBackend::AudioDecoder { - public: - ~DestructableAudioDecoder() override = default; - - virtual void OnInitialized() = 0; -}; - -class ActiveAudioDecoderWrapper : public DestructableAudioDecoder { - public: - ActiveAudioDecoderWrapper( - MediaPipelineBackend::AudioDecoder* backend_decoder, - AudioContentType type, - MediaPipelineBackendManager::BufferDelegate* buffer_delegate); - - ActiveAudioDecoderWrapper(const ActiveAudioDecoderWrapper&) = delete; - ActiveAudioDecoderWrapper& operator=(const ActiveAudioDecoderWrapper&) = - delete; - - ~ActiveAudioDecoderWrapper() override; - - AudioContentType content_type() const { return content_type_; } - - private: - // DestructableAudioDecoder implementation: - void OnInitialized() override; - void SetDelegate(Delegate* delegate) override; - BufferStatus PushBuffer(scoped_refptr buffer) override; - bool SetConfig(const AudioConfig& config) override; - bool SetVolume(float multiplier) override; - RenderingDelay GetRenderingDelay() override; - void GetStatistics(Statistics* statistics) override; - AudioTrackTimestamp GetAudioTrackTimestamp() override; - int GetStartThresholdInFrames() override; - bool RequiresDecryption() override; - - AudioDecoderSoftwareWrapper decoder_; - const AudioContentType content_type_; - - MediaPipelineBackendManager::BufferDelegate* const buffer_delegate_; - bool initialized_; - bool delegate_active_; - - float stream_volume_multiplier_; - - scoped_refptr pushed_buffer_; -}; - -class AudioDecoderWrapper : public CmaBackend::AudioDecoder { - public: - // Create a functional "real" AudioDecoder. - AudioDecoderWrapper( - MediaPipelineBackend::AudioDecoder* backend_decoder, - AudioContentType type, - MediaPipelineBackendManager::BufferDelegate* buffer_delegate); - // Create a "fake" AudioDecoder that's already in revoked state. - AudioDecoderWrapper(AudioContentType type); - - AudioDecoderWrapper(const AudioDecoderWrapper&) = delete; - AudioDecoderWrapper& operator=(const AudioDecoderWrapper&) = delete; - - ~AudioDecoderWrapper() override; - - void OnInitialized(); - void Revoke(); - - private: - // CmaBackend::AudioDecoder implementation: - void SetDelegate(Delegate* delegate) override; - BufferStatus PushBuffer(scoped_refptr buffer) override; - bool SetConfig(const AudioConfig& config) override; - bool SetVolume(float multiplier) override; - RenderingDelay GetRenderingDelay() override; - void GetStatistics(Statistics* statistics) override; - AudioTrackTimestamp GetAudioTrackTimestamp() override; - int GetStartThresholdInFrames() override; - bool RequiresDecryption() override; - - bool decoder_revoked_; - - std::unique_ptr audio_decoder_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_COMMON_AUDIO_DECODER_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/common/base/decoder_config_logging.cc chromium-132.0.6834.159/chromecast/media/common/base/decoder_config_logging.cc --- chromium-132.0.6834.110/chromecast/media/common/base/decoder_config_logging.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/base/decoder_config_logging.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/base/decoder_config_logging.h" - -#include "base/notreached.h" - -std::ostream& operator<<(std::ostream& stream, - ::chromecast::media::AudioCodec codec) { - switch (codec) { - case ::chromecast::media::kAudioCodecUnknown: - return stream << "unknown"; - case ::chromecast::media::kCodecAAC: - return stream << "AAC"; - case ::chromecast::media::kCodecMP3: - return stream << "MP3"; - case ::chromecast::media::kCodecPCM: - return stream << "PCM"; - case ::chromecast::media::kCodecPCM_S16BE: - return stream << "PCM_S16BE"; - case ::chromecast::media::kCodecVorbis: - return stream << "Vorbis"; - case ::chromecast::media::kCodecOpus: - return stream << "Opus"; - case ::chromecast::media::kCodecEAC3: - return stream << "EAC3"; - case ::chromecast::media::kCodecAC3: - return stream << "AC3"; - case ::chromecast::media::kCodecDTS: - return stream << "DTS"; - case ::chromecast::media::kCodecDTSXP2: - return stream << "DTS:X Profile 2"; - case ::chromecast::media::kCodecDTSE: - return stream << "DTS Express"; - case ::chromecast::media::kCodecFLAC: - return stream << "FLAC"; - case ::chromecast::media::kCodecMpegHAudio: - return stream << "MPEG-H Audio"; - } - NOTREACHED(); -} - -std::ostream& operator<<(std::ostream& stream, - ::chromecast::media::SampleFormat format) { - switch (format) { - case ::chromecast::media::kUnknownSampleFormat: - return stream << "unknown"; - case ::chromecast::media::kSampleFormatU8: - return stream << "interleaved unsigned 8-bit int"; - case ::chromecast::media::kSampleFormatS16: - return stream << "interleaved signed 16-bit int"; - case ::chromecast::media::kSampleFormatS32: - return stream << "interleaved signed 32-bit int"; - case ::chromecast::media::kSampleFormatF32: - return stream << "interleaved float"; - case ::chromecast::media::kSampleFormatPlanarS16: - return stream << "planar signed 16-bit int"; - case ::chromecast::media::kSampleFormatPlanarF32: - return stream << "planar float"; - case ::chromecast::media::kSampleFormatPlanarS32: - return stream << "planar signed 32-bit int"; - case ::chromecast::media::kSampleFormatS24: - return stream << "interleaved signed 24-bit int"; - case ::chromecast::media::kSampleFormatPlanarU8: - return stream << "planar unsigned 8-bit int"; - } - NOTREACHED(); -} diff -Nru chromium-132.0.6834.110/chromecast/media/common/base/decoder_config_logging.h chromium-132.0.6834.159/chromecast/media/common/base/decoder_config_logging.h --- chromium-132.0.6834.110/chromecast/media/common/base/decoder_config_logging.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/base/decoder_config_logging.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_COMMON_BASE_DECODER_CONFIG_LOGGING_H_ -#define CHROMECAST_MEDIA_COMMON_BASE_DECODER_CONFIG_LOGGING_H_ - -#include - -#include "chromecast/public/media/decoder_config.h" - -std::ostream& operator<<(std::ostream& stream, - ::chromecast::media::AudioCodec codec); -std::ostream& operator<<(std::ostream& stream, - ::chromecast::media::SampleFormat format); - -#endif // CHROMECAST_MEDIA_COMMON_BASE_DECODER_CONFIG_LOGGING_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/common/media_pipeline_backend_manager.cc chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_manager.cc --- chromium-132.0.6834.110/chromecast/media/common/media_pipeline_backend_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,290 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/media_pipeline_backend_manager.h" - -#include -#include -#include - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/common/audio_decoder_wrapper.h" -#include "chromecast/media/common/media_pipeline_backend_wrapper.h" -#include "chromecast/public/volume_control.h" - -#define RUN_ON_MEDIA_THREAD(method, ...) \ - media_task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&MediaPipelineBackendManager::method, \ - weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); - -#define MAKE_SURE_MEDIA_THREAD(method, ...) \ - if (!media_task_runner_->BelongsToCurrentThread()) { \ - RUN_ON_MEDIA_THREAD(method, ##__VA_ARGS__) \ - return; \ - } - -namespace chromecast { -namespace media { - -namespace { - -constexpr int kAudioDecoderLimit = std::numeric_limits::max(); -constexpr int kVideoDecoderLimit = 1; -constexpr base::TimeDelta kPowerSaveWaitTime = base::Seconds(5); - -} // namespace - -MediaPipelineBackendManager::MediaPipelineBackendManager( - scoped_refptr media_task_runner, - MediaResourceTracker* media_resource_tracker) - : media_task_runner_(std::move(media_task_runner)), - media_resource_tracker_(media_resource_tracker), - playing_audio_streams_count_({{AudioContentType::kMedia, 0}, - {AudioContentType::kAlarm, 0}, - {AudioContentType::kCommunication, 0}, - {AudioContentType::kOther, 0}}), - playing_noneffects_audio_streams_count_( - {{AudioContentType::kMedia, 0}, - {AudioContentType::kAlarm, 0}, - {AudioContentType::kCommunication, 0}, - {AudioContentType::kOther, 0}}), - active_audio_stream_observers_( - base::MakeRefCounted< - base::ObserverListThreadSafe>()), - backend_wrapper_using_video_decoder_(nullptr), - buffer_delegate_(nullptr), - weak_factory_(this) { - DCHECK(media_task_runner_); - DCHECK_EQ(playing_audio_streams_count_.size(), - static_cast(AudioContentType::kNumTypes)); - DCHECK_EQ(playing_noneffects_audio_streams_count_.size(), - static_cast(AudioContentType::kNumTypes)); - for (int i = 0; i < NUM_DECODER_TYPES; ++i) { - decoder_count_[i] = 0; - } - - RUN_ON_MEDIA_THREAD(CreateMixerConnection); -} - -MediaPipelineBackendManager::~MediaPipelineBackendManager() { - DCHECK(media_task_runner_->BelongsToCurrentThread()); -} - -std::unique_ptr MediaPipelineBackendManager::CreateBackend( - const media::MediaPipelineDeviceParams& params) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - return std::make_unique(params, this, - media_resource_tracker_); -} - -scoped_refptr -MediaPipelineBackendManager::GetMediaTaskRunner() { - return media_task_runner_; -} - -void MediaPipelineBackendManager::BackendDestroyed( - MediaPipelineBackendWrapper* backend_wrapper) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - if (backend_wrapper_using_video_decoder_ == backend_wrapper) { - backend_wrapper_using_video_decoder_ = nullptr; - } -} - -void MediaPipelineBackendManager::BackendUseVideoDecoder( - MediaPipelineBackendWrapper* backend_wrapper) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - DCHECK(backend_wrapper); - if (backend_wrapper_using_video_decoder_ && - backend_wrapper_using_video_decoder_ != backend_wrapper) { - LOG(INFO) << __func__ << " revoke old backend : " - << backend_wrapper_using_video_decoder_; - backend_wrapper_using_video_decoder_->Revoke(); - } - backend_wrapper_using_video_decoder_ = backend_wrapper; -} - -bool MediaPipelineBackendManager::IncrementDecoderCount(DecoderType type) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - DCHECK(type < NUM_DECODER_TYPES); - const int limit = - (type == VIDEO_DECODER) ? kVideoDecoderLimit : kAudioDecoderLimit; - if (decoder_count_[type] >= limit) { - LOG(WARNING) << "Decoder limit reached for type " << type; - return false; - } - - ++decoder_count_[type]; - return true; -} - -void MediaPipelineBackendManager::DecrementDecoderCount(DecoderType type) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - DCHECK(type < NUM_DECODER_TYPES); - DCHECK_GT(decoder_count_[type], 0); - - decoder_count_[type]--; -} - -void MediaPipelineBackendManager::UpdatePlayingAudioCount( - bool sfx, - const AudioContentType type, - int change) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - DCHECK(change == -1 || change == 1) << "bad count change: " << change; - - bool had_playing_audio_streams = (TotalPlayingAudioStreamsCount() > 0); - bool had_playing_primary_streams = - (TotalPlayingNoneffectsAudioStreamsCount() > 0); - - playing_audio_streams_count_[type] += change; - DCHECK_GE(playing_audio_streams_count_[type], 0); - - if (!sfx) { - playing_noneffects_audio_streams_count_[type] += change; - DCHECK_GE(playing_noneffects_audio_streams_count_[type], 0); - } - - HandlePlayingAudioStreamsChange(had_playing_audio_streams, - had_playing_primary_streams); -} - -void MediaPipelineBackendManager::OnMixerStreamCountChange(int primary_streams, - int sfx_streams) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - bool had_playing_audio_streams = (TotalPlayingAudioStreamsCount() > 0); - bool had_playing_primary_streams = - (TotalPlayingNoneffectsAudioStreamsCount() > 0); - - mixer_primary_stream_count_ = primary_streams; - mixer_sfx_stream_count_ = sfx_streams; - - HandlePlayingAudioStreamsChange(had_playing_audio_streams, - had_playing_primary_streams); -} - -void MediaPipelineBackendManager::HandlePlayingAudioStreamsChange( - bool had_playing_audio_streams, - bool had_playing_primary_streams) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - int new_playing_audio_streams = TotalPlayingAudioStreamsCount(); - if (new_playing_audio_streams == 0) { - power_save_timer_.Start(FROM_HERE, kPowerSaveWaitTime, this, - &MediaPipelineBackendManager::EnterPowerSaveMode); - } else if (!had_playing_audio_streams && new_playing_audio_streams > 0) { - if (power_save_timer_.IsRunning()) { - metrics::CastMetricsHelper::GetInstance()->RecordSimpleAction( - "Cast.Platform.VolumeControl.PowerSaveTimerCancelled"); - } - power_save_timer_.Stop(); - if (VolumeControl::SetPowerSaveMode) { - metrics::CastMetricsHelper::GetInstance()->RecordSimpleAction( - "Cast.Platform.VolumeControl.PowerSaveOff"); - VolumeControl::SetPowerSaveMode(false); - } - } - - bool new_playing_primary_streams = - (TotalPlayingNoneffectsAudioStreamsCount() > 0); - if (new_playing_primary_streams != had_playing_primary_streams) { - active_audio_stream_observers_->Notify( - FROM_HERE, &ActiveAudioStreamObserver::OnActiveAudioStreamChange, - new_playing_primary_streams); - } -} - -int MediaPipelineBackendManager::TotalPlayingAudioStreamsCount() { - int total = 0; - for (auto entry : playing_audio_streams_count_) { - total += entry.second; - } - return std::max(total, mixer_primary_stream_count_ + mixer_sfx_stream_count_); -} - -int MediaPipelineBackendManager::TotalPlayingNoneffectsAudioStreamsCount() { - int total = 0; - for (auto entry : playing_noneffects_audio_streams_count_) { - total += entry.second; - } - return std::max(total, mixer_primary_stream_count_); -} - -void MediaPipelineBackendManager::EnterPowerSaveMode() { - DCHECK_EQ(TotalPlayingAudioStreamsCount(), 0); - if (!VolumeControl::SetPowerSaveMode || !power_save_enabled_) { - return; - } - metrics::CastMetricsHelper::GetInstance()->RecordSimpleAction( - "Cast.Platform.VolumeControl.PowerSaveOn"); - VolumeControl::SetPowerSaveMode(true); -} - -void MediaPipelineBackendManager::AddActiveAudioStreamObserver( - ActiveAudioStreamObserver* observer) { - active_audio_stream_observers_->AddObserver(observer); -} - -void MediaPipelineBackendManager::RemoveActiveAudioStreamObserver( - ActiveAudioStreamObserver* observer) { - active_audio_stream_observers_->RemoveObserver(observer); -} - -void MediaPipelineBackendManager::AddExtraPlayingStream( - bool sfx, - const AudioContentType type) { - MAKE_SURE_MEDIA_THREAD(AddExtraPlayingStream, sfx, type); - UpdatePlayingAudioCount(sfx, type, 1); -} - -void MediaPipelineBackendManager::RemoveExtraPlayingStream( - bool sfx, - const AudioContentType type) { - MAKE_SURE_MEDIA_THREAD(RemoveExtraPlayingStream, sfx, type); - UpdatePlayingAudioCount(sfx, type, -1); -} - -void MediaPipelineBackendManager::SetBufferDelegate( - BufferDelegate* buffer_delegate) { - MAKE_SURE_MEDIA_THREAD(SetBufferDelegate, buffer_delegate); - DCHECK(buffer_delegate); - DCHECK(!buffer_delegate_); - buffer_delegate_ = buffer_delegate; -} - -void MediaPipelineBackendManager::SetPowerSaveEnabled(bool power_save_enabled) { - MAKE_SURE_MEDIA_THREAD(SetPowerSaveEnabled, power_save_enabled); - power_save_enabled_ = power_save_enabled; - if (!VolumeControl::SetPowerSaveMode) { - return; - } - if (!power_save_enabled_) { - VolumeControl::SetPowerSaveMode(false); - } else if (!power_save_timer_.IsRunning() && - TotalPlayingAudioStreamsCount() == 0) { - EnterPowerSaveMode(); - } -} - -void MediaPipelineBackendManager::TemporaryDisablePowerSave() { - MAKE_SURE_MEDIA_THREAD(TemporaryDisablePowerSave); - int playing_audio_streams = TotalPlayingAudioStreamsCount(); - if (playing_audio_streams == 0) { - if (VolumeControl::SetPowerSaveMode) { - LOG(INFO) << "Temporarily disable power save"; - VolumeControl::SetPowerSaveMode(false); - power_save_timer_.Start(FROM_HERE, kPowerSaveWaitTime, this, - &MediaPipelineBackendManager::EnterPowerSaveMode); - } - } -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/media_pipeline_backend_manager.h chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_manager.h --- chromium-132.0.6834.110/chromecast/media/common/media_pipeline_backend_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,206 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_COMMON_MEDIA_PIPELINE_BACKEND_MANAGER_H_ -#define CHROMECAST_MEDIA_COMMON_MEDIA_PIPELINE_BACKEND_MANAGER_H_ - -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list_threadsafe.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/timer/timer.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { - -enum class AudioContentType; -class CastDecoderBuffer; -class CmaBackend; -class MediaPipelineBackendWrapper; -class ActiveMediaPipelineBackendWrapper; -class MediaResourceTracker; - -// This class tracks all created media backends, tracking whether or not volume -// feedback sounds should be enabled based on the currently active backends. -// Volume feedback sounds are only enabled when there are no active audio -// streams (apart from sound-effects streams). -class MediaPipelineBackendManager : public media::CmaBackendFactory { - public: - class ActiveAudioStreamObserver { - public: - // Called when we transition between "no active audio streams" and - // "have at least one active audio stream" states. For this purpose, sound - // effects streams are ignored. - virtual void OnActiveAudioStreamChange(bool have_active_streams) = 0; - - protected: - virtual ~ActiveAudioStreamObserver() = default; - }; - - // Delegate which can process Audio buffers sent to us. - class BufferDelegate { - public: - // Returns |true| if the delegate is accepting buffers. - virtual bool IsActive() = 0; - - // Called when calls to |OnPushBuffer| will start. - virtual void OnStreamStarted() = 0; - - // Called when calls to |OnPushBuffer| will stop. - virtual void OnStreamStopped() = 0; - - // If |IsActive| returns true, the media stream's audio buffers will be sent - // to the delegate and the media stream's volume will be set to 0. - // - // The client may only assume the buffer is in scope during the callback. - // If the client needs to use the buffer out of scope of the callback (e.g. - // posted onto a different thread), it must make a copy. - virtual void OnPushBuffer(const CastDecoderBuffer* buffer) = 0; - - // Called when the media stream's audio config changes. After this call, all - // subsequent buffers will have the new config. This method will be called - // regardless if |IsActive| returs true or false. - virtual void OnSetConfig(const AudioConfig& config) = 0; - - // Called when volume changes. |volume| is from [0.0, 1.0]. - virtual void OnSetVolume(float volume) = 0; - - protected: - virtual ~BufferDelegate() = default; - }; - - enum DecoderType { - AUDIO_DECODER, - VIDEO_DECODER, - SFX_DECODER, - NUM_DECODER_TYPES - }; - - MediaPipelineBackendManager( - scoped_refptr media_task_runner, - MediaResourceTracker* media_resource_tracker); - - MediaPipelineBackendManager(const MediaPipelineBackendManager&) = delete; - MediaPipelineBackendManager& operator=(const MediaPipelineBackendManager&) = - delete; - - ~MediaPipelineBackendManager() override; - - // media::CmaBackendFactory implementation: - std::unique_ptr CreateBackend( - const MediaPipelineDeviceParams& params) override; - scoped_refptr GetMediaTaskRunner() override; - - // Inform that a backend previously created is destroyed. - // Must be called on the same thread as |media_task_runner_|. - void BackendDestroyed(MediaPipelineBackendWrapper* backend_wrapper); - // |backend_wrapper| will use a VideoDecoder. - // MediaPipelineBackendManager needs to record the backend that uses the - // VideoDecoder; and if there is an active backend using VideoDecoder, that - // backend needs to be revoked. - // Must be called on the same thread as |media_task_runner_|. - void BackendUseVideoDecoder(MediaPipelineBackendWrapper* backend_wrapper); - - base::SingleThreadTaskRunner* task_runner() const { - return media_task_runner_.get(); - } - - // Adds/removes an observer for when volume feedback sounds are allowed. - // An observer must be removed on the same thread that added it. - void AddActiveAudioStreamObserver(ActiveAudioStreamObserver* observer); - void RemoveActiveAudioStreamObserver(ActiveAudioStreamObserver* observer); - - // Add/remove a playing audio stream that is not accounted for by a - // CmaBackend instance. |sfx| indicates whether or not the stream is a sound - // effects stream (has no effect on volume feedback). - void AddExtraPlayingStream(bool sfx, const AudioContentType type); - void RemoveExtraPlayingStream(bool sfx, const AudioContentType type); - - // |buffer_delegate| will get notified for all buffers on the media stream. - // |buffer_delegate| must outlive |this|. - // Can only be set once. - void SetBufferDelegate(BufferDelegate* buffer_delegate); - - BufferDelegate* buffer_delegate() const { return buffer_delegate_; } - - // If |power_save_enabled| is |false|, power save will be turned off and - // automatic power save will be disabled until this is called with |true|. - void SetPowerSaveEnabled(bool power_save_enabled); - - // Temporarily disables power save mode even if there are no currently-playing - // audio streams. Useful to disable power save ahead of time if audio will - // start playing soon (within 5 seconds). - void TemporaryDisablePowerSave(); - - private: - friend class ActiveMediaPipelineBackendWrapper; - - class MixerConnection { - public: - virtual ~MixerConnection() = default; - }; - - void CreateMixerConnection(); - - // Backend wrapper instances must use these APIs when allocating and releasing - // decoder objects, so we can enforce global limit on #concurrent decoders. - bool IncrementDecoderCount(DecoderType type); - void DecrementDecoderCount(DecoderType type); - - // Update the count of playing non-effects audio streams. - void UpdatePlayingAudioCount(bool sfx, - const AudioContentType type, - int change); - void OnMixerStreamCountChange(int primary_streams, int sfx_streams); - void HandlePlayingAudioStreamsChange(bool had_playing_audio_streams, - bool had_playing_primary_streams); - int TotalPlayingAudioStreamsCount(); - int TotalPlayingNoneffectsAudioStreamsCount(); - - void EnterPowerSaveMode(); - - const scoped_refptr media_task_runner_; - MediaResourceTracker* const media_resource_tracker_; - - // Total count of decoders created - int decoder_count_[NUM_DECODER_TYPES]; - - // Total number of playing audio streams. - base::flat_map playing_audio_streams_count_; - - // Total number of playing non-effects streams. - base::flat_map playing_noneffects_audio_streams_count_; - - scoped_refptr> - active_audio_stream_observers_; - - // Previously issued MediaPipelineBackendWrapper that uses a video decoder. - MediaPipelineBackendWrapper* backend_wrapper_using_video_decoder_; - - BufferDelegate* buffer_delegate_; - - bool power_save_enabled_ = true; - - base::OneShotTimer power_save_timer_; - - std::unique_ptr mixer_connection_; - int mixer_primary_stream_count_ = 0; - int mixer_sfx_stream_count_ = 0; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_COMMON_MEDIA_PIPELINE_BACKEND_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/common/media_pipeline_backend_wrapper.cc chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_wrapper.cc --- chromium-132.0.6834.110/chromecast/media/common/media_pipeline_backend_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,373 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/media_pipeline_backend_wrapper.h" - -#include "base/check.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/notreached.h" -#include "chromecast/media/common/audio_decoder_wrapper.h" -#include "chromecast/media/common/media_pipeline_backend_manager.h" -#include "chromecast/media/common/video_decoder_wrapper.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { -namespace { - -std::unique_ptr CreateMediaPipelineBackend( - const media::MediaPipelineDeviceParams& params) { - LOG(INFO) << "Beginning creation of MediaPipelineBackend..."; - auto backend = base::WrapUnique( - media::CastMediaShlib::CreateMediaPipelineBackend(params)); - LOG(INFO) << "Completed creation of MediaPipelineBackend!"; - return backend; -} - -} // namespace - -using DecoderType = MediaPipelineBackendManager::DecoderType; - -// DecoderCreatorCmaBackend transfers the ownership of the created Decoders. -class DecoderCreatorCmaBackend : public CmaBackend { - public: - virtual std::unique_ptr CreateAudioDecoderWrapper() = 0; - virtual std::unique_ptr CreateVideoDecoderWrapper() = 0; -}; - -namespace { - -class RevokedMediaPipelineBackendWrapper : public DecoderCreatorCmaBackend { - public: - RevokedMediaPipelineBackendWrapper(const AudioContentType& content_type, - int64_t current_pts) - : content_type_(content_type), current_pts_(current_pts) {} - - RevokedMediaPipelineBackendWrapper( - const RevokedMediaPipelineBackendWrapper&) = delete; - RevokedMediaPipelineBackendWrapper& operator=( - const RevokedMediaPipelineBackendWrapper&) = delete; - - ~RevokedMediaPipelineBackendWrapper() override = default; - - std::unique_ptr CreateAudioDecoderWrapper() override { - return std::make_unique(content_type_); - } - - std::unique_ptr CreateVideoDecoderWrapper() override { - return std::make_unique(); - } - - // CmaBackend implementation: - CmaBackend::AudioDecoder* CreateAudioDecoder() override { NOTREACHED(); } - - CmaBackend::VideoDecoder* CreateVideoDecoder() override { NOTREACHED(); } - - bool Initialize() override { return true; } - bool Start(int64_t start_pts) override { return true; } - void Stop() override {} - bool Pause() override { return true; } - bool Resume() override { return true; } - int64_t GetCurrentPts() override { return current_pts_; } - bool SetPlaybackRate(float rate) override { return true; } - void LogicalPause() override {} - void LogicalResume() override {} - - private: - const AudioContentType content_type_; - const int64_t current_pts_; -}; - -} // namespace - -class ActiveMediaPipelineBackendWrapper : public DecoderCreatorCmaBackend { - public: - ActiveMediaPipelineBackendWrapper( - const media::MediaPipelineDeviceParams& params, - MediaPipelineBackendWrapper* wrapping_backend, - MediaPipelineBackendManager* backend_manager, - MediaResourceTracker* media_resource_tracker); - - ActiveMediaPipelineBackendWrapper(const ActiveMediaPipelineBackendWrapper&) = - delete; - ActiveMediaPipelineBackendWrapper& operator=( - const ActiveMediaPipelineBackendWrapper&) = delete; - - ~ActiveMediaPipelineBackendWrapper() override; - - // DecoderCreatorCmaBackend implementation: - // Audio/VideoDecoders are owned by the MediaPipelineBackendWrapper. - std::unique_ptr CreateAudioDecoderWrapper() override; - std::unique_ptr CreateVideoDecoderWrapper() override; - - // CmaBackend implementation: - AudioDecoder* CreateAudioDecoder() override; - VideoDecoder* CreateVideoDecoder() override; - bool Initialize() override; - bool Start(int64_t start_pts) override; - void Stop() override; - bool Pause() override; - bool Resume() override; - int64_t GetCurrentPts() override; - bool SetPlaybackRate(float rate) override; - void LogicalPause() override; - void LogicalResume() override; - - private: - void SetPlaying(bool playing); - - bool IsSfx() { - return audio_stream_type_ == - media::MediaPipelineDeviceParams::kAudioStreamSoundEffects; - } - - AudioDecoderWrapper* audio_decoder_ptr_; - bool video_decoder_created_; - const std::unique_ptr backend_; - MediaPipelineBackendWrapper* const wrapping_backend_; - MediaPipelineBackendManager* const backend_manager_; - const MediaPipelineDeviceParams::AudioStreamType audio_stream_type_; - const AudioContentType content_type_; - - // Acquire the media resource at construction. The resource will be released - // when this class is destructed. - MediaResourceTracker::ScopedUsage media_resource_usage_; - - bool playing_; -}; - -ActiveMediaPipelineBackendWrapper::ActiveMediaPipelineBackendWrapper( - const media::MediaPipelineDeviceParams& params, - MediaPipelineBackendWrapper* wrapping_backend, - MediaPipelineBackendManager* backend_manager, - MediaResourceTracker* media_resource_tracker) - : audio_decoder_ptr_(nullptr), - video_decoder_created_(false), - backend_(CreateMediaPipelineBackend(params)), - wrapping_backend_(wrapping_backend), - backend_manager_(backend_manager), - audio_stream_type_(params.audio_type), - content_type_(params.content_type), - media_resource_usage_(media_resource_tracker), - playing_(false) { - DCHECK(backend_); - DCHECK(backend_manager_); -} - -ActiveMediaPipelineBackendWrapper::~ActiveMediaPipelineBackendWrapper() { - // When the backend is revoked, the video/audio_decoder should be considered - // gone to |backend_manager_|. The reason is that the replacement of the - // Audio/VideoDecoderWrapper are dummy ones that are not actually playing. - if (audio_decoder_ptr_) { - backend_manager_->DecrementDecoderCount( - IsSfx() ? DecoderType::SFX_DECODER : DecoderType::AUDIO_DECODER); - if (playing_) { - backend_manager_->UpdatePlayingAudioCount(IsSfx(), content_type_, -1); - } - } - if (video_decoder_created_) { - backend_manager_->DecrementDecoderCount(DecoderType::VIDEO_DECODER); - } -} - -CmaBackend::AudioDecoder* -ActiveMediaPipelineBackendWrapper::CreateAudioDecoder() { - NOTREACHED(); -} - -CmaBackend::VideoDecoder* -ActiveMediaPipelineBackendWrapper::CreateVideoDecoder() { - NOTREACHED(); -} - -void ActiveMediaPipelineBackendWrapper::LogicalPause() { - SetPlaying(false); -} - -void ActiveMediaPipelineBackendWrapper::LogicalResume() { - SetPlaying(true); -} - -std::unique_ptr -ActiveMediaPipelineBackendWrapper::CreateAudioDecoderWrapper() { - DCHECK(!audio_decoder_ptr_); - - if (!backend_manager_->IncrementDecoderCount( - IsSfx() ? DecoderType::SFX_DECODER : DecoderType::AUDIO_DECODER)) - return nullptr; - MediaPipelineBackend::AudioDecoder* real_decoder = - backend_->CreateAudioDecoder(); - if (!real_decoder) { - return nullptr; - } - - MediaPipelineBackendManager::BufferDelegate* delegate = nullptr; - // Only set delegate for the primary media stream. - if (content_type_ == media::AudioContentType::kMedia && - audio_stream_type_ == - media::MediaPipelineDeviceParams::kAudioStreamNormal) { - delegate = backend_manager_->buffer_delegate(); - } - - auto audio_decoder = std::make_unique( - real_decoder, content_type_, delegate); - audio_decoder_ptr_ = audio_decoder.get(); - return audio_decoder; -} - -std::unique_ptr -ActiveMediaPipelineBackendWrapper::CreateVideoDecoderWrapper() { - DCHECK(!video_decoder_created_); - backend_manager_->BackendUseVideoDecoder(wrapping_backend_); - - if (!backend_manager_->IncrementDecoderCount(DecoderType::VIDEO_DECODER)) - return nullptr; - - MediaPipelineBackend::VideoDecoder* real_decoder = - backend_->CreateVideoDecoder(); - if (!real_decoder) { - return nullptr; - } - - video_decoder_created_ = true; - auto video_decoder = std::make_unique(real_decoder); - return video_decoder; -} - -bool ActiveMediaPipelineBackendWrapper::Initialize() { - LOG(INFO) << "Beginning initialization of MediaPipelineBackend..."; - bool success = backend_->Initialize(); - if (success && audio_decoder_ptr_) { - audio_decoder_ptr_->OnInitialized(); - } - LOG(INFO) << "Initialization of MediaPipelineBackend " - << (success ? "succeeded!" : "failed!"); - return success; -} - -bool ActiveMediaPipelineBackendWrapper::Start(int64_t start_pts) { - if (!backend_->Start(start_pts)) { - return false; - } - SetPlaying(true); - return true; -} - -void ActiveMediaPipelineBackendWrapper::Stop() { - backend_->Stop(); - SetPlaying(false); -} - -bool ActiveMediaPipelineBackendWrapper::Pause() { - if (!backend_->Pause()) { - return false; - } - SetPlaying(false); - return true; -} - -bool ActiveMediaPipelineBackendWrapper::Resume() { - if (!backend_->Resume()) { - return false; - } - SetPlaying(true); - return true; -} - -int64_t ActiveMediaPipelineBackendWrapper::GetCurrentPts() { - return backend_->GetCurrentPts(); -} - -bool ActiveMediaPipelineBackendWrapper::SetPlaybackRate(float rate) { - return backend_->SetPlaybackRate(rate); -} - -void ActiveMediaPipelineBackendWrapper::SetPlaying(bool playing) { - if (playing == playing_) { - return; - } - playing_ = playing; - if (audio_decoder_ptr_) { - backend_manager_->UpdatePlayingAudioCount(IsSfx(), content_type_, - (playing_ ? 1 : -1)); - } -} - -MediaPipelineBackendWrapper::MediaPipelineBackendWrapper( - const media::MediaPipelineDeviceParams& params, - MediaPipelineBackendManager* backend_manager, - MediaResourceTracker* media_resource_tracker) - : revoked_(false), - backend_manager_(backend_manager), - content_type_(params.content_type) { - backend_ = std::make_unique( - params, this, backend_manager, media_resource_tracker); -} - -MediaPipelineBackendWrapper::~MediaPipelineBackendWrapper() { - backend_manager_->BackendDestroyed(this); -} - -void MediaPipelineBackendWrapper::Revoke() { - if (!revoked_) { - revoked_ = true; - if (audio_decoder_) - audio_decoder_->Revoke(); - if (video_decoder_) - video_decoder_->Revoke(); - - backend_ = std::make_unique( - content_type_, backend_->GetCurrentPts()); - } -} - -CmaBackend::AudioDecoder* MediaPipelineBackendWrapper::CreateAudioDecoder() { - LOG(INFO) << "Beginning creation of AudioDecoder..."; - DCHECK(!audio_decoder_); - audio_decoder_ = backend_->CreateAudioDecoderWrapper(); - LOG(INFO) << "Completed creation of AudioDecoder!"; - return audio_decoder_.get(); -} - -CmaBackend::VideoDecoder* MediaPipelineBackendWrapper::CreateVideoDecoder() { - LOG(INFO) << "Beginning creation of VideoDecoder..."; - DCHECK(!video_decoder_); - video_decoder_ = backend_->CreateVideoDecoderWrapper(); - LOG(INFO) << "VideoDecoder creation of AudioDecoder!"; - return video_decoder_.get(); -} - -bool MediaPipelineBackendWrapper::Initialize() { - return backend_->Initialize(); -} -bool MediaPipelineBackendWrapper::Start(int64_t start_pts) { - return backend_->Start(start_pts); -} -void MediaPipelineBackendWrapper::Stop() { - backend_->Stop(); -} -bool MediaPipelineBackendWrapper::Pause() { - return backend_->Pause(); -} -bool MediaPipelineBackendWrapper::Resume() { - return backend_->Resume(); -} -int64_t MediaPipelineBackendWrapper::GetCurrentPts() { - return backend_->GetCurrentPts(); -} -bool MediaPipelineBackendWrapper::SetPlaybackRate(float rate) { - return backend_->SetPlaybackRate(rate); -} -void MediaPipelineBackendWrapper::LogicalPause() { - return backend_->LogicalPause(); -} -void MediaPipelineBackendWrapper::LogicalResume() { - return backend_->LogicalResume(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/media_pipeline_backend_wrapper.h chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_wrapper.h --- chromium-132.0.6834.110/chromecast/media/common/media_pipeline_backend_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/media_pipeline_backend_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_COMMON_MEDIA_PIPELINE_BACKEND_WRAPPER_H_ -#define CHROMECAST_MEDIA_COMMON_MEDIA_PIPELINE_BACKEND_WRAPPER_H_ - -#include - -#include - -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/media/common/media_resource_tracker.h" -#include "chromecast/public/media/media_pipeline_device_params.h" - -namespace chromecast { -namespace media { - -enum class AudioContentType; -class AudioDecoderWrapper; -class VideoDecoderWrapper; -class MediaPipelineBackend; -class MediaPipelineBackendManager; -class DecoderCreatorCmaBackend; - -class MediaPipelineBackendWrapper : public CmaBackend { - public: - MediaPipelineBackendWrapper(const media::MediaPipelineDeviceParams& params, - MediaPipelineBackendManager* backend_manager, - MediaResourceTracker* media_resource_tracker); - - MediaPipelineBackendWrapper(const MediaPipelineBackendWrapper&) = delete; - MediaPipelineBackendWrapper& operator=(const MediaPipelineBackendWrapper&) = - delete; - - ~MediaPipelineBackendWrapper() override; - - // After revocation, this class releases the media resource on the device, - // so the next MediaPipelineBackend can be created for the next application. - // See b/69180616. - void Revoke(); - - // CmaBackend implementation: - AudioDecoder* CreateAudioDecoder() override; - VideoDecoder* CreateVideoDecoder() override; - bool Initialize() override; - bool Start(int64_t start_pts) override; - void Stop() override; - bool Pause() override; - bool Resume() override; - int64_t GetCurrentPts() override; - bool SetPlaybackRate(float rate) override; - void LogicalPause() override; - void LogicalResume() override; - - private: - std::unique_ptr audio_decoder_; - std::unique_ptr video_decoder_; - - bool revoked_; - std::unique_ptr backend_; - MediaPipelineBackendManager* const backend_manager_; - const AudioContentType content_type_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_COMMON_MEDIA_PIPELINE_BACKEND_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/common/media_resource_tracker.cc chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker.cc --- chromium-132.0.6834.110/chromecast/media/common/media_resource_tracker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,163 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/media_resource_tracker.h" - -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/task/bind_post_task.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -MediaResourceTracker::ScopedUsage::ScopedUsage(MediaResourceTracker* tracker) - : tracker_(tracker) { - DCHECK(tracker_); - DCHECK(tracker_->media_task_runner_->BelongsToCurrentThread()); - tracker_->IncrementUsageCount(); -} - -MediaResourceTracker::ScopedUsage::~ScopedUsage() { - DCHECK(tracker_->media_task_runner_->BelongsToCurrentThread()); - tracker_->DecrementUsageCount(); -} - -MediaResourceTracker::MediaResourceTracker( - scoped_refptr ui_task_runner, - scoped_refptr media_task_runner) - : media_use_count_(0), - media_lib_initialized_(false), - delete_on_finalize_(false), - ui_task_runner_(std::move(ui_task_runner)), - media_task_runner_(std::move(media_task_runner)) { - DCHECK(ui_task_runner_); - DCHECK(media_task_runner_); - DCHECK(ui_task_runner_->BelongsToCurrentThread()); -} - -MediaResourceTracker::~MediaResourceTracker() {} - -void MediaResourceTracker::InitializeMediaLib() { - DCHECK(ui_task_runner_->BelongsToCurrentThread()); - media_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MediaResourceTracker::CallInitializeOnMediaThread, - base::Unretained(this))); -} - -void MediaResourceTracker::FinalizeMediaLib(base::OnceClosure completion_cb) { - DCHECK(ui_task_runner_->BelongsToCurrentThread()); - DCHECK(!completion_cb.is_null()); - - media_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MediaResourceTracker::MaybeCallFinalizeOnMediaThread, - base::Unretained(this), std::move(completion_cb))); -} - -void MediaResourceTracker::FinalizeAndDestroy() { - DCHECK(ui_task_runner_->BelongsToCurrentThread()); - - media_task_runner_->PostTask( - FROM_HERE, - base::BindOnce( - &MediaResourceTracker::MaybeCallFinalizeOnMediaThreadAndDeleteSelf, - base::Unretained(this))); -} - -void MediaResourceTracker::IncrementUsageCount() { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - DCHECK(media_lib_initialized_); - DCHECK(!finalize_completion_cb_); - media_use_count_++; -} - -void MediaResourceTracker::DecrementUsageCount() { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - media_use_count_--; - - if (media_use_count_ == 0 && - (delete_on_finalize_ || finalize_completion_cb_)) { - CallFinalizeOnMediaThread(); - } -} - -void MediaResourceTracker::CallInitializeOnMediaThread() { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - if (media_lib_initialized_) - return; - - DoInitializeMediaLib(); - media_lib_initialized_ = true; -} - -void MediaResourceTracker::MaybeCallFinalizeOnMediaThread( - base::OnceClosure completion_cb) { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - DCHECK(!finalize_completion_cb_); - - finalize_completion_cb_ = - base::BindPostTask(ui_task_runner_, std::move(completion_cb)); - if (!media_lib_initialized_) { - if (finalize_completion_cb_) - std::move(finalize_completion_cb_).Run(); - return; - } - - // If there are things using media, we must wait for them to stop. - // CallFinalize will get called later from DecrementUsageCount when - // usage count drops to 0. - if (media_use_count_ == 0) - CallFinalizeOnMediaThread(); -} - -void MediaResourceTracker::MaybeCallFinalizeOnMediaThreadAndDeleteSelf() { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - - if (!media_lib_initialized_) { - ui_task_runner_->DeleteSoon(FROM_HERE, this); - return; - } - - delete_on_finalize_ = true; - - // If there are things using media, we must wait for them to stop. - // CallFinalize will get called later from DecrementUsageCount when - // usage count drops to 0. - if (media_use_count_ == 0) - CallFinalizeOnMediaThread(); -} - -void MediaResourceTracker::CallFinalizeOnMediaThread() { - DCHECK(media_task_runner_->BelongsToCurrentThread()); - DCHECK_EQ(media_use_count_, 0ul); - DCHECK(media_lib_initialized_); - - DoFinalizeMediaLib(); - media_lib_initialized_ = false; - - if (finalize_completion_cb_) - std::move(finalize_completion_cb_).Run(); - - if (delete_on_finalize_) - ui_task_runner_->DeleteSoon(FROM_HERE, this); -} - -void MediaResourceTracker::DoInitializeMediaLib() { - base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); - media::CastMediaShlib::Initialize(cmd_line->argv()); - VolumeControl::Initialize(cmd_line->argv()); -} - -void MediaResourceTracker::DoFinalizeMediaLib() { - CastMediaShlib::Finalize(); - VolumeControl::Finalize(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/media_resource_tracker.h chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker.h --- chromium-132.0.6834.110/chromecast/media/common/media_resource_tracker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_COMMON_MEDIA_RESOURCE_TRACKER_H_ -#define CHROMECAST_MEDIA_COMMON_MEDIA_RESOURCE_TRACKER_H_ - -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/task/sequenced_task_runner_helpers.h" - -namespace base { -class SingleThreadTaskRunner; -} - -namespace chromecast { -namespace media { - -// Keeps track of internal usage of resources that need access to underlying -// media playback hardware. Some example users are the CMA pipeline, and the -// CDMs. When it's time to release media resources, this class can be used -// to be wait and receive notification when all such users have stopped. -// -// Application should have one MediaResourceTracker instance and perform all -// CastMediaShlib::Initialize/Finalize through this interface. -// Threading model and lifetime: -// * This class interacts on both UI and media threads (task runners required -// by ctor to perform thread hopping and checks). See function-level comments -// on which thread to use for which operations. -// * The application should instantiate a single MediaResourceTracker instance. -// Destruction should be performed by calling FinalizeAndDestroy from the UI -// thread. -class MediaResourceTracker { - public: - // Helper class to manage media resource usage count. - // Create an instance of this class when a media resource is created. - // Delete the instance *after* the media resource is deleted. - // This class is not thread-safe. It must be created and deleted on - // |MediaResourceTracker::media_task_runner_|. - class ScopedUsage { - public: - ScopedUsage(MediaResourceTracker* tracker); - - ScopedUsage(const ScopedUsage&) = delete; - ScopedUsage& operator=(const ScopedUsage&) = delete; - - ~ScopedUsage(); - - private: - MediaResourceTracker* tracker_; - }; - - MediaResourceTracker( - scoped_refptr ui_task_runner, - scoped_refptr media_task_runner); - - MediaResourceTracker(const MediaResourceTracker&) = delete; - MediaResourceTracker& operator=(const MediaResourceTracker&) = delete; - - // Media resource acquire implementation. Must call on ui thread; runs - // CastMediaShlib::Initialize on media thread. Safe to call even if media lib - // already initialized. - void InitializeMediaLib(); - - // Media resource release implementation: - // (1) Waits for usage count to drop to zero - // (2) Calls CastMediaShlib::Finalize on media thread - // (3) Calls completion_cb - // Must be called on UI thread. Only one Finalize request may be in flight - // at a time. |completion_cb| must not be null. - void FinalizeMediaLib(base::OnceClosure completion_cb); - - // Shutdown process: - // (1) Waits for usage count to drop to zero - // (2) Calls CastMediaShlib::Finalize on media thread - // (3) Deletes this object - // Must be called on UI thread. No further calls should be made on UI thread - // after this. - void FinalizeAndDestroy(); - - // Users of media resource (e.g. CMA pipeline) should call these when they - // start and stop using media calls (must be called on media thread). - void IncrementUsageCount(); - void DecrementUsageCount(); - - private: - friend class base::DeleteHelper; - friend class TestMediaResourceTracker; - virtual ~MediaResourceTracker(); - - // Tasks posted to media thread - void CallInitializeOnMediaThread(); - void MaybeCallFinalizeOnMediaThread(base::OnceClosure completion_cb); - void MaybeCallFinalizeOnMediaThreadAndDeleteSelf(); - void CallFinalizeOnMediaThread(); - - // Hooks for testing - virtual void DoInitializeMediaLib(); - virtual void DoFinalizeMediaLib(); - - // Accessed on media thread + ctor - size_t media_use_count_; - bool media_lib_initialized_; - base::OnceClosure finalize_completion_cb_; - bool delete_on_finalize_; - - scoped_refptr ui_task_runner_; - scoped_refptr media_task_runner_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_COMMON_MEDIA_RESOURCE_TRACKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/common/media_resource_tracker_unittest.cc chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker_unittest.cc --- chromium-132.0.6834.110/chromecast/media/common/media_resource_tracker_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/media_resource_tracker_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,180 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/media_resource_tracker.h" - -#include - -#include "base/functional/bind.h" -#include "base/run_loop.h" -#include "base/test/task_environment.h" -#include "chromecast/media/common/test_media_resource_tracker.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -class MediaResourceTrackerTest : public ::testing::Test { - public: - MediaResourceTrackerTest() {} - - MediaResourceTrackerTest(const MediaResourceTrackerTest&) = delete; - MediaResourceTrackerTest& operator=(const MediaResourceTrackerTest&) = delete; - - ~MediaResourceTrackerTest() override {} - - protected: - void SetUp() override { - test_mocks_.reset(new MediaResourceTrackerTestMocks()); - - resource_tracker_ = new TestMediaResourceTracker( - task_environment_.GetMainThreadTaskRunner(), - task_environment_.GetMainThreadTaskRunner(), test_mocks_.get()); - } - - void InitializeMediaLib() { - EXPECT_CALL(*test_mocks_, Initialize()).Times(1); - resource_tracker_->InitializeMediaLib(); - base::RunLoop().RunUntilIdle(); - } - - base::test::SingleThreadTaskEnvironment task_environment_; - TestMediaResourceTracker* resource_tracker_; - std::unique_ptr test_mocks_; -}; - -TEST_F(MediaResourceTrackerTest, BasicLifecycle) { - // Startup and shutdown flow: Initialize then FinalizeAndDestroy - EXPECT_CALL(*test_mocks_, Initialize()).Times(1); - EXPECT_CALL(*test_mocks_, Finalize()).Times(1); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(1); - - resource_tracker_->InitializeMediaLib(); - resource_tracker_->FinalizeAndDestroy(); - base::RunLoop().RunUntilIdle(); -} - -TEST_F(MediaResourceTrackerTest, InitializeTwice) { - EXPECT_CALL(*test_mocks_, Initialize()).Times(1); - EXPECT_CALL(*test_mocks_, Finalize()).Times(1); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(1); - - resource_tracker_->InitializeMediaLib(); - resource_tracker_->InitializeMediaLib(); - resource_tracker_->FinalizeAndDestroy(); - base::RunLoop().RunUntilIdle(); -} - -TEST_F(MediaResourceTrackerTest, FinalizeWithoutInitialize) { - EXPECT_CALL(*test_mocks_, Initialize()).Times(0); - EXPECT_CALL(*test_mocks_, Finalize()).Times(0); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(1); - - resource_tracker_->FinalizeAndDestroy(); - base::RunLoop().RunUntilIdle(); -} - -// Check FinalizeCastMediaShlib works correctly with no users of -// media resource. -TEST_F(MediaResourceTrackerTest, FinalizeResourceNotInUse) { - InitializeMediaLib(); - - EXPECT_CALL(*test_mocks_, Finalize()).Times(1); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(0); - EXPECT_CALL(*test_mocks_, FinalizeCallback()).Times(1); - resource_tracker_->FinalizeMediaLib( - base::BindOnce(&MediaResourceTrackerTestMocks::FinalizeCallback, - base::Unretained(test_mocks_.get()))); - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*test_mocks_, Destroyed()).Times(1); - resource_tracker_->FinalizeAndDestroy(); - base::RunLoop().RunUntilIdle(); -} - -// Check FinalizeCastMediaShlib waits for resource to not be in use. -TEST_F(MediaResourceTrackerTest, FinalizeResourceInUse) { - InitializeMediaLib(); - - resource_tracker_->IncrementUsageCount(); - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*test_mocks_, Finalize()).Times(0); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(0); - resource_tracker_->FinalizeMediaLib( - base::BindOnce(&MediaResourceTrackerTestMocks::FinalizeCallback, - base::Unretained(test_mocks_.get()))); - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*test_mocks_, Finalize()).Times(1); - EXPECT_CALL(*test_mocks_, FinalizeCallback()).Times(1); - resource_tracker_->DecrementUsageCount(); - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*test_mocks_, Destroyed()).Times(1); - resource_tracker_->FinalizeAndDestroy(); - base::RunLoop().RunUntilIdle(); -} - -// Check FinalizeAndDestroy waits for resource to not be in use. -TEST_F(MediaResourceTrackerTest, DestroyWaitForNoUsers) { - InitializeMediaLib(); - - resource_tracker_->IncrementUsageCount(); - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*test_mocks_, Finalize()).Times(0); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(0); - resource_tracker_->FinalizeAndDestroy(); - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*test_mocks_, Finalize()).Times(1); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(1); - resource_tracker_->DecrementUsageCount(); - base::RunLoop().RunUntilIdle(); -} - -// Check finalize callback still made if FinalizeAndDestroy called -// while waiting for resource usage to end. -TEST_F(MediaResourceTrackerTest, DestroyWithPendingFinalize) { - InitializeMediaLib(); - - resource_tracker_->IncrementUsageCount(); - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*test_mocks_, Finalize()).Times(0); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(0); - resource_tracker_->FinalizeMediaLib( - base::BindOnce(&MediaResourceTrackerTestMocks::FinalizeCallback, - base::Unretained(test_mocks_.get()))); - resource_tracker_->FinalizeAndDestroy(); - base::RunLoop().RunUntilIdle(); - - EXPECT_CALL(*test_mocks_, Finalize()).Times(1); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(1); - EXPECT_CALL(*test_mocks_, FinalizeCallback()).Times(1); - resource_tracker_->DecrementUsageCount(); - base::RunLoop().RunUntilIdle(); -} - -TEST_F(MediaResourceTrackerTest, ScopedUsage) { - InitializeMediaLib(); - - EXPECT_EQ(0u, resource_tracker_->media_use_count()); - { - std::unique_ptr scoped_usage( - new MediaResourceTracker::ScopedUsage(resource_tracker_)); - EXPECT_EQ(1u, resource_tracker_->media_use_count()); - } - EXPECT_EQ(0u, resource_tracker_->media_use_count()); - - EXPECT_CALL(*test_mocks_, Finalize()).Times(1); - EXPECT_CALL(*test_mocks_, Destroyed()).Times(1); - resource_tracker_->FinalizeAndDestroy(); - base::RunLoop().RunUntilIdle(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/test_media_resource_tracker.cc chromium-132.0.6834.159/chromecast/media/common/test_media_resource_tracker.cc --- chromium-132.0.6834.110/chromecast/media/common/test_media_resource_tracker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/test_media_resource_tracker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/test_media_resource_tracker.h" - -#include "base/task/single_thread_task_runner.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { - -MediaResourceTrackerTestMocks::MediaResourceTrackerTestMocks() = default; - -MediaResourceTrackerTestMocks::~MediaResourceTrackerTestMocks() = default; - -TestMediaResourceTracker::TestMediaResourceTracker( - scoped_refptr ui_task_runner, - scoped_refptr media_task_runner, - MediaResourceTrackerTestMocks* test_mocks) - : MediaResourceTracker(std::move(ui_task_runner), - std::move(media_task_runner)), - test_mocks_(test_mocks) {} - -TestMediaResourceTracker::~TestMediaResourceTracker() { - EXPECT_TRUE(ui_task_runner_->BelongsToCurrentThread()); - if (test_mocks_) - test_mocks_->Destroyed(); -} - -void TestMediaResourceTracker::DoInitializeMediaLib() { - ASSERT_TRUE(media_task_runner_->BelongsToCurrentThread()); - if (test_mocks_) - test_mocks_->Initialize(); -} - -void TestMediaResourceTracker::DoFinalizeMediaLib() { - ASSERT_TRUE(media_task_runner_->BelongsToCurrentThread()); - if (test_mocks_) - test_mocks_->Finalize(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/test_media_resource_tracker.h chromium-132.0.6834.159/chromecast/media/common/test_media_resource_tracker.h --- chromium-132.0.6834.110/chromecast/media/common/test_media_resource_tracker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/test_media_resource_tracker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Contains classes to aid in testing code that uses MediaResourceTracker. - -#ifndef CHROMECAST_MEDIA_COMMON_TEST_MEDIA_RESOURCE_TRACKER_H_ -#define CHROMECAST_MEDIA_COMMON_TEST_MEDIA_RESOURCE_TRACKER_H_ - -#include "base/memory/scoped_refptr.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/common/media_resource_tracker.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace media { - -// Collection of mocks to verify MediaResourceTracker takes the correct actions. -class MediaResourceTrackerTestMocks { - public: - MediaResourceTrackerTestMocks(); - ~MediaResourceTrackerTestMocks(); - MOCK_METHOD0(Initialize, void()); - MOCK_METHOD0(Finalize, void()); - MOCK_METHOD0(Destroyed, void()); - MOCK_METHOD0(FinalizeCallback, void()); -}; - -class TestMediaResourceTracker : public MediaResourceTracker { - public: - TestMediaResourceTracker( - scoped_refptr ui_task_runner, - scoped_refptr media_task_runner, - MediaResourceTrackerTestMocks* test_mocks); - - TestMediaResourceTracker(const TestMediaResourceTracker&) = delete; - TestMediaResourceTracker& operator=(const TestMediaResourceTracker&) = delete; - - ~TestMediaResourceTracker() override; - - size_t media_use_count() const { return media_use_count_; } - - private: - // MediaResourceTracker implementation: - void DoInitializeMediaLib() override; - void DoFinalizeMediaLib() override; - - MediaResourceTrackerTestMocks* const test_mocks_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_COMMON_TEST_MEDIA_RESOURCE_TRACKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/common/video_decoder_wrapper.cc chromium-132.0.6834.159/chromecast/media/common/video_decoder_wrapper.cc --- chromium-132.0.6834.110/chromecast/media/common/video_decoder_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/video_decoder_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/common/video_decoder_wrapper.h" - -#include - -#include "chromecast/media/api/decoder_buffer_base.h" - -namespace chromecast { -namespace media { - -// This fake VideoDecoder would behave as one with buffer filled -// up and the playback is stalled. -class VideoDecoderWrapper::RevokedVideoDecoder - : public MediaPipelineBackend::VideoDecoder { - public: - explicit RevokedVideoDecoder(const Statistics& statistics) - : statistics_(statistics) {} - - RevokedVideoDecoder(const RevokedVideoDecoder&) = delete; - RevokedVideoDecoder& operator=(const RevokedVideoDecoder&) = delete; - - ~RevokedVideoDecoder() override = default; - - private: - // MediaPipelineBackend::VideoDecoder implementation: - void SetDelegate(Delegate* delegate) override {} - - BufferStatus PushBuffer(CastDecoderBuffer* buffer) override { - return MediaPipelineBackend::kBufferPending; - } - - bool SetConfig(const VideoConfig& config) override { return true; } - - void GetStatistics(Statistics* statistics) override { - *statistics = statistics_; - } - - Statistics statistics_; -}; - -VideoDecoderWrapper::VideoDecoderWrapper( - MediaPipelineBackend::VideoDecoder* decoder) - : decoder_(decoder) { - DCHECK(decoder_); -} - -VideoDecoderWrapper::VideoDecoderWrapper() { - Statistics default_statistics; - revoked_video_decoder_ = - std::make_unique(default_statistics); - decoder_ = revoked_video_decoder_.get(); -} - -void VideoDecoderWrapper::Revoke() { - if (!revoked_video_decoder_) { - Statistics statistics; - decoder_->GetStatistics(&statistics); - - revoked_video_decoder_ = std::make_unique(statistics); - decoder_ = revoked_video_decoder_.get(); - } -} - -VideoDecoderWrapper::~VideoDecoderWrapper() = default; - -void VideoDecoderWrapper::SetDelegate( - media::CmaBackend::VideoDecoder::Delegate* delegate) { - decoder_->SetDelegate(delegate); -} - -media::CmaBackend::BufferStatus VideoDecoderWrapper::PushBuffer( - scoped_refptr buffer) { - pushed_buffer_ = std::move(buffer); - return decoder_->PushBuffer(pushed_buffer_.get()); -} - -bool VideoDecoderWrapper::SetConfig(const media::VideoConfig& config) { - return decoder_->SetConfig(config); -} - -void VideoDecoderWrapper::GetStatistics(Statistics* statistics) { - decoder_->GetStatistics(statistics); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/common/video_decoder_wrapper.h chromium-132.0.6834.159/chromecast/media/common/video_decoder_wrapper.h --- chromium-132.0.6834.110/chromecast/media/common/video_decoder_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/common/video_decoder_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_COMMON_VIDEO_DECODER_WRAPPER_H_ -#define CHROMECAST_MEDIA_COMMON_VIDEO_DECODER_WRAPPER_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/media/api/cma_backend.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/public/media/media_pipeline_backend.h" - -namespace chromecast { -namespace media { -class DecoderBufferBase; - -class VideoDecoderWrapper : public CmaBackend::VideoDecoder { - public: - // Create a functional VideoDecoderWrapper. - explicit VideoDecoderWrapper(MediaPipelineBackend::VideoDecoder* decoder); - // Create a VideoDecoderWrapper that's already been revoked. - VideoDecoderWrapper(); - - VideoDecoderWrapper(const VideoDecoderWrapper&) = delete; - VideoDecoderWrapper& operator=(const VideoDecoderWrapper&) = delete; - - ~VideoDecoderWrapper() override; - - void Revoke(); - - private: - class RevokedVideoDecoder; - - // CmaBackend::VideoDecoder implementation: - void SetDelegate(Delegate* delegate) override; - BufferStatus PushBuffer(scoped_refptr buffer) override; - bool SetConfig(const VideoConfig& config) override; - void GetStatistics(Statistics* statistics) override; - - scoped_refptr pushed_buffer_; - - MediaPipelineBackend::VideoDecoder* decoder_; - std::unique_ptr revoked_video_decoder_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_COMMON_VIDEO_DECODER_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/gpu/DEPS chromium-132.0.6834.159/chromecast/media/gpu/DEPS --- chromium-132.0.6834.110/chromecast/media/gpu/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/gpu/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -include_rules = [ - "+chromecast/mojo", - "+gpu", - "+media/gpu", - "+media/mojo/clients", - "+media/video", - "+services/viz/public/cpp/gpu", -] diff -Nru chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory.h chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory.h --- chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_H_ -#define CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_H_ - -#include - -#include "base/memory/scoped_refptr.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace gpu { -class GpuMemoryBufferManager; -} // namespace gpu - -namespace media { -class VideoDecoder; -class VideoEncodeAccelerator; -} // namespace media - -namespace viz { -class ContextProviderCommandBuffer; -} // namespace viz - -namespace chromecast { - -class RemoteInterfaces; - -// Abstraction for accessing GPU related capabilities from non-Renderer -// process (e.g., Utility process). All APIs must be invoked from the -// provided |mojo_task_runner|. -class CastGpuFactory { - public: - static std::unique_ptr Create( - scoped_refptr mojo_task_runner, - RemoteInterfaces* browser_services); - - virtual ~CastGpuFactory() = default; - - // Create and return a CommandBuffer context provider for OpenGL related - // operations. - virtual scoped_refptr - CreateOpenGLContextProvider() = 0; - - // Create and return VideoDecoder. - virtual std::unique_ptr<::media::VideoDecoder> CreateVideoDecoder() = 0; - - // Create and return VideoEncodeAccelerator. - virtual std::unique_ptr<::media::VideoEncodeAccelerator> - CreateVideoEncoder() = 0; - - virtual gpu::GpuMemoryBufferManager* GpuMemoryBufferManager() = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory_dummy.cc chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_dummy.cc --- chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/gpu/cast_gpu_factory_dummy.h" - -#include "base/task/single_thread_task_runner.h" -#include "media/base/video_decoder.h" -#include "media/video/video_encode_accelerator.h" -#include "services/viz/public/cpp/gpu/context_provider_command_buffer.h" - -namespace chromecast { - -// static. -std::unique_ptr CastGpuFactory::Create( - scoped_refptr mojo_task_runner, - RemoteInterfaces* browser_services) { - return std::make_unique(); -} - -CastGpuFactoryDummy::CastGpuFactoryDummy() = default; - -CastGpuFactoryDummy::~CastGpuFactoryDummy() = default; - -scoped_refptr -CastGpuFactoryDummy::CreateOpenGLContextProvider() { - return nullptr; -} - -std::unique_ptr<::media::VideoDecoder> -CastGpuFactoryDummy::CreateVideoDecoder() { - return nullptr; -} - -std::unique_ptr<::media::VideoEncodeAccelerator> -CastGpuFactoryDummy::CreateVideoEncoder() { - return nullptr; -} - -gpu::GpuMemoryBufferManager* CastGpuFactoryDummy::GpuMemoryBufferManager() { - return nullptr; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory_dummy.h chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_dummy.h --- chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory_dummy.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_dummy.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_DUMMY_H_ -#define CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_DUMMY_H_ - -#include "chromecast/media/gpu/cast_gpu_factory.h" - -namespace chromecast { - -class CastGpuFactoryDummy : public CastGpuFactory { - public: - CastGpuFactoryDummy(); - ~CastGpuFactoryDummy() override; - CastGpuFactoryDummy(const CastGpuFactoryDummy&) = delete; - CastGpuFactoryDummy& operator=(const CastGpuFactoryDummy&) = delete; - - private: - // CastGpuFactory implementation: - scoped_refptr CreateOpenGLContextProvider() - override; - std::unique_ptr<::media::VideoDecoder> CreateVideoDecoder() override; - std::unique_ptr<::media::VideoEncodeAccelerator> CreateVideoEncoder() - override; - gpu::GpuMemoryBufferManager* GpuMemoryBufferManager() override; -}; - -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_DUMMY_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory_impl.cc chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_impl.cc --- chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,337 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/gpu/cast_gpu_factory_impl.h" - -#include "base/check.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/mojo/remote_interfaces.h" -#include "gpu/command_buffer/client/gles2_interface.h" -#include "gpu/config/gpu_info.h" -#include "media/base/media_util.h" -#include "media/gpu/gpu_video_accelerator_util.h" -#include "media/gpu/gpu_video_decode_accelerator_helpers.h" -#include "media/mojo/clients/mojo_video_decoder.h" -#include "media/mojo/clients/mojo_video_encode_accelerator.h" -#include "services/viz/public/cpp/gpu/context_provider_command_buffer.h" -#include "services/viz/public/cpp/gpu/gpu.h" - -namespace chromecast { -namespace { - -void OnRequestOverlayInfo(bool decoder_requires_restart_for_overlay, - ::media::ProvideOverlayInfoCB overlay_info_cb) { - // Android overlays are not supported. - if (overlay_info_cb) - overlay_info_cb.Run(::media::OverlayInfo()); -} - -} // namespace - -// static. -std::unique_ptr CastGpuFactory::Create( - scoped_refptr mojo_task_runner, - RemoteInterfaces* browser_services) { - return std::make_unique(std::move(mojo_task_runner), - browser_services); -} - -CastGpuFactoryImpl::CastGpuFactoryImpl( - scoped_refptr mojo_task_runner, - RemoteInterfaces* browser_services) - : gpu_io_thread_("CastGpuIo"), - mojo_task_runner_(std::move(mojo_task_runner)), - media_log_(std::make_unique<::media::NullMediaLog>()), - browser_services_(browser_services) { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - DCHECK(browser_services_); - - base::Thread::Options options; - options.message_pump_type = base::MessagePumpType::IO; - options.thread_type = base::ThreadType::kDisplayCritical; - gpu_io_thread_.StartWithOptions(std::move(options)); - - mojo::PendingRemote remote_gpu; - browser_services_->Bind(remote_gpu.InitWithNewPipeAndPassReceiver()); - gpu_ = viz::Gpu::Create(std::move(remote_gpu), gpu_io_thread_.task_runner()); - DCHECK(gpu_); - - // Perform SetupContext asynchronously as the thread (e.g., - // CastRendererVirtualCamera) that's handling |browser_services_| GetInterface - // request could be blocking waiting for this construction to completed, this - // will allow that thread to be unblocked. - mojo_task_runner_->PostTask(FROM_HERE, - base::BindOnce(&CastGpuFactoryImpl::SetupContext, - base::Unretained(this))); -} - -CastGpuFactoryImpl::~CastGpuFactoryImpl() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); -} - -scoped_refptr -CastGpuFactoryImpl::CreateOpenGLContextProvider() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - gpu::ContextCreationAttribs attributes; - attributes.alpha_size = -1; - attributes.depth_size = 0; - attributes.stencil_size = 0; - attributes.samples = 0; - attributes.sample_buffers = 0; - attributes.bind_generates_resource = false; - attributes.lose_context_when_out_of_memory = true; - attributes.enable_gles2_interface = true; - attributes.enable_raster_interface = false; - attributes.enable_oop_rasterization = false; - attributes.context_type = gpu::CONTEXT_TYPE_OPENGLES3; - attributes.gpu_preference = gl::GpuPreference::kHighPerformance; - return base::MakeRefCounted( - gpu_channel_host_, gpu_->gpu_memory_buffer_manager(), 0 /* stream ID */, - gpu::SchedulingPriority::kHigh, gpu::kNullSurfaceHandle, - GURL("chrome://gpu/opengl"), false /* automatic_flushes */, - false /* support_locking */, false /* support_grcontext */, - gpu::SharedMemoryLimits::ForMailboxContext(), attributes, - viz::command_buffer_metrics::ContextType::WEBGL); -} - -std::unique_ptr<::media::VideoDecoder> -CastGpuFactoryImpl::CreateVideoDecoder() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - return CreateVideoDecoder(media_log_.get(), - base::BindRepeating(&OnRequestOverlayInfo)); -} - -std::unique_ptr<::media::VideoEncodeAccelerator> -CastGpuFactoryImpl::CreateVideoEncoder() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - return CreateVideoEncodeAccelerator(); -} - -// Return whether GPU decoding is enabled. -bool CastGpuFactoryImpl::IsGpuVideoDecodeAcceleratorEnabled() { - return true; -} - -// Return whether GPU encoding is enabled. -bool CastGpuFactoryImpl::IsGpuVideoEncodeAcceleratorEnabled() { - return true; -} - -// Return the channel token, or an empty token if the channel is unusable. -base::UnguessableToken CastGpuFactoryImpl::GetChannelToken() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - if (CheckContextLost()) { - return base::UnguessableToken(); - } - - return channel_token_; -} - -// Returns the |route_id| of the command buffer, or 0 if there is none. -int32_t CastGpuFactoryImpl::GetCommandBufferRouteId() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - if (CheckContextLost()) { - return 0; - } - return context_provider_->GetCommandBufferProxy()->route_id(); -} - -// Return true if |config| is potentially supported by a decoder created with -// CreateVideoDecoder(). -::media::GpuVideoAcceleratorFactories::Supported -CastGpuFactoryImpl::IsDecoderConfigSupported( - const ::media::VideoDecoderConfig& config) { - if (config.codec() == ::media::VideoCodec::kH264) { - return Supported::kTrue; - } - return Supported::kFalse; -} - -bool CastGpuFactoryImpl::IsDecoderSupportKnown() { - return true; -} - -void CastGpuFactoryImpl::NotifyDecoderSupportKnown(base::OnceClosure callback) { - base::SequencedTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE, - std::move(callback)); -} - -std::unique_ptr<::media::VideoDecoder> CastGpuFactoryImpl::CreateVideoDecoder( - ::media::MediaLog* media_log, - ::media::RequestOverlayInfoCB request_overlay_info_cb) { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - DCHECK(media_interface_factory_.is_bound()); - - if (CheckContextLost()) { - return nullptr; - } - - mojo::PendingRemote video_decoder; - media_interface_factory_->CreateVideoDecoder( - video_decoder.InitWithNewPipeAndPassReceiver()); - return std::make_unique<::media::MojoVideoDecoder>( - mojo_task_runner_, this, media_log, std::move(video_decoder), - request_overlay_info_cb, gfx::ColorSpace::CreateSRGB()); -} - -std::optional<::media::VideoEncodeAccelerator::SupportedProfiles> -CastGpuFactoryImpl::GetVideoEncodeAcceleratorSupportedProfiles() { - return ::media::VideoEncodeAccelerator::SupportedProfiles(); -} - -bool CastGpuFactoryImpl::IsEncoderSupportKnown() { - return true; -} - -void CastGpuFactoryImpl::NotifyEncoderSupportKnown(base::OnceClosure callback) { - base::SequencedTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE, - std::move(callback)); -} - -std::optional -CastGpuFactoryImpl::GetSupportedVideoDecoderConfigs() { - if (CheckContextLost()) { - return std::nullopt; - } - - return ::media::ConvertFromSupportedProfiles( - ::media::GpuVideoAcceleratorUtil::ConvertGpuToMediaDecodeProfiles( - gpu_channel_host_->gpu_info() - .video_decode_accelerator_supported_profiles)); -} - -std::unique_ptr<::media::VideoEncodeAccelerator> -CastGpuFactoryImpl::CreateVideoEncodeAccelerator() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - - if (CheckContextLost()) { - return nullptr; - } - if (!vea_provider_) { - return nullptr; - } - - mojo::PendingRemote<::media::mojom::VideoEncodeAccelerator> vea; - vea_provider_->CreateVideoEncodeAccelerator( - vea.InitWithNewPipeAndPassReceiver()); - return std::make_unique<::media::VideoEncodeAccelerator>( - std::move(vea), - ::media::GpuVideoAcceleratorUtil::ConvertGpuToMediaEncodeProfiles( - gpu_channel_host_->gpu_info() - .video_encode_accelerator_supported_profiles)); -} - -std::unique_ptr CastGpuFactoryImpl::CreateGpuMemoryBuffer( - const gfx::Size& size, - gfx::BufferFormat format, - gfx::BufferUsage usage) { - return nullptr; -} - -bool CastGpuFactoryImpl::ShouldUseGpuMemoryBuffersForVideoFrames( - bool for_media_stream) const { - return false; -} - -unsigned CastGpuFactoryImpl::ImageTextureTarget(gfx::BufferFormat format) { - return 0; -} - -media::GpuVideoAcceleratorFactories::OutputFormat -CastGpuFactoryImpl::VideoFrameOutputFormat( - ::media::VideoPixelFormat pixel_format) { - return ::media::GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED; -} - -gpu::SharedImageInterface* CastGpuFactoryImpl::SharedImageInterface() { - return nullptr; -} - -gpu::GpuMemoryBufferManager* CastGpuFactoryImpl::GpuMemoryBufferManager() { - return gpu_->gpu_memory_buffer_manager(); -} - -base::UnsafeSharedMemoryRegion CastGpuFactoryImpl::CreateSharedMemoryRegion( - size_t size) { - return base::UnsafeSharedMemoryRegion(); -} - -scoped_refptr CastGpuFactoryImpl::GetTaskRunner() { - return nullptr; -} - -viz::RasterContextProvider* CastGpuFactoryImpl::GetMediaContextProvider() { - return nullptr; -} - -void CastGpuFactoryImpl::SetRenderingColorSpace( - const gfx::ColorSpace& color_space) {} - -const gfx::ColorSpace& CastGpuFactoryImpl::GetRenderingColorSpace() const { - return rendering_color_space_; -} - -void CastGpuFactoryImpl::SetupContext() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - LOG(INFO) << __func__; - gpu_channel_host_ = gpu_->EstablishGpuChannelSync(); - if (!gpu_channel_host_) { - LOG(ERROR) << "Failed to obtained GPU channel host"; - return; - } - - gpu::ContextCreationAttribs attributes; - attributes.alpha_size = -1; - attributes.depth_size = 0; - attributes.stencil_size = 0; - attributes.samples = 0; - attributes.sample_buffers = 0; - attributes.bind_generates_resource = false; - attributes.lose_context_when_out_of_memory = true; - attributes.enable_gles2_interface = true; - attributes.enable_raster_interface = false; - attributes.enable_oop_rasterization = false; - context_provider_ = base::MakeRefCounted( - gpu_channel_host_, gpu_->gpu_memory_buffer_manager(), 0 /* stream ID */, - gpu::SchedulingPriority::kHigh, gpu::kNullSurfaceHandle, - GURL("chrome://gpu/CastVideoAcceleratorFactory"), - false /* automatic_flushes */, false /* support_locking */, - gpu::SharedMemoryLimits::ForMailboxContext(), attributes, - viz::command_buffer_metrics::ContextType::MEDIA); - DCHECK(context_provider_); - - if (context_provider_->BindToCurrentSequence() != - gpu::ContextResult::kSuccess) { - LOG(ERROR) << "Failed to bind ContextProvider to current thread"; - context_provider_ = nullptr; - } - - // Get the channel token for the current connection. - context_provider_->GetCommandBufferProxy()->GetGpuChannel().GetChannelToken( - &channel_token_); - - gpu_->CreateVideoEncodeAcceleratorProvider( - vea_provider_.BindNewPipeAndPassReceiver()); - DCHECK(vea_provider_); - - DCHECK(browser_services_); - browser_services_->BindNewPipe(&media_interface_factory_); - DCHECK(media_interface_factory_); -} - -bool CastGpuFactoryImpl::CheckContextLost() { - DCHECK(mojo_task_runner_->BelongsToCurrentThread()); - if (!context_provider_ || - context_provider_->ContextGL()->GetGraphicsResetStatusKHR() != - GL_NO_ERROR) { - LOG(ERROR) << "ContextProvider no longer connected"; - context_provider_ = nullptr; - // Re-setup GPU context. - SetupContext(); - } - return !context_provider_; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory_impl.h chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_impl.h --- chromium-132.0.6834.110/chromecast/media/gpu/cast_gpu_factory_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/gpu/cast_gpu_factory_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_IMPL_H_ -#define CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_IMPL_H_ - -#include "base/memory/scoped_refptr.h" -#include "base/task/sequenced_task_runner.h" -#include "base/threading/thread.h" -#include "chromecast/media/gpu/cast_gpu_factory.h" -#include "media/mojo/clients/mojo_video_decoder.h" -#include "media/mojo/mojom/interface_factory.mojom.h" -#include "media/mojo/mojom/video_encode_accelerator.mojom.h" -#include "media/video/gpu_video_accelerator_factories.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "ui/gfx/geometry/size.h" - -namespace base { -class SingleThreadTaskRunner; -class UnguessableToken; -} // namespace base - -namespace gpu { -class GpuChannelHost; -} // namespace gpu - -namespace viz { -class Gpu; -} // namespace viz - -namespace chromecast { - -class RemoteInterfaces; - -class CastGpuFactoryImpl : public CastGpuFactory, - public ::media::GpuVideoAcceleratorFactories { - public: - CastGpuFactoryImpl( - scoped_refptr mojo_task_runner, - RemoteInterfaces* browser_services); - ~CastGpuFactoryImpl() override; - CastGpuFactoryImpl(const CastGpuFactoryImpl&) = delete; - CastGpuFactoryImpl& operator=(const CastGpuFactoryImpl&) = delete; - - private: - // CastGpuFactory implementation: - scoped_refptr CreateOpenGLContextProvider() - override; - std::unique_ptr<::media::VideoDecoder> CreateVideoDecoder() override; - std::unique_ptr<::media::VideoEncodeAccelerator> CreateVideoEncoder() - override; - - // media::GpuVideoAcceleratorFactories implementation. - bool IsGpuVideoDecodeAcceleratorEnabled() override; - bool IsGpuVideoEncodeAcceleratorEnabled() override; - base::UnguessableToken GetChannelToken() override; - int32_t GetCommandBufferRouteId() override; - ::media::GpuVideoAcceleratorFactories::Supported IsDecoderConfigSupported( - const ::media::VideoDecoderConfig& config) override; - bool IsDecoderSupportKnown() override; - void NotifyDecoderSupportKnown(base::OnceClosure) override; - std::unique_ptr CreateVideoDecoder( - ::media::MediaLog* media_log, - ::media::RequestOverlayInfoCB request_overlay_info_cb) override; - std::optional - GetVideoEncodeAcceleratorSupportedProfiles() override; - bool IsEncoderSupportKnown() override; - void NotifyEncoderSupportKnown(base::OnceClosure) override; - std::optional - GetSupportedVideoDecoderConfigs() override; - std::unique_ptr<::media::VideoEncodeAccelerator> - CreateVideoEncodeAccelerator() override; - std::unique_ptr CreateGpuMemoryBuffer( - const gfx::Size& size, - gfx::BufferFormat format, - gfx::BufferUsage usage) override; - bool ShouldUseGpuMemoryBuffersForVideoFrames( - bool for_media_stream) const override; - unsigned ImageTextureTarget(gfx::BufferFormat format) override; - OutputFormat VideoFrameOutputFormat( - ::media::VideoPixelFormat pixel_format) override; - gpu::SharedImageInterface* SharedImageInterface() override; - gpu::GpuMemoryBufferManager* GpuMemoryBufferManager() override; - base::UnsafeSharedMemoryRegion CreateSharedMemoryRegion(size_t size) override; - scoped_refptr GetTaskRunner() override; - viz::RasterContextProvider* GetMediaContextProvider() override; - void SetRenderingColorSpace(const gfx::ColorSpace& color_space) override; - const gfx::ColorSpace& GetRenderingColorSpace() const override; - - // Setup GPU context. - void SetupContext(); - - // Verify the context provider connection. Return true if connection - // is lost. - bool CheckContextLost(); - - base::UnguessableToken channel_token_; - base::Thread gpu_io_thread_; - scoped_refptr mojo_task_runner_; - std::unique_ptr gpu_; - scoped_refptr gpu_channel_host_; - scoped_refptr context_provider_; - mojo::Remote vea_provider_; - mojo::Remote media_interface_factory_; - - // The default color space is invalid color space. - gfx::ColorSpace rendering_color_space_; - - std::unique_ptr<::media::MediaLog> media_log_; - RemoteInterfaces* const browser_services_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_GPU_CAST_GPU_FACTORY_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/mojom/OWNERS chromium-132.0.6834.159/chromecast/media/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/media/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS -per-file *_mojom_traits*.*=set noparent -per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS -per-file *.typemap=set noparent -per-file *.typemap=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/media/mojom/decoder_config_mojom_traits.cc chromium-132.0.6834.159/chromecast/media/mojom/decoder_config_mojom_traits.cc --- chromium-132.0.6834.110/chromecast/media/mojom/decoder_config_mojom_traits.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/mojom/decoder_config_mojom_traits.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/mojom/decoder_config_mojom_traits.h" - -namespace mojo { - -// static -bool StructTraits:: - Read(chromecast::media::mojom::AudioConfigDataView input, - chromecast::media::AudioConfig* output) { - chromecast::media::StreamId id; - if (!input.ReadId(&id)) { - return false; - } - - chromecast::media::AudioCodec codec; - if (!input.ReadCodec(&codec)) { - return false; - } - - chromecast::media::ChannelLayout channel_layout; - if (!input.ReadChannelLayout(&channel_layout)) { - return false; - } - - chromecast::media::SampleFormat sample_format; - if (!input.ReadSampleFormat(&sample_format)) { - return false; - } - - std::vector extra_data; - if (!input.ReadExtraData(&extra_data)) { - return false; - } - - chromecast::media::EncryptionScheme encryption_scheme; - if (!input.ReadEncryptionScheme(&encryption_scheme)) { - return false; - } - - output->id = id; - output->codec = codec; - output->channel_layout = channel_layout; - output->sample_format = sample_format; - output->bytes_per_channel = input.bytes_per_channel(); - output->channel_number = input.channel_number(); - output->samples_per_second = input.samples_per_second(); - output->extra_data = std::move(extra_data); - output->encryption_scheme = encryption_scheme; - - return true; -} - -} // namespace mojo diff -Nru chromium-132.0.6834.110/chromecast/media/mojom/decoder_config_mojom_traits.h chromium-132.0.6834.159/chromecast/media/mojom/decoder_config_mojom_traits.h --- chromium-132.0.6834.110/chromecast/media/mojom/decoder_config_mojom_traits.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/mojom/decoder_config_mojom_traits.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,334 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MEDIA_MOJOM_DECODER_CONFIG_MOJOM_TRAITS_H_ -#define CHROMECAST_MEDIA_MOJOM_DECODER_CONFIG_MOJOM_TRAITS_H_ - -#include "chromecast/media/mojom/media_types.mojom-shared.h" -#include "chromecast/public/media/decoder_config.h" - -namespace mojo { - -template <> -struct mojo::EnumTraits { - static chromecast::media::mojom::AudioCodec ToMojom( - chromecast::media::AudioCodec input) { - switch (input) { - case (chromecast::media::AudioCodec::kAudioCodecUnknown): - return chromecast::media::mojom::AudioCodec::kAudioCodecUnknown; - case (chromecast::media::AudioCodec::kCodecAAC): - return chromecast::media::mojom::AudioCodec::kCodecAAC; - case (chromecast::media::AudioCodec::kCodecMP3): - return chromecast::media::mojom::AudioCodec::kCodecMP3; - case (chromecast::media::AudioCodec::kCodecPCM): - return chromecast::media::mojom::AudioCodec::kCodecPCM; - case (chromecast::media::AudioCodec::kCodecPCM_S16BE): - return chromecast::media::mojom::AudioCodec::kCodecPCM_S16BE; - case (chromecast::media::AudioCodec::kCodecVorbis): - return chromecast::media::mojom::AudioCodec::kCodecVorbis; - case (chromecast::media::AudioCodec::kCodecOpus): - return chromecast::media::mojom::AudioCodec::kCodecOpus; - case (chromecast::media::AudioCodec::kCodecEAC3): - return chromecast::media::mojom::AudioCodec::kCodecEAC3; - case (chromecast::media::AudioCodec::kCodecAC3): - return chromecast::media::mojom::AudioCodec::kCodecAC3; - case (chromecast::media::AudioCodec::kCodecDTS): - return chromecast::media::mojom::AudioCodec::kCodecDTS; - case (chromecast::media::AudioCodec::kCodecDTSXP2): - return chromecast::media::mojom::AudioCodec::kCodecDTSXP2; - case (chromecast::media::AudioCodec::kCodecDTSE): - return chromecast::media::mojom::AudioCodec::kCodecDTSE; - case (chromecast::media::AudioCodec::kCodecFLAC): - return chromecast::media::mojom::AudioCodec::kCodecFLAC; - case (chromecast::media::AudioCodec::kCodecMpegHAudio): - return chromecast::media::mojom::AudioCodec::kCodecMpegHAudio; - } - DLOG(FATAL) << "Unrecognized AudioCodec"; - return chromecast::media::mojom::AudioCodec::kAudioCodecUnknown; - } - - static bool FromMojom(chromecast::media::mojom::AudioCodec input, - chromecast::media::AudioCodec* output) { - switch (input) { - case (chromecast::media::mojom::AudioCodec::kAudioCodecUnknown): - *output = chromecast::media::AudioCodec::kAudioCodecUnknown; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecAAC): - *output = chromecast::media::AudioCodec::kCodecAAC; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecMP3): - *output = chromecast::media::AudioCodec::kCodecMP3; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecPCM): - *output = chromecast::media::AudioCodec::kCodecPCM; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecPCM_S16BE): - *output = chromecast::media::AudioCodec::kCodecPCM_S16BE; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecVorbis): - *output = chromecast::media::AudioCodec::kCodecVorbis; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecOpus): - *output = chromecast::media::AudioCodec::kCodecOpus; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecEAC3): - *output = chromecast::media::AudioCodec::kCodecEAC3; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecAC3): - *output = chromecast::media::AudioCodec::kCodecAC3; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecDTS): - *output = chromecast::media::AudioCodec::kCodecDTS; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecDTSXP2): - *output = chromecast::media::AudioCodec::kCodecDTSXP2; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecDTSE): - *output = chromecast::media::AudioCodec::kCodecDTSE; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecFLAC): - *output = chromecast::media::AudioCodec::kCodecFLAC; - return true; - case (chromecast::media::mojom::AudioCodec::kCodecMpegHAudio): - *output = chromecast::media::AudioCodec::kCodecMpegHAudio; - return true; - } - return false; - } -}; - -template <> -struct mojo::EnumTraits { - static chromecast::media::mojom::ChannelLayout ToMojom( - chromecast::media::ChannelLayout input) { - switch (input) { - case (chromecast::media::ChannelLayout::UNSUPPORTED): - return chromecast::media::mojom::ChannelLayout::kUnsupported; - case (chromecast::media::ChannelLayout::MONO): - return chromecast::media::mojom::ChannelLayout::kMono; - case (chromecast::media::ChannelLayout::STEREO): - return chromecast::media::mojom::ChannelLayout::kStereo; - case (chromecast::media::ChannelLayout::SURROUND_5_1): - return chromecast::media::mojom::ChannelLayout::kSurround_5_1; - case (chromecast::media::ChannelLayout::BITSTREAM): - return chromecast::media::mojom::ChannelLayout::kBitstream; - case (chromecast::media::ChannelLayout::DISCRETE): - return chromecast::media::mojom::ChannelLayout::kDiscrete; - } - DLOG(FATAL) << "Unrecognized ChannelLayout"; - return chromecast::media::mojom::ChannelLayout::kUnsupported; - } - - static bool FromMojom(chromecast::media::mojom::ChannelLayout input, - chromecast::media::ChannelLayout* output) { - switch (input) { - case (chromecast::media::mojom::ChannelLayout::kUnsupported): - *output = chromecast::media::ChannelLayout::UNSUPPORTED; - return true; - case (chromecast::media::mojom::ChannelLayout::kMono): - *output = chromecast::media::ChannelLayout::MONO; - return true; - case (chromecast::media::mojom::ChannelLayout::kStereo): - *output = chromecast::media::ChannelLayout::STEREO; - return true; - case (chromecast::media::mojom::ChannelLayout::kSurround_5_1): - *output = chromecast::media::ChannelLayout::SURROUND_5_1; - return true; - case (chromecast::media::mojom::ChannelLayout::kBitstream): - *output = chromecast::media::ChannelLayout::BITSTREAM; - return true; - case (chromecast::media::mojom::ChannelLayout::kDiscrete): - *output = chromecast::media::ChannelLayout::DISCRETE; - return true; - } - return false; - } -}; - -template <> -struct mojo::EnumTraits { - static chromecast::media::mojom::SampleFormat ToMojom( - chromecast::media::SampleFormat input) { - switch (input) { - case (chromecast::media::SampleFormat::kUnknownSampleFormat): - return chromecast::media::mojom::SampleFormat::kUnknownSampleFormat; - case (chromecast::media::SampleFormat::kSampleFormatU8): - return chromecast::media::mojom::SampleFormat::kSampleFormatU8; - case (chromecast::media::SampleFormat::kSampleFormatS16): - return chromecast::media::mojom::SampleFormat::kSampleFormatS16; - case (chromecast::media::SampleFormat::kSampleFormatS32): - return chromecast::media::mojom::SampleFormat::kSampleFormatS32; - case (chromecast::media::SampleFormat::kSampleFormatF32): - return chromecast::media::mojom::SampleFormat::kSampleFormatF32; - case (chromecast::media::SampleFormat::kSampleFormatPlanarU8): - return chromecast::media::mojom::SampleFormat::kSampleFormatPlanarU8; - case (chromecast::media::SampleFormat::kSampleFormatPlanarS16): - return chromecast::media::mojom::SampleFormat::kSampleFormatPlanarS16; - case (chromecast::media::SampleFormat::kSampleFormatPlanarF32): - return chromecast::media::mojom::SampleFormat::kSampleFormatPlanarF32; - case (chromecast::media::SampleFormat::kSampleFormatPlanarS32): - return chromecast::media::mojom::SampleFormat::kSampleFormatPlanarS32; - case (chromecast::media::SampleFormat::kSampleFormatS24): - return chromecast::media::mojom::SampleFormat::kSampleFormatS24; - } - DLOG(FATAL) << "Unrecognized SampleFormat"; - return chromecast::media::mojom::SampleFormat::kUnknownSampleFormat; - } - - static bool FromMojom(chromecast::media::mojom::SampleFormat input, - chromecast::media::SampleFormat* output) { - switch (input) { - case (chromecast::media::mojom::SampleFormat::kUnknownSampleFormat): - *output = chromecast::media::SampleFormat::kUnknownSampleFormat; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatU8): - *output = chromecast::media::SampleFormat::kSampleFormatU8; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatS16): - *output = chromecast::media::SampleFormat::kSampleFormatS16; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatS32): - *output = chromecast::media::SampleFormat::kSampleFormatS32; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatF32): - *output = chromecast::media::SampleFormat::kSampleFormatF32; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatPlanarU8): - *output = chromecast::media::SampleFormat::kSampleFormatPlanarU8; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatPlanarS16): - *output = chromecast::media::SampleFormat::kSampleFormatPlanarS16; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatPlanarF32): - *output = chromecast::media::SampleFormat::kSampleFormatPlanarF32; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatPlanarS32): - *output = chromecast::media::SampleFormat::kSampleFormatPlanarS32; - return true; - case (chromecast::media::mojom::SampleFormat::kSampleFormatS24): - *output = chromecast::media::SampleFormat::kSampleFormatS24; - return true; - } - return false; - } -}; - -template <> -struct mojo::EnumTraits { - static chromecast::media::mojom::EncryptionScheme ToMojom( - chromecast::media::EncryptionScheme input) { - switch (input) { - case (chromecast::media::EncryptionScheme::kUnencrypted): - return chromecast::media::mojom::EncryptionScheme::kUnencrypted; - case (chromecast::media::EncryptionScheme::kAesCtr): - return chromecast::media::mojom::EncryptionScheme::kAesCtr; - case (chromecast::media::EncryptionScheme::kAesCbc): - return chromecast::media::mojom::EncryptionScheme::kAesCbc; - } - DLOG(FATAL) << "Unrecognized EncryptionScheme"; - return chromecast::media::mojom::EncryptionScheme::kUnencrypted; - } - - static bool FromMojom(chromecast::media::mojom::EncryptionScheme input, - chromecast::media::EncryptionScheme* output) { - switch (input) { - case (chromecast::media::mojom::EncryptionScheme::kUnencrypted): - *output = chromecast::media::EncryptionScheme::kUnencrypted; - return true; - case (chromecast::media::mojom::EncryptionScheme::kAesCtr): - *output = chromecast::media::EncryptionScheme::kAesCtr; - return true; - case (chromecast::media::mojom::EncryptionScheme::kAesCbc): - *output = chromecast::media::EncryptionScheme::kAesCbc; - return true; - } - return false; - } -}; - -template <> -struct mojo::EnumTraits { - static chromecast::media::mojom::StreamId ToMojom( - chromecast::media::StreamId input) { - switch (input) { - case (chromecast::media::StreamId::kPrimary): - return chromecast::media::mojom::StreamId::kPrimary; - case (chromecast::media::StreamId::kSecondary): - return chromecast::media::mojom::StreamId::kSecondary; - } - DLOG(FATAL) << "Unrecognized StreamId"; - return chromecast::media::mojom::StreamId::kPrimary; - } - - static bool FromMojom(chromecast::media::mojom::StreamId input, - chromecast::media::StreamId* output) { - switch (input) { - case (chromecast::media::mojom::StreamId::kPrimary): - *output = chromecast::media::StreamId::kPrimary; - return true; - case (chromecast::media::mojom::StreamId::kSecondary): - *output = chromecast::media::StreamId::kSecondary; - return true; - } - return false; - } -}; - -template <> -struct StructTraits { - static chromecast::media::StreamId id( - const chromecast::media::AudioConfig& input) { - return input.id; - } - - static chromecast::media::AudioCodec codec( - const chromecast::media::AudioConfig& input) { - return input.codec; - } - - static chromecast::media::ChannelLayout channel_layout( - const chromecast::media::AudioConfig& input) { - return input.channel_layout; - } - - static chromecast::media::SampleFormat sample_format( - const chromecast::media::AudioConfig& input) { - return input.sample_format; - } - - static int bytes_per_channel(const chromecast::media::AudioConfig& input) { - return input.bytes_per_channel; - } - - static int channel_number(const chromecast::media::AudioConfig& input) { - return input.channel_number; - } - - static int samples_per_second(const chromecast::media::AudioConfig& input) { - return input.samples_per_second; - } - - static chromecast::media::EncryptionScheme encryption_scheme( - const chromecast::media::AudioConfig& input) { - return input.encryption_scheme; - } - - static const std::vector& extra_data( - const chromecast::media::AudioConfig& input) { - return input.extra_data; - } - - static bool Read(chromecast::media::mojom::AudioConfigDataView input, - chromecast::media::AudioConfig* output); -}; - -} // namespace mojo - -#endif // CHROMECAST_MEDIA_MOJOM_DECODER_CONFIG_MOJOM_TRAITS_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/mojom/media_types.mojom chromium-132.0.6834.159/chromecast/media/mojom/media_types.mojom --- chromium-132.0.6834.110/chromecast/media/mojom/media_types.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/mojom/media_types.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// 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. - -module chromecast.media.mojom; - -enum AudioCodec { - kAudioCodecUnknown, - kCodecAAC, - kCodecMP3, - kCodecPCM, - kCodecPCM_S16BE, - kCodecVorbis, - kCodecOpus, - kCodecEAC3, - kCodecAC3, - kCodecDTS, - kCodecDTSXP2, - kCodecDTSE, - kCodecFLAC, - kCodecMpegHAudio, -}; - -enum ChannelLayout { - kUnsupported, - kMono, - kStereo, - kSurround_5_1, - kBitstream, - kDiscrete, -}; - -enum SampleFormat { - kUnknownSampleFormat, - kSampleFormatU8, - kSampleFormatS16, - kSampleFormatS32, - kSampleFormatF32, - kSampleFormatPlanarS16, - kSampleFormatPlanarF32, - kSampleFormatPlanarS32, - kSampleFormatS24, - kSampleFormatPlanarU8, -}; - -enum StreamId { - kPrimary, - kSecondary -}; - -enum EncryptionScheme { - kUnencrypted, - kAesCtr, - kAesCbc -}; - -// This defines a mojo transport format for chromecast::media::AudioConfig. -// See chromecast/public/media/decoder_config.h for descriptions. -struct AudioConfig { - StreamId id; - AudioCodec codec; - ChannelLayout channel_layout; - SampleFormat sample_format; - int32 bytes_per_channel; - int32 channel_number; - int32 samples_per_second; - array extra_data; - EncryptionScheme encryption_scheme; -}; diff -Nru chromium-132.0.6834.110/chromecast/media/service/DEPS chromium-132.0.6834.159/chromecast/media/service/DEPS --- chromium-132.0.6834.110/chromecast/media/service/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -include_rules = [ - "+chromecast/common/mojom", - "+media/mojo", - "+mojo/public/cpp", - "+services/service_manager/public", -] diff -Nru chromium-132.0.6834.110/chromecast/media/service/cast_mojo_media_client.cc chromium-132.0.6834.159/chromecast/media/service/cast_mojo_media_client.cc --- chromium-132.0.6834.110/chromecast/media/service/cast_mojo_media_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/cast_mojo_media_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/service/cast_mojo_media_client.h" - -#include - -#include "base/task/single_thread_task_runner.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/service/cast_renderer.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "media/base/cdm_factory.h" -#include "media/base/media_log.h" -#include "media/base/overlay_info.h" - -namespace chromecast { -namespace media { - -CastMojoMediaClient::CastMojoMediaClient( - CmaBackendFactory* backend_factory, - const CreateCdmFactoryCB& create_cdm_factory_cb, - VideoModeSwitcher* video_mode_switcher, - VideoResolutionPolicy* video_resolution_policy, - CastMojoMediaClient::EnableBufferingCB enable_buffering_cb) - : backend_factory_(backend_factory), - create_cdm_factory_cb_(create_cdm_factory_cb), - video_mode_switcher_(video_mode_switcher), - video_resolution_policy_(video_resolution_policy), - enable_buffering_cb_(std::move(enable_buffering_cb)) { - DCHECK(backend_factory_); -} - -CastMojoMediaClient::~CastMojoMediaClient() = default; - -#if BUILDFLAG(ENABLE_CAST_RENDERER) -void CastMojoMediaClient::SetVideoGeometrySetterService( - VideoGeometrySetterService* video_geometry_setter) { - video_geometry_setter_ = video_geometry_setter; -} - -std::unique_ptr<::media::Renderer> CastMojoMediaClient::CreateCastRenderer( - ::media::mojom::FrameInterfaceFactory* frame_interfaces, - scoped_refptr task_runner, - ::media::MediaLog* /* media_log */, - const base::UnguessableToken& overlay_plane_id) { - DCHECK(video_geometry_setter_); - auto cast_renderer = std::make_unique( - backend_factory_, task_runner, video_mode_switcher_, - video_resolution_policy_, overlay_plane_id, frame_interfaces, - enable_buffering_cb_.Run()); - cast_renderer->SetVideoGeometrySetterService(video_geometry_setter_); - return cast_renderer; -} -#endif - -std::unique_ptr<::media::Renderer> CastMojoMediaClient::CreateRenderer( - ::media::mojom::FrameInterfaceFactory* frame_interfaces, - scoped_refptr task_runner, - ::media::MediaLog* /* media_log */, - const std::string& audio_device_id) { - // TODO(guohuideng): CastMojoMediaClient is used only when build flag - // ENABLE_CAST_RENDERER is set. We can get rid of a number of related macros - // and the [[maybe_unused]]. - NOTREACHED(); -} - -std::unique_ptr<::media::CdmFactory> CastMojoMediaClient::CreateCdmFactory( - ::media::mojom::FrameInterfaceFactory* frame_interfaces) { - return create_cdm_factory_cb_.Run(frame_interfaces); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/service/cast_mojo_media_client.h chromium-132.0.6834.159/chromecast/media/service/cast_mojo_media_client.h --- chromium-132.0.6834.110/chromecast/media/service/cast_mojo_media_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/cast_mojo_media_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_SERVICE_CAST_MOJO_MEDIA_CLIENT_H_ -#define CHROMECAST_MEDIA_SERVICE_CAST_MOJO_MEDIA_CLIENT_H_ - -#include -#include - -#include "base/task/single_thread_task_runner.h" -#include "base/unguessable_token.h" -#include "media/mojo/buildflags.h" -#include "media/mojo/services/mojo_media_client.h" - -namespace chromecast { -namespace media { - -class CmaBackendFactory; -class VideoGeometrySetterService; -class VideoModeSwitcher; -class VideoResolutionPolicy; - -class CastMojoMediaClient : public ::media::MojoMediaClient { - public: - using CreateCdmFactoryCB = - base::RepeatingCallback( - ::media::mojom::FrameInterfaceFactory*)>; - using EnableBufferingCB = base::RepeatingCallback; - - CastMojoMediaClient(CmaBackendFactory* backend_factory, - const CreateCdmFactoryCB& create_cdm_factory_cb, - VideoModeSwitcher* video_mode_switcher, - VideoResolutionPolicy* video_resolution_policy, - EnableBufferingCB enable_buffering_cb); - - CastMojoMediaClient(const CastMojoMediaClient&) = delete; - CastMojoMediaClient& operator=(const CastMojoMediaClient&) = delete; - - ~CastMojoMediaClient() override; - -#if BUILDFLAG(ENABLE_CAST_RENDERER) - void SetVideoGeometrySetterService( - VideoGeometrySetterService* video_geometry_setter); -#endif - - // MojoMediaClient implementation: -#if BUILDFLAG(ENABLE_CAST_RENDERER) - std::unique_ptr<::media::Renderer> CreateCastRenderer( - ::media::mojom::FrameInterfaceFactory* frame_interfaces, - scoped_refptr task_runner, - ::media::MediaLog* media_log, - const base::UnguessableToken& overlay_plane_id) override; -#endif - std::unique_ptr<::media::Renderer> CreateRenderer( - ::media::mojom::FrameInterfaceFactory* frame_interfaces, - scoped_refptr task_runner, - ::media::MediaLog* media_log, - const std::string& audio_device_id) override; - std::unique_ptr<::media::CdmFactory> CreateCdmFactory( - ::media::mojom::FrameInterfaceFactory* frame_interfaces) override; - - private: - CmaBackendFactory* const backend_factory_; - const CreateCdmFactoryCB create_cdm_factory_cb_; - [[maybe_unused]] VideoModeSwitcher* video_mode_switcher_; - [[maybe_unused]] VideoResolutionPolicy* video_resolution_policy_; - const EnableBufferingCB enable_buffering_cb_; - -#if BUILDFLAG(ENABLE_CAST_RENDERER) - VideoGeometrySetterService* video_geometry_setter_; -#endif -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_SERVICE_CAST_MOJO_MEDIA_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/service/cast_renderer.cc chromium-132.0.6834.159/chromecast/media/service/cast_renderer.cc --- chromium-132.0.6834.110/chromecast/media/service/cast_renderer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/cast_renderer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,427 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/media/service/cast_renderer.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/task_runner_impl.h" -#include "chromecast/media/base/audio_device_ids.h" -#include "chromecast/media/base/video_mode_switcher.h" -#include "chromecast/media/base/video_resolution_policy.h" -#include "chromecast/media/cdm/cast_cdm_context.h" -#include "chromecast/media/cma/base/balanced_media_task_runner_factory.h" -#include "chromecast/media/cma/base/demuxer_stream_adapter.h" -#include "chromecast/media/cma/pipeline/media_pipeline_impl.h" -#include "chromecast/media/cma/pipeline/video_pipeline_client.h" -#include "chromecast/media/service/video_geometry_setter_service.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" -#include "media/audio/audio_device_description.h" -#include "media/base/audio_decoder_config.h" -#include "media/base/demuxer_stream.h" -#include "media/base/media_log.h" -#include "media/base/media_resource.h" -#include "media/base/renderer_client.h" - -namespace chromecast { -namespace media { - -namespace { - -// Maximum difference between audio frame PTS and video frame PTS -// for frames read from the DemuxerStream. -const base::TimeDelta kMaxDeltaFetcher(base::Milliseconds(2000)); - -void VideoModeSwitchCompletionCb(::media::PipelineStatusCallback init_cb, - bool success) { - if (!success) { - LOG(ERROR) << "Video mode switch failed."; - std::move(init_cb).Run(::media::PIPELINE_ERROR_INITIALIZATION_FAILED); - return; - } - LOG(INFO) << "Video mode switched successfully."; - std::move(init_cb).Run(::media::PIPELINE_OK); -} -} // namespace - -CastRenderer::CastRenderer( - CmaBackendFactory* backend_factory, - const scoped_refptr& task_runner, - VideoModeSwitcher* video_mode_switcher, - VideoResolutionPolicy* video_resolution_policy, - const base::UnguessableToken& overlay_plane_id, - ::media::mojom::FrameInterfaceFactory* frame_interfaces, - bool is_buffering_enabled) - : backend_factory_(backend_factory), - task_runner_(task_runner), - video_mode_switcher_(video_mode_switcher), - video_resolution_policy_(video_resolution_policy), - overlay_plane_id_(overlay_plane_id), - frame_interfaces_(frame_interfaces), - client_(nullptr), - cast_cdm_context_(nullptr), - media_task_runner_factory_( - new BalancedMediaTaskRunnerFactory(kMaxDeltaFetcher)), - video_geometry_setter_service_(nullptr), - is_buffering_enabled_(is_buffering_enabled), - weak_factory_(this) { - DCHECK(backend_factory_); - LOG(INFO) << __FUNCTION__ << ": " << this; - - if (video_resolution_policy_) - video_resolution_policy_->AddObserver(this); - - if (frame_interfaces_) { - frame_interfaces_->BindEmbedderReceiver(mojo::GenericPendingReceiver( - service_connector_.BindNewPipeAndPassReceiver())); - } -} - -CastRenderer::~CastRenderer() { - LOG(INFO) << __FUNCTION__ << ": " << this; - DCHECK(task_runner_->BelongsToCurrentThread()); - - if (video_resolution_policy_) - video_resolution_policy_->RemoveObserver(this); -} - -void CastRenderer::SetVideoGeometrySetterService( - VideoGeometrySetterService* video_geometry_setter_service) { - video_geometry_setter_service_ = video_geometry_setter_service; -} - -void CastRenderer::Initialize(::media::MediaResource* media_resource, - ::media::RendererClient* client, - ::media::PipelineStatusCallback init_cb) { - LOG(INFO) << __FUNCTION__ << ": " << this; - DCHECK(task_runner_->BelongsToCurrentThread()); - - init_cb_ = std::move(init_cb); - - if (video_geometry_setter_service_) { - video_geometry_setter_service_->GetVideoGeometryChangeSubscriber( - video_geometry_change_subcriber_remote_.BindNewPipeAndPassReceiver()); - DCHECK(video_geometry_change_subcriber_remote_); - - video_geometry_change_subcriber_remote_->SubscribeToVideoGeometryChange( - overlay_plane_id_, - video_geometry_change_client_receiver_.BindNewPipeAndPassRemote(), - base::BindOnce(&CastRenderer::OnSubscribeToVideoGeometryChange, - base::Unretained(this), media_resource, client)); - } else { - OnSubscribeToVideoGeometryChange(media_resource, client); - } -} - -void CastRenderer::OnSubscribeToVideoGeometryChange( - ::media::MediaResource* media_resource, - ::media::RendererClient* client) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(!application_media_info_manager_remote_); - - // Retrieve application_media_info_manager_remote_ if it is available via - // CastApplicationMediaInfoManager. - - if (frame_interfaces_) { - frame_interfaces_->BindEmbedderReceiver(mojo::GenericPendingReceiver( - application_media_info_manager_remote_.BindNewPipeAndPassReceiver())); - } - - if (application_media_info_manager_remote_) { - application_media_info_manager_remote_->GetCastApplicationMediaInfo( - base::BindOnce(&CastRenderer::OnApplicationMediaInfoReceived, - weak_factory_.GetWeakPtr(), media_resource, client)); - } else { - // If a CastRenderer is created for a purpose other than a web application, - // the CastApplicationMediaInfoManager interface is not available, and - // default CastApplicationMediaInfo value below will be used. - OnApplicationMediaInfoReceived( - media_resource, client, - ::media::mojom::CastApplicationMediaInfo::New( - std::string(), true /* mixer_audio_enabled */, - false /* is_audio_only_session */)); - } -} - -void CastRenderer::OnApplicationMediaInfoReceived( - ::media::MediaResource* media_resource, - ::media::RendererClient* client, - ::media::mojom::CastApplicationMediaInfoPtr application_media_info) { - DCHECK(task_runner_->BelongsToCurrentThread()); - LOG(INFO) << __FUNCTION__ << ": " << this - << " session_id=" << application_media_info->application_session_id - << ", mixer_audio_enabled=" - << application_media_info->mixer_audio_enabled; - // Create pipeline backend. - backend_task_runner_.reset(new TaskRunnerImpl()); - // TODO(erickung): crbug.com/443956. Need to provide right LoadType. - LoadType load_type = kLoadTypeMediaSource; - MediaPipelineDeviceParams::MediaSyncType sync_type = - (load_type == kLoadTypeMediaStream || !is_buffering_enabled_) - ? MediaPipelineDeviceParams::kModeIgnorePts - : MediaPipelineDeviceParams::kModeSyncPts; - - MediaPipelineDeviceParams params( - sync_type, backend_task_runner_.get(), AudioContentType::kMedia, - ::media::AudioDeviceDescription::kDefaultDeviceId); - params.session_id = application_media_info->application_session_id; - params.pass_through_audio_support_desired = - !application_media_info->mixer_audio_enabled; - - auto backend = backend_factory_->CreateBackend(params); - - // Create pipeline. - MediaPipelineClient pipeline_client; - pipeline_client.error_cb = - base::BindRepeating(&CastRenderer::OnError, weak_factory_.GetWeakPtr()); - pipeline_client.buffering_state_cb = base::BindRepeating( - &CastRenderer::OnBufferingStateChange, weak_factory_.GetWeakPtr()); - pipeline_.reset(new MediaPipelineImpl()); - pipeline_->SetClient(std::move(pipeline_client)); - pipeline_->Initialize(load_type, std::move(backend), is_buffering_enabled_); - - // TODO(servolk): Implement support for multiple streams. For now use the - // first enabled audio and video streams to preserve the existing behavior. - ::media::DemuxerStream* audio_stream = - media_resource->GetFirstStream(::media::DemuxerStream::AUDIO); - ::media::DemuxerStream* video_stream = - media_resource->GetFirstStream(::media::DemuxerStream::VIDEO); - - // Initialize audio. - if (audio_stream) { - AvPipelineClient audio_client; - audio_client.waiting_cb = base::BindRepeating(&CastRenderer::OnWaiting, - weak_factory_.GetWeakPtr()); - audio_client.eos_cb = base::BindRepeating( - &CastRenderer::OnEnded, weak_factory_.GetWeakPtr(), STREAM_AUDIO); - audio_client.playback_error_cb = - base::BindRepeating(&CastRenderer::OnError, weak_factory_.GetWeakPtr()); - audio_client.statistics_cb = base::BindRepeating( - &CastRenderer::OnStatisticsUpdate, weak_factory_.GetWeakPtr()); - std::unique_ptr frame_provider(new DemuxerStreamAdapter( - task_runner_, media_task_runner_factory_, audio_stream)); - - ::media::PipelineStatus status = pipeline_->InitializeAudio( - audio_stream->audio_decoder_config(), std::move(audio_client), - std::move(frame_provider)); - if (status != ::media::PIPELINE_OK) { - RunInitCallback(status); - return; - } - audio_stream->EnableBitstreamConverter(); - } - - // Initialize video. - if (video_stream) { - VideoPipelineClient video_client; - video_client.av_pipeline_client.waiting_cb = base::BindRepeating( - &CastRenderer::OnWaiting, weak_factory_.GetWeakPtr()); - video_client.av_pipeline_client.eos_cb = base::BindRepeating( - &CastRenderer::OnEnded, weak_factory_.GetWeakPtr(), STREAM_VIDEO); - video_client.av_pipeline_client.playback_error_cb = - base::BindRepeating(&CastRenderer::OnError, weak_factory_.GetWeakPtr()); - video_client.av_pipeline_client.statistics_cb = base::BindRepeating( - &CastRenderer::OnStatisticsUpdate, weak_factory_.GetWeakPtr()); - video_client.natural_size_changed_cb = base::BindRepeating( - &CastRenderer::OnVideoNaturalSizeChange, weak_factory_.GetWeakPtr()); - // TODO(alokp): Change MediaPipelineImpl API to accept a single config - // after CmaRenderer is deprecated. - std::vector<::media::VideoDecoderConfig> video_configs; - video_configs.push_back(video_stream->video_decoder_config()); - std::unique_ptr frame_provider(new DemuxerStreamAdapter( - task_runner_, media_task_runner_factory_, video_stream)); - - ::media::PipelineStatus status = pipeline_->InitializeVideo( - video_configs, std::move(video_client), std::move(frame_provider)); - if (status != ::media::PIPELINE_OK) { - RunInitCallback(status); - return; - } - video_stream->EnableBitstreamConverter(); - } - - if (cast_cdm_context_) { - pipeline_->SetCdm(cast_cdm_context_); - cast_cdm_context_ = nullptr; - } - - if (pending_volume_.has_value()) { - pipeline_->SetVolume(pending_volume_.value()); - pending_volume_.reset(); - } - - client_ = client; - - if (video_stream && video_mode_switcher_) { - std::vector<::media::VideoDecoderConfig> video_configs; - video_configs.push_back(video_stream->video_decoder_config()); - auto mode_switch_completion_cb = - base::BindOnce(&CastRenderer::OnVideoInitializationFinished, - weak_factory_.GetWeakPtr()); - video_mode_switcher_->SwitchMode( - video_configs, base::BindOnce(&VideoModeSwitchCompletionCb, - std::move(mode_switch_completion_cb))); - } else if (video_stream) { - // No mode switch needed. - OnVideoInitializationFinished(::media::PIPELINE_OK); - } else { - RunInitCallback(::media::PIPELINE_OK); - } -} - -void CastRenderer::RunInitCallback(::media::PipelineStatus status) { - if (init_cb_) - std::move(init_cb_).Run(status); -} - -void CastRenderer::OnVideoInitializationFinished( - ::media::PipelineStatus status) { - RunInitCallback(status); - if (status == ::media::PIPELINE_OK) { - // Force compositor to treat video as opaque (needed for overlay codepath). - OnVideoOpacityChange(true); - } -} - -void CastRenderer::SetCdm(::media::CdmContext* cdm_context, - CdmAttachedCB cdm_attached_cb) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(cdm_context); - - auto* cast_cdm_context = static_cast(cdm_context); - - if (!pipeline_) { - // If the pipeline has not yet been created in Initialize(), cache - // |cast_cdm_context| and pass it in when Initialize() is called. - cast_cdm_context_ = cast_cdm_context; - } else { - pipeline_->SetCdm(cast_cdm_context); - } - - std::move(cdm_attached_cb).Run(true); -} - -void CastRenderer::SetLatencyHint(std::optional latency_hint) { -} - -void CastRenderer::Flush(base::OnceClosure flush_cb) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(pipeline_); - pipeline_->Flush(std::move(flush_cb)); -} - -void CastRenderer::StartPlayingFrom(base::TimeDelta time) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(pipeline_); - - eos_[STREAM_AUDIO] = !pipeline_->HasAudio(); - eos_[STREAM_VIDEO] = !pipeline_->HasVideo(); - pipeline_->StartPlayingFrom(time); -} - -void CastRenderer::SetPlaybackRate(double playback_rate) { - DCHECK(task_runner_->BelongsToCurrentThread()); - pipeline_->SetPlaybackRate(playback_rate); -} - -void CastRenderer::SetVolume(float volume) { - DCHECK(task_runner_->BelongsToCurrentThread()); - // If pipeline is not initialized, cache the volume and delay the volume set - // until media pipeline is setup. - if (!pipeline_) { - pending_volume_ = volume; - return; - } - - pipeline_->SetVolume(volume); -} - -base::TimeDelta CastRenderer::GetMediaTime() { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(pipeline_); - return pipeline_->GetMediaTime(); -} - -::media::RendererType CastRenderer::GetRendererType() { - return ::media::RendererType::kCast; -} - -void CastRenderer::OnVideoResolutionPolicyChanged() { - DCHECK(task_runner_->BelongsToCurrentThread()); - if (!video_resolution_policy_) - return; - - if (video_resolution_policy_->ShouldBlock(video_res_)) - OnError(::media::PIPELINE_ERROR_DECODE); -} - -void CastRenderer::OnVideoGeometryChange(const gfx::RectF& rect_f, - gfx::OverlayTransform transform) { - GetOverlayCompositedCallback().Run(rect_f, transform); -} - -void CastRenderer::OnError(::media::PipelineStatus status) { - DCHECK(task_runner_->BelongsToCurrentThread()); - if (client_) { - client_->OnError(status); - } -} - -void CastRenderer::OnEnded(Stream stream) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(!eos_[stream]); - eos_[stream] = true; - LOG(INFO) << __FUNCTION__ << ": eos_audio=" << eos_[STREAM_AUDIO] - << " eos_video=" << eos_[STREAM_VIDEO]; - if (eos_[STREAM_AUDIO] && eos_[STREAM_VIDEO]) - client_->OnEnded(); -} - -void CastRenderer::OnStatisticsUpdate( - const ::media::PipelineStatistics& stats) { - DCHECK(task_runner_->BelongsToCurrentThread()); - client_->OnStatisticsUpdate(stats); -} - -void CastRenderer::OnBufferingStateChange( - ::media::BufferingState state, - ::media::BufferingStateChangeReason reason) { - DCHECK(task_runner_->BelongsToCurrentThread()); - client_->OnBufferingStateChange(state, reason); -} - -void CastRenderer::OnWaiting(::media::WaitingReason reason) { - DCHECK(task_runner_->BelongsToCurrentThread()); - client_->OnWaiting(reason); -} - -void CastRenderer::OnVideoNaturalSizeChange(const gfx::Size& size) { - DCHECK(task_runner_->BelongsToCurrentThread()); - client_->OnVideoNaturalSizeChange(size); - - video_res_ = size; - OnVideoResolutionPolicyChanged(); -} - -void CastRenderer::OnVideoOpacityChange(bool opaque) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(opaque); - client_->OnVideoOpacityChange(opaque); -} - -// static -void CastRenderer::SetOverlayCompositedCallback( - const OverlayCompositedCallback& cb) { - GetOverlayCompositedCallback() = cb; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/service/cast_renderer.h chromium-132.0.6834.159/chromecast/media/service/cast_renderer.h --- chromium-132.0.6834.110/chromecast/media/service/cast_renderer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/cast_renderer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,153 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_SERVICE_CAST_RENDERER_H_ -#define CHROMECAST_MEDIA_SERVICE_CAST_RENDERER_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/no_destructor.h" -#include "base/unguessable_token.h" -#include "chromecast/common/mojom/service_connector.mojom.h" -#include "chromecast/media/api/cma_backend_factory.h" -#include "chromecast/media/base/video_resolution_policy.h" -#include "chromecast/media/service/mojom/video_geometry_setter.mojom.h" -#include "media/base/renderer.h" -#include "media/base/waiting.h" -#include "media/mojo/mojom/cast_application_media_info_manager.mojom.h" -#include "media/mojo/mojom/frame_interface_factory.mojom.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "ui/gfx/geometry/rect_f.h" -#include "ui/gfx/overlay_transform.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace chromecast { -class TaskRunnerImpl; - -namespace media { -class BalancedMediaTaskRunnerFactory; -class CastCdmContext; -class MediaPipelineImpl; -class VideoGeometrySetterService; -class VideoModeSwitcher; - -class CastRenderer final : public ::media::Renderer, - public VideoResolutionPolicy::Observer, - public mojom::VideoGeometryChangeClient { - public: - // |frame_interfaces| provides interfaces tied to RenderFrameHost. - CastRenderer(CmaBackendFactory* backend_factory, - const scoped_refptr& task_runner, - VideoModeSwitcher* video_mode_switcher, - VideoResolutionPolicy* video_resolution_policy, - const base::UnguessableToken& overlay_plane_id, - ::media::mojom::FrameInterfaceFactory* frame_interfaces, - bool is_buffering_enabled); - - CastRenderer(const CastRenderer&) = delete; - CastRenderer& operator=(const CastRenderer&) = delete; - - ~CastRenderer() override; - // For CmaBackend implementation, CastRenderer must be connected to - // VideoGeometrySetterService. - void SetVideoGeometrySetterService( - VideoGeometrySetterService* video_geometry_setter_service); - - // ::media::Renderer implementation. - void Initialize(::media::MediaResource* media_resource, - ::media::RendererClient* client, - ::media::PipelineStatusCallback init_cb) override; - void SetCdm(::media::CdmContext* cdm_context, - CdmAttachedCB cdm_attached_cb) override; - void SetLatencyHint(std::optional latency_hint) override; - void Flush(base::OnceClosure flush_cb) override; - void StartPlayingFrom(base::TimeDelta time) override; - void SetPlaybackRate(double playback_rate) override; - void SetVolume(float volume) override; - base::TimeDelta GetMediaTime() override; - ::media::RendererType GetRendererType() override; - - // VideoResolutionPolicy::Observer implementation. - void OnVideoResolutionPolicyChanged() override; - - // mojom::VideoGeometryChangeClient implementation. - void OnVideoGeometryChange(const gfx::RectF& rect_f, - gfx::OverlayTransform transform) override; - - // TODO(guohuideng): For now we use a global callback to gain access to - // VideoPlaneController so CastRenderer can set the video geometry. We - // should separate the SetGeometry from VideoPlaneController and get rid - // of this callback. see b/79266094. - using OverlayCompositedCallback = - base::RepeatingCallback; - static void SetOverlayCompositedCallback(const OverlayCompositedCallback& cb); - - private: - enum Stream { STREAM_AUDIO, STREAM_VIDEO }; - void OnSubscribeToVideoGeometryChange(::media::MediaResource* media_resource, - ::media::RendererClient* client); - void OnApplicationMediaInfoReceived( - ::media::MediaResource* media_resource, - ::media::RendererClient* client, - ::media::mojom::CastApplicationMediaInfoPtr application_media_info); - void OnError(::media::PipelineStatus status); - void OnEnded(Stream stream); - void OnStatisticsUpdate(const ::media::PipelineStatistics& stats); - void OnBufferingStateChange(::media::BufferingState state, - ::media::BufferingStateChangeReason reason); - void OnWaiting(::media::WaitingReason reason); - void OnVideoNaturalSizeChange(const gfx::Size& size); - void OnVideoOpacityChange(bool opaque); - void CheckVideoResolutionPolicy(); - void RunInitCallback(::media::PipelineStatus status); - void OnVideoInitializationFinished(::media::PipelineStatus status); - - CmaBackendFactory* const backend_factory_; - scoped_refptr task_runner_; - VideoModeSwitcher* video_mode_switcher_; - VideoResolutionPolicy* video_resolution_policy_; - base::UnguessableToken overlay_plane_id_; - mojo::Remote service_connector_; - ::media::mojom::FrameInterfaceFactory* frame_interfaces_; - - ::media::RendererClient* client_; - CastCdmContext* cast_cdm_context_; - scoped_refptr media_task_runner_factory_; - std::unique_ptr backend_task_runner_; - std::unique_ptr pipeline_; - bool eos_[2]; - gfx::Size video_res_; - - mojo::Remote<::media::mojom::CastApplicationMediaInfoManager> - application_media_info_manager_remote_; - VideoGeometrySetterService* video_geometry_setter_service_; - mojo::Remote - video_geometry_change_subcriber_remote_; - ::media::PipelineStatusCallback init_cb_; - mojo::Receiver - video_geometry_change_client_receiver_{this}; - - static OverlayCompositedCallback& GetOverlayCompositedCallback() { - static base::NoDestructor - g_overlay_composited_callback; - return *g_overlay_composited_callback; - } - - std::optional pending_volume_; - - const bool is_buffering_enabled_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_SERVICE_CAST_RENDERER_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/service/mojom/OWNERS chromium-132.0.6834.159/chromecast/media/service/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/media/service/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS - diff -Nru chromium-132.0.6834.110/chromecast/media/service/mojom/video_geometry_setter.mojom chromium-132.0.6834.159/chromecast/media/service/mojom/video_geometry_setter.mojom --- chromium-132.0.6834.110/chromecast/media/service/mojom/video_geometry_setter.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/mojom/video_geometry_setter.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.media.mojom; - -import "mojo/public/mojom/base/unguessable_token.mojom"; -import "ui/gfx/geometry/mojom/geometry.mojom"; -import "ui/gfx/mojom/overlay_transform.mojom"; - -// The purpose of VideoGeometrySetterService is to provide a brokerage between -// chromecast::media::CastRenderers and viz::OverlayStrategyUnderlayCast, in a -// situation where multiple instances of CastRenderers possibly run within -// different instances of MediaService. When OverlayStrategyUnderlayCast decides -// to set video geometry on a certain CastRenderer, it relies on -// VideoGeometrySetterService to pass the geometry information to the right CastRenderer. - -// CastRenderer must implement this interface. -// CastRenderer is used in multiple places but right now only CastRenderers -// running within ::media::MediaService, on browser process, are using -// video geometry setter service. -interface VideoGeometryChangeClient { -// Implementation of VideoGeometryChangeClient sets the video geometry on -// itself. - OnVideoGeometryChange(gfx.mojom.RectF rect_f, gfx.mojom.OverlayTransform - transform); -}; - -// A single instance of VideoGeometrySetterService provides both the interface -// and VideoGeometryChangeSubscriber and VideoGeometrySetter. - -// To be used by a VideoGeometryChangeClient(i.e., a CastRenderer). -// CastRenders running in browser process can subscribe for the video geometry -// information, that would be sent from compositor, which is being migrated -// from browser process to GPU process. -interface VideoGeometryChangeSubscriber { -// A VideoGeometryChangeClient informs VideoGeometrySetterService its existence. -// |overlay_plane_id| identifies the VideoGeometryChangeClient, -// |client_pending_remote| is the pending remote bound to the -// VideoGeometryChangeClient itself. - SubscribeToVideoGeometryChange( - mojo_base.mojom.UnguessableToken overlay_plane_id, - pending_remote client_pending_remote) => (); -}; - -// To be used by OverlayStrategyUnderlayCast, which is part of compositor that -// is being migrated to GPU process. Within GPU process -// OverlayStrategyUnderlayCast cannot access CastRenderer any more, so it -// uses VideoGeometrySetter interface to send out the geometry information to -// VideoGeometrySetter, which then forward it to the right CastRenderer. -interface VideoGeometrySetter { -// Informs VideoGeometrySetterService the video geometry information and the -// target CastRenderer, identified by |overlay_plane_id|, that the geometry is -// set to. - SetVideoGeometry(gfx.mojom.RectF rect_f, - gfx.mojom.OverlayTransform transform, - mojo_base.mojom.UnguessableToken overlay_plane_id); -}; diff -Nru chromium-132.0.6834.110/chromecast/media/service/video_geometry_setter_service.cc chromium-132.0.6834.159/chromecast/media/service/video_geometry_setter_service.cc --- chromium-132.0.6834.110/chromecast/media/service/video_geometry_setter_service.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/video_geometry_setter_service.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "video_geometry_setter_service.h" - -#include - -#include "base/task/sequenced_task_runner.h" - -#define MAKE_SURE_ON_SEQUENCE(callback, ...) \ - if (!task_runner_->RunsTasksInCurrentSequence()) { \ - task_runner_->PostTask( \ - FROM_HERE, base::BindOnce(&VideoGeometrySetterService::callback, \ - weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); \ - return; \ - } - -namespace chromecast { -namespace media { - -VideoGeometrySetterService::VideoGeometrySetterService() - : task_runner_(base::SequencedTaskRunner::GetCurrentDefault()), - weak_factory_(this) {} - -VideoGeometrySetterService::~VideoGeometrySetterService() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); -} - -void VideoGeometrySetterService::GetVideoGeometryChangeSubscriber( - mojo::PendingReceiver - pending_receiver) { - MAKE_SURE_ON_SEQUENCE(GetVideoGeometryChangeSubscriber, - std::move(pending_receiver)); - video_geometry_change_subscriber_receivers_.Add(this, - std::move(pending_receiver)); -} -void VideoGeometrySetterService::GetVideoGeometrySetter( - mojo::PendingReceiver pending_receiver) { - MAKE_SURE_ON_SEQUENCE(GetVideoGeometrySetter, std::move(pending_receiver)); - if (video_geometry_setter_receiver_.is_bound()) { - LOG(ERROR) << __func__ << " VideoGeometrySetter dropped"; - video_geometry_setter_receiver_.reset(); - } - video_geometry_setter_receiver_.Bind(std::move(pending_receiver)); -} - -void VideoGeometrySetterService::SubscribeToVideoGeometryChange( - const base::UnguessableToken& overlay_plane_id, - mojo::PendingRemote client_pending_remote, - SubscribeToVideoGeometryChangeCallback callback) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - auto client = mojo::Remote( - std::move(client_pending_remote)); - // The remote end closes the message pipe for the client when it no longer - // wants to receive updates. - // If the disconnect_handler is called, |this| must be alive, so Unretained is - // safe. - client.set_disconnect_handler(base::BindOnce( - &VideoGeometrySetterService::OnVideoGeometryChangeClientGone, - base::Unretained(this), overlay_plane_id)); - video_geometry_change_clients_[overlay_plane_id] = std::move(client); - - std::move(callback).Run(); -} - -void VideoGeometrySetterService::SetVideoGeometry( - const gfx::RectF& rect_f, - gfx::OverlayTransform transform, - const base::UnguessableToken& overlay_plane_id) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - auto video_geometry_change_client = - video_geometry_change_clients_.find(overlay_plane_id); - if (video_geometry_change_client != video_geometry_change_clients_.end()) { - video_geometry_change_client->second->OnVideoGeometryChange(rect_f, - transform); - } -} - -// When a VideoGeometryChangeClient is gone, delete the corresponding entry in -// the mapping. -void VideoGeometrySetterService::OnVideoGeometryChangeClientGone( - const base::UnguessableToken overlay_plane_id) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - video_geometry_change_clients_.erase(overlay_plane_id); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/media/service/video_geometry_setter_service.h chromium-132.0.6834.159/chromecast/media/service/video_geometry_setter_service.h --- chromium-132.0.6834.110/chromecast/media/service/video_geometry_setter_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/service/video_geometry_setter_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_MEDIA_SERVICE_VIDEO_GEOMETRY_SETTER_SERVICE_H_ -#define CHROMECAST_MEDIA_SERVICE_VIDEO_GEOMETRY_SETTER_SERVICE_H_ - -#include "base/containers/flat_map.h" -#include "base/functional/bind.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/unguessable_token.h" -#include "chromecast/media/service/mojom/video_geometry_setter.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/receiver_set.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace chromecast { -namespace media { - -// This service runs and destructs on the sequence where it's constructed, but -// the public methods can be run on any sequence. -class VideoGeometrySetterService final - : public mojom::VideoGeometryChangeSubscriber, - public mojom::VideoGeometrySetter { - public: - VideoGeometrySetterService(); - - VideoGeometrySetterService(const VideoGeometrySetterService&) = delete; - VideoGeometrySetterService& operator=(const VideoGeometrySetterService&) = - delete; - - ~VideoGeometrySetterService() override; - - void GetVideoGeometryChangeSubscriber( - mojo::PendingReceiver - pending_receiver); - void GetVideoGeometrySetter( - mojo::PendingReceiver pending_receiver); - - private: - // mojom::VideoGeometryChangeSubscriber implementation. - void SubscribeToVideoGeometryChange( - const base::UnguessableToken& overlay_plane_id, - mojo::PendingRemote - client_pending_remote, - SubscribeToVideoGeometryChangeCallback callback) override; - // mojom::VideoGeometrySetter implementation. - void SetVideoGeometry( - const gfx::RectF& rect_f, - gfx::OverlayTransform transform, - const base::UnguessableToken& overlay_plane_id) override; - - void OnVideoGeometryChangeClientGone( - const base::UnguessableToken overlay_plane_id); - - const scoped_refptr task_runner_; - - base::flat_map> - video_geometry_change_clients_; - - mojo::ReceiverSet - video_geometry_change_subscriber_receivers_; - mojo::Receiver video_geometry_setter_receiver_{ - this}; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_MEDIA_SERVICE_VIDEO_GEOMETRY_SETTER_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/media/test/run_all_unittests.cc chromium-132.0.6834.159/chromecast/media/test/run_all_unittests.cc --- chromium-132.0.6834.110/chromecast/media/test/run_all_unittests.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/media/test/run_all_unittests.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/functional/bind.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "build/build_config.h" -#include "media/base/media.h" -#include "mojo/core/embedder/embedder.h" - -class CastMediaTestSuite : public base::TestSuite { - public: - // Note: the base class constructor creates an AtExitManager. - CastMediaTestSuite(int argc, char** argv) : TestSuite(argc, argv) {} - ~CastMediaTestSuite() override {} - - protected: - void Initialize() override; -}; - -void CastMediaTestSuite::Initialize() { - // Run TestSuite::Initialize first so that logging is initialized. - base::TestSuite::Initialize(); - - // Initialize the FFMpeg library. - // Note: at this time, AtExitManager is already present. - media::InitializeMediaLibrary(); -} - -int main(int argc, char** argv) { - CastMediaTestSuite test_suite(argc, argv); - mojo::core::Init(); - - return base::LaunchUnitTests( - argc, argv, - base::BindOnce(&CastMediaTestSuite::Run, base::Unretained(&test_suite))); -} diff -Nru chromium-132.0.6834.110/chromecast/metrics/DEPS chromium-132.0.6834.159/chromecast/metrics/DEPS --- chromium-132.0.6834.110/chromecast/metrics/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -include_rules = [ - "+components/metrics", - "+components/prefs", - "+components/variations/synthetic_trial_registry.h", - "+net/base", - "+services/network/public", - "+third_party/metrics_proto", -] diff -Nru chromium-132.0.6834.110/chromecast/metrics/OWNERS chromium-132.0.6834.159/chromecast/metrics/OWNERS --- chromium-132.0.6834.110/chromecast/metrics/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -gfhuang@chromium.org -salilr@google.com diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_event_builder.cc chromium-132.0.6834.159/chromecast/metrics/cast_event_builder.cc --- chromium-132.0.6834.110/chromecast/metrics/cast_event_builder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_event_builder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/cast_event_builder.h" - -#include "third_party/metrics_proto/cast_logs.pb.h" - -namespace chromecast { - -// static -void CastEventBuilder::SetLaunchFromProto( - ::metrics::CastLogsProto_CastEventProto* out, - LaunchFrom launch_from) { - switch (launch_from) { - case FROM_UNKNOWN: - out->set_launch_from( - ::metrics::CastLogsProto_CastEventProto::FROM_UNKNOWN); - break; - case FROM_LOCAL: - out->set_launch_from(::metrics::CastLogsProto_CastEventProto::FROM_LOCAL); - break; - case FROM_DIAL: - out->set_launch_from(::metrics::CastLogsProto_CastEventProto::FROM_DIAL); - break; - case FROM_CAST_V2: - out->set_launch_from( - ::metrics::CastLogsProto_CastEventProto::FROM_CAST_V2); - break; - case FROM_CCS: - out->set_launch_from(::metrics::CastLogsProto_CastEventProto::FROM_CCS); - break; - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_event_builder.h chromium-132.0.6834.159/chromecast/metrics/cast_event_builder.h --- chromium-132.0.6834.110/chromecast/metrics/cast_event_builder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_event_builder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,131 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_CAST_EVENT_BUILDER_H_ -#define CHROMECAST_METRICS_CAST_EVENT_BUILDER_H_ - -#include - -#include -#include -#include - -namespace base { -class TimeTicks; -} // namespace base - -namespace metrics { -class CastLogsProto_CastEventProto; -} - -namespace net { -class IPAddressBytes; -} - -namespace chromecast { - -// Builder for CastLogsProto_CastEventProto. -class CastEventBuilder { - public: - // TODO(sanfin): as in the Build() method below, ideally this should just be - // the proto-generated enum, but we don't want to depend on the metrics - // component for now (in particular, because this requires generating the - // proto headers before compiling any translation unit that #includes this - // header, which is complicated by the fact that some code uses this header - // that is compiled outside the gn build system.) - enum LaunchFrom { - FROM_UNKNOWN, - FROM_LOCAL, - FROM_DIAL, - FROM_CAST_V2, - FROM_CCS, - }; - - // This is used to preclude a header file dependency on the header generated - // from third_party/metrics_proto/cast_logs.proto. - static void SetLaunchFromProto(::metrics::CastLogsProto_CastEventProto* out, - LaunchFrom launch_from); - - virtual ~CastEventBuilder() {} - - // Returns the unhashed event name set for this builder. - virtual std::string GetName() = 0; - - virtual CastEventBuilder& SetName(const std::string& name) = 0; - virtual CastEventBuilder& SetTime(const base::TimeTicks& time) = 0; - - virtual CastEventBuilder& SetTimezoneId(const std::string& timezone_id) = 0; - virtual CastEventBuilder& SetAppId(const std::string& app_id) = 0; - virtual CastEventBuilder& SetRemoteAppId( - const std::string& remote_app_id) = 0; - virtual CastEventBuilder& SetSessionId(const std::string& session_id) = 0; - virtual CastEventBuilder& SetSdkVersion(const std::string& sdk_version) = 0; - virtual CastEventBuilder& SetMplVersion(const std::string& mpl_version) = 0; - virtual CastEventBuilder& SetConnectionInfo( - const std::string& transport_connection_id, - const std::string& virtual_connection_id) = 0; - virtual CastEventBuilder& SetGroupUuid(const std::string& group_uuid) = 0; - virtual CastEventBuilder& SetExtraValue(int64_t extra_value) = 0; - virtual CastEventBuilder& SetConversationKey( - const std::string& conversation_key) = 0; - virtual CastEventBuilder& SetRequestId(int32_t request_id) = 0; - virtual CastEventBuilder& SetEventId(const std::string& event_id) = 0; - virtual CastEventBuilder& SetAoghRequestId(const std::string& request_id) = 0; - virtual CastEventBuilder& SetAoghLocalDeviceId(int64_t local_id) = 0; - virtual CastEventBuilder& SetAoghAgentId(const std::string& agent_id) = 0; - virtual CastEventBuilder& SetAoghStandardAgentId( - const std::string& standard_agent_id) = 0; - virtual CastEventBuilder& SetUiVersion(const std::string& ui_version) = 0; - virtual CastEventBuilder& SetAuditReport(const std::string& audit_report) = 0; - virtual CastEventBuilder& SetDuoCoreVersion(int64_t version) = 0; - virtual CastEventBuilder& SetHotwordModelId(const std::string& model_id) = 0; - - // Only used for reporting discovery related events. Sets the application - // subtype related to the event, where |app_id| is the 8-byte hex string - // for the given V2 app. - virtual CastEventBuilder& SetDiscoveryAppSubtype( - const std::string& app_id) = 0; - // Only used for reporting discovery related events. Sets the namespace - // subtype related to the event, where |namespace_hash| is the SHA-1 hash - // string for the given V2 app namespace. - virtual CastEventBuilder& SetDiscoveryNamespaceSubtype( - const std::string& namespace_hash) = 0; - // Only used for reporting discovery related events. Sets the sender IP - // address associated with the given event. Used to track requests and - // responses on a per sender basis. |sender_ip| is a vector containing each - // byte in the IP address in network order. - virtual CastEventBuilder& SetDiscoverySender( - const net::IPAddressBytes& sender_ip) = 0; - // Only used for reported discovery related events. Sets/unsets the unicast - // flag used to specify what type of discovery is occurring, and to compare - // unicast vs. multicast usage and reliability. - // - // TODO(maclellant): Refactor discovery metrics into more general events that - // can be shared between all the discovery protocols. Right now this unicast - // flag is really only specific to MDNS to signal the type of request or - // response. - virtual CastEventBuilder& SetDiscoveryUnicastFlag(bool uses_unicast) = 0; - - virtual CastEventBuilder& SetFeatureVector( - const std::vector& features) = 0; - virtual CastEventBuilder& AddMetadata(const std::string& name, - int64_t value) = 0; - - virtual CastEventBuilder& SetLaunchFrom(LaunchFrom launch_from) = 0; - - // Populates fields from the provided CastEventProto. Similar to the protobuf - // MergeFrom method, singular fields are overwritten and repeated fields like - // metadata are concatenated. - virtual CastEventBuilder& MergeFrom( - const ::metrics::CastLogsProto_CastEventProto* event_proto) = 0; - - // Build the proto, caller takes ownership. - // TODO(gfhuang): Ideally this should be std::unique_ptr, but we don't want to - // have cast to depend on metrics component for now. - virtual ::metrics::CastLogsProto_CastEventProto* Build() = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_METRICS_CAST_EVENT_BUILDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_impl.cc chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl.cc --- chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,255 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/cast_event_builder_impl.h" - -#include "base/logging.h" -#include "base/metrics/metrics_hashes.h" -#include "base/ranges/algorithm.h" -#include "base/time/time.h" -#include "chromecast/base/hash_util.h" -#include "chromecast/metrics/cast_event_builder.h" -#include "chromecast/metrics/metrics_util.h" -#include "third_party/metrics_proto/cast_logs.pb.h" - -namespace chromecast { - -namespace { -// Bitmasks and values for the |transport_connection_id| field when recording -// discovery metrics for MDNS. -const uint32_t kDiscoverySenderMask = 0x0000FFFF; -const uint32_t kDiscoveryUnicastBit = 0x80000000; -} // namespace - -CastEventBuilderImpl::CastEventBuilderImpl() - : event_proto_(new ::metrics::CastLogsProto_CastEventProto) { - event_proto_->set_time_msec( - (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds()); -} - -CastEventBuilderImpl::~CastEventBuilderImpl() {} - -std::string CastEventBuilderImpl::GetName() { - return unhashed_event_name_; -} - -CastEventBuilder& CastEventBuilderImpl::SetName(const std::string& name) { - unhashed_event_name_ = name; - event_proto_->set_name_hash(base::HashMetricName(name)); - DVLOG(2) << "Hash metric " << name << " = " << std::hex - << event_proto_->name_hash(); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetTime(const base::TimeTicks& time) { - event_proto_->set_time_msec((time - base::TimeTicks()).InMilliseconds()); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetTimezoneId( - const std::string& timezone_id) { - event_proto_->set_timezone_id(timezone_id); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetAppId(const std::string& app_id) { - event_proto_->set_app_id(HashAppId32(app_id)); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetRemoteAppId( - const std::string& remote_app_id) { - event_proto_->set_remote_app_id(HashAppId32(remote_app_id)); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetSessionId( - const std::string& session_id) { - event_proto_->set_application_session_id(HashSessionId64(session_id)); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetSdkVersion( - const std::string& sdk_version) { - event_proto_->set_cast_receiver_version(HashSdkVersion64(sdk_version)); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetMplVersion( - const std::string& mpl_version) { - event_proto_->set_cast_mpl_version(HashSdkVersion64(mpl_version)); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetConnectionInfo( - const std::string& transport_connection_id, - const std::string& virtual_connection_id) { - event_proto_->set_transport_connection_id( - HashSocketId32(transport_connection_id)); - event_proto_->set_virtual_connection_id( - HashConnectionId32(virtual_connection_id)); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetGroupUuid( - const std::string& group_uuid) { - event_proto_->set_group_uuid(base::HashMetricName(group_uuid)); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetExtraValue(int64_t extra_value) { - event_proto_->set_value(extra_value); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetConversationKey( - const std::string& conversation_key) { - event_proto_->set_conversation_key(conversation_key); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetRequestId(int32_t request_id) { - event_proto_->set_request_id(request_id); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetEventId( - const std::string& event_id) { - event_proto_->set_event_id(event_id); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetAoghRequestId( - const std::string& request_id) { - event_proto_->set_aogh_request_id(request_id); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetAoghLocalDeviceId(int64_t local_id) { - event_proto_->set_aogh_local_device_id(local_id); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetAoghAgentId( - const std::string& agent_id) { - event_proto_->set_aogh_agent_id(agent_id); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetAoghStandardAgentId( - const std::string& standard_agent_id) { - event_proto_->set_aogh_standard_agent_id(standard_agent_id); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetUiVersion(const std::string& value) { - event_proto_->set_ui_version(value); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetAuditReport( - const std::string& audit_report) { - event_proto_->set_selinux_audit_detail(audit_report); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetDuoCoreVersion(int64_t version) { - event_proto_->set_duo_core_version(version); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetHotwordModelId( - const std::string& model_id) { - event_proto_->set_hotword_model_id(model_id); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetDiscoveryAppSubtype( - const std::string& app_id) { - // Application subtype can be directly added in full. - event_proto_->set_app_id(HashAppId32(app_id)); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetDiscoveryNamespaceSubtype( - const std::string& namespace_hash) { - // Namespace hash is a SHA-1 string that is 160-bits (20 bytes) of - // information, so a 40 character long hex string. We only have 32-bits to - // upload, so pull out the first 8 characters and hex decode it like an app- - // id. - event_proto_->set_app_id(HashAppId32(namespace_hash.substr(0, 8))); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetDiscoverySender( - const net::IPAddressBytes& sender_ip) { - // Pack the last two bytes of the sender IP address into a fragment that takes - // up the final two bytes. - uint32_t sender_fragment = GetIPAddressFragmentForLogging(sender_ip); - - // Re-use the |transport_connection_id| field to store sender IP address info, - // since discovery messages will not use this field normally. This gives - // 32-bits of space to store sender IP info, although only the lower 16-bits - // are used. - // - // Preserve the existing fields by only clearing the sender address (lower - // 16-bits), then OR with new sender fragment. - uint32_t value = event_proto_->transport_connection_id(); - value &= ~kDiscoverySenderMask; - value |= (sender_fragment & kDiscoverySenderMask); - event_proto_->set_transport_connection_id(value); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetDiscoveryUnicastFlag( - bool uses_unicast) { - // Re-use the highest bit in |transport_connection_id| field to store the - // unicast status of the discovery event, since discovery messages will not - // use this field normally. Other data may be stored in bits 0-30, so preserve - // the existing bits by only modifying the unicast bit. - uint32_t value = event_proto_->transport_connection_id(); - if (uses_unicast) { - value |= kDiscoveryUnicastBit; - } else { - value &= ~kDiscoveryUnicastBit; - } - event_proto_->set_transport_connection_id(value); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetFeatureVector( - const std::vector& features) { - event_proto_->mutable_feature_vector()->Resize(features.size(), 0); - float* mutable_data = event_proto_->mutable_feature_vector()->mutable_data(); - base::ranges::copy(features, mutable_data); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::AddMetadata(const std::string& name, - int64_t value) { - ::metrics::CastLogsProto_CastEventProto_Metadata* const metadata = - event_proto_->add_metadata(); - metadata->set_name_hash(base::HashMetricName(name)); - metadata->set_value(value); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::SetLaunchFrom(LaunchFrom launch_from) { - SetLaunchFromProto(event_proto_.get(), launch_from); - return *this; -} - -CastEventBuilder& CastEventBuilderImpl::MergeFrom( - const ::metrics::CastLogsProto_CastEventProto* event_proto) { - if (event_proto) { - event_proto_->MergeFrom(*event_proto); - } - return *this; -} - -::metrics::CastLogsProto_CastEventProto* CastEventBuilderImpl::Build() { - return event_proto_.release(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_impl.h chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl.h --- chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_CAST_EVENT_BUILDER_IMPL_H_ -#define CHROMECAST_METRICS_CAST_EVENT_BUILDER_IMPL_H_ - -#include -#include -#include - -#include "chromecast/metrics/cast_event_builder.h" - -namespace chromecast { - -class CastEventBuilderImpl : public CastEventBuilder { - public: - CastEventBuilderImpl(); - CastEventBuilderImpl(const CastEventBuilderImpl&) = delete; - CastEventBuilderImpl& operator=(const CastEventBuilderImpl&) = delete; - ~CastEventBuilderImpl() override; - - // CastEventBuilder implementation - std::string GetName() override; - CastEventBuilder& SetName(const std::string& name) override; - CastEventBuilder& SetTime(const base::TimeTicks& time) override; - CastEventBuilder& SetTimezoneId(const std::string& timezone_id) override; - CastEventBuilder& SetAppId(const std::string& app_id) override; - CastEventBuilder& SetRemoteAppId(const std::string& remote_app_id) override; - CastEventBuilder& SetSessionId(const std::string& session_id) override; - CastEventBuilder& SetSdkVersion(const std::string& sdk_version) override; - CastEventBuilder& SetMplVersion(const std::string& mpl_version) override; - CastEventBuilder& SetConnectionInfo( - const std::string& transport_connection_id, - const std::string& virtual_connection_id) override; - CastEventBuilder& SetGroupUuid(const std::string& group_uuid) override; - CastEventBuilder& SetExtraValue(int64_t extra_value) override; - CastEventBuilder& SetConversationKey( - const std::string& conversation_key) override; - CastEventBuilder& SetRequestId(int32_t request_id) override; - CastEventBuilder& SetEventId(const std::string& event_id) override; - CastEventBuilder& SetAoghRequestId(const std::string& request_id) override; - CastEventBuilder& SetAoghLocalDeviceId(int64_t local_id) override; - CastEventBuilder& SetAoghAgentId(const std::string& agent_id) override; - CastEventBuilder& SetAoghStandardAgentId( - const std::string& standard_agent_id) override; - CastEventBuilder& SetUiVersion(const std::string& ui_version) override; - CastEventBuilder& SetAuditReport(const std::string& audit_report) override; - CastEventBuilder& SetDuoCoreVersion(int64_t version) override; - CastEventBuilder& SetHotwordModelId(const std::string& model_id) override; - CastEventBuilder& SetDiscoveryAppSubtype(const std::string& app_id) override; - CastEventBuilder& SetDiscoveryNamespaceSubtype( - const std::string& namespace_hash) override; - CastEventBuilder& SetDiscoverySender( - const net::IPAddressBytes& sender_ip) override; - CastEventBuilder& SetDiscoveryUnicastFlag(bool uses_unicast) override; - CastEventBuilder& SetFeatureVector( - const std::vector& features) override; - CastEventBuilder& AddMetadata(const std::string& name, - int64_t value) override; - CastEventBuilder& SetLaunchFrom(LaunchFrom launch_from) override; - CastEventBuilder& MergeFrom( - const ::metrics::CastLogsProto_CastEventProto* event_proto) override; - - ::metrics::CastLogsProto_CastEventProto* Build() override; - - private: - std::unique_ptr<::metrics::CastLogsProto_CastEventProto> event_proto_; - std::string unhashed_event_name_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_METRICS_CAST_EVENT_BUILDER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_impl_unittest.cc chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl_unittest.cc --- chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_impl_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_impl_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,166 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/cast_event_builder_impl.h" - -#include "base/memory/ptr_util.h" -#include "base/metrics/metrics_hashes.h" -#include "net/base/ip_address.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/metrics_proto/cast_logs.pb.h" - -namespace chromecast { - -namespace { - -// Bitmasks and values for the |transport_connection_id| field when recording -// discovery metrics for mDNS. -const uint32_t kDiscoverySenderMask = 0x0000FFFF; -const uint32_t kDiscoveryUnicastBit = 0x80000000; - -} // namespace - -//============================================================================= -// CastEventBuilderImplTest -//============================================================================= - -TEST(CastEventBuilderImplTest, GetName) { - const char kCastEvent[] = "Cast.Test.Event"; - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - EXPECT_STRCASEEQ(builder.GetName().c_str(), kCastEvent); - auto proto = base::WrapUnique(builder.Build()); - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); -} - -TEST(CastEventBuilderImplTest, MergeFromCastEventProto) { - const char kOldCastEvent[] = "Cast.Test.Event.Old"; - const char kNewCastEvent[] = "Cast.Test.Event.New"; - auto old_proto = - base::WrapUnique(CastEventBuilderImpl().SetName(kOldCastEvent).Build()); - auto new_proto = - base::WrapUnique(CastEventBuilderImpl().SetName(kNewCastEvent).Build()); - auto merged_proto = base::WrapUnique(CastEventBuilderImpl() - .SetName(kOldCastEvent) - .MergeFrom(new_proto.get()) - .Build()); - EXPECT_NE(old_proto->name_hash(), merged_proto->name_hash()); - EXPECT_EQ(new_proto->name_hash(), merged_proto->name_hash()); -} - -TEST(CastEventBuilderImplTest, DiscoveryEvent_AppSubtype) { - const char kCastEvent[] = "Cast.Discovery.App.Subtype"; - - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - builder.SetDiscoveryAppSubtype("1234ABCD"); - auto proto = base::WrapUnique(builder.Build()); - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); - EXPECT_EQ(proto->app_id(), 0x1234ABCDu); -} - -TEST(CastEventBuilderImplTest, DiscoveryEvent_NamespaceSubtype) { - const char kCastEvent[] = "Cast.Discovery.Namespace.Subtype"; - - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - builder.SetDiscoveryNamespaceSubtype( - "4abd03646f53722ded0335a84493136da95d5dcb"); - auto proto = base::WrapUnique(builder.Build()); - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); - EXPECT_EQ(proto->app_id(), 0x4ABD0364u); -} - -TEST(CastEventBuilderImplTest, DiscoveryEvent_UnicastFlag) { - const char kCastEvent[] = "Cast.Discovery.Generic.Event"; - - // Set unicast bit, i.e. multicast was not used for discovery event. - { - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - builder.SetDiscoveryUnicastFlag(true); - auto proto = base::WrapUnique(builder.Build()); - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); - EXPECT_TRUE(proto->transport_connection_id() & kDiscoveryUnicastBit); - } - - // Clear unicast bit, i.e. multicast was used for discovery event. - { - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - builder.SetDiscoveryUnicastFlag(false); - auto proto = base::WrapUnique(builder.Build()); - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); - EXPECT_FALSE(proto->transport_connection_id() & kDiscoveryUnicastBit); - } -} - -TEST(CastEventBuilderImplTest, DiscoveryEvent_SenderAddress) { - const char kCastEvent[] = "Cast.Discovery.Generic.Event"; - - // IPv4 sender IP address. The last 2 bytes of the address in network order - // are grabbed and packed into 32-bit value. - { - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - net::IPAddress sender_ip; - ASSERT_TRUE(sender_ip.AssignFromIPLiteral("172.17.36.97")); - builder.SetDiscoverySender(sender_ip.bytes()); - auto proto = base::WrapUnique(builder.Build()); - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); - EXPECT_EQ(proto->transport_connection_id() & kDiscoverySenderMask, - 0x00002461u); - } - // IPv6 sender IP address. The last 2 bytes of the address in network order - // are grabbed and packed into 32-bit value. - { - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - net::IPAddress sender_ip; - ASSERT_TRUE( - sender_ip.AssignFromIPLiteral("2620:0:1000:2100:c59c:d8ec:85fe:11fe")); - builder.SetDiscoverySender(sender_ip.bytes()); - auto proto = base::WrapUnique(builder.Build()); - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); - EXPECT_EQ(proto->transport_connection_id() & kDiscoverySenderMask, - 0x000011FEu); - } - // IPv4 mapped address, where IPv4 address is mapped into a IPv6 address. The - // last 2 bytes of the original IPv4 address and mapped IPv4 address should - // match. - // "172.17.36.97" (IPv4) -> "0:0:0:0:0:ffff:ac11:2461" (IPv6) - { - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - net::IPAddress sender_ip; - ASSERT_TRUE(sender_ip.AssignFromIPLiteral("0:0:0:0:0:ffff:ac11:2461")); - builder.SetDiscoverySender(sender_ip.bytes()); - auto proto = base::WrapUnique(builder.Build()); - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); - // Last 4 bytes of mapped IPv4 address should match original IPv4 address. - EXPECT_EQ(proto->transport_connection_id() & kDiscoverySenderMask, - 0x00002461u); - } -} - -TEST(CastEventBuilderImplTest, DiscoveryEvent_AddressAndFlags) { - const char kCastEvent[] = "Cast.Discovery.Generic.Event"; - - CastEventBuilderImpl builder; - builder.SetName(kCastEvent); - builder.SetDiscoveryUnicastFlag(false); - net::IPAddress sender_ip; - ASSERT_TRUE(sender_ip.AssignFromIPLiteral("172.17.36.97")); - builder.SetDiscoverySender(sender_ip.bytes()); - builder.SetDiscoveryUnicastFlag(true); - auto proto = base::WrapUnique(builder.Build()); - - EXPECT_EQ(proto->name_hash(), base::HashMetricName(kCastEvent)); - EXPECT_EQ(proto->transport_connection_id() & kDiscoverySenderMask, - 0x00002461u); - EXPECT_TRUE(proto->transport_connection_id() & kDiscoveryUnicastBit); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_simple.cc chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_simple.cc --- chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_simple.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_simple.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,173 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/cast_event_builder_simple.h" - -#include "base/time/time.h" -#include "third_party/metrics_proto/cast_logs.pb.h" - -namespace chromecast { - -CastEventBuilderSimple::CastEventBuilderSimple() - : event_proto_(new ::metrics::CastLogsProto_CastEventProto) { - event_proto_->set_time_msec( - (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds()); -} - -CastEventBuilderSimple::~CastEventBuilderSimple() {} - -std::string CastEventBuilderSimple::GetName() { - return ""; -} - -CastEventBuilder& CastEventBuilderSimple::SetName(const std::string& name) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetTime(const base::TimeTicks& time) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetTimezoneId( - const std::string& timezone_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetAppId(const std::string& app_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetRemoteAppId( - const std::string& remote_app_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetSessionId( - const std::string& session_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetSdkVersion( - const std::string& sdk_version) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetMplVersion( - const std::string& mpl_version) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetConnectionInfo( - const std::string& transport_connection_id, - const std::string& virtual_connection_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetGroupUuid( - const std::string& group_uuid) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetExtraValue(int64_t extra_value) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetConversationKey( - const std::string& conversation_key) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetRequestId(int32_t request_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetEventId( - const std::string& event_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetAoghRequestId( - const std::string& request_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetAoghLocalDeviceId( - int64_t local_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetAoghAgentId( - const std::string& agent_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetAoghStandardAgentId( - const std::string& standard_agent_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetUiVersion( - const std::string& value) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetAuditReport( - const std::string& audit_report) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetDuoCoreVersion(int64_t version) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetHotwordModelId( - const std::string& model_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetDiscoveryAppSubtype( - const std::string& app_id) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetDiscoveryNamespaceSubtype( - const std::string& namespace_hash) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetDiscoverySender( - const net::IPAddressBytes& sender_ip) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetDiscoveryUnicastFlag( - bool uses_unicast) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetFeatureVector( - const std::vector& features) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::AddMetadata(const std::string& name, - int64_t value) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::SetLaunchFrom( - LaunchFrom launch_from) { - return *this; -} - -CastEventBuilder& CastEventBuilderSimple::MergeFrom( - const ::metrics::CastLogsProto_CastEventProto* event_proto) { - return *this; -} - -::metrics::CastLogsProto_CastEventProto* CastEventBuilderSimple::Build() { - return event_proto_.release(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_simple.h chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_simple.h --- chromium-132.0.6834.110/chromecast/metrics/cast_event_builder_simple.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_event_builder_simple.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_CAST_EVENT_BUILDER_SIMPLE_H_ -#define CHROMECAST_METRICS_CAST_EVENT_BUILDER_SIMPLE_H_ - -#include -#include -#include - -#include "chromecast/metrics/cast_event_builder.h" - -namespace chromecast { - -class CastEventBuilderSimple : public CastEventBuilder { - public: - CastEventBuilderSimple(); - ~CastEventBuilderSimple() override; - - // CastEventBuilder implementation - std::string GetName() override; - CastEventBuilder& SetName(const std::string& name) override; - CastEventBuilder& SetTime(const base::TimeTicks& time) override; - CastEventBuilder& SetTimezoneId(const std::string& timezone_id) override; - CastEventBuilder& SetAppId(const std::string& app_id) override; - CastEventBuilder& SetRemoteAppId(const std::string& remote_app_id) override; - CastEventBuilder& SetSessionId(const std::string& session_id) override; - CastEventBuilder& SetSdkVersion(const std::string& sdk_version) override; - CastEventBuilder& SetMplVersion(const std::string& mpl_version) override; - CastEventBuilder& SetConnectionInfo( - const std::string& transport_connection_id, - const std::string& virtual_connection_id) override; - CastEventBuilder& SetGroupUuid(const std::string& group_uuid) override; - CastEventBuilder& SetExtraValue(int64_t extra_value) override; - CastEventBuilder& SetConversationKey( - const std::string& conversation_key) override; - CastEventBuilder& SetRequestId(int32_t request_id) override; - CastEventBuilder& SetEventId(const std::string& event_id) override; - CastEventBuilder& SetAoghRequestId(const std::string& request_id) override; - CastEventBuilder& SetAoghLocalDeviceId(int64_t local_id) override; - CastEventBuilder& SetAoghAgentId(const std::string& agent_id) override; - CastEventBuilder& SetAoghStandardAgentId( - const std::string& standard_agent_id) override; - CastEventBuilder& SetUiVersion(const std::string& ui_version) override; - CastEventBuilder& SetAuditReport(const std::string& audit_report) override; - CastEventBuilder& SetDuoCoreVersion(int64_t version) override; - CastEventBuilder& SetHotwordModelId(const std::string& model_id) override; - CastEventBuilder& SetDiscoveryAppSubtype(const std::string& app_id) override; - CastEventBuilder& SetDiscoveryNamespaceSubtype( - const std::string& namespace_hash) override; - CastEventBuilder& SetDiscoverySender( - const net::IPAddressBytes& sender_ip) override; - CastEventBuilder& SetDiscoveryUnicastFlag(bool uses_unicast) override; - CastEventBuilder& SetFeatureVector( - const std::vector& features) override; - CastEventBuilder& AddMetadata(const std::string& name, - int64_t value) override; - CastEventBuilder& SetLaunchFrom(LaunchFrom launch_from) override; - CastEventBuilder& MergeFrom( - const ::metrics::CastLogsProto_CastEventProto* event_proto) override; - - ::metrics::CastLogsProto_CastEventProto* Build() override; - - private: - std::unique_ptr<::metrics::CastLogsProto_CastEventProto> event_proto_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_METRICS_CAST_EVENT_BUILDER_SIMPLE_H_ diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_metrics_service_client.cc chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client.cc --- chromium-132.0.6834.110/chromecast/metrics/cast_metrics_service_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,413 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/cast_metrics_service_client.h" - -#include -#include - -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/i18n/rtl.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "base/task/single_thread_task_runner.h" -#include "base/uuid.h" -#include "build/build_config.h" -#include "chromecast/base/cast_sys_info_util.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/base/path_utils.h" -#include "chromecast/base/pref_names.h" -#include "chromecast/base/version.h" -#include "components/metrics/client_info.h" -#include "components/metrics/enabled_state_provider.h" -#include "components/metrics/metrics_log_uploader.h" -#include "components/metrics/metrics_provider.h" -#include "components/metrics/metrics_service.h" -#include "components/metrics/metrics_state_manager.h" -#include "components/metrics/net/net_metrics_log_uploader.h" -#include "components/metrics/persistent_synthetic_trial_observer.h" -#include "components/metrics/url_constants.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/pref_service.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" - -#if BUILDFLAG(IS_ANDROID) -#include "chromecast/base/android/dumpstate_writer.h" -#endif - -namespace chromecast { -namespace metrics { - -namespace { - -const int kStandardUploadIntervalMinutes = 5; - -const char kMetricsOldClientID[] = "user_experience_metrics.client_id"; - -#if BUILDFLAG(IS_ANDROID) -const char kClientIdName[] = "Client ID"; -#endif // BUILDFLAG(IS_ANDROID) - -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - -const struct ChannelMap { - const char* chromecast_channel; - const ::metrics::SystemProfileProto::Channel chrome_channel; -} kMetricsChannelMap[] = { - {"canary-channel", ::metrics::SystemProfileProto::CHANNEL_CANARY}, - {"dev-channel", ::metrics::SystemProfileProto::CHANNEL_DEV}, - {"developer-channel", ::metrics::SystemProfileProto::CHANNEL_DEV}, - {"beta-channel", ::metrics::SystemProfileProto::CHANNEL_BETA}, - {"dogfood-channel", ::metrics::SystemProfileProto::CHANNEL_BETA}, - {"stable-channel", ::metrics::SystemProfileProto::CHANNEL_STABLE}, -}; - -::metrics::SystemProfileProto::Channel GetReleaseChannelFromUpdateChannelName( - const std::string& channel_name) { - if (channel_name.empty()) - return ::metrics::SystemProfileProto::CHANNEL_UNKNOWN; - - for (const auto& channel_map : kMetricsChannelMap) { - if (channel_name.compare(channel_map.chromecast_channel) == 0) - return channel_map.chrome_channel; - } - - // Any non-empty channel name is considered beta channel - return ::metrics::SystemProfileProto::CHANNEL_BETA; -} -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - -} // namespace - -void CastMetricsServiceClient::RegisterPrefs(PrefRegistrySimple* registry) { - registry->RegisterStringPref(kMetricsOldClientID, std::string()); -} - -variations::SyntheticTrialRegistry* -CastMetricsServiceClient::GetSyntheticTrialRegistry() { - return synthetic_trial_registry_.get(); -} - -::metrics::MetricsService* CastMetricsServiceClient::GetMetricsService() { - return metrics_service_.get(); -} - -void CastMetricsServiceClient::SetMetricsClientId( - const std::string& client_id) { - client_id_ = client_id; - LOG(INFO) << "Metrics client ID set: " << client_id; - if (delegate_) - delegate_->SetMetricsClientId(client_id); -#if BUILDFLAG(IS_ANDROID) - DumpstateWriter::AddDumpValue(kClientIdName, client_id); -#endif -} - -void CastMetricsServiceClient::StoreClientInfo( - const ::metrics::ClientInfo& client_info) { - // TODO(gfhuang): |force_client_id_| logic is super ugly, we should refactor - // to align load/save logic of |force_client_id_| with Load/StoreClientInfo. - // Currently it's lumped inside SetMetricsClientId(client_id). -} - -std::unique_ptr<::metrics::ClientInfo> -CastMetricsServiceClient::LoadClientInfo() { - std::unique_ptr<::metrics::ClientInfo> client_info(new ::metrics::ClientInfo); - client_info_loaded_ = true; - - // kMetricsIsNewClientID would be missing if either the device was just - // FDR'ed, or it is on pre-v1.2 build. - if (!pref_service_->GetBoolean(prefs::kMetricsIsNewClientID)) { - // If the old client id exists, the device must be on pre-v1.2 build, - // instead of just being FDR'ed. - if (!pref_service_->GetString(kMetricsOldClientID).empty()) { - // Force old client id to be regenerated. See b/9487011. - client_info->client_id = - base::Uuid::GenerateRandomV4().AsLowercaseString(); - pref_service_->SetBoolean(prefs::kMetricsIsNewClientID, true); - return client_info; - } - // else the device was just FDR'ed, pass through. - } - - // Use "forced" client ID if available. - if (!force_client_id_.empty() && - base::Uuid::ParseCaseInsensitive(force_client_id_).is_valid()) { - client_info->client_id = force_client_id_; - return client_info; - } - - if (force_client_id_.empty()) { - LOG(WARNING) << "Empty client id from platform," - << " assuming this is the first boot up of a new device."; - } else { - LOG(ERROR) << "Invalid client id from platform: " << force_client_id_ - << " from platform."; - } - return nullptr; -} - -int32_t CastMetricsServiceClient::GetProduct() { - // Chromecast currently uses the same product identifier as Chrome. - return ::metrics::ChromeUserMetricsExtension::CAST; -} - -std::string CastMetricsServiceClient::GetApplicationLocale() { - return base::i18n::GetConfiguredLocale(); -} - -const network_time::NetworkTimeTracker* -CastMetricsServiceClient::GetNetworkTimeTracker() { - return nullptr; -} - -bool CastMetricsServiceClient::GetBrand(std::string* brand_code) { - return false; -} - -::metrics::SystemProfileProto::Channel CastMetricsServiceClient::GetChannel() { -#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA) - switch (cast_sys_info_->GetBuildType()) { - case CastSysInfo::BUILD_ENG: - return ::metrics::SystemProfileProto::CHANNEL_UNKNOWN; - case CastSysInfo::BUILD_BETA: - return ::metrics::SystemProfileProto::CHANNEL_BETA; - case CastSysInfo::BUILD_PRODUCTION: - return ::metrics::SystemProfileProto::CHANNEL_STABLE; - } - NOTREACHED(); -#else - // Use the system (or signed) release channel here to avoid the noise in the - // metrics caused by the virtual channel which could be temporary or - // arbitrary. - return GetReleaseChannelFromUpdateChannelName( - cast_sys_info_->GetSystemReleaseChannel()); -#endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA) -} - -bool CastMetricsServiceClient::IsExtendedStableChannel() { - return false; // Not supported on Chromecast. -} - -std::string CastMetricsServiceClient::GetVersionString() { - int build_number; - if (!base::StringToInt(CAST_BUILD_INCREMENTAL, &build_number)) - build_number = 0; - - // Sample result: 31.0.1650.0-K15386-devel - std::string version_string(PRODUCT_VERSION); - - version_string.append("-K"); - version_string.append(base::NumberToString(build_number)); - - const ::metrics::SystemProfileProto::Channel channel = GetChannel(); - CHECK(!CAST_IS_DEBUG_BUILD() || - channel != ::metrics::SystemProfileProto::CHANNEL_STABLE); - const bool is_official_build = - build_number > 0 && !CAST_IS_DEBUG_BUILD() && - channel != ::metrics::SystemProfileProto::CHANNEL_UNKNOWN; - if (!is_official_build) - version_string.append("-devel"); - - return version_string; -} - -void CastMetricsServiceClient::CollectFinalMetricsForLog( - base::OnceClosure done_callback) { - if (collect_final_metrics_cb_) - collect_final_metrics_cb_.Run(std::move(done_callback)); - else - std::move(done_callback).Run(); -} - -void CastMetricsServiceClient::SetCallbacks( - base::RepeatingCallback collect_final_metrics_cb, - base::RepeatingCallback external_events_cb) { - collect_final_metrics_cb_ = collect_final_metrics_cb; - external_events_cb_ = external_events_cb; -} - -GURL CastMetricsServiceClient::GetMetricsServerUrl() { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kOverrideMetricsUploadUrl)) { - return GURL( - command_line->GetSwitchValueASCII(switches::kOverrideMetricsUploadUrl)); - } - // Note: This uses the old metrics service URL because some server-side - // provisioning is needed to support the extra Cast traffic on the new URL. - return GURL(::metrics::kOldMetricsServerUrl); -} - -std::unique_ptr<::metrics::MetricsLogUploader> -CastMetricsServiceClient::CreateUploader( - const GURL& server_url, - const GURL& insecure_server_url, - std::string_view mime_type, - ::metrics::MetricsLogUploader::MetricServiceType service_type, - const ::metrics::MetricsLogUploader::UploadCallback& on_upload_complete) { - return std::make_unique<::metrics::NetMetricsLogUploader>( - url_loader_factory_, server_url, insecure_server_url, mime_type, - service_type, on_upload_complete); -} - -base::TimeDelta CastMetricsServiceClient::GetStandardUploadInterval() { - return base::Minutes(kStandardUploadIntervalMinutes); -} - -::metrics::MetricsLogStore::StorageLimits -CastMetricsServiceClient::GetStorageLimits() const { - auto limits = ::metrics::MetricsServiceClient::GetStorageLimits(); - if (delegate_) - delegate_->ApplyMetricsStorageLimits(&limits); - return limits; -} - -bool CastMetricsServiceClient::IsConsentGiven() const { - return pref_service_->GetBoolean(prefs::kOptInStats); -} - -bool CastMetricsServiceClient::IsReportingEnabled() const { - // Recording metrics is controlled by the opt-in stats preference - // (`IsConsentGiven()`), but reporting them to Google is controlled by - // ToS being accepted. - return pref_service_->GetBoolean(prefs::kTosAccepted) && - ::metrics::EnabledStateProvider::IsReportingEnabled(); -} - -void CastMetricsServiceClient::UpdateMetricsServiceState() { - if (!task_runner_->BelongsToCurrentThread()) { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&CastMetricsServiceClient::UpdateMetricsServiceState, - base::Unretained(this))); - return; - } - - if (IsConsentGiven()) { - metrics_service_->Start(); - if (!IsReportingEnabled()) { - // Metrics are only reported after ToS have been accepted. If usage - // reporting is enabled, but ToS is not accepted, we can record metrics - // but must not report/upload them. - // - // `MetricsServiceImpl::Start()` will start recording and reporting. - // We must call `DisableReporting()` which will update the internal - // state machine of the reporting service and stop the upload scheduler - // from running. - metrics_service_->DisableReporting(); - } - } else { - metrics_service_->Stop(); - } -} - -void CastMetricsServiceClient::DisableMetricsService() { - if (!task_runner_->BelongsToCurrentThread()) { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&CastMetricsServiceClient::DisableMetricsService, - base::Unretained(this))); - return; - } - metrics_service_->Stop(); -} - -CastMetricsServiceClient::CastMetricsServiceClient( - CastMetricsServiceDelegate* delegate, - PrefService* pref_service, - scoped_refptr url_loader_factory) - : delegate_(delegate), - pref_service_(pref_service), - client_info_loaded_(false), - task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()), - url_loader_factory_(url_loader_factory), - cast_sys_info_(CreateSysInfo()) {} - -CastMetricsServiceClient::~CastMetricsServiceClient() = default; - -void CastMetricsServiceClient::OnApplicationNotIdle() { - metrics_service_->OnApplicationNotIdle(); -} - -void CastMetricsServiceClient::SetForceClientId(const std::string& client_id) { - DCHECK(force_client_id_.empty()); - DCHECK(!client_info_loaded_) - << "Force client ID must be set before client info is loaded."; - force_client_id_ = client_id; - SetMetricsClientId(force_client_id_); -} - -void CastMetricsServiceClient::InitializeMetricsService() { - DCHECK(!metrics_state_manager_); - metrics_state_manager_ = ::metrics::MetricsStateManager::Create( - pref_service_, this, std::wstring(), - // Pass an empty file path since Chromecast does not use the Variations - // framework. - /*user_data_dir=*/base::FilePath(), - ::metrics::StartupVisibility::kUnknown, ::metrics::EntropyParams{}, - base::BindRepeating(&CastMetricsServiceClient::StoreClientInfo, - base::Unretained(this)), - base::BindRepeating(&CastMetricsServiceClient::LoadClientInfo, - base::Unretained(this))); - - // Check that the FieldTrialList already exists. This happens in - // CastMainDelegate::PostEarlyInitialization(). - DCHECK(base::FieldTrialList::GetInstance()); - // Perform additional setup that should be done after the FieldTrialList, the - // MetricsStateManager, and its CleanExitBeacon exist. Since the list already - // exists, the entropy provider type is unused. - // TODO(crbug.com/40791269): Make Chromecast consistent with other platforms. - // I.e. create the FieldTrialList and the MetricsStateManager around the same - // time. - metrics_state_manager_->InstantiateFieldTrialList(); - - synthetic_trial_registry_ = - std::make_unique(); - synthetic_trial_observation_.Observe(synthetic_trial_registry_.get()); - - metrics_service_.reset(new ::metrics::MetricsService( - metrics_state_manager_.get(), this, pref_service_)); - - // Always create a client id as it may also be used by crash reporting, - // (indirectly) included in feedback, and can be queried during setup. For UMA - // and crash reporting, associated opt-in settings control sending reports as - // directed by the user. For setup (which also communicates the user's opt-in - // preferences), report the client id and expect setup to handle the current - // opt-in value. - metrics_state_manager_->ForceClientIdCreation(); - // Populate |client_id| in other component parts. - SetMetricsClientId(metrics_state_manager_->client_id()); -} - -void CastMetricsServiceClient::StartMetricsService() { - if (delegate_) - delegate_->RegisterMetricsProviders(metrics_service_.get()); - - metrics_service_->InitializeMetricsRecordingState(); -#if !BUILDFLAG(IS_ANDROID) - // Signal that the session has not yet exited cleanly. We later signal that - // the session exited cleanly via MetricsService::LogCleanShutdown(). - // TODO(crbug.com/40766116): See whether this can be called even earlier. - metrics_state_manager_->LogHasSessionShutdownCleanly(false); -#endif // !BUILDFLAG(IS_ANDROID) - - UpdateMetricsServiceState(); -} - -void CastMetricsServiceClient::Finalize() { - metrics_service_->Stop(); -} - -void CastMetricsServiceClient::ProcessExternalEvents(base::OnceClosure cb) { - if (external_events_cb_) - external_events_cb_.Run(std::move(cb)); - else - std::move(cb).Run(); -} - -} // namespace metrics -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_metrics_service_client.h chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client.h --- chromium-132.0.6834.110/chromecast/metrics/cast_metrics_service_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,156 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_CAST_METRICS_SERVICE_CLIENT_H_ -#define CHROMECAST_METRICS_CAST_METRICS_SERVICE_CLIENT_H_ - -#include - -#include -#include -#include - -#include "base/memory/raw_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/scoped_observation.h" -#include "build/build_config.h" -#include "chromecast/public/cast_sys_info.h" -#include "components/metrics/enabled_state_provider.h" -#include "components/metrics/metrics_log_store.h" -#include "components/metrics/metrics_log_uploader.h" -#include "components/metrics/metrics_service_client.h" -#include "components/metrics/persistent_synthetic_trial_observer.h" -#include "components/variations/synthetic_trial_registry.h" - -class PrefRegistrySimple; -class PrefService; - -namespace base { -class SingleThreadTaskRunner; -} - -namespace metrics { -struct ClientInfo; -class MetricsService; -class MetricsStateManager; -} // namespace metrics - -namespace network { -class SharedURLLoaderFactory; -} - -namespace chromecast { -namespace metrics { - -class CastMetricsServiceDelegate { - public: - // Invoked when the metrics client ID changes. - virtual void SetMetricsClientId(const std::string& client_id) = 0; - - // Allows registration of extra metrics providers. - virtual void RegisterMetricsProviders(::metrics::MetricsService* service) = 0; - - // Adds Cast embedder-specific storage limits to |limits| object. - virtual void ApplyMetricsStorageLimits( - ::metrics::MetricsLogStore::StorageLimits* limits) {} - - protected: - virtual ~CastMetricsServiceDelegate() = default; -}; - -class CastMetricsServiceClient : public ::metrics::MetricsServiceClient, - public ::metrics::EnabledStateProvider { - public: - CastMetricsServiceClient( - CastMetricsServiceDelegate* delegate, - PrefService* pref_service, - scoped_refptr url_loader_factory); - ~CastMetricsServiceClient() override; - - CastMetricsServiceClient(const CastMetricsServiceClient&) = delete; - CastMetricsServiceClient& operator=(const CastMetricsServiceClient&) = delete; - - static void RegisterPrefs(PrefRegistrySimple* registry); - - // Use |client_id| when starting MetricsService instead of generating a new - // client ID. If used, SetForceClientId must be called before Initialize. - void SetForceClientId(const std::string& client_id); - void OnApplicationNotIdle(); - - // Processes all events from shared file. This should be used to consume all - // events in the file before shutdown. This function is safe to call from any - // thread. - void ProcessExternalEvents(base::OnceClosure cb); - - void InitializeMetricsService(); - void StartMetricsService(); - void Finalize(); - - // ::metrics::MetricsServiceClient: - variations::SyntheticTrialRegistry* GetSyntheticTrialRegistry() override; - ::metrics::MetricsService* GetMetricsService() override; - void SetMetricsClientId(const std::string& client_id) override; - int32_t GetProduct() override; - std::string GetApplicationLocale() override; - const network_time::NetworkTimeTracker* GetNetworkTimeTracker() override; - bool GetBrand(std::string* brand_code) override; - ::metrics::SystemProfileProto::Channel GetChannel() override; - bool IsExtendedStableChannel() override; - std::string GetVersionString() override; - void CollectFinalMetricsForLog(base::OnceClosure done_callback) override; - GURL GetMetricsServerUrl() override; - std::unique_ptr<::metrics::MetricsLogUploader> CreateUploader( - const GURL& server_url, - const GURL& insecure_server_url, - std::string_view mime_type, - ::metrics::MetricsLogUploader::MetricServiceType service_type, - const ::metrics::MetricsLogUploader::UploadCallback& on_upload_complete) - override; - base::TimeDelta GetStandardUploadInterval() override; - ::metrics::MetricsLogStore::StorageLimits GetStorageLimits() const override; - - // ::metrics::EnabledStateProvider: - bool IsConsentGiven() const override; - bool IsReportingEnabled() const override; - - // Starts/stops the metrics service. - void UpdateMetricsServiceState(); - void DisableMetricsService(); - - std::string client_id() const { return client_id_; } - - PrefService* pref_service() const { return pref_service_; } - void SetCallbacks( - base::RepeatingCallback collect_final_metrics_cb, - base::RepeatingCallback external_events_cb); - - private: - std::unique_ptr<::metrics::ClientInfo> LoadClientInfo(); - void StoreClientInfo(const ::metrics::ClientInfo& client_info); - - const raw_ptr delegate_; - const raw_ptr pref_service_; - std::string client_id_; - std::string force_client_id_; - bool client_info_loaded_; - - const scoped_refptr task_runner_; - std::unique_ptr<::metrics::MetricsStateManager> metrics_state_manager_; - std::unique_ptr synthetic_trial_registry_; - ::metrics::PersistentSyntheticTrialObserver synthetic_trial_observer_; - base::ScopedObservation - synthetic_trial_observation_{&synthetic_trial_observer_}; - std::unique_ptr<::metrics::MetricsService> metrics_service_; - std::unique_ptr<::metrics::EnabledStateProvider> enabled_state_provider_; - scoped_refptr url_loader_factory_; - base::RepeatingCallback collect_final_metrics_cb_; - base::RepeatingCallback external_events_cb_; - const std::unique_ptr cast_sys_info_; -}; - -} // namespace metrics -} // namespace chromecast - -#endif // CHROMECAST_METRICS_CAST_METRICS_SERVICE_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/metrics/cast_metrics_service_client_unittest.cc chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client_unittest.cc --- chromium-132.0.6834.110/chromecast/metrics/cast_metrics_service_client_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/cast_metrics_service_client_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,100 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/cast_metrics_service_client.h" - -#include "base/test/task_environment.h" -#include "chromecast/metrics/mock_cast_sys_info_util.h" -#include "components/metrics/metrics_log_store.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace metrics { -namespace { - -class FakeCastMetricsServiceDelegate : public CastMetricsServiceDelegate { - public: - void SetStorageLimits(::metrics::MetricsLogStore::StorageLimits limits) { - storage_limits_ = std::move(limits); - } - - private: - void SetMetricsClientId(const std::string& client_id) override {} - void RegisterMetricsProviders(::metrics::MetricsService* service) override {} - void ApplyMetricsStorageLimits( - ::metrics::MetricsLogStore::StorageLimits* limits) override { - *limits = std::move(storage_limits_); - } - - ::metrics::MetricsLogStore::StorageLimits storage_limits_; -}; - -class CastMetricsServiceClientTest : public testing::Test { - public: - CastMetricsServiceClientTest() {} - CastMetricsServiceClientTest(const CastMetricsServiceClientTest&) = delete; - CastMetricsServiceClientTest& operator=(const CastMetricsServiceClientTest&) = - delete; - - protected: - base::test::SingleThreadTaskEnvironment task_environment_; -}; - -/** - * Validates that class instatiation and calls to GetChannel() only - * result in a single method invocation of CreateSysInfo(). - */ -TEST_F(CastMetricsServiceClientTest, CreateSysInfoSingleInvocation) { - EXPECT_EQ(chromecast::GetSysInfoCreatedCount(), 0); - - CastMetricsServiceClient client(nullptr, nullptr, nullptr); - - client.GetChannel(); - client.GetChannel(); - - // Despite muiltiple calls to GetChannel(), - // SysInfo should only be created a single time - EXPECT_EQ(chromecast::GetSysInfoCreatedCount(), 1); -} - -TEST_F(CastMetricsServiceClientTest, UsesDelegateToGetStorageLimits) { - FakeCastMetricsServiceDelegate delegate; - CastMetricsServiceClient client(&delegate, nullptr, nullptr); - - // Set arbitrary limits to ensure the limits propagate to the client - // correctly. - ::metrics::MetricsLogStore::StorageLimits expected_limits = { - .initial_log_queue_limits = - ::metrics::UnsentLogStore::UnsentLogStoreLimits{ - .min_log_count = 10, - .min_queue_size_bytes = 2000, - }, - .ongoing_log_queue_limits = - ::metrics::UnsentLogStore::UnsentLogStoreLimits{ - .min_log_count = 30, - .min_queue_size_bytes = 4000, - .max_log_size_bytes = 5000, - }, - }; - delegate.SetStorageLimits(expected_limits); - ::metrics::MetricsLogStore::StorageLimits actual_limits = - client.GetStorageLimits(); - EXPECT_EQ(actual_limits.initial_log_queue_limits.min_log_count, - expected_limits.initial_log_queue_limits.min_log_count); - EXPECT_EQ(actual_limits.initial_log_queue_limits.min_queue_size_bytes, - expected_limits.initial_log_queue_limits.min_queue_size_bytes); - EXPECT_EQ(actual_limits.initial_log_queue_limits.max_log_size_bytes, - expected_limits.initial_log_queue_limits.max_log_size_bytes); - EXPECT_EQ(actual_limits.ongoing_log_queue_limits.min_log_count, - expected_limits.ongoing_log_queue_limits.min_log_count); - EXPECT_EQ(actual_limits.ongoing_log_queue_limits.min_queue_size_bytes, - expected_limits.ongoing_log_queue_limits.min_queue_size_bytes); - EXPECT_EQ(actual_limits.ongoing_log_queue_limits.max_log_size_bytes, - expected_limits.ongoing_log_queue_limits.max_log_size_bytes); -} - -} // namespace -} // namespace metrics -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/metrics_recorder.cc chromium-132.0.6834.159/chromecast/metrics/metrics_recorder.cc --- chromium-132.0.6834.110/chromecast/metrics/metrics_recorder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/metrics_recorder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,328 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/metrics_recorder.h" - -#include - -#include -#include -#include -#include - -#include "base/check.h" -#include "base/containers/flat_map.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" -#include "base/notreached.h" -#include "base/observer_list.h" -#include "base/synchronization/lock.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/metrics/cast_event_builder.h" -#include "net/base/ip_address.h" - -namespace chromecast { - -namespace { - -bool IsLogOn(int verbose_log_level) { - // TODO(b/135640848): Determine a better way to log metrics for - // Fuchsia, without producing logspam during development. - return -verbose_log_level >= logging::GetMinLogLevel() || - (DCHECK_IS_ON() && VLOG_IS_ON(verbose_log_level)); -} - -// A no-op dummy event builder, used when MetricsRecorder is nullptr. -class DummyEventBuilder : public CastEventBuilder { - public: - // receiver::CastEventBuilder implementation - std::string GetName() override { return ""; } - - CastEventBuilder& SetName(const std::string& name) override { return *this; } - - CastEventBuilder& SetTime(const base::TimeTicks& time) override { - return *this; - } - - CastEventBuilder& SetTimezoneId(const std::string& timezone_id) override { - return *this; - } - - CastEventBuilder& SetAppId(const std::string& app_id) override { - return *this; - } - - CastEventBuilder& SetRemoteAppId(const std::string& remote_app_id) override { - return *this; - } - - CastEventBuilder& SetSessionId(const std::string& session_id) override { - return *this; - } - - CastEventBuilder& SetSdkVersion(const std::string& sdk_version) override { - return *this; - } - - CastEventBuilder& SetMplVersion(const std::string& mpl_version) override { - return *this; - } - - CastEventBuilder& SetConnectionInfo( - const std::string& transport_connection_id, - const std::string& virtual_connection_id) override { - return *this; - } - - CastEventBuilder& SetGroupUuid(const std::string& group_uuid) override { - return *this; - } - - CastEventBuilder& SetExtraValue(int64_t extra_value) override { - return *this; - } - - CastEventBuilder& SetConversationKey( - const std::string& conversation_key) override { - return *this; - } - - CastEventBuilder& SetRequestId(int32_t request_id) override { return *this; } - - CastEventBuilder& SetEventId(const std::string& event_id) override { - return *this; - } - - CastEventBuilder& SetAoghRequestId(const std::string& request_id) override { - return *this; - } - - CastEventBuilder& SetAoghLocalDeviceId(int64_t local_id) override { - return *this; - } - - CastEventBuilder& SetAoghAgentId(const std::string& agent_id) override { - return *this; - } - - CastEventBuilder& SetAoghStandardAgentId( - const std::string& agent_id) override { - return *this; - } - - CastEventBuilder& SetUiVersion(const std::string& ui_version) override { - return *this; - } - - CastEventBuilder& SetAuditReport(const std::string& audit_report) override { - return *this; - } - - CastEventBuilder& SetDuoCoreVersion(int64_t version) override { - return *this; - } - - CastEventBuilder& SetHotwordModelId(const std::string& model_id) override { - return *this; - } - - CastEventBuilder& SetDiscoveryAppSubtype(const std::string& app_id) override { - return *this; - } - - CastEventBuilder& SetDiscoveryNamespaceSubtype( - const std::string& namespace_hash) override { - return *this; - } - - CastEventBuilder& SetDiscoverySender( - const net::IPAddressBytes& sender_ip) override { - return *this; - } - - CastEventBuilder& SetDiscoveryUnicastFlag(bool uses_unicast) override { - return *this; - } - - CastEventBuilder& SetFeatureVector( - const std::vector& features) override { - return *this; - } - - CastEventBuilder& AddMetadata(const std::string& name, - int64_t value) override { - return *this; - } - - CastEventBuilder& SetLaunchFrom(LaunchFrom launch_from) override { - return *this; - } - - CastEventBuilder& MergeFrom( - const ::metrics::CastLogsProto_CastEventProto* event_proto) override { - return *this; - } - - ::metrics::CastLogsProto_CastEventProto* Build() override { NOTREACHED(); } -}; - -MetricsRecorder* g_instance = nullptr; - -} // namespace - -void RecordEventWithLogPrefix(const std::string& action, - std::unique_ptr event_builder, - int verbose_log_level, - const std::string& log_prefix) { - MetricsRecorder* recorder = MetricsRecorder::GetInstance(); - if (recorder && event_builder) { - recorder->RecordCastEvent(std::move(event_builder)); - } - - if (IsLogOn(verbose_log_level)) { - VLOG_STREAM(verbose_log_level) << log_prefix << action; - } -} - -std::unique_ptr CreateCastEvent(const std::string& name) { - MetricsRecorder* recorder = MetricsRecorder::GetInstance(); - if (recorder) { - return recorder->CreateEventBuilder(name); - } - return std::make_unique(); -} - -void RecordCastEvent(const std::string& log_name, - std::unique_ptr event_builder, - int verbose_log_level) { - RecordEventWithLogPrefix(log_name, std::move(event_builder), - verbose_log_level, "cast event: "); -} - -void RecordAction(const std::string& action, int verbose_log_level) { - RecordEventWithLogPrefix(action, CreateCastEvent(action), verbose_log_level, - "Record action: "); -} - -void LogAction(const std::string& action, int verbose_log_level) { - RecordEventWithLogPrefix(action, std::unique_ptr(), - verbose_log_level, "Log action: "); -} - -void RecordHistogramTime(const std::string& name, - int sample, - int min, - int max, - int num_buckets, - int verbose_log_level) { - MetricsRecorder* recorder = MetricsRecorder::GetInstance(); - if (recorder) { - recorder->RecordHistogramTime(name, sample, min, max, num_buckets); - } - - if (IsLogOn(verbose_log_level)) { - VLOG_STREAM(verbose_log_level) - << "Time histogram: " << name << ", sample=" << sample - << ", max=" << max << ", min=" << min - << ", num_buckets=" << num_buckets; - } -} - -void RecordHistogramCount(const std::string& name, - int sample, - int min, - int max, - int num_buckets, - int verbose_log_level) { - MetricsRecorder* recorder = MetricsRecorder::GetInstance(); - if (recorder) { - recorder->RecordHistogramCount(name, sample, min, max, num_buckets); - } - - if (IsLogOn(verbose_log_level)) { - VLOG_STREAM(verbose_log_level) - << "Count histogram: " << name << ", sample=" << sample - << ", max=" << max << ", min=" << min - << ", num_buckets=" << num_buckets; - } -} - -void RecordHistogramEnum(const std::string& name, - int sample, - int boundary, - int verbose_log_level) { - MetricsRecorder* recorder = MetricsRecorder::GetInstance(); - if (recorder) { - recorder->RecordHistogramEnum(name, sample, boundary); - } - - if (IsLogOn(verbose_log_level)) { - VLOG_STREAM(verbose_log_level) - << "Count histogram: " << name << ", sample=" << sample - << ", boundary=" << boundary; - } -} - -struct MetricsRecorder::ObserverList { - base::ObserverList::Unchecked list; -}; - -// static -void MetricsRecorder::SetInstance(MetricsRecorder* recorder) { - g_instance = recorder; -} - -// static -MetricsRecorder* MetricsRecorder::GetInstance() { - return g_instance; -} - -MetricsRecorder::MetricsRecorder() - : observer_list_(std::make_unique()) {} - -MetricsRecorder::~MetricsRecorder() = default; - -void MetricsRecorder::NotifyOnPreUpload() { - for (auto& o : observer_list_->list) - o.OnPreUpload(); -} - -void MetricsRecorder::AddObserver(Observer* o) { - DCHECK(o); - observer_list_->list.AddObserver(o); -} -void MetricsRecorder::RemoveObserver(Observer* o) { - DCHECK(o); - observer_list_->list.RemoveObserver(o); -} - -void RecordCastEvent(const std::string& event, - bool has_extra_value, - int64_t value, - MetricsRecorder* metrics_recorder) { - DCHECK(metrics_recorder); - auto event_builder = metrics_recorder->CreateEventBuilder(event); - if (has_extra_value) { - event_builder->SetExtraValue(value); - } - metrics_recorder->RecordCastEvent(std::move(event_builder)); -} - -void RecordCastEventWithMetadata( - const std::string& event, - const base::flat_map& settings_map, - MetricsRecorder* metrics_recorder) { - DCHECK(metrics_recorder); - auto event_builder = metrics_recorder->CreateEventBuilder(event); - for (const auto& kv_pair : settings_map) { - event_builder->AddMetadata(kv_pair.first, kv_pair.second); - } - metrics_recorder->RecordCastEvent(std::move(event_builder)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/metrics_recorder.h chromium-132.0.6834.159/chromecast/metrics/metrics_recorder.h --- chromium-132.0.6834.110/chromecast/metrics/metrics_recorder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/metrics_recorder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,173 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_METRICS_RECORDER_H_ -#define CHROMECAST_METRICS_METRICS_RECORDER_H_ - -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/time/time.h" -#include "chromecast/metrics/cast_event_builder.h" - -namespace base { -class Value; -} // namespace base - -namespace net { -class IPAddressBytes; -} // namespace net - -namespace chromecast { - -// TODO(b/176503058): Further remove the following 3 static functions. -void RecordEventWithLogPrefix(const std::string& action, - std::unique_ptr event_builder, - int verbose_log_level, - const std::string& log_prefix); - -// Create a CastEventBuilder, caller takes ownership. -std::unique_ptr CreateCastEvent(const std::string& name); - -// Records a cast event (and reports it to UMA server if CastReceiver sets an -// instance of MetricsRecorder). -void RecordCastEvent(const std::string& log_name, - std::unique_ptr event_builder, - int verbose_log_level); - -// Records action (and reports it to UMA server if CastReceiver sets an instance -// of MetricsRecorder). -void RecordAction(const std::string& action, int verbose_log_level); - -// Logs action but not reporting to UMA server. -void LogAction(const std::string& action, int verbose_log_level); - -// Records time/count/enum histograms. -void RecordHistogramTime(const std::string& histogram_name, - int sample, - int min, - int max, - int num_buckets, - int verbose_log_level); -void RecordHistogramCount(const std::string& histogram_name, - int sample, - int min, - int max, - int num_buckets, - int verbose_log_level); -void RecordHistogramEnum(const std::string& histogram_name, - int value, - int boundary, - int verbose_log_level); - -// Base class for metrics reporting. The caller of cast receiver should -// implement the subclass of this. -class MetricsRecorder { - public: - static void SetInstance(MetricsRecorder* recorder); - static MetricsRecorder* GetInstance(); - - class Observer { - public: - // Will be called right before metrics are uploaded. - // Will be called on the UI thread. Must not post tasks, otherwise they will - // not be guaranteed to run before metrics upload. - virtual void OnPreUpload() = 0; - - protected: - virtual ~Observer() = default; - }; - - virtual ~MetricsRecorder(); - - // Creates cast event. - virtual std::unique_ptr CreateEventBuilder( - const std::string& name) = 0; - - // Adds/Removes active virtual connections. Infos of active connections whose - // ids are referred by RecordEvent() will be sent at the same UMA log entry. - // The sender's IPv4 or IPv6 address can be passed into |sender_ip|, which is - // a network order byte array for the address. If the address is invalid - // then empty address will be logged (0.0.0.0). - virtual void AddActiveConnection(const std::string& transport_connection_id, - const std::string& virtual_connection_id, - const base::Value& sender_info, - const net::IPAddressBytes& sender_ip) = 0; - virtual void RemoveActiveConnection(const std::string& connection_id) = 0; - - // Records a cast event. - virtual void RecordCastEvent( - std::unique_ptr event_builder) = 0; - - // Records |sample| time in milliseconds. - virtual void RecordHistogramTime(const std::string& name, - int sample, - int min, - int max, - int num_buckets) = 0; - - // Records |sample| count. - virtual void RecordHistogramCount(const std::string& name, - int sample, - int min, - int max, - int num_buckets) = 0; - - // Records |sample| |count| number of times. - virtual void RecordHistogramCountRepeated(const std::string& name, - int sample, - int min, - int max, - int num_buckets, - int count) = 0; - - // Records |sample| enumeration value. - virtual void RecordHistogramEnum(const std::string& name, - int sample, - int boundary) = 0; - - // Records |sample| in sparse histogram. - virtual void RecordHistogramSparse(const std::string& name, int sample) = 0; - - // Measures the time elapsed between now and the next occurrence of - // |event_name|. A metrics event named |measurement_name| will be logged when - // the event occurs, along with the elapsed time in milliseconds. These - // methods can be called from any thread. - virtual void MeasureTimeUntilEvent(const std::string& event_name, - const std::string& measurement_name) {} - virtual void MeasureTimeUntilEvent(const std::string& event_name, - const std::string& measurement_name, - base::TimeTicks start_time) {} - virtual void RecordTimelineEvent(const std::string& event_name) {} - - void AddObserver(Observer* o); - void RemoveObserver(Observer* o); - - protected: - MetricsRecorder(); - void NotifyOnPreUpload(); - - private: - struct ObserverList; - - std::unique_ptr observer_list_; -}; - -// Records a cast event. -void RecordCastEvent(const std::string& event, - bool has_extra_value, - int64_t value, - MetricsRecorder* metrics_recorder); - -// Records a cast event. -void RecordCastEventWithMetadata( - const std::string& event, - const base::flat_map& settings_map, - MetricsRecorder* metrics_recorder); - -} // namespace chromecast - -#endif // CHROMECAST_METRICS_METRICS_RECORDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/metrics/metrics_recorder_base.cc chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base.cc --- chromium-132.0.6834.110/chromecast/metrics/metrics_recorder_base.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/metrics_recorder_base.h" - -namespace chromecast { - -MetricsRecorderBase::MetricsRecorderBase(const base::TickClock* tick_clock) - : tick_clock_(tick_clock) {} - -MetricsRecorderBase::~MetricsRecorderBase() = default; - -void MetricsRecorderBase::MeasureTimeUntilEvent( - const std::string& end_event, - const std::string& measurement_name) { - base::TimeTicks now = - tick_clock_ ? tick_clock_->NowTicks() : base::TimeTicks::Now(); - timed_event_recorder_.MeasureTimeUntilEvent(end_event, measurement_name, now); -} - -void MetricsRecorderBase::MeasureTimeUntilEvent( - const std::string& end_event, - const std::string& measurement_name, - base::TimeTicks start_time) { - timed_event_recorder_.MeasureTimeUntilEvent(end_event, measurement_name, - start_time); -} - -void MetricsRecorderBase::RecordTimelineEvent(const std::string& event_name) { - base::TimeTicks now = - tick_clock_ ? tick_clock_->NowTicks() : base::TimeTicks::Now(); - timed_event_recorder_.RecordEvent(event_name, now); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/metrics_recorder_base.h chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base.h --- chromium-132.0.6834.110/chromecast/metrics/metrics_recorder_base.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_METRICS_RECORDER_BASE_H_ -#define CHROMECAST_METRICS_METRICS_RECORDER_BASE_H_ - -#include - -#include "base/memory/raw_ptr.h" -#include "base/time/tick_clock.h" -#include "chromecast/metrics/metrics_recorder.h" -#include "chromecast/metrics/timed_event_recorder.h" - -namespace chromecast { - -class MetricsRecorderBase : public MetricsRecorder { - public: - ~MetricsRecorderBase() override; - - // MetricsRecorder implementation (partial): - void MeasureTimeUntilEvent(const std::string& event_name, - const std::string& measurement_name) override; - void MeasureTimeUntilEvent(const std::string& event_name, - const std::string& measurement_name, - base::TimeTicks start_time) override; - void RecordTimelineEvent(const std::string& event_name) override; - - protected: - explicit MetricsRecorderBase(const base::TickClock* tick_clock = nullptr); - - private: - const raw_ptr tick_clock_; - TimedEventRecorder timed_event_recorder_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_METRICS_METRICS_RECORDER_BASE_H_ diff -Nru chromium-132.0.6834.110/chromecast/metrics/metrics_recorder_base_unittest.cc chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base_unittest.cc --- chromium-132.0.6834.110/chromecast/metrics/metrics_recorder_base_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/metrics_recorder_base_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,161 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/metrics_recorder_base.h" - -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "chromecast/metrics/mock_cast_event_builder.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::_; - -namespace chromecast { - -namespace { - -class MockMetricsRecorder : public MetricsRecorderBase { - public: - explicit MockMetricsRecorder(const base::TickClock* tick_clock) - : MetricsRecorderBase(tick_clock) {} - ~MockMetricsRecorder() override; - - std::unique_ptr CreateEventBuilder( - const std::string& name) override { - auto builder = std::make_unique(); - builder->SetName(name); - return builder; - } - - MOCK_METHOD(void, - AddActiveConnection, - (const std::string&, - const std::string&, - const base::Value&, - const net::IPAddressBytes&), - (override)); - MOCK_METHOD(void, RemoveActiveConnection, (const std::string&), (override)); - MOCK_METHOD(void, - RecordCastEvent, - (std::unique_ptr event_builder), - (override)); - MOCK_METHOD(void, - RecordHistogramTime, - (const std::string&, int, int, int, int), - (override)); - MOCK_METHOD(void, - RecordHistogramCount, - (const std::string&, int, int, int, int), - (override)); - MOCK_METHOD(void, - RecordHistogramCountRepeated, - (const std::string&, int, int, int, int, int), - (override)); - MOCK_METHOD(void, - RecordHistogramEnum, - (const std::string&, int, int), - (override)); - MOCK_METHOD(void, - RecordHistogramSparse, - (const std::string&, int), - (override)); -}; - -inline MockMetricsRecorder::~MockMetricsRecorder() = default; - -MATCHER_P2(NameAndExtraValue, name, extra_value, "") { - auto* builder = static_cast(arg.get()); - if (!builder) - return false; - return builder->name == name && builder->extra_value == extra_value; -} - -} // namespace - -class MetricsRecorderTest : public ::testing::Test { - public: - MetricsRecorderTest() - : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME), - recorder_(task_environment_.GetMockTickClock()) {} - - base::test::TaskEnvironment task_environment_; - MockMetricsRecorder recorder_; -}; - -TEST_F(MetricsRecorderTest, TimelineIntervals) { - // Demonstrates usage of the timeline measurement functions. - recorder_.MeasureTimeUntilEvent("MyEvent", "MyEvent.LatencyMs"); - task_environment_.FastForwardBy(base::Milliseconds(1500)); - - EXPECT_CALL(recorder_, - RecordCastEvent(NameAndExtraValue("MyEvent.LatencyMs", 1500))); - recorder_.RecordTimelineEvent("MyEvent"); -} - -TEST_F(MetricsRecorderTest, TimelineIntervalsMultipleMeasurement) { - // Multiple measurements with the same end event will each trigger a - // measurement metric event. - recorder_.MeasureTimeUntilEvent("MyEvent", "First.Measurement.LatencyMs"); - task_environment_.FastForwardBy(base::Milliseconds(300)); - recorder_.MeasureTimeUntilEvent("MyEvent", "Second.Measurement.LatencyMs"); - task_environment_.FastForwardBy(base::Milliseconds(800)); - - EXPECT_CALL(recorder_, RecordCastEvent(NameAndExtraValue( - "First.Measurement.LatencyMs", 1100))); - EXPECT_CALL(recorder_, RecordCastEvent(NameAndExtraValue( - "Second.Measurement.LatencyMs", 800))); - recorder_.RecordTimelineEvent("MyEvent"); -} - -TEST_F(MetricsRecorderTest, TimelineIntervalsDuplicateMeasurement) { - // Measurements can have the same name and/or end event. Each instance will - // emit a metric event containing the measurement value. - recorder_.MeasureTimeUntilEvent("AnEvent", "AnEvent.LatencyMs"); - task_environment_.FastForwardBy(base::Milliseconds(600)); - recorder_.MeasureTimeUntilEvent("AnEvent", "AnEvent.LatencyMs"); - task_environment_.FastForwardBy(base::Milliseconds(700)); - - EXPECT_CALL(recorder_, - RecordCastEvent(NameAndExtraValue("AnEvent.LatencyMs", 1300))); - EXPECT_CALL(recorder_, - RecordCastEvent(NameAndExtraValue("AnEvent.LatencyMs", 700))); - recorder_.RecordTimelineEvent("AnEvent"); -} - -TEST_F(MetricsRecorderTest, TimelineIntervalsRepeatEnd) { - // The measurement should be cleared when the ending event is triggered. - recorder_.MeasureTimeUntilEvent("SomeEvent", "SomeEvent.LatencyMs"); - task_environment_.FastForwardBy(base::Milliseconds(2300)); - - EXPECT_CALL(recorder_, - RecordCastEvent(NameAndExtraValue("SomeEvent.LatencyMs", 2300))); - recorder_.RecordTimelineEvent("SomeEvent"); - - // Repeating the end event won't trigger another latency measurement event. - task_environment_.FastForwardBy(base::Milliseconds(800)); - EXPECT_CALL(recorder_, RecordCastEvent(_)).Times(0); - recorder_.RecordTimelineEvent("SomeEvent"); -} - -TEST_F(MetricsRecorderTest, TimelineIntervalsRepeatMonitoring) { - // Measurements can be repeated after they have finished. - recorder_.MeasureTimeUntilEvent("AnEvent", "AnEvent.LatencyMs"); - task_environment_.FastForwardBy(base::Milliseconds(1100)); - - EXPECT_CALL(recorder_, - RecordCastEvent(NameAndExtraValue("AnEvent.LatencyMs", 1100))); - recorder_.RecordTimelineEvent("AnEvent"); - - // Monitoring again should eventually generate another latency event if both - // monitored events are triggered in order. - recorder_.MeasureTimeUntilEvent("AnEvent", "AnEvent.LatencyMs"); - task_environment_.FastForwardBy(base::Milliseconds(500)); - - EXPECT_CALL(recorder_, - RecordCastEvent(NameAndExtraValue("AnEvent.LatencyMs", 500))); - recorder_.RecordTimelineEvent("AnEvent"); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/metrics_util.cc chromium-132.0.6834.159/chromecast/metrics/metrics_util.cc --- chromium-132.0.6834.110/chromecast/metrics/metrics_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/metrics_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/metrics_util.h" - -#include "base/logging.h" - -namespace chromecast { - -uint32_t GetIPAddressFragmentForLogging(const net::IPAddressBytes& sender_ip) { - // Check if address is valid IPv4 or IPv6 byte array. If not then fill in - // with zeros as a default value. - if (sender_ip.size() != net::IPAddress::kIPv4AddressSize && - sender_ip.size() != net::IPAddress::kIPv6AddressSize) { - DVLOG(1) << "Sender IP is not IPv4 or IPv6; zeroing out sender fragment."; - return 0; - } - // Grab the last 2 bytes of sender IP address in network order and store as - // packed 16-bit integer. The unused bits in the final packed value should - // be empty. - uint32_t packed_address = 0; - if (sender_ip.size() >= 2) { - int i = sender_ip.size() - 1; - packed_address |= (sender_ip[i--]); - packed_address |= (sender_ip[i--] << 8); - } - - return packed_address; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/metrics_util.h chromium-132.0.6834.159/chromecast/metrics/metrics_util.h --- chromium-132.0.6834.110/chromecast/metrics/metrics_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/metrics_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_METRICS_UTIL_H_ -#define CHROMECAST_METRICS_METRICS_UTIL_H_ - -#include "net/base/ip_address.h" - -namespace chromecast { - -// Pack last two bytes of IPv4 or IPv6 address into value used for logging -// partial sender IP fragments (e.g. discovery code and virtual connection -// details). If the address is empty or not valid IPv4/IPv6 then zeros will -// be filled into the packed fragment. -uint32_t GetIPAddressFragmentForLogging(const net::IPAddressBytes& sender_ip); - -} // namespace chromecast - -#endif // CHROMECAST_METRICS_METRICS_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/metrics/mock_cast_event_builder.cc chromium-132.0.6834.159/chromecast/metrics/mock_cast_event_builder.cc --- chromium-132.0.6834.110/chromecast/metrics/mock_cast_event_builder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/mock_cast_event_builder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,238 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/mock_cast_event_builder.h" - -using ::testing::_; -using ::testing::Return; -using ::testing::ReturnRef; - -namespace chromecast { - -MockCastEventBuilder::MockCastEventBuilder() { - ON_CALL(*this, GetName()).WillByDefault(Return("")); - ON_CALL(*this, SetName(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetTime(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetAppId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetRemoteAppId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetSessionId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetSdkVersion(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetMplVersion(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetConnectionInfo(_, _)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetGroupUuid(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetExtraValue(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetConversationKey(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetRequestId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetEventId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetAoghRequestId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetAoghLocalDeviceId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetAoghAgentId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetAoghStandardAgentId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetUiVersion(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetAuditReport(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetDuoCoreVersion(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetHotwordModelId(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetDiscoveryAppSubtype(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetDiscoveryNamespaceSubtype(_)) - .WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetDiscoverySender(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetDiscoveryUnicastFlag(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, SetFeatureVector(_)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, AddMetadata(_, _)).WillByDefault(ReturnRef(*this)); - ON_CALL(*this, MergeFrom(_)).WillByDefault(ReturnRef(*this)); -} - -MockCastEventBuilder::~MockCastEventBuilder() {} - -FakeCastEventBuilder::FakeCastEventBuilder() {} - -FakeCastEventBuilder::~FakeCastEventBuilder() {} - -std::string FakeCastEventBuilder::GetName() { - return name; -} - -CastEventBuilder& FakeCastEventBuilder::SetName(const std::string& arg_name) { - name = arg_name; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetTime( - const base::TimeTicks& arg_time) { - time = arg_time; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetTimezoneId( - const std::string& arg_timezone_id) { - timezone_id = arg_timezone_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetAppId( - const std::string& arg_app_id) { - app_id = arg_app_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetRemoteAppId( - const std::string& arg_remote_app_id) { - remote_app_id = arg_remote_app_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetSessionId( - const std::string& arg_session_id) { - session_id = arg_session_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetSdkVersion( - const std::string& arg_sdk_version) { - sdk_version = arg_sdk_version; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetMplVersion( - const std::string& arg_mpl_version) { - mpl_version = arg_mpl_version; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetConnectionInfo( - const std::string& arg_transport_connection_id, - const std::string& arg_virtual_connection_id) { - transport_connection_id = arg_transport_connection_id; - virtual_connection_id = arg_virtual_connection_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetGroupUuid( - const std::string& arg_group_uuid) { - group_uuid = arg_group_uuid; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetExtraValue(int64_t arg_extra_value) { - extra_value = arg_extra_value; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetConversationKey( - const std::string& arg_conversation_key) { - conversation_key = arg_conversation_key; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetRequestId(int32_t arg_request_id) { - request_id = arg_request_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetEventId(const std::string& arg_id) { - event_id = arg_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetAoghRequestId( - const std::string& arg_request_id) { - aogh_request_id = arg_request_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetAoghLocalDeviceId( - int64_t arg_local_id) { - aogh_local_device_id = arg_local_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetAoghAgentId( - const std::string& arg_agent_id) { - aogh_agent_id = arg_agent_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetAoghStandardAgentId( - const std::string& standard_agent_id) { - aogh_standard_agent_id = standard_agent_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetUiVersion( - const std::string& arg_ui_version) { - ui_version = arg_ui_version; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetAuditReport( - const std::string& arg_audit_report) { - audit_report = arg_audit_report; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetDuoCoreVersion(int64_t version) { - duo_core_version = version; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetHotwordModelId( - const std::string& model_id) { - hotword_model_id = model_id; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetDiscoveryAppSubtype( - const std::string& arg_discovery_app_subtype) { - discovery_app_subtype = arg_discovery_app_subtype; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetDiscoveryNamespaceSubtype( - const std::string& arg_discovery_namespace_subtype) { - discovery_namespace_subtype = arg_discovery_namespace_subtype; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetDiscoverySender( - const net::IPAddressBytes& arg_discovery_sender_bytes) { - discovery_sender_bytes = arg_discovery_sender_bytes; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetDiscoveryUnicastFlag( - bool arg_discovery_unicast_flag) { - discovery_unicast_flag = arg_discovery_unicast_flag; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetFeatureVector( - const std::vector& arg_features) { - features = arg_features; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::AddMetadata(const std::string& arg_name, - int64_t arg_value) { - metadata.name = arg_name; - metadata.value = arg_value; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::SetLaunchFrom( - LaunchFrom new_launch_from) { - launch_from = new_launch_from; - return *this; -} - -CastEventBuilder& FakeCastEventBuilder::MergeFrom( - const ::metrics::CastLogsProto_CastEventProto* event_proto) { - cast_event_proto = event_proto; - return *this; -} - -::metrics::CastLogsProto_CastEventProto* FakeCastEventBuilder::Build() { - return nullptr; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/mock_cast_event_builder.h chromium-132.0.6834.159/chromecast/metrics/mock_cast_event_builder.h --- chromium-132.0.6834.110/chromecast/metrics/mock_cast_event_builder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/mock_cast_event_builder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,214 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_MOCK_CAST_EVENT_BUILDER_H_ -#define CHROMECAST_METRICS_MOCK_CAST_EVENT_BUILDER_H_ - -#include -#include - -#include "base/check_op.h" -#include "base/memory/raw_ptr.h" -#include "base/time/time.h" -#include "chromecast/metrics/cast_event_builder.h" -#include "net/base/ip_address.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { - -class MockCastEventBuilder : public CastEventBuilder { - public: - MockCastEventBuilder(); - MockCastEventBuilder(const MockCastEventBuilder&) = delete; - MockCastEventBuilder& operator=(const MockCastEventBuilder&) = delete; - ~MockCastEventBuilder() override; - MOCK_METHOD(std::string, GetName, (), (override)); - MOCK_METHOD(CastEventBuilder&, SetName, (const std::string&), (override)); - MOCK_METHOD(CastEventBuilder&, SetTime, (const base::TimeTicks&), (override)); - MOCK_METHOD(CastEventBuilder&, - SetTimezoneId, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, SetAppId, (const std::string&), (override)); - MOCK_METHOD(CastEventBuilder&, - SetRemoteAppId, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetSessionId, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetSdkVersion, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetMplVersion, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetConnectionInfo, - (const std::string&, const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetGroupUuid, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, SetExtraValue, (int64_t), (override)); - MOCK_METHOD(CastEventBuilder&, - SetConversationKey, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, SetRequestId, (int32_t), (override)); - MOCK_METHOD(CastEventBuilder&, SetEventId, (const std::string&), (override)); - MOCK_METHOD(CastEventBuilder&, - SetAoghRequestId, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, SetAoghLocalDeviceId, (int64_t), (override)); - MOCK_METHOD(CastEventBuilder&, - SetAoghAgentId, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetAoghStandardAgentId, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetUiVersion, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetAuditReport, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, SetDuoCoreVersion, (int64_t), (override)); - MOCK_METHOD(CastEventBuilder&, - SetHotwordModelId, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetDiscoveryAppSubtype, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetDiscoveryNamespaceSubtype, - (const std::string&), - (override)); - MOCK_METHOD(CastEventBuilder&, - SetDiscoverySender, - (const net::IPAddressBytes&), - (override)); - MOCK_METHOD(CastEventBuilder&, SetDiscoveryUnicastFlag, (bool), (override)); - MOCK_METHOD(CastEventBuilder&, - SetFeatureVector, - (const std::vector&), - (override)); - MOCK_METHOD(CastEventBuilder&, - AddMetadata, - (const std::string&, int64_t), - (override)); - MOCK_METHOD(CastEventBuilder&, SetLaunchFrom, (LaunchFrom), (override)); - - MOCK_METHOD(CastEventBuilder&, - MergeFrom, - (const ::metrics::CastLogsProto_CastEventProto*), - (override)); - MOCK_METHOD(::metrics::CastLogsProto_CastEventProto*, Build, (), (override)); -}; - -// Stores the last value of each field that was set in the builder. These values -// are exposed as public members for tests to verify. -class FakeCastEventBuilder : public CastEventBuilder { - public: - FakeCastEventBuilder(); - FakeCastEventBuilder(const FakeCastEventBuilder&) = delete; - FakeCastEventBuilder& operator=(const FakeCastEventBuilder&) = delete; - ~FakeCastEventBuilder() override; - - std::string GetName() override; - CastEventBuilder& SetName(const std::string& arg_name) override; - CastEventBuilder& SetTime(const base::TimeTicks& arg_time) override; - CastEventBuilder& SetTimezoneId(const std::string& arg_timezone_id) override; - CastEventBuilder& SetAppId(const std::string& arg_app_id) override; - CastEventBuilder& SetRemoteAppId( - const std::string& arg_remote_app_id) override; - CastEventBuilder& SetSessionId(const std::string& arg_session_id) override; - CastEventBuilder& SetSdkVersion(const std::string& arg_sdk_version) override; - CastEventBuilder& SetMplVersion(const std::string& arg_mpl_version) override; - CastEventBuilder& SetConnectionInfo( - const std::string& arg_transport_connection_id, - const std::string& arg_virtual_connection_id) override; - CastEventBuilder& SetGroupUuid(const std::string& arg_group_uuid) override; - CastEventBuilder& SetExtraValue(int64_t arg_extra_value) override; - CastEventBuilder& SetConversationKey( - const std::string& arg_conversation_key) override; - CastEventBuilder& SetRequestId(int32_t request_id) override; - CastEventBuilder& SetEventId(const std::string& id) override; - CastEventBuilder& SetAoghRequestId(const std::string& request_id) override; - CastEventBuilder& SetAoghLocalDeviceId(int64_t local_id) override; - CastEventBuilder& SetAoghAgentId(const std::string& request_id) override; - CastEventBuilder& SetAoghStandardAgentId( - const std::string& standard_agent_id) override; - CastEventBuilder& SetUiVersion(const std::string& ui_version) override; - CastEventBuilder& SetAuditReport(const std::string& audit_report) override; - CastEventBuilder& SetDuoCoreVersion(int64_t version) override; - CastEventBuilder& SetHotwordModelId(const std::string& model_id) override; - CastEventBuilder& SetDiscoveryAppSubtype( - const std::string& arg_discovery_app_subtype) override; - CastEventBuilder& SetDiscoveryNamespaceSubtype( - const std::string& arg_discovery_namespace_subtype) override; - CastEventBuilder& SetDiscoverySender( - const net::IPAddressBytes& arg_discovery_sender_bytes) override; - CastEventBuilder& SetDiscoveryUnicastFlag( - bool arg_discovery_unicast_flag) override; - CastEventBuilder& SetFeatureVector( - const std::vector& arg_features) override; - CastEventBuilder& AddMetadata(const std::string& name, - int64_t value) override; - CastEventBuilder& SetLaunchFrom(LaunchFrom launch_from) override; - CastEventBuilder& MergeFrom( - const ::metrics::CastLogsProto_CastEventProto* event_proto) override; - ::metrics::CastLogsProto_CastEventProto* Build() override; - - std::string name; - base::TimeTicks time; - std::string timezone_id; - std::string app_id; - std::string remote_app_id; - std::string session_id; - std::string sdk_version; - std::string mpl_version; - std::string transport_connection_id; - std::string virtual_connection_id; - std::string group_uuid; - int64_t extra_value; - std::string conversation_key; - int32_t request_id; - std::string event_id; - std::string aogh_request_id; - int64_t aogh_local_device_id; - std::string aogh_agent_id; - std::string aogh_standard_agent_id; - std::string ui_version; - std::string audit_report; - int64_t duo_core_version; - std::string hotword_model_id; - std::string discovery_app_subtype; - std::string discovery_namespace_subtype; - net::IPAddressBytes discovery_sender_bytes; - bool discovery_unicast_flag; - std::vector features; - struct Metadata { - std::string name; - int64_t value; - }; - Metadata metadata; - LaunchFrom launch_from = FROM_UNKNOWN; - raw_ptr cast_event_proto; -}; - -} // namespace chromecast - -#endif // CHROMECAST_INTERNAL_METRICS_MOCK_CAST_EVENT_BUILDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/metrics/mock_cast_sys_info_util.cc chromium-132.0.6834.159/chromecast/metrics/mock_cast_sys_info_util.cc --- chromium-132.0.6834.110/chromecast/metrics/mock_cast_sys_info_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/mock_cast_sys_info_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/mock_cast_sys_info_util.h" - -#include "chromecast/base/cast_sys_info_dummy.h" - -namespace chromecast { - -static int times_sys_info_created_ = 0; - -int GetSysInfoCreatedCount() { - return times_sys_info_created_; -} - -std::unique_ptr CreateSysInfo() { - times_sys_info_created_ += 1; - return std::make_unique(); -} - -} // namespace chromecast \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/metrics/mock_cast_sys_info_util.h chromium-132.0.6834.159/chromecast/metrics/mock_cast_sys_info_util.h --- chromium-132.0.6834.110/chromecast/metrics/mock_cast_sys_info_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/mock_cast_sys_info_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include "chromecast/base/cast_sys_info_util.h" - -#ifndef CHROMECAST_METRICS_MOCK_CAST_SYS_INFO_UTIL_H_ -#define CHROMECAST_METRICS_MOCK_CAST_SYS_INFO_UTIL_H_ - -namespace chromecast { - -int GetSysInfoCreatedCount(); -std::unique_ptr CreateSysInfo(); - -} // namespace chromecast - -#endif // CHROMECAST_METRICS_MOCK_CAST_SYS_INFO_UTIL_H_ \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromecast/metrics/timed_event_recorder.cc chromium-132.0.6834.159/chromecast/metrics/timed_event_recorder.cc --- chromium-132.0.6834.110/chromecast/metrics/timed_event_recorder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/timed_event_recorder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/metrics/timed_event_recorder.h" - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/metrics/cast_event_builder.h" -#include "chromecast/metrics/metrics_recorder.h" - -namespace chromecast { - -#define MAKE_SURE_SEQUENCE(task_runner, classname_with_method, ...) \ - if (!task_runner->RunsTasksInCurrentSequence()) { \ - task_runner->PostTask( \ - FROM_HERE, base::BindOnce(&classname_with_method, \ - weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); \ - return; \ - } - -TimedEventRecorder::TimedEventRecorder(MetricsRecorder* metrics_recorder) - : metrics_recorder_(metrics_recorder), - task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) { - DCHECK(metrics_recorder_); -} - -TimedEventRecorder::~TimedEventRecorder() = default; - -void TimedEventRecorder::MeasureTimeUntilEvent( - const std::string& event_name, - const std::string& measurement_name, - base::TimeTicks now) { - MAKE_SURE_SEQUENCE(task_runner_, TimedEventRecorder::MeasureTimeUntilEvent, - event_name, measurement_name, now); - event_name_to_measurements_[event_name].push_back({measurement_name, now}); -} - -void TimedEventRecorder::RecordEvent(const std::string& event_name, - base::TimeTicks now) { - MAKE_SURE_SEQUENCE(task_runner_, TimedEventRecorder::RecordEvent, event_name, - now); - auto it_measurements = event_name_to_measurements_.find(event_name); - if (it_measurements == event_name_to_measurements_.end()) { - return; - } - for (const auto& measurement : it_measurements->second) { - auto delta_ms = (now - measurement.start_time).InMilliseconds(); - DVLOG(1) << "Latency event: " << measurement.name << ": " << delta_ms - << "ms"; - - auto event_builder = - metrics_recorder_->CreateEventBuilder(measurement.name); - event_builder->SetExtraValue(delta_ms); - metrics_recorder_->RecordCastEvent(std::move(event_builder)); - } - // Clear all measurements for this end event. - it_measurements->second.clear(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/metrics/timed_event_recorder.h chromium-132.0.6834.159/chromecast/metrics/timed_event_recorder.h --- chromium-132.0.6834.110/chromecast/metrics/timed_event_recorder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/metrics/timed_event_recorder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_METRICS_TIMED_EVENT_RECORDER_H_ -#define CHROMECAST_METRICS_TIMED_EVENT_RECORDER_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/memory/raw_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/time/tick_clock.h" -#include "base/time/time.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace chromecast { - -class MetricsRecorder; - -// Helper class to measure and record the time until a named event. The class -// must be destroyed on the same sequence it was created on, but is otherwise -// thread safe. -class TimedEventRecorder final { - public: - explicit TimedEventRecorder(MetricsRecorder* metrics_recorder); - ~TimedEventRecorder(); - - TimedEventRecorder(const TimedEventRecorder&) = delete; - TimedEventRecorder& operator=(const TimedEventRecorder&) = delete; - - // Start measuring the time until RecordEvent(|event_name|). When the event - // occurs, a metrics event will be recorded with the name |measurement_name| - // and the elapsed time in milliseconds. - void MeasureTimeUntilEvent(const std::string& event_name, - const std::string& measurement_name, - base::TimeTicks now); - - // Make a record of |event_name| and handle any matching ongoing measurements. - void RecordEvent(const std::string& event_name, base::TimeTicks now); - - private: - struct TimelineMeasurement { - std::string name; - base::TimeTicks start_time; - }; - - const raw_ptr metrics_recorder_; - const scoped_refptr task_runner_; - - // Maps a named event to a set of TimelineMeasurements that will conclude with - // that event. - base::flat_map> - event_name_to_measurements_; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_METRICS_TIMED_EVENT_RECORDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/mojo/DEPS chromium-132.0.6834.159/chromecast/mojo/DEPS --- chromium-132.0.6834.110/chromecast/mojo/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/bindings", -] diff -Nru chromium-132.0.6834.110/chromecast/mojo/OWNERS chromium-132.0.6834.159/chromecast/mojo/OWNERS --- chromium-132.0.6834.110/chromecast/mojo/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -seantopping@chromium.org -lijiawei@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/mojo/binder_factory.cc chromium-132.0.6834.159/chromecast/mojo/binder_factory.cc --- chromium-132.0.6834.110/chromecast/mojo/binder_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/binder_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// 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 "chromecast/mojo/binder_factory.h" - -namespace chromecast { - -MultiBinderFactory::MultiBinderFactory() = default; - -MultiBinderFactory::~MultiBinderFactory() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/mojo/binder_factory.h chromium-132.0.6834.159/chromecast/mojo/binder_factory.h --- chromium-132.0.6834.110/chromecast/mojo/binder_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/binder_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,342 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MOJO_BINDER_FACTORY_H_ -#define CHROMECAST_MOJO_BINDER_FACTORY_H_ - -#include -#include -#include - -#include "base/check.h" -#include "base/containers/flat_map.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/logging.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "base/task/sequenced_task_runner.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/receiver_set.h" - -namespace chromecast { - -// A class to provide callback for binding mojo PendingReceiver with -// mojo interface implementation. This class is designed to be inherited by -// mojo interface implementation. Service class can call BinderFactory class's -// GetBinder() directly to add the binder callback to a BinderRegistry. -// Binding management on interface implementation side can be avoided by -// utilizing this. -// -// For example, -// -// demo_code_impl.h: -// -// class DemoCodeImpl : public mojom::DemoCode, -// public BinderFactory { -// public: -// DemoCodeImpl(); -// ... -// private: -// ... -// }; -// -// demo_service.h: -// -// class DemoService : public service_manager::Service { -// public: -// DemoService(); -// ~DemoService(); -// -// // service_manager::Service implementation: -// void OnStart() override; -// void OnBindInterface(const service_manager::BindSourceInfo& source, -// const std::string& interface_name, -// mojo::ScopedMessagePipeHandle interface_pipe) -// override; -// private: -// ... -// service_manager::BinderRegistry registry_; -// std::unique_ptr demo_code_; -// ... -// } -// -// demo_service.cc: -// -// void DemoService::OnStart() { -// registry_.AddInterface(demo_code_.GetBinder()); -// } -// -// void DemoService::OnBindInterface( -// const service_manager::BindSourceInfo& source, -// const std::string& interface_name, -// mojo::ScopedMessagePipeHandle interface_pipe) { -// registry_.TryBindInterface(interface_name, &interface_pipe); -// } - -// Non-template base class for BinderFactory. This allows multiple instances of -// BinderFactoryBase to be stored in a generic data structure. -class BinderFactoryBase { - public: - virtual ~BinderFactoryBase() {} - - // Binds a message pipe handle to an endpoint. - virtual void BindPipe(mojo::ScopedMessagePipeHandle handle) = 0; - - // Returns a callback which wraps BinderFactoryBase::BindPipe(). - virtual base::RepeatingCallback - GetPipeBinder() = 0; -}; - -template -class BinderFactory : public BinderFactoryBase { - public: - explicit BinderFactory( - Interface* impl, - scoped_refptr task_runner = nullptr, - bool single_binder = false) - : impl_(impl), - task_runner_(std::move(task_runner)), - use_single_binder_(single_binder), - single_receiver_(impl_), - weak_factory_(this) { - DCHECK(impl_) << "Implementation for interface '" << Interface::Name_ - << "' is null!"; - } - BinderFactory(const BinderFactory&) = delete; - - ~BinderFactory() override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - } - BinderFactory& operator=(const BinderFactory&) = delete; - - base::RepeatingCallback)> GetBinder() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return base::BindRepeating(&BinderFactory::Bind, - weak_factory_.GetWeakPtr()); - } - - void Bind(mojo::PendingReceiver request) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (use_single_binder_) { - if (single_receiver_.is_bound()) { - LOG(ERROR) << Interface::Name_ << " implementation is already bound, " - << " this request will be dropped."; - return; - } - single_receiver_.Bind(std::move(request), task_runner_); - single_receiver_.set_disconnect_handler( - base::BindRepeating(&mojo::Receiver::reset, - base::Unretained(&single_receiver_))); - } else { - receivers_.Add(impl_, std::move(request), task_runner_); - } - } - - // BinderFactoryBase implementation: - base::RepeatingCallback GetPipeBinder() - override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return base::BindRepeating(&BinderFactory::BindPipe, - weak_factory_.GetWeakPtr()); - } - - void BindPipe(mojo::ScopedMessagePipeHandle handle) override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - receivers_.Add(impl_, mojo::PendingReceiver(std::move(handle)), - task_runner_); - } - - private: - Interface* const impl_; - scoped_refptr task_runner_; - const bool use_single_binder_; - - mojo::ReceiverSet receivers_; - mojo::Receiver single_receiver_; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory weak_factory_; -}; - -// Syntactic sugar for classes that want to implement a single and -// also receive the helpful binding functions for BinderFactory. -template -class Bindable : public BinderFactory, public Interface { - public: - Bindable() : BinderFactory(this) {} - ~Bindable() override = default; -}; - -// This implementation wraps a callback that accepts a PendingReceiver. This -// allows MultiBinderFactory to work with clients that provide their own binding -// logic. -template -class BinderCallbackWrapper : public BinderFactoryBase { - public: - explicit BinderCallbackWrapper( - const base::RepeatingCallback)>& - callback, - scoped_refptr task_runner = nullptr) - : callback_(callback), task_runner_(task_runner), weak_factory_(this) { - DCHECK(callback_); - } - BinderCallbackWrapper(const BinderCallbackWrapper&) = delete; - BinderCallbackWrapper& operator=(const BinderCallbackWrapper&) = delete; - - // BinderFactoryBase implementation: - base::RepeatingCallback GetPipeBinder() - override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return base::BindRepeating(&BinderCallbackWrapper::BindPipe, - weak_factory_.GetWeakPtr()); - } - - void BindPipe(mojo::ScopedMessagePipeHandle handle) override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - mojo::PendingReceiver request(std::move(handle)); - if (task_runner_ && !task_runner_->RunsTasksInCurrentSequence()) { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&BinderCallbackWrapper::BindOnTaskRunner, - weak_factory_.GetWeakPtr(), std::move(request))); - return; - } - callback_.Run(std::move(request)); - } - - private: - void BindOnTaskRunner(mojo::PendingReceiver request) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - callback_.Run(std::move(request)); - } - - base::RepeatingCallback)> callback_; - scoped_refptr task_runner_; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory weak_factory_; -}; - -// Similar to BinderFactory, MultiBinderFactory can provide binder functions for -// more than one interface. -// -// Example code: -// -// MultiBinderFactory factory; -// factory.AddInterface(&foo_impl); -// factory.AddInterface(&bar_impl); -// -// service_manager::BinderRegistry registry; -// registry.AddInterface(factory.GetBinder()); -// registry.AddInterface(factory.GetBinder()); -// -// auto bad_binder = factory.GetBinder(); -// ASSERT_TRUE(bad_binder.is_null()); -class MultiBinderFactory { - public: - MultiBinderFactory(); - MultiBinderFactory(const MultiBinderFactory&) = delete; - ~MultiBinderFactory(); - MultiBinderFactory& operator=(const MultiBinderFactory&) = delete; - - template - void AddInterface(Interface* interface) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto result = binder_factories_.emplace( - Interface::Name_, - std::make_unique>(interface)); - DCHECK(result.second); - } - - template - void AddSingleBinderInterface(Interface* interface) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto result = binder_factories_.emplace( - Interface::Name_, std::make_unique>( - interface, nullptr, true /* single_binder */)); - DCHECK(result.second); - } - - template - void AddBinder( - const base::RepeatingCallback)>& - callback, - scoped_refptr task_runner = nullptr) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto result = binder_factories_.emplace( - Interface::Name_, std::make_unique>( - callback, task_runner)); - DCHECK(result.second); - } - - bool HasInterface(const std::string& interface_name) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto it = binder_factories_.find(interface_name); - return it != binder_factories_.end(); - } - - template - bool HasInterface() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return HasInterface(Interface::Name_); - } - - template - void RemoveInterface() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto it = binder_factories_.find(Interface::Name_); - if (it == binder_factories_.end()) { - return; - } - binder_factories_.erase(it); - } - - template - base::RepeatingCallback)> GetBinder() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto it = binder_factories_.find(Interface::Name_); - if (it == binder_factories_.end()) { - return base::RepeatingCallback)>(); - } - return base::BindRepeating(&ForwardToPipeBinder, - it->second->GetPipeBinder()); - } - - template - bool Bind(mojo::PendingReceiver request) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return Bind(Interface::Name_, request.PassPipe()); - } - - bool Bind(const std::string& interface_name, - mojo::ScopedMessagePipeHandle handle) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto it = binder_factories_.find(interface_name); - if (it == binder_factories_.end()) { - return false; - } - it->second->BindPipe(std::move(handle)); - return true; - } - - private: - template - static void ForwardToPipeBinder( - base::RepeatingCallback pipe_binder, - mojo::PendingReceiver request) { - pipe_binder.Run(request.PassPipe()); - } - - base::flat_map> - binder_factories_; - - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace chromecast - -#endif // CHROMECAST_MOJO_BINDER_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/mojo/binder_factory_test.cc chromium-132.0.6834.159/chromecast/mojo/binder_factory_test.cc --- chromium-132.0.6834.110/chromecast/mojo/binder_factory_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/binder_factory_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,140 +0,0 @@ -// 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 "chromecast/mojo/binder_factory.h" - -#include - -#include "base/functional/bind.h" -#include "base/test/task_environment.h" -#include "chromecast/mojo/test/test_interfaces.test-mojom.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; - -namespace chromecast { - -class MockInterface : public test::mojom::StringInterface, - public test::mojom::IntInterface, - public test::mojom::BoolInterface { - public: - MOCK_METHOD(void, StringMethod, (const std::string& s), (override)); - MOCK_METHOD(void, IntMethod, (int32_t i), (override)); - MOCK_METHOD(void, BoolMethod, (bool b), (override)); -}; - -class MockErrorHandler { - public: - MOCK_METHOD(void, OnError, ()); -}; - -class BinderFactoryTest : public testing::Test { - protected: - BinderFactoryTest() {} - - base::test::TaskEnvironment task_environment_; - - MockInterface mock_interface_; -}; - -TEST_F(BinderFactoryTest, BinderFactoryBind) { - BinderFactory s_factory(&mock_interface_); - - mojo::Remote s_remote; - s_factory.Bind(s_remote.BindNewPipeAndPassReceiver()); - - // Verify implementation is connected. - std::string s = "Hello, world!"; - EXPECT_CALL(mock_interface_, StringMethod(s)); - s_remote->StringMethod(s); - task_environment_.RunUntilIdle(); -} - -TEST_F(BinderFactoryTest, BinderFactoryGetBinder) { - BinderFactory s_factory(&mock_interface_); - - auto binder = s_factory.GetBinder(); - ASSERT_TRUE(!binder.is_null()); - - mojo::Remote s_remote; - s_factory.Bind(s_remote.BindNewPipeAndPassReceiver()); - - // Verify implementation is connected. - std::string s = "Hello, world!"; - EXPECT_CALL(mock_interface_, StringMethod(s)); - s_remote->StringMethod(s); - task_environment_.RunUntilIdle(); -} - -TEST_F(BinderFactoryTest, BinderFactoryLifetime) { - MockErrorHandler s_handler; - auto s_factory = - std::make_unique>( - &mock_interface_); - - auto binder = s_factory->GetBinder(); - ASSERT_TRUE(!binder.is_null()); - - mojo::Remote s_remote; - s_factory->Bind(s_remote.BindNewPipeAndPassReceiver()); - - s_remote.set_disconnect_handler( - base::BindOnce(&MockErrorHandler::OnError, base::Unretained(&s_handler))); - - // Remotes which were bound via the BinderFactory will invalidated when the - // factory is destroyed. - EXPECT_CALL(s_handler, OnError()).Times(1); - - s_factory.reset(); - task_environment_.RunUntilIdle(); -} - -TEST_F(BinderFactoryTest, MultiBinderFactory) { - MockErrorHandler s_handler; - MockErrorHandler i_handler; - auto factory = std::make_unique(); - factory->AddInterface(&mock_interface_); - factory->AddInterface(&mock_interface_); - - auto s_binder = factory->GetBinder(); - ASSERT_FALSE(s_binder.is_null()); - auto i_binder = factory->GetBinder(); - ASSERT_FALSE(i_binder.is_null()); - - // There is no binder for BoolInterface. - ASSERT_TRUE(factory->GetBinder().is_null()); - - mojo::Remote s_remote; - s_binder.Run(s_remote.BindNewPipeAndPassReceiver()); - - mojo::Remote i_remote; - i_binder.Run(i_remote.BindNewPipeAndPassReceiver()); - - std::string s = "Hello, world!"; - EXPECT_CALL(mock_interface_, StringMethod(s)); - s_remote->StringMethod(s); - task_environment_.RunUntilIdle(); - - int i = 1234; - EXPECT_CALL(mock_interface_, IntMethod(i)); - i_remote->IntMethod(i); - task_environment_.RunUntilIdle(); - - s_remote.set_disconnect_handler( - base::BindOnce(&MockErrorHandler::OnError, base::Unretained(&s_handler))); - i_remote.set_disconnect_handler( - base::BindOnce(&MockErrorHandler::OnError, base::Unretained(&i_handler))); - - // Pointers which were bound via the MultiBinderFactory will invalidated when - // the factory is destroyed. - EXPECT_CALL(s_handler, OnError()).Times(1); - EXPECT_CALL(i_handler, OnError()).Times(1); - - factory.reset(); - task_environment_.RunUntilIdle(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/mojo/interface_bundle.cc chromium-132.0.6834.159/chromecast/mojo/interface_bundle.cc --- chromium-132.0.6834.110/chromecast/mojo/interface_bundle.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/interface_bundle.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ -// 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 "chromecast/mojo/interface_bundle.h" - -#include - -namespace chromecast { - -InterfaceBundle::InterfaceBundle() = default; - -InterfaceBundle::~InterfaceBundle() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -void InterfaceBundle::Close() { - client_receivers_.Clear(); -} - -mojo::PendingRemote InterfaceBundle::CreateRemote() { - mojo::PendingRemote pending_remote; - AddClient(pending_remote.InitWithNewPipeAndPassReceiver()); - return pending_remote; -} - -void InterfaceBundle::BindInterface(const std::string& interface_name, - mojo::ScopedMessagePipeHandle handle) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (local_interfaces_.HasInterface(interface_name)) { - local_interfaces_.Bind(interface_name, std::move(handle)); - return; - } - LOG(WARNING) << "Interface '" << interface_name << "' is not exposed by this " - << "bundle, but a consumer tried to bind it."; -} - -void InterfaceBundle::AddClient( - mojo::PendingReceiver receiver) { - client_receivers_.Add(this, std::move(receiver)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/mojo/interface_bundle.h chromium-132.0.6834.159/chromecast/mojo/interface_bundle.h --- chromium-132.0.6834.110/chromecast/mojo/interface_bundle.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/interface_bundle.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,152 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MOJO_INTERFACE_BUNDLE_H_ -#define CHROMECAST_MOJO_INTERFACE_BUNDLE_H_ - -#include - -#include "base/functional/callback.h" -#include "base/logging.h" -#include "base/sequence_checker.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/mojo/binder_factory.h" -#include "chromecast/mojo/mojom/remote_interfaces.mojom.h" -#include "mojo/public/cpp/bindings/generic_pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { - -// This class essentially combines RemoteInterfaces and BinderRegistry into -// one. On the host side, this class can be created and used like a -// BinderRegistry. InterfaceBundle can also dispense RemoteInterfaces remotes -// for clients to invoke local binders. -// -// This class should only be used on one sequence. Local interfaces will be -// bound to the sequence that the InterfaceBundle is created on, unless a task -// runner is provided in AddBinder(). -// -// Implementations that are added via raw pointer (instead of a binder callback) -// will have the Receiver owned by the InterfaceBundle. When the InterfaceBundle -// is destroyed, the connection is severed. All implementations that are added -// by raw pointer must therefore outlive the InterfaceBundle. -// -// ============================================================================= -// Example Usage -// ============================================================================= -// -// Add implementations to the bundle, no Binding boilerplate required: -// -// InterfaceBundle bundle; -// bundle.AddInterface(GetFooImpl()); -// bundle.AddInterface(GetBarImpl()); -// -// Dispense a RemoteInterfaces, which can be used by clients: -// -// mojo::Remote provider(bundle.CreateRemote()); -// mojo::Remote bar; -// provider->BindNewPipe(&bar); -// bar->DoBarStuff(); -class InterfaceBundle final : private mojom::RemoteInterfaces { - public: - // Specifies the number of expected clients for a given Receiver. - enum ReceiverType { - MULTIPLE_BINDERS, // Multiple clients, use a ReceiverSet. - SINGLE_BINDER, // Single client, use a Receiver. - }; - - InterfaceBundle(); - InterfaceBundle(const InterfaceBundle&) = delete; - ~InterfaceBundle() override; - InterfaceBundle& operator=(const InterfaceBundle&) = delete; - - // Adds an implementation for an interface of type . When the - // interface is requested via one of the consumer methods below, |interface| - // will receive the method calls. - // - // |interface| *must* outlive the InterfaceBundle, or else mojo method calls - // could be invoked on a destroyed object. - template - bool AddInterface(Interface* interface, - ReceiverType receiver_type = MULTIPLE_BINDERS) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (local_interfaces_.HasInterface()) { - LOG(DFATAL) << "Local interface '" << Interface::Name_ << "' has already " - << "been added to this bundle."; - return false; - } - if (receiver_type == MULTIPLE_BINDERS) { - local_interfaces_.AddInterface(interface); - } else { - local_interfaces_.AddSingleBinderInterface(interface); - } - return true; - } - - // Similar to BinderRegistry::AddInterface(), AddBinder() allows clients to - // provide their own binder callbacks and task runners. If |task_runner| is - // provided, then |callback| will be invoked on |task_runner| for every - // incoming request to . Subsequent calls to 's methods - // will post to |task_runner|. If |task_runner| is not provided, the current - // SequencedTaskRunner will receive incoming bind requests and method calls. - template - bool AddBinder( - const base::RepeatingCallback)>& - callback, - scoped_refptr task_runner = nullptr) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (local_interfaces_.HasInterface()) { - LOG(DFATAL) << "Local interface '" << Interface::Name_ << "' has already " - << "been added to this bundle."; - return false; - } - local_interfaces_.AddBinder(callback, task_runner); - return true; - } - - template - void RemoveInterface() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - local_interfaces_.RemoveInterface(); - } - - // Creates a remote reference which can be passed over IPC to a remote client. - mojo::PendingRemote CreateRemote(); - - // Severs all client connections. This should only be called on teardown. - void Close(); - - // mojom::RemoteInterfaces implementation: - void BindInterface(const std::string& interface_name, - mojo::ScopedMessagePipeHandle handle) override; - void AddClient( - mojo::PendingReceiver receiver) override; - - // Attempt to bind a generic receiver. Succeeds if there is an available - // implementation or binder callback registered. - bool TryBindReceiver(mojo::GenericPendingReceiver& receiver) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (local_interfaces_.HasInterface(*receiver.interface_name())) { - std::string interface_name = *receiver.interface_name(); - local_interfaces_.Bind(interface_name, receiver.PassPipe()); - return true; - } - return false; - } - - private: - // For interfaces that are provided as a local pointer without any binding - // logic, we can use MultiBinderFactory to expose a binding surface. - MultiBinderFactory local_interfaces_; - - mojo::ReceiverSet client_receivers_; - - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace chromecast - -#endif // CHROMECAST_MOJO_INTERFACE_BUNDLE_H_ diff -Nru chromium-132.0.6834.110/chromecast/mojo/interface_bundle_test.cc chromium-132.0.6834.159/chromecast/mojo/interface_bundle_test.cc --- chromium-132.0.6834.110/chromecast/mojo/interface_bundle_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/interface_bundle_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,133 +0,0 @@ -// 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 "chromecast/mojo/interface_bundle.h" - -#include - -#include "base/functional/bind.h" -#include "base/test/task_environment.h" -#include "chromecast/mojo/remote_interfaces.h" -#include "chromecast/mojo/test/test_interfaces.test-mojom.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; - -namespace chromecast { - -class MockInterface : public test::mojom::StringInterface, - public test::mojom::IntInterface, - public test::mojom::BoolInterface { - public: - MOCK_METHOD(void, StringMethod, (const std::string& s), (override)); - MOCK_METHOD(void, IntMethod, (int32_t i), (override)); - MOCK_METHOD(void, BoolMethod, (bool b), (override)); -}; - -class MockErrorHandler { - public: - MOCK_METHOD(void, OnError, ()); -}; - -class InterfaceBundleTest : public testing::Test { - protected: - InterfaceBundleTest() {} - - base::test::TaskEnvironment task_environment_; - - MockInterface mock_interface_; -}; - -TEST_F(InterfaceBundleTest, ExampleUsage) { - InterfaceBundle bundle; - RemoteInterfaces interfaces(bundle.CreateRemote()); - - // =========================================================================== - // Success Scenarios - // =========================================================================== - // Add an implementation of StringInterface to this bundle. - ASSERT_TRUE( - bundle.AddInterface(&mock_interface_)); - - // RemoteInterfaces dispenses Remotes on behalf of InterfaceBundle. - mojo::Remote remote; - interfaces.BindNewPipe(&remote); - ASSERT_TRUE(remote.is_bound()); - - // The newly created Remote will call into the implementation. - std::string s = "Hello, world!"; - EXPECT_CALL(mock_interface_, StringMethod(s)); - remote->StringMethod(s); - task_environment_.RunUntilIdle(); - - // =========================================================================== - // Error Scenarios - // =========================================================================== - // IntInterface wasn't provided, but we allow a new Remote to be created. - // However, once the request is rejected by InterfaceBundle, the Remote will - // be disconnected. - auto bad_remote = interfaces.CreateRemote(); - ASSERT_TRUE(bad_remote.is_bound()); - ASSERT_TRUE(bad_remote.is_connected()); - - task_environment_.RunUntilIdle(); - ASSERT_FALSE(bad_remote.is_connected()); -} - -TEST_F(InterfaceBundleTest, Lifetime) { - MockErrorHandler error_handler_; - mojo::Remote remote; - { - InterfaceBundle bundle; - RemoteInterfaces interfaces(bundle.CreateRemote()); - - ASSERT_TRUE( - bundle.AddInterface(&mock_interface_)); - interfaces.BindNewPipe(&remote); - - // Verify the Remote is usable. - std::string s = "Hello, world!"; - EXPECT_CALL(mock_interface_, StringMethod(s)); - remote->StringMethod(s); - task_environment_.RunUntilIdle(); - - remote.set_disconnect_handler(base::BindOnce( - &MockErrorHandler::OnError, base::Unretained(&error_handler_))); - - // When the InterfaceBundle is destroyed, all dispensed Remotes will be - // invalidated. - EXPECT_CALL(error_handler_, OnError()).Times(1); - } - task_environment_.RunUntilIdle(); - ASSERT_FALSE(remote.is_connected()); -} - -TEST_F(InterfaceBundleTest, LateBinding) { - InterfaceBundle bundle; - // Don't link to the InterfaceBundle just yet. - RemoteInterfaces interfaces; - - ASSERT_TRUE( - bundle.AddInterface(&mock_interface_)); - - mojo::Remote remote; - interfaces.BindNewPipe(&remote); - std::string s = "Hello, world!"; - - // We do not have a link to an implementation yet, but the client can still - // try to use the interface anyway. - EXPECT_CALL(mock_interface_, StringMethod(s)).Times(0); - remote->StringMethod(s); - remote->StringMethod(s); - remote->StringMethod(s); - task_environment_.RunUntilIdle(); - - // When we bind the provider late, all requests should be fulfilled. - EXPECT_CALL(mock_interface_, StringMethod(s)).Times(3); - interfaces.SetProvider(bundle.CreateRemote()); - task_environment_.RunUntilIdle(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/mojo/mojom/OWNERS chromium-132.0.6834.159/chromecast/mojo/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/mojo/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/mojo/mojom/remote_interfaces.mojom chromium-132.0.6834.159/chromecast/mojo/mojom/remote_interfaces.mojom --- chromium-132.0.6834.110/chromecast/mojo/mojom/remote_interfaces.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/mojom/remote_interfaces.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// 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. - -module chromecast.mojom; - -// Note for reviewers: Never allow an instance of RemoteInterfaces to be exposed -// to a sandboxed process (e.g. render process). -// -// Generic interface for binding a message pipe |pipe| to an interface with type -// |interface_name|. As a generic binding surface, this interface will never be -// provided to an unprivileged process. When implementing or using this -// interface, keep in mind the following: -// -// 1. This interface is accessible only to unsandboxed, privileged processes -// running trusted code. -// 2. Trusted clients are free to pass and wrap this interface around as they -// see fit. Therefore, make no assumptions about which trusted system -// components have access to it, since there is no programmatic enforcement. -// -// This interface is only used on Cast devices. This offers an easy way to move -// off of the Service Manager. For example, an instance of RemoteInterfaces can -// be injected into a process that uses the service_manager::Connector to bind -// Remotes to other services. -interface RemoteInterfaces { - // Requests to bind |pipe| to a named interface type. - BindInterface(string interface_name, handle pipe); - - // Binds a remote client to the implementation. - AddClient(pending_receiver receiver); -}; diff -Nru chromium-132.0.6834.110/chromecast/mojo/remote_interfaces.cc chromium-132.0.6834.159/chromecast/mojo/remote_interfaces.cc --- chromium-132.0.6834.110/chromecast/mojo/remote_interfaces.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/remote_interfaces.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// 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 "chromecast/mojo/remote_interfaces.h" - -#include "base/check.h" - -namespace chromecast { - -RemoteInterfaces::RemoteInterfaces() { - Init(); - DCHECK(remote_provider_.is_bound()); -} - -RemoteInterfaces::RemoteInterfaces( - mojo::PendingRemote provider) { - Init(); - DCHECK(remote_provider_.is_bound()); - SetProvider(std::move(provider)); -} - -RemoteInterfaces::~RemoteInterfaces() = default; - -void RemoteInterfaces::SetProvider( - mojo::PendingRemote provider) { - DCHECK(waiting_receiver_); - mojo::FusePipes(std::move(waiting_receiver_), std::move(provider)); -} - -mojo::PendingRemote RemoteInterfaces::Forward() { - mojo::PendingRemote pending_remote; - remote_provider_->AddClient(pending_remote.InitWithNewPipeAndPassReceiver()); - return pending_remote; -} - -mojo::PendingReceiver RemoteInterfaces::GetReceiver() { - DCHECK(waiting_receiver_); - return std::move(waiting_receiver_); -} - -void RemoteInterfaces::Bind(mojo::GenericPendingReceiver receiver) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - // Important: We need to copy the interface name before sending it. - std::string interface_name = *receiver.interface_name(); - remote_provider_->BindInterface(interface_name, receiver.PassPipe()); -} - -void RemoteInterfaces::Init() { - if (remote_provider_.is_bound()) { - LOG(WARNING) << "Remote provider disconnected, reseting..."; - remote_provider_.reset(); - } - waiting_receiver_ = remote_provider_.BindNewPipeAndPassReceiver(); - remote_provider_.set_disconnect_handler( - base::BindOnce(&RemoteInterfaces::Init, base::Unretained(this))); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/mojo/remote_interfaces.h chromium-132.0.6834.159/chromecast/mojo/remote_interfaces.h --- chromium-132.0.6834.110/chromecast/mojo/remote_interfaces.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/remote_interfaces.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,113 +0,0 @@ -// 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. - -#ifndef CHROMECAST_MOJO_REMOTE_INTERFACES_H_ -#define CHROMECAST_MOJO_REMOTE_INTERFACES_H_ - -#include "base/sequence_checker.h" -#include "chromecast/mojo/mojom/remote_interfaces.mojom.h" -#include "mojo/public/cpp/bindings/generic_pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { - -// Client helper object which wraps a mojo::Remote and -// provides convenience methods for binding local Remote stubs. -// -// ============================================================================= -// Example Usage -// ============================================================================= -// -// From a service, create a pending RemoteInterfaces, such as from -// InterfaceBundle: -// -// InterfaceBundle bundle; -// bundle.AddInterface(GetFooImpl()); -// bundle.AddInterface(GetBarImpl()); -// mojo::PendingRemote pending_provider = -// bundle.CreateRemote(); -// -// In a different service, we can use RemoteInterfaces to wrap -// |pending_provider| and access the interfaces that were added: -// -// RemoteService::InjectInterfaces( -// mojo::PendingRemote pending_provider) { -// RemoteInterfaces provider(std::move(pending_provider)); -// mojo::Remote bar = bundle.GetRemote(); -// bar->DoBarStuff(); -// } -class RemoteInterfaces { - public: - RemoteInterfaces(); - explicit RemoteInterfaces( - mojo::PendingRemote provider); - ~RemoteInterfaces(); - - RemoteInterfaces(const RemoteInterfaces&) = delete; - RemoteInterfaces& operator=(const RemoteInterfaces&) = delete; - - // Late-binds a provider if one was not injected on creation. - void SetProvider(mojo::PendingRemote provider); - - // Exposes interfaces to a remote provider. - mojo::PendingRemote Forward(); - - // Gets the currently unbound receiver to pass to a remote provider. There - // must not already be a receiver bound to this class. - mojo::PendingReceiver GetReceiver(); - - // =========================================================================== - // Interface binding methods: After binding, the Remotes/PendingRemotes which - // are bound are guaranteed to be bound and connected (i.e. remote.is_bound() - // and remote.is_connected() will return true immediately). Clients can safely - // start issuing method calls at this point. However, if the remote provider - // does not fulfill the request, then the Remote/PendingRemote will become - // disconnected (remote.is_connected() == false), but still be bound. - // =========================================================================== - - // Binds a generic receiver to an implementation in the remote provider. - void Bind(mojo::GenericPendingReceiver receiver); - - // Binds an implementation in the remote provider. - template - void Bind(mojo::PendingReceiver receiver) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - remote_provider_->BindInterface(Interface::Name_, receiver.PassPipe()); - } - - // Binds a new message pipe to |remote|, and passes the request to the remote - // provider. - template - void BindNewPipe(mojo::Remote* remote) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - auto pending_receiver = remote->BindNewPipeAndPassReceiver(); - Bind(std::move(pending_receiver)); - } - - // Dispenses a mojo::Remote which is bound by the remote provider. - template - mojo::Remote CreateRemote() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - mojo::Remote remote; - BindNewPipe(&remote); - return remote; - } - - private: - void Init(); - - mojo::Remote remote_provider_; - - // Temporary pending receiver which allows the client to immediately - // start acquiring remote interfaces while we wait for an implementation - // to be provided. - mojo::PendingReceiver waiting_receiver_; - - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace chromecast - -#endif // CHROMECAST_MOJO_REMOTE_INTERFACES_H_ diff -Nru chromium-132.0.6834.110/chromecast/mojo/test/DEPS chromium-132.0.6834.159/chromecast/mojo/test/DEPS --- chromium-132.0.6834.110/chromecast/mojo/test/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/test/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -include_rules = [ - "+mojo/core/embedder", -] diff -Nru chromium-132.0.6834.110/chromecast/mojo/test/run_all_unittests.cc chromium-132.0.6834.159/chromecast/mojo/test/run_all_unittests.cc --- chromium-132.0.6834.110/chromecast/mojo/test/run_all_unittests.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/test/run_all_unittests.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// 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 "base/functional/bind.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "mojo/core/embedder/embedder.h" - -int main(int argc, char** argv) { - base::TestSuite test_suite(argc, argv); - mojo::core::Init(); - return base::LaunchUnitTests( - argc, argv, - base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite))); -} diff -Nru chromium-132.0.6834.110/chromecast/mojo/test/test_interfaces.test-mojom chromium-132.0.6834.159/chromecast/mojo/test/test_interfaces.test-mojom --- chromium-132.0.6834.110/chromecast/mojo/test/test_interfaces.test-mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/mojo/test/test_interfaces.test-mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -// 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. - -module chromecast.test.mojom; - -// Simple interfaces for testing. -interface StringInterface { - StringMethod(string s); -}; - -interface IntInterface { - IntMethod(int32 i); -}; - -interface BoolInterface { - BoolMethod(bool b); -}; diff -Nru chromium-132.0.6834.110/chromecast/net/DEPS chromium-132.0.6834.159/chromecast/net/DEPS --- chromium-132.0.6834.110/chromecast/net/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -include_rules = [ - "+components/proxy_config", - "+mojo/public/cpp/bindings", - "+net", - "+services/network/public/cpp", - "+services/network/public/mojom", - "+services/network/test", -] diff -Nru chromium-132.0.6834.110/chromecast/net/connectivity_checker.cc chromium-132.0.6834.159/chromecast/net/connectivity_checker.cc --- chromium-132.0.6834.110/chromecast/net/connectivity_checker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/connectivity_checker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -// 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 "chromecast/net/connectivity_checker.h" - -#include "base/task/single_thread_task_runner.h" -#include "chromecast/net/connectivity_checker_impl.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" - -namespace chromecast { - -ConnectivityChecker::ConnectivityChecker( - scoped_refptr task_runner) - : RefCountedDeleteOnSequence(std::move(task_runner)), - connectivity_observer_list_( - base::MakeRefCounted< - base::ObserverListThreadSafe>()), - connectivity_check_failure_observer_list_( - base::MakeRefCounted>()) {} - -ConnectivityChecker::~ConnectivityChecker() = default; - -void ConnectivityChecker::AddConnectivityObserver( - ConnectivityObserver* observer) { - connectivity_observer_list_->AddObserver(observer); -} - -void ConnectivityChecker::RemoveConnectivityObserver( - ConnectivityObserver* observer) { - connectivity_observer_list_->RemoveObserver(observer); -} - -void ConnectivityChecker::Notify(bool connected) { - DCHECK(connectivity_observer_list_.get()); - connectivity_observer_list_->Notify( - FROM_HERE, &ConnectivityObserver::OnConnectivityChanged, connected); -} - -void ConnectivityChecker::AddConnectivityCheckFailureObserver( - ConnectivityCheckFailureObserver* observer) { - connectivity_check_failure_observer_list_->AddObserver(observer); -} - -void ConnectivityChecker::RemoveConnectivityCheckFailureObserver( - ConnectivityCheckFailureObserver* observer) { - connectivity_check_failure_observer_list_->RemoveObserver(observer); -} - -void ConnectivityChecker::NotifyCheckFailure() { - DCHECK(connectivity_check_failure_observer_list_.get()); - connectivity_check_failure_observer_list_->Notify( - FROM_HERE, &ConnectivityCheckFailureObserver::OnConnectivityCheckFailed); -} - -// static -scoped_refptr ConnectivityChecker::Create( - const scoped_refptr& task_runner, - std::unique_ptr - pending_url_loader_factory, - network::NetworkConnectionTracker* network_connection_tracker, - TimeSyncTracker* time_sync_tracker) { - return ConnectivityCheckerImpl::Create( - task_runner, std::move(pending_url_loader_factory), - network_connection_tracker, time_sync_tracker); -} - -// static -scoped_refptr ConnectivityChecker::Create( - const scoped_refptr& task_runner, - std::unique_ptr - pending_url_loader_factory, - network::NetworkConnectionTracker* network_connection_tracker, - base::TimeDelta disconnected_probe_period, - base::TimeDelta connected_probe_period, - TimeSyncTracker* time_sync_tracker) { - return ConnectivityCheckerImpl::Create( - task_runner, std::move(pending_url_loader_factory), - network_connection_tracker, disconnected_probe_period, - connected_probe_period, time_sync_tracker); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/connectivity_checker.h chromium-132.0.6834.159/chromecast/net/connectivity_checker.h --- chromium-132.0.6834.110/chromecast/net/connectivity_checker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/connectivity_checker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,121 +0,0 @@ -// 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. - -#ifndef CHROMECAST_NET_CONNECTIVITY_CHECKER_H_ -#define CHROMECAST_NET_CONNECTIVITY_CHECKER_H_ - -#include - -#include "base/memory/ref_counted_delete_on_sequence.h" -#include "base/observer_list_threadsafe.h" -#include "base/task/sequenced_task_runner_helpers.h" -#include "base/time/time.h" -#include "chromecast/net/time_sync_tracker.h" - -namespace base { -class SingleThreadTaskRunner; -} - -namespace network { -class PendingSharedURLLoaderFactory; -class NetworkConnectionTracker; -} // namespace network - -namespace chromecast { - -// Checks if internet connectivity is available. -class ConnectivityChecker - : public base::RefCountedDeleteOnSequence { - public: - class ConnectivityObserver { - public: - ConnectivityObserver(const ConnectivityObserver&) = delete; - ConnectivityObserver& operator=(const ConnectivityObserver&) = delete; - - // Will be called when internet connectivity changes. - virtual void OnConnectivityChanged(bool connected) = 0; - - protected: - ConnectivityObserver() {} - virtual ~ConnectivityObserver() {} - }; - - class ConnectivityCheckFailureObserver { - public: - ConnectivityCheckFailureObserver(const ConnectivityCheckFailureObserver&) = - delete; - ConnectivityCheckFailureObserver& operator=( - const ConnectivityCheckFailureObserver&) = delete; - - // will be called when connectivity check failed. - virtual void OnConnectivityCheckFailed() = 0; - - protected: - ConnectivityCheckFailureObserver() = default; - virtual ~ConnectivityCheckFailureObserver() = default; - }; - - static scoped_refptr Create( - const scoped_refptr& task_runner, - std::unique_ptr - pending_url_loader_factory, - network::NetworkConnectionTracker* network_connection_tracker, - TimeSyncTracker* time_sync_tracker = nullptr); - - // Static factory with additional parameters for connectivity check period - // - disconnected_probe_period: - // connectivity check period while disconnected. - // - connected_probe_period: - // connectivity check period while connected. - static scoped_refptr Create( - const scoped_refptr& task_runner, - std::unique_ptr - pending_url_loader_factory, - network::NetworkConnectionTracker* network_connection_tracker, - base::TimeDelta disconnected_probe_period, - base::TimeDelta connected_probe_period, - TimeSyncTracker* time_sync_tracker = nullptr); - - ConnectivityChecker(const ConnectivityChecker&) = delete; - ConnectivityChecker& operator=(const ConnectivityChecker&) = delete; - - void AddConnectivityObserver(ConnectivityObserver* observer); - void RemoveConnectivityObserver(ConnectivityObserver* observer); - - void AddConnectivityCheckFailureObserver( - ConnectivityCheckFailureObserver* observer); - void RemoveConnectivityCheckFailureObserver( - ConnectivityCheckFailureObserver* observer); - - // Returns if there is internet connectivity. - virtual bool Connected() const = 0; - - // Checks for connectivity. - virtual void Check() = 0; - - protected: - explicit ConnectivityChecker( - scoped_refptr task_runner); - virtual ~ConnectivityChecker(); - - // Notifies observes that connectivity has changed. - void Notify(bool connected); - - // Notifies observers that connectivity check failed. - void NotifyCheckFailure(); - - private: - friend class base::RefCountedDeleteOnSequence; - friend class base::DeleteHelper; - - const scoped_refptr> - connectivity_observer_list_; - const scoped_refptr< - base::ObserverListThreadSafe> - connectivity_check_failure_observer_list_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_CONNECTIVITY_CHECKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/connectivity_checker_impl.cc chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl.cc --- chromium-132.0.6834.110/chromecast/net/connectivity_checker_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,374 +0,0 @@ -// 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 "chromecast/net/connectivity_checker_impl.h" - -#include - -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/net/net_switches.h" -#include "chromecast/net/time_sync_tracker.h" -#include "net/base/request_priority.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_status_code.h" -#include "services/network/public/cpp/resource_request.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" -#include "services/network/public/cpp/simple_url_loader.h" -#include "services/network/public/mojom/url_response_head.mojom.h" - -namespace chromecast { - -namespace { - -// How often connectivity checks are performed while not connected. -constexpr base::TimeDelta kDisconnectedProbePeriod = base::Seconds(1); - -// How often connectivity checks are performed while connected. -constexpr base::TimeDelta kConnectedProbePeriod = base::Seconds(60); - -// Number of consecutive connectivity check errors before status is changed -// to offline. -const unsigned int kNumErrorsToNotifyOffline = 3; - -// Request timeout value. -constexpr base::TimeDelta kRequestTimeout = base::Seconds(3); - -const char kMetricNameNetworkConnectivityCheckingErrorType[] = - "Network.ConnectivityChecking.ErrorType"; - -} // namespace - -// static -scoped_refptr ConnectivityCheckerImpl::Create( - scoped_refptr task_runner, - std::unique_ptr - pending_url_loader_factory, - network::NetworkConnectionTracker* network_connection_tracker, - TimeSyncTracker* time_sync_tracker) { - DCHECK(task_runner); - - return Create(task_runner, std::move(pending_url_loader_factory), - network_connection_tracker, kDisconnectedProbePeriod, - kConnectedProbePeriod, time_sync_tracker); -} - -// static -scoped_refptr ConnectivityCheckerImpl::Create( - scoped_refptr task_runner, - std::unique_ptr - pending_url_loader_factory, - network::NetworkConnectionTracker* network_connection_tracker, - base::TimeDelta disconnected_probe_period, - base::TimeDelta connected_probe_period, - TimeSyncTracker* time_sync_tracker) { - DCHECK(task_runner); - - auto connectivity_checker = base::WrapRefCounted(new ConnectivityCheckerImpl( - task_runner, network_connection_tracker, disconnected_probe_period, - connected_probe_period, time_sync_tracker)); - task_runner->PostTask( - FROM_HERE, - base::BindOnce(&ConnectivityCheckerImpl::Initialize, connectivity_checker, - std::move(pending_url_loader_factory))); - return connectivity_checker; -} - -ConnectivityCheckerImpl::ConnectivityCheckerImpl( - scoped_refptr task_runner, - network::NetworkConnectionTracker* network_connection_tracker, - base::TimeDelta disconnected_probe_period, - base::TimeDelta connected_probe_period, - TimeSyncTracker* time_sync_tracker) - : ConnectivityChecker(task_runner), - task_runner_(std::move(task_runner)), - network_connection_tracker_(network_connection_tracker), - time_sync_tracker_(time_sync_tracker), - cast_metrics_helper_(metrics::CastMetricsHelper::GetInstance()), - connected_and_time_synced_(false), - network_connected_(false), - connection_type_(network::mojom::ConnectionType::CONNECTION_NONE), - check_errors_(0), - network_changed_pending_(false), - disconnected_probe_period_(disconnected_probe_period), - connected_probe_period_(connected_probe_period), - weak_factory_(this) { - DCHECK(task_runner_); - DCHECK(network_connection_tracker_); - DCHECK(cast_metrics_helper_); - DCHECK(!disconnected_probe_period_.is_zero()); - DCHECK(!connected_probe_period_.is_zero()); - weak_this_ = weak_factory_.GetWeakPtr(); - - if (time_sync_tracker_) { - time_sync_tracker_->AddObserver(this); - } -} - -void ConnectivityCheckerImpl::Initialize( - std::unique_ptr - pending_url_loader_factory) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(pending_url_loader_factory); - url_loader_factory_ = network::SharedURLLoaderFactory::Create( - std::move(pending_url_loader_factory)); - - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - base::CommandLine::StringType check_url_str = - command_line->GetSwitchValueNative(switches::kConnectivityCheckUrl); - connectivity_check_url_ = std::make_unique( - check_url_str.empty() ? kDefaultConnectivityCheckUrl : check_url_str); - - network_connection_tracker_->AddNetworkConnectionObserver(this); - - Check(); -} - -ConnectivityCheckerImpl::~ConnectivityCheckerImpl() { - DCHECK(task_runner_); - DCHECK(task_runner_->BelongsToCurrentThread()); - network_connection_tracker_->RemoveNetworkConnectionObserver(this); -} - -bool ConnectivityCheckerImpl::Connected() const { - base::AutoLock auto_lock(connected_lock_); - return connected_and_time_synced_; -} - -void ConnectivityCheckerImpl::SetConnected(bool connected) { - DCHECK(task_runner_->BelongsToCurrentThread()); - { - base::AutoLock auto_lock(connected_lock_); - network_connected_ = connected; - - // If a time_sync_tracker is not provided, is it assumed that network - // connectivity is equivalent to time being synced. - bool connected_and_time_synced = network_connected_; - if (time_sync_tracker_) { - connected_and_time_synced &= time_sync_tracker_->IsTimeSynced(); - } - - if (connected_and_time_synced_ == connected_and_time_synced) { - return; - } - - connected_and_time_synced_ = connected_and_time_synced; - } - - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - base::CommandLine::StringType check_url_str = - command_line->GetSwitchValueNative(switches::kConnectivityCheckUrl); - if (check_url_str.empty()) { - connectivity_check_url_ = std::make_unique( - connected_and_time_synced_ ? kHttpConnectivityCheckUrl - : kDefaultConnectivityCheckUrl); - LOG(INFO) << "Change check url=" << *connectivity_check_url_; - } - - Notify(connected_and_time_synced_); - LOG(INFO) << "Global connection is: " - << (connected_and_time_synced_ ? "Up" : "Down"); -} - -void ConnectivityCheckerImpl::Check() { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&ConnectivityCheckerImpl::CheckInternal, weak_this_)); -} - -void ConnectivityCheckerImpl::CheckInternal() { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(url_loader_factory_); - - auto connection_type = network::mojom::ConnectionType::CONNECTION_UNKNOWN; - bool is_sync = network_connection_tracker_->GetConnectionType( - &connection_type, - base::BindOnce(&ConnectivityCheckerImpl::OnConnectionChanged, - weak_this_)); - - // Don't check connectivity if network is offline. - // Also don't check connectivity if the connection_type cannot be - // synchronously retrieved, since OnConnectionChanged will be triggered later - // which will cause duplicate checks. - if (!is_sync || - connection_type == network::mojom::ConnectionType::CONNECTION_NONE) { - return; - } - - // If url_loader_ is non-null, there is already a check going on. Don't - // start another. - if (url_loader_) { - return; - } - - VLOG(1) << "Connectivity check: url=" << *connectivity_check_url_; - auto resource_request = std::make_unique(); - resource_request->url = GURL(*connectivity_check_url_); - resource_request->method = "HEAD"; - resource_request->priority = net::MAXIMUM_PRIORITY; - - url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), - MISSING_TRAFFIC_ANNOTATION); - - // To enable ssl_info in the response. - url_loader_->SetURLLoaderFactoryOptions( - network::mojom::kURLLoadOptionSendSSLInfoWithResponse | - network::mojom::kURLLoadOptionSendSSLInfoForCertificateError); - - // Configure the loader to treat HTTP error status codes as successful loads. - // This setting allows us to inspect the status code and log it as an error. - url_loader_->SetAllowHttpErrorResults(true); - - network::SimpleURLLoader::HeadersOnlyCallback callback = base::BindOnce( - &ConnectivityCheckerImpl::OnConnectivityCheckComplete, weak_this_); - url_loader_->DownloadHeadersOnly(url_loader_factory_.get(), - std::move(callback)); - // Exponential backoff for timeout in 3, 6 and 12 sec. - const base::TimeDelta timeout = - kRequestTimeout * - std::pow(2, std::min(check_errors_, static_cast(2))); - timeout_.Reset(base::BindOnce(&ConnectivityCheckerImpl::OnUrlRequestTimeout, - weak_this_, timeout)); - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, timeout_.callback(), timeout); -} - -void ConnectivityCheckerImpl::SetCastMetricsHelperForTesting( - metrics::CastMetricsHelper* cast_metrics_helper) { - DCHECK(cast_metrics_helper); - cast_metrics_helper_ = cast_metrics_helper; -} - -void ConnectivityCheckerImpl::OnConnectionChanged( - network::mojom::ConnectionType type) { - DVLOG(2) << "OnConnectionChanged " << type; - connection_type_ = type; - - if (network_changed_pending_) { - return; - } - if (std::exchange(first_connection_, false)) { - OnConnectionChangedInternal(); - return; - } - network_changed_pending_ = true; - base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&ConnectivityCheckerImpl::OnConnectionChangedInternal, - weak_this_), - kNetworkChangedDelay); -} - -void ConnectivityCheckerImpl::OnConnectionChangedInternal() { - network_changed_pending_ = false; - Cancel(); - - if (connection_type_ == network::mojom::ConnectionType::CONNECTION_NONE) { - SetConnected(false); - return; - } - - Check(); -} - -void ConnectivityCheckerImpl::OnTimeSynced() { - SetConnected(network_connected_); -} - -void ConnectivityCheckerImpl::OnConnectivityCheckComplete( - scoped_refptr headers) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(url_loader_); - - // Move url_loader_ onto the stack to ensure it gets deleted when this - // function completes. - std::unique_ptr url_loader = std::move(url_loader_); - - timeout_.Cancel(); - int error = url_loader->NetError(); - if (error == net::ERR_INSECURE_RESPONSE && url_loader->ResponseInfo() && - url_loader->ResponseInfo()->ssl_info) { - LOG(ERROR) << "OnSSLCertificateError: cert_status=" - << url_loader->ResponseInfo()->ssl_info->cert_status; - OnUrlRequestError(ErrorType::SSL_CERTIFICATE_ERROR); - return; - } - if (error != net::OK) { - // Captures non-HTTP errors here. All HTTP status codes (including error - // codes) are treated as network success and won't be logged here. HTTP - // errors are handled further below to provide more precise granularity. - LOG(ERROR) << "Connectivity check failed: net_error=" << error; - OnUrlRequestError(ErrorType::NET_ERROR); - return; - } - - // At this point, network connection is considered successful, but we still - // need to check HTTP response for errors. If headers are empty, use an - // implicit zero status code. - int http_response_code = headers ? headers->response_code() : 0; - - if (http_response_code != kConnectivitySuccessStatusCode) { - LOG(ERROR) << "Connectivity check failed: http_response_code=" - << http_response_code; - OnUrlRequestError(ErrorType::BAD_HTTP_STATUS); - return; - } - - DVLOG(1) << "Connectivity check succeeded"; - check_errors_ = 0; - SetConnected(true); - // Some products don't have an idle screen that makes periodic network - // requests. Schedule another check to ensure connectivity hasn't dropped. - delayed_check_.Reset( - base::BindOnce(&ConnectivityCheckerImpl::CheckInternal, weak_this_)); - task_runner_->PostDelayedTask(FROM_HERE, delayed_check_.callback(), - connected_probe_period_); -} - -void ConnectivityCheckerImpl::OnUrlRequestError(ErrorType type) { - DCHECK(task_runner_->BelongsToCurrentThread()); - ++check_errors_; - if (check_errors_ > kNumErrorsToNotifyOffline) { - LOG(INFO) << "Notify connectivity check failure."; - NotifyCheckFailure(); - - // Only record event on the connectivity transition. - if (connected_and_time_synced_) { - cast_metrics_helper_->RecordEventWithValue( - kMetricNameNetworkConnectivityCheckingErrorType, - static_cast(type)); - } - check_errors_ = kNumErrorsToNotifyOffline; - SetConnected(false); - } - // Check again. - delayed_check_.Reset( - base::BindOnce(&ConnectivityCheckerImpl::CheckInternal, weak_this_)); - task_runner_->PostDelayedTask(FROM_HERE, delayed_check_.callback(), - disconnected_probe_period_); -} - -void ConnectivityCheckerImpl::OnUrlRequestTimeout(base::TimeDelta timeout) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DCHECK(url_loader_); - url_loader_ = nullptr; - LOG(WARNING) << "timed out after " << timeout; - OnUrlRequestError(ErrorType::REQUEST_TIMEOUT); -} - -void ConnectivityCheckerImpl::Cancel() { - DCHECK(task_runner_->BelongsToCurrentThread()); - if (!url_loader_) { - return; - } - VLOG(2) << "Cancel connectivity check in progress"; - url_loader_ = nullptr; - timeout_.Cancel(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/connectivity_checker_impl.h chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl.h --- chromium-132.0.6834.110/chromecast/net/connectivity_checker_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,186 +0,0 @@ -// 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. - -#ifndef CHROMECAST_NET_CONNECTIVITY_CHECKER_IMPL_H_ -#define CHROMECAST_NET_CONNECTIVITY_CHECKER_IMPL_H_ - -#include - -#include "base/cancelable_callback.h" -#include "base/memory/raw_ptr.h" -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "chromecast/base/metrics/cast_metrics_helper.h" -#include "chromecast/net/connectivity_checker.h" -#include "chromecast/net/time_sync_tracker.h" -#include "net/http/http_status_code.h" -#include "services/network/public/cpp/network_connection_tracker.h" - -class GURL; - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace net { -class HttpResponseHeaders; -} // namespace net - -namespace network { -class SharedURLLoaderFactory; -class SimpleURLLoader; -} // namespace network - -namespace chromecast { - -// Default (HTTPS) url for connectivity checking. -constexpr char kDefaultConnectivityCheckUrl[] = - "https://connectivitycheck.gstatic.com/generate_204"; - -// HTTP url for connectivity checking. -constexpr char kHttpConnectivityCheckUrl[] = - "http://connectivitycheck.gstatic.com/generate_204"; - -// The default URLs above are expected to respond with HTTP 204 (no content). -constexpr net::HttpStatusCode kConnectivitySuccessStatusCode = - net::HTTP_NO_CONTENT; - -// Delay notification of network change events to smooth out rapid flipping. -constexpr base::TimeDelta kNetworkChangedDelay = base::Seconds(3); - -// Simple class to check network connectivity by sending a HEAD http request -// to given url. -class ConnectivityCheckerImpl - : public ConnectivityChecker, - public network::NetworkConnectionTracker::NetworkConnectionObserver, - public TimeSyncTracker::Observer { - public: - // Types of errors that can occur when making a network URL request. - enum class ErrorType { - BAD_HTTP_STATUS = 1, - SSL_CERTIFICATE_ERROR = 2, - REQUEST_TIMEOUT = 3, - - // A network error not captured by the ones above. See - // net/base/net_error_list.h for full set of errors that might fall under - // this category. - NET_ERROR = 4, - }; - - // Connectivity checking and initialization will run on task_runner. - static scoped_refptr Create( - scoped_refptr task_runner, - std::unique_ptr - pending_url_loader_factory, - network::NetworkConnectionTracker* network_connection_tracker, - TimeSyncTracker* time_sync_tracker); - - // Connectivity checking and initialization will run on task_runner. - static scoped_refptr Create( - scoped_refptr task_runner, - std::unique_ptr - pending_url_loader_factory, - network::NetworkConnectionTracker* network_connection_tracker, - base::TimeDelta disconnected_probe_period, - base::TimeDelta connected_probe_period, - TimeSyncTracker* time_sync_tracker); - - ConnectivityCheckerImpl(const ConnectivityCheckerImpl&) = delete; - ConnectivityCheckerImpl& operator=(const ConnectivityCheckerImpl&) = delete; - - // ConnectivityChecker implementation: - bool Connected() const override; - void Check() override; - - void SetCastMetricsHelperForTesting( - metrics::CastMetricsHelper* cast_metrics_helper); - - protected: - ConnectivityCheckerImpl( - scoped_refptr task_runner, - network::NetworkConnectionTracker* network_connection_tracker, - base::TimeDelta disconnected_probe_period, - base::TimeDelta connected_probe_period, - TimeSyncTracker* time_sync_tracker); - ~ConnectivityCheckerImpl() override; - - private: - // Initializes ConnectivityChecker - void Initialize(std::unique_ptr - pending_url_loader_factory); - - // network::NetworkConnectionTracker::NetworkConnectionObserver - // implementation: - void OnConnectionChanged(network::mojom::ConnectionType type) override; - - // TimeSyncTracker::Observer implementation: - void OnTimeSynced() override; - - void OnConnectionChangedInternal(); - - void OnConnectivityCheckComplete( - scoped_refptr headers); - - // Cancels current connectivity checking in progress. - void Cancel(); - - // Sets connectivity and alerts observers if it has changed - void SetConnected(bool connected); - - // Called when URL request failed. - void OnUrlRequestError(ErrorType type); - - // Called when URL request timed out. |Timeout| stores how long we waited - // for the URL request to finish before giving up. - void OnUrlRequestTimeout(base::TimeDelta timeout); - - void CheckInternal(); - - std::unique_ptr connectivity_check_url_; - scoped_refptr url_loader_factory_; - std::unique_ptr url_loader_; - const scoped_refptr task_runner_; - const raw_ptr network_connection_tracker_; - const raw_ptr time_sync_tracker_; - raw_ptr cast_metrics_helper_; - - // connected_lock_ protects access to connected_ which is shared across - // threads. - mutable base::Lock connected_lock_; - // Represents that the device has network connectivity and that time has - // synced. - bool connected_and_time_synced_; - - // If the device has network connectivity. - bool network_connected_; - - network::mojom::ConnectionType connection_type_; - // Number of connectivity check errors. - unsigned int check_errors_; - bool network_changed_pending_; - // Timeout handler for connectivity checks. - // Note: Cancelling this timeout can cause the destructor for this class to be - // called. - base::CancelableOnceCallback timeout_; - - // Cancelable check handler used to cancel duplicate connectivity check. - base::CancelableOnceCallback delayed_check_; - - // How often connectivity checks are performed while not connected. - const base::TimeDelta disconnected_probe_period_; - // How often connectivity checks are performed while connected. - const base::TimeDelta connected_probe_period_; - // Keeps track of whether this is the first time checking network - // connectivity due to a network change. To prevent unnecessary delays in Cast - // receiver initialization, kNetworkChangedDelay should only be applied on - // network changes after the first one. - bool first_connection_ = true; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_CONNECTIVITY_CHECKER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/connectivity_checker_impl_unittest.cc chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl_unittest.cc --- chromium-132.0.6834.110/chromecast/net/connectivity_checker_impl_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/connectivity_checker_impl_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,449 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/connectivity_checker_impl.h" - -#include - -#include "base/memory/scoped_refptr.h" -#include "base/run_loop.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "chromecast/base/metrics/mock_cast_metrics_helper.h" -#include "chromecast/net/fake_shared_url_loader_factory.h" -#include "net/http/http_status_code.h" -#include "services/network/public/cpp/network_connection_tracker.h" -#include "services/network/public/cpp/url_loader_completion_status.h" -#include "services/network/public/mojom/network_change_manager.mojom-shared.h" -#include "services/network/public/mojom/url_response_head.mojom-forward.h" -#include "services/network/test/test_network_connection_tracker.h" -#include "services/network/test/test_url_loader_factory.h" -#include "services/network/test/test_utils.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace chromecast { - -using ::testing::InvokeWithoutArgs; -using ::testing::NiceMock; - -constexpr const char* kDefaultConnectivityCheckUrls[] = { - kDefaultConnectivityCheckUrl, - kHttpConnectivityCheckUrl, -}; - -// Number of consecutive connectivity check errors before status is changed -// to offline. -const unsigned int kNumErrorsToNotifyOffline = 3; - -// Most tests use the TestNetworkConnectionChecker from -// services/network/test/test_network_connection_tracker.h, but some tests -// require testing how many times GetConnectionType() is called by -// ConnectivityCheckerImpl. For these tests, we use a fake that records the -// number of invocations and otherwise has the default behavior. -class FakeNetworkConnectionTracker : public network::NetworkConnectionTracker { - public: - // Spoof a valid connection type. - bool GetConnectionType(network::mojom::ConnectionType* type, - ConnectionTypeCallback callback) override { - check_counter_++; - *type = network::mojom::ConnectionType::CONNECTION_UNKNOWN; - return true; - } - - void NotifyNetworkTypeChanged(network::mojom::ConnectionType type) { - OnNetworkChanged(type); - } - - unsigned int check_counter() const { return check_counter_; } - - private: - // To memorize how many times GetConnectionType() called by checker - unsigned int check_counter_ = 0; -}; - -class ConnectivityCheckPeriods { - public: - ConnectivityCheckPeriods(base::TimeDelta disconnected_check_period, - base::TimeDelta connected_check_period) - : disconnected_check_period_(disconnected_check_period), - connected_check_period_(connected_check_period) {} - - static const ConnectivityCheckPeriods Empty() { return empty_; } - - bool IsEmpty() { - return disconnected_check_period_ == empty_.disconnected_check_period_ && - connected_check_period_ == empty_.connected_check_period_; - } - - const base::TimeDelta disconnected_check_period_; - const base::TimeDelta connected_check_period_; - - private: - // empty object: use minimum and negative TimeDeltas for empty object. - static const ConnectivityCheckPeriods empty_; -}; - -const ConnectivityCheckPeriods ConnectivityCheckPeriods::empty_ = - ConnectivityCheckPeriods(base::TimeDelta::Min(), base::TimeDelta::Min()); - -std::ostream& operator<<(std::ostream& out, const ConnectivityCheckPeriods& x) { - return out << "{disconnected_check_period: " << x.disconnected_check_period_ - << ", connected_check_period: " << x.connected_check_period_ - << "}"; -} - -template -class ConnectivityCheckerImplBaseTest : public ::testing::Test { - public: - explicit ConnectivityCheckerImplBaseTest( - std::unique_ptr tracker, - ConnectivityCheckPeriods check_periods = - ConnectivityCheckPeriods::Empty(), - std::unique_ptr pending_factory = - std::make_unique()) - : tracker_(std::move(tracker)), - fake_shared_url_loader_factory_( - pending_factory->fake_shared_url_loader_factory()), - checker_(check_periods.IsEmpty() - ? ConnectivityCheckerImpl::Create( - task_environment_.GetMainThreadTaskRunner(), - std::move(pending_factory), - tracker_.get(), - /* time_sync_tracker */ nullptr) - : ConnectivityCheckerImpl::Create( - task_environment_.GetMainThreadTaskRunner(), - std::move(pending_factory), - tracker_.get(), - check_periods.disconnected_check_period_, - check_periods.connected_check_period_, - /* time_sync_tracker */ nullptr)) { - checker_->SetCastMetricsHelperForTesting(&cast_metrics_helper_); - } - - void SetUp() final { - // Run pending initialization tasks. - base::RunLoop().RunUntilIdle(); - } - - void TearDown() final { test_url_loader_factory().ClearResponses(); } - - protected: - void SetResponsesWithStatusCode(net::HttpStatusCode status) { - for (const char* url : kDefaultConnectivityCheckUrls) { - test_url_loader_factory().AddResponse(url, /*content=*/"", status); - } - } - - void ConnectAndCheck() { - SetResponsesWithStatusCode(kConnectivitySuccessStatusCode); - checker_->Check(); - base::RunLoop().RunUntilIdle(); - test_url_loader_factory().ClearResponses(); - } - - void DisconnectAndCheck() { - SetResponsesWithStatusCode(net::HTTP_INTERNAL_SERVER_ERROR); - checker_->Check(); - base::RunLoop().RunUntilIdle(); - test_url_loader_factory().ClearResponses(); - } - - void CheckAndExpectRecordedError( - ConnectivityCheckerImpl::ErrorType error_type) { - base::RunLoop run_loop; - EXPECT_CALL(cast_metrics_helper_, - RecordEventWithValue("Network.ConnectivityChecking.ErrorType", - static_cast(error_type))) - .WillOnce( - InvokeWithoutArgs([quit = run_loop.QuitClosure()] { quit.Run(); })); - checker_->Check(); - run_loop.Run(); - } - - network::TestURLLoaderFactory& test_url_loader_factory() { - return fake_shared_url_loader_factory_->test_url_loader_factory(); - } - - base::test::SingleThreadTaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME, - }; - std::unique_ptr tracker_; - scoped_refptr fake_shared_url_loader_factory_; - NiceMock cast_metrics_helper_; - scoped_refptr checker_; -}; - -class ConnectivityCheckerImplTest : public ConnectivityCheckerImplBaseTest< - network::TestNetworkConnectionTracker> { - public: - ConnectivityCheckerImplTest() - : ConnectivityCheckerImplBaseTest( - network::TestNetworkConnectionTracker::CreateInstance()) {} -}; - -TEST_F(ConnectivityCheckerImplTest, StartsDisconnected) { - EXPECT_FALSE(checker_->Connected()); -} - -TEST_F(ConnectivityCheckerImplTest, DetectsConnected) { - tracker_->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - ConnectAndCheck(); - EXPECT_TRUE(checker_->Connected()); -} - -class ConnectivityCheckerImplTestParameterized - : public ConnectivityCheckerImplTest, - public ::testing::WithParamInterface {}; - -TEST_P(ConnectivityCheckerImplTestParameterized, - RecordsDisconnectDueToBadHttpStatus) { - tracker_->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - ConnectAndCheck(); - SetResponsesWithStatusCode(GetParam()); - CheckAndExpectRecordedError( - ConnectivityCheckerImpl::ErrorType::BAD_HTTP_STATUS); -} - -// Test 3xx, 4xx, 5xx responses. -INSTANTIATE_TEST_SUITE_P(ConnectivityCheckerImplTestBadHttpStatus, - ConnectivityCheckerImplTestParameterized, - ::testing::Values(net::HTTP_TEMPORARY_REDIRECT, - net::HTTP_BAD_REQUEST, - net::HTTP_INTERNAL_SERVER_ERROR)); - -class ConnectivityCheckerImplTestPeriodParameterized - : public ConnectivityCheckerImplBaseTest< - network::TestNetworkConnectionTracker>, - // disconnected probe period - public ::testing::WithParamInterface { - public: - ConnectivityCheckerImplTestPeriodParameterized() - : ConnectivityCheckerImplBaseTest( - network::TestNetworkConnectionTracker::CreateInstance(), - GetParam()) {} -}; - -TEST_P(ConnectivityCheckerImplTestPeriodParameterized, - CheckWithCustomizedPeriodsConnected) { - const ConnectivityCheckPeriods periods = GetParam(); - const base::TimeDelta margin = base::Milliseconds(100); - tracker_->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - - // Initial: disconnected. First Check. - // Next check is scheduled in disconnected_check_period_. - DisconnectAndCheck(); - // Connect. - SetResponsesWithStatusCode(kConnectivitySuccessStatusCode); - - // Jump to right before the next Check. Result is still not connected. - task_environment_.FastForwardBy(periods.disconnected_check_period_ - margin); - EXPECT_FALSE(checker_->Connected()); - // After the Check --> connected. - // Next check is scheduled in connected_check_period_. - task_environment_.FastForwardBy(margin * 2); - EXPECT_TRUE(checker_->Connected()); -} - -TEST_P(ConnectivityCheckerImplTestPeriodParameterized, - CheckWithCustomizedPeriodsDisconnected) { - const ConnectivityCheckPeriods periods = GetParam(); - const base::TimeDelta margin = base::Milliseconds(100); - tracker_->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - - // Initial: connected. First Check. - // Next check is scheduled in disconnected_check_period_. - ConnectAndCheck(); - // Disconnect. - SetResponsesWithStatusCode(net::HTTP_INTERNAL_SERVER_ERROR); - - // Jump to right before the next Check. Result is still connected. - task_environment_.FastForwardBy(periods.connected_check_period_ - margin); - EXPECT_TRUE(checker_->Connected()); - - // After the Check, still connected. - // It retries kNumErrorsToNotifyOffline times to switch to disconnected. - task_environment_.FastForwardBy(margin * 2); - // Fast forward by kNumErrorsToNotifyOffline * connected_check_period_. - for (unsigned int i = 0; i < kNumErrorsToNotifyOffline; i++) { - EXPECT_TRUE(checker_->Connected()); - // Check again. - task_environment_.FastForwardBy(periods.disconnected_check_period_); - } - // After retries, the result becomes disconnected. - EXPECT_FALSE(checker_->Connected()); -} - -// Test various connected/disconnected check periods -INSTANTIATE_TEST_SUITE_P( - ConnectivityCheckerImplTestCheckPeriods, - ConnectivityCheckerImplTestPeriodParameterized, - ::testing::Values( - ConnectivityCheckPeriods(base::Seconds(1), base::Seconds(1)), - ConnectivityCheckPeriods(base::Seconds(1), base::Seconds(60)), - ConnectivityCheckPeriods(base::Seconds(60), base::Seconds(1)), - ConnectivityCheckPeriods(base::Seconds(10), base::Seconds(120)), - ConnectivityCheckPeriods(base::Seconds(50), base::Seconds(200)))); - -TEST_F(ConnectivityCheckerImplTest, RecordsDisconnectDueToRequestTimeout) { - tracker_->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - ConnectAndCheck(); - - // Don't send a response for the request. - test_url_loader_factory().ClearResponses(); - CheckAndExpectRecordedError( - ConnectivityCheckerImpl::ErrorType::REQUEST_TIMEOUT); -} - -TEST_F(ConnectivityCheckerImplTest, RecordsDisconnectDueToNetError) { - tracker_->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - ConnectAndCheck(); - - // Set up a generic failure - network::URLLoaderCompletionStatus status; - status.error_code = net::ERR_FAILED; - - // Simulate network responses using the configured network error. - for (const char* url : kDefaultConnectivityCheckUrls) { - test_url_loader_factory().AddResponse( - GURL(url), - network::CreateURLResponseHead(kConnectivitySuccessStatusCode), - /*content=*/"", status, /*redirects=*/{}, - network::TestURLLoaderFactory::kSendHeadersOnNetworkError); - } - - CheckAndExpectRecordedError(ConnectivityCheckerImpl::ErrorType::NET_ERROR); -} - -TEST_F(ConnectivityCheckerImplTest, InitialCheckIsNotDelayed) { - // Do not set an initial connection type. This causes the first check to be - // delayed. - EXPECT_FALSE(checker_->Connected()); - // Notify that a network connection is established after the checker is - // constructed. A check should be automatically started when the connection - // is established. - SetResponsesWithStatusCode(kConnectivitySuccessStatusCode); - tracker_->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - // Poke the task runner, but don't fast forward the clock, to prove that the - // check is not a delayed task. We don't want the first check to be delayed - // after the network is initially connected because a lot of initialization of - // the Cast shell is bottlenecked on establishing network connectivity, and - // any delay of the initial check shows up as a user-visible delay in the - // Cast receiver becoming discoverable after boot. - task_environment_.FastForwardBy(base::TimeDelta()); - EXPECT_TRUE(checker_->Connected()); -} - -TEST_F(ConnectivityCheckerImplTest, InitialCheck_NoNetwork) { - // Do not set an initial connection type. This causes the first check to be - // delayed. - EXPECT_FALSE(checker_->Connected()); - // Initialize the network tracker to indicate that there is no connection at - // first. - SetResponsesWithStatusCode(kConnectivitySuccessStatusCode); - tracker_->SetConnectionType(network::mojom::ConnectionType::CONNECTION_NONE); - // Network connection still isn't established after flushing tasks. - task_environment_.FastForwardBy(base::TimeDelta()); - EXPECT_FALSE(checker_->Connected()); - // Establish a connection. - SetResponsesWithStatusCode(kConnectivitySuccessStatusCode); - tracker_->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - // Subsequent network checks are delayed due to rate limiting, so the - // connectivity status doesn't update until delay elapses. - task_environment_.FastForwardBy(base::TimeDelta()); - EXPECT_FALSE(checker_->Connected()); - task_environment_.FastForwardBy(kNetworkChangedDelay); - EXPECT_TRUE(checker_->Connected()); -} - -class ConnectivityCheckerImplTestPeriodicCheck - : public ConnectivityCheckerImplBaseTest, - public ::testing::WithParamInterface { - public: - ConnectivityCheckerImplTestPeriodicCheck() - : ConnectivityCheckerImplBaseTest( - std::make_unique(), - GetParam()) {} -}; - -TEST_P(ConnectivityCheckerImplTestPeriodicCheck, NoDuplicateConnectedCheck) { - const ConnectivityCheckPeriods periods = GetParam(); - constexpr base::TimeDelta kCheckRequestDelay = base::Milliseconds(100); - constexpr unsigned int kRounds = 10; - tracker_->NotifyNetworkTypeChanged( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - - // Initial: connected. First Check. - // A check is scheduled in connected_check_period_. - ConnectAndCheck(); - - // Add a delay to prevent the new check() from being ignored due to the - // duplicate url loader request - task_environment_.FastForwardBy(kCheckRequestDelay); - SetResponsesWithStatusCode(kConnectivitySuccessStatusCode); - tracker_->NotifyNetworkTypeChanged( - network::mojom::ConnectionType::CONNECTION_WIFI); - - // Wait for the internal network change delay. - // A check will be executed and the next check will be schedule in - // connected_check_period_. The old scheduled check should be removed. - task_environment_.FastForwardBy(kNetworkChangedDelay); - - // Fast forward and count the times of check() - unsigned int counter_start = tracker_->check_counter(); - task_environment_.FastForwardBy(periods.connected_check_period_ * kRounds); - - // The check_counter should increase by kRounds. - EXPECT_EQ(tracker_->check_counter() - counter_start, kRounds); -} - -TEST_P(ConnectivityCheckerImplTestPeriodicCheck, NoDuplicateDisconnectedCheck) { - const ConnectivityCheckPeriods periods = GetParam(); - constexpr base::TimeDelta kCheckRequestDelay = base::Milliseconds(100); - constexpr unsigned int kRounds = 10; - tracker_->NotifyNetworkTypeChanged( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - - // Initial: disconnected. First Check. - // A check is scheduled in disconnected_check_period_. - DisconnectAndCheck(); - - // Add a delay to prevent the new check() from being ignored due to the - // duplicate url loader request - task_environment_.FastForwardBy(kCheckRequestDelay); - SetResponsesWithStatusCode(net::HTTP_INTERNAL_SERVER_ERROR); - tracker_->NotifyNetworkTypeChanged( - network::mojom::ConnectionType::CONNECTION_WIFI); - - // Wait for the internal network change delay. - // A check will be executed and the next check will be schedule in - // disconnected_check_period_. The old scheduled check should be removed. - task_environment_.FastForwardBy(kNetworkChangedDelay); - - // Fast forward and count the times of check() - unsigned int counter_start = tracker_->check_counter(); - task_environment_.FastForwardBy(periods.disconnected_check_period_ * kRounds); - - // The check_counter should increase by kRounds. - EXPECT_EQ(tracker_->check_counter() - counter_start, kRounds); -} - -INSTANTIATE_TEST_SUITE_P( - ConnectivityCheckerImplTestCheckPeriodicCheck, - ConnectivityCheckerImplTestPeriodicCheck, - ::testing::Values( - ConnectivityCheckPeriods(base::Seconds(1), base::Seconds(1)), - ConnectivityCheckPeriods(base::Seconds(10), base::Seconds(10)), - ConnectivityCheckPeriods(base::Seconds(1), base::Seconds(60)))); - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/fake_connectivity_checker.cc chromium-132.0.6834.159/chromecast/net/fake_connectivity_checker.cc --- chromium-132.0.6834.110/chromecast/net/fake_connectivity_checker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/fake_connectivity_checker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// 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 "chromecast/net/fake_connectivity_checker.h" -#include "base/task/single_thread_task_runner.h" - -namespace chromecast { - -FakeConnectivityChecker::FakeConnectivityChecker() - : ConnectivityChecker(base::SingleThreadTaskRunner::GetCurrentDefault()), - connected_(true) {} - -FakeConnectivityChecker::~FakeConnectivityChecker() {} - -bool FakeConnectivityChecker::Connected() const { - return connected_; -} - -void FakeConnectivityChecker::Check() { -} - -void FakeConnectivityChecker::SetConnectedForTest(bool connected) { - if (connected_ == connected) - return; - - connected_ = connected; - Notify(connected); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/fake_connectivity_checker.h chromium-132.0.6834.159/chromecast/net/fake_connectivity_checker.h --- chromium-132.0.6834.110/chromecast/net/fake_connectivity_checker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/fake_connectivity_checker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// 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. - -#ifndef CHROMECAST_NET_FAKE_CONNECTIVITY_CHECKER_H_ -#define CHROMECAST_NET_FAKE_CONNECTIVITY_CHECKER_H_ - -#include "chromecast/net/connectivity_checker.h" - -namespace chromecast { - -// A simple fake connectivity checker for testing. Will appeared to be -// connected by default. -class FakeConnectivityChecker : public ConnectivityChecker { - public: - FakeConnectivityChecker(); - - FakeConnectivityChecker(const FakeConnectivityChecker&) = delete; - FakeConnectivityChecker& operator=(const FakeConnectivityChecker&) = delete; - - // ConnectivityChecker implementation: - bool Connected() const override; - void Check() override; - - // Sets connectivity and notifies observers if it has changed. - void SetConnectedForTest(bool connected); - - protected: - ~FakeConnectivityChecker() override; - - private: - friend class base::RefCountedThreadSafe; - bool connected_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_FAKE_CONNECTIVITY_CHECKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/fake_shared_url_loader_factory.cc chromium-132.0.6834.159/chromecast/net/fake_shared_url_loader_factory.cc --- chromium-132.0.6834.110/chromecast/net/fake_shared_url_loader_factory.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/fake_shared_url_loader_factory.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/fake_shared_url_loader_factory.h" - -#include "base/notreached.h" - -namespace chromecast { - -void FakeSharedURLLoaderFactory::Clone( - mojo::PendingReceiver receiver) { - test_url_loader_factory_.Clone(std::move(receiver)); -} - -void FakeSharedURLLoaderFactory::CreateLoaderAndStart( - mojo::PendingReceiver loader, - int32_t request_id, - uint32_t options, - const network::ResourceRequest& request, - mojo::PendingRemote client, - const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) { - test_url_loader_factory_.CreateLoaderAndStart( - std::move(loader), request_id, options, request, std::move(client), - traffic_annotation); -} - -std::unique_ptr -FakeSharedURLLoaderFactory::Clone() { - NOTREACHED(); -} - -FakePendingSharedURLLoaderFactory::FakePendingSharedURLLoaderFactory() - : fake_shared_url_loader_factory_( - base::MakeRefCounted()) {} - -FakePendingSharedURLLoaderFactory::~FakePendingSharedURLLoaderFactory() {} - -scoped_refptr -FakePendingSharedURLLoaderFactory::CreateFactory() { - return fake_shared_url_loader_factory_; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/fake_shared_url_loader_factory.h chromium-132.0.6834.159/chromecast/net/fake_shared_url_loader_factory.h --- chromium-132.0.6834.110/chromecast/net/fake_shared_url_loader_factory.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/fake_shared_url_loader_factory.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_NET_FAKE_SHARED_URL_LOADER_FACTORY_H_ -#define CHROMECAST_NET_FAKE_SHARED_URL_LOADER_FACTORY_H_ - -#include "base/memory/ref_counted.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" -#include "services/network/test/test_url_loader_factory.h" - -namespace chromecast { - -// A simple SharedURLLoaderFactory implementation for tests. -class FakeSharedURLLoaderFactory final - : public network::SharedURLLoaderFactory { - public: - FakeSharedURLLoaderFactory() = default; - - // network::mojom::URLLoaderFactory implementation: - void Clone(mojo::PendingReceiver receiver) - override; - void CreateLoaderAndStart( - mojo::PendingReceiver loader, - int32_t request_id, - uint32_t options, - const network::ResourceRequest& request, - mojo::PendingRemote client, - const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) - override; - - // network::SharedURLLoaderFactory implementation: - std::unique_ptr Clone() override; - - network::TestURLLoaderFactory& test_url_loader_factory() { - return test_url_loader_factory_; - } - - private: - friend class base::RefCounted; - - ~FakeSharedURLLoaderFactory() override = default; - - network::TestURLLoaderFactory test_url_loader_factory_; - - FakeSharedURLLoaderFactory(const FakeSharedURLLoaderFactory&) = delete; - FakeSharedURLLoaderFactory& operator=(const FakeSharedURLLoaderFactory&) = - delete; -}; - -// A simple PendingSharedURLLoaderFactory implementation for tests. -class FakePendingSharedURLLoaderFactory - : public network::PendingSharedURLLoaderFactory { - public: - FakePendingSharedURLLoaderFactory(); - ~FakePendingSharedURLLoaderFactory() override; - - scoped_refptr fake_shared_url_loader_factory() { - return fake_shared_url_loader_factory_; - } - - private: - friend class network::SharedURLLoaderFactory; - - // network::PendingSharedURLLoaderFactory implementation: - scoped_refptr CreateFactory() override; - - scoped_refptr fake_shared_url_loader_factory_; - - FakePendingSharedURLLoaderFactory(const FakePendingSharedURLLoaderFactory&) = - delete; - FakePendingSharedURLLoaderFactory& operator=( - const FakePendingSharedURLLoaderFactory&) = delete; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_FAKE_SHARED_URL_LOADER_FACTORY_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/fake_stream_socket.cc chromium-132.0.6834.159/chromecast/net/fake_stream_socket.cc --- chromium-132.0.6834.110/chromecast/net/fake_stream_socket.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/fake_stream_socket.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,219 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/fake_stream_socket.h" - -#include -#include -#include - -#include "base/check_op.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/memory/raw_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "net/base/io_buffer.h" -#include "net/base/net_errors.h" -#include "net/socket/next_proto.h" -#include "net/traffic_annotation/network_traffic_annotation.h" - -namespace chromecast { - -// Buffer used for communication between two FakeStreamSockets. -class SocketBuffer { - public: - SocketBuffer() : pending_read_data_(nullptr), pending_read_len_(0) {} - - SocketBuffer(const SocketBuffer&) = delete; - SocketBuffer& operator=(const SocketBuffer&) = delete; - - ~SocketBuffer() {} - - // Reads |len| bytes from the buffer and writes it to |data|. Returns the - // number of bytes written to |data| if the read is synchronous, or - // ERR_IO_PENDING if the read is asynchronous. If the read is asynchronous, - // |callback| is called with the number of bytes written to |data| once the - // data has been written. - int Read(char* data, size_t len, net::CompletionOnceCallback callback) { - DCHECK(data); - DCHECK_GT(len, 0u); - DCHECK(callback); - if (data_.empty()) { - if (eos_) { - return 0; - } - pending_read_data_ = data; - pending_read_len_ = len; - pending_read_callback_ = std::move(callback); - return net::ERR_IO_PENDING; - } - return ReadInternal(data, len); - } - - // Writes |len| bytes from |data| to the buffer. The write is always completed - // synchronously and all bytes are guaranteed to be written. - void Write(const char* data, size_t len) { - DCHECK(data); - DCHECK_GT(len, 0u); - data_.insert(data_.end(), data, data + len); - if (!pending_read_callback_.is_null()) { - int result = ReadInternal(pending_read_data_, pending_read_len_); - pending_read_data_ = nullptr; - pending_read_len_ = 0; - PostReadCallback(std::move(pending_read_callback_), result); - } - } - - // Called when the remote end of the fake connection disconnects. - void ReceiveEOS() { - eos_ = true; - if (pending_read_callback_ && data_.empty()) { - PostReadCallback(std::move(pending_read_callback_), 0); - } - } - - private: - int ReadInternal(char* data, size_t len) { - DCHECK(data); - DCHECK_GT(len, 0u); - len = std::min(len, data_.size()); - std::memcpy(data, data_.data(), len); - data_.erase(data_.begin(), data_.begin() + len); - return len; - } - - void PostReadCallback(net::CompletionOnceCallback callback, int result) { - base::SequencedTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&SocketBuffer::CallReadCallback, - weak_factory_.GetWeakPtr(), - std::move(callback), result)); - } - - // Need a member function to asynchronously call the read callback, so we - // can use weak ptr. - void CallReadCallback(net::CompletionOnceCallback callback, int result) { - std::move(callback).Run(result); - } - - std::vector data_; - raw_ptr pending_read_data_; - size_t pending_read_len_; - net::CompletionOnceCallback pending_read_callback_; - bool eos_ = false; - base::WeakPtrFactory weak_factory_{this}; -}; - -FakeStreamSocket::FakeStreamSocket() : FakeStreamSocket(net::IPEndPoint()) {} - -FakeStreamSocket::FakeStreamSocket(const net::IPEndPoint& local_address) - : local_address_(local_address), - buffer_(std::make_unique()), - peer_(nullptr) {} - -FakeStreamSocket::~FakeStreamSocket() { - if (peer_) { - peer_->RemoteDisconnected(); - } -} - -void FakeStreamSocket::SetPeer(FakeStreamSocket* peer) { - DCHECK(peer); - peer_ = peer; -} - -void FakeStreamSocket::RemoteDisconnected() { - peer_ = nullptr; - buffer_->ReceiveEOS(); -} - -void FakeStreamSocket::SetBadSenderMode(bool bad_sender) { - bad_sender_mode_ = bad_sender; -} - -int FakeStreamSocket::Read(net::IOBuffer* buf, - int buf_len, - net::CompletionOnceCallback callback) { - DCHECK(buf); - return buffer_->Read(buf->data(), buf_len, std::move(callback)); -} - -int FakeStreamSocket::Write( - net::IOBuffer* buf, - int buf_len, - net::CompletionOnceCallback /* callback */, - const net::NetworkTrafficAnnotationTag& /*traffic_annotation*/) { - DCHECK(buf); - if (!peer_) { - return net::ERR_SOCKET_NOT_CONNECTED; - } - int amount_to_send = buf_len; - if (bad_sender_mode_) { - amount_to_send = std::min(buf_len, buf_len / 2 + 1); - } - peer_->buffer_->Write(buf->data(), amount_to_send); - return amount_to_send; -} - -int FakeStreamSocket::SetReceiveBufferSize(int32_t /* size */) { - return net::OK; -} - -int FakeStreamSocket::SetSendBufferSize(int32_t /* size */) { - return net::OK; -} - -int FakeStreamSocket::Connect(net::CompletionOnceCallback /* callback */) { - return net::OK; -} - -void FakeStreamSocket::Disconnect() {} - -bool FakeStreamSocket::IsConnected() const { - return true; -} - -bool FakeStreamSocket::IsConnectedAndIdle() const { - return false; -} - -int FakeStreamSocket::GetPeerAddress(net::IPEndPoint* address) const { - DCHECK(address); - if (!peer_) { - return net::ERR_SOCKET_NOT_CONNECTED; - } - *address = peer_->local_address_; - return net::OK; -} - -int FakeStreamSocket::GetLocalAddress(net::IPEndPoint* address) const { - DCHECK(address); - *address = local_address_; - return net::OK; -} - -const net::NetLogWithSource& FakeStreamSocket::NetLog() const { - return net_log_; -} - -bool FakeStreamSocket::WasEverUsed() const { - return false; -} - -net::NextProto FakeStreamSocket::GetNegotiatedProtocol() const { - return net::kProtoUnknown; -} - -bool FakeStreamSocket::GetSSLInfo(net::SSLInfo* /* ssl_info */) { - return false; -} - -int64_t FakeStreamSocket::GetTotalReceivedBytes() const { - return 0; -} - -void FakeStreamSocket::ApplySocketTag(const net::SocketTag& tag) {} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/fake_stream_socket.h chromium-132.0.6834.159/chromecast/net/fake_stream_socket.h --- chromium-132.0.6834.110/chromecast/net/fake_stream_socket.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/fake_stream_socket.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_NET_FAKE_STREAM_SOCKET_H_ -#define CHROMECAST_NET_FAKE_STREAM_SOCKET_H_ - -#include - -#include - -#include "base/memory/raw_ptr.h" -#include "net/base/ip_endpoint.h" -#include "net/log/net_log_with_source.h" -#include "net/socket/stream_socket.h" -#include "net/traffic_annotation/network_traffic_annotation.h" - -namespace chromecast { -class SocketBuffer; - -// Fake StreamSocket that communicates with another instance in memory. -class FakeStreamSocket : public net::StreamSocket { - public: - FakeStreamSocket(); - explicit FakeStreamSocket(const net::IPEndPoint& local_address); - - FakeStreamSocket(const FakeStreamSocket&) = delete; - FakeStreamSocket& operator=(const FakeStreamSocket&) = delete; - - ~FakeStreamSocket() override; - - // Sets the peer for this socket. - void SetPeer(FakeStreamSocket* peer); - - // Enables/disables "bad sender mode", where Write() will always try to send - // less than the full buffer. Disabled by default. - void SetBadSenderMode(bool bad_sender); - - // net::StreamSocket implementation: - int Read(net::IOBuffer* buf, - int buf_len, - net::CompletionOnceCallback callback) override; - int Write( - net::IOBuffer* buf, - int buf_len, - net::CompletionOnceCallback callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) override; - int SetReceiveBufferSize(int32_t size) override; - int SetSendBufferSize(int32_t size) override; - int Connect(net::CompletionOnceCallback callback) override; - void Disconnect() override; - bool IsConnected() const override; - bool IsConnectedAndIdle() const override; - int GetPeerAddress(net::IPEndPoint* address) const override; - int GetLocalAddress(net::IPEndPoint* address) const override; - const net::NetLogWithSource& NetLog() const override; - bool WasEverUsed() const override; - net::NextProto GetNegotiatedProtocol() const override; - bool GetSSLInfo(net::SSLInfo* ssl_info) override; - int64_t GetTotalReceivedBytes() const override; - void ApplySocketTag(const net::SocketTag& tag) override; - - private: - void RemoteDisconnected(); - - const net::IPEndPoint local_address_; - const std::unique_ptr buffer_; - raw_ptr peer_; - net::NetLogWithSource net_log_; - bool bad_sender_mode_ = false; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_FAKE_STREAM_SOCKET_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/fake_stream_socket_unittest.cc chromium-132.0.6834.159/chromecast/net/fake_stream_socket_unittest.cc --- chromium-132.0.6834.110/chromecast/net/fake_stream_socket_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/fake_stream_socket_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,139 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/memory/ref_counted.h" -#include "base/test/task_environment.h" -#include "chromecast/net/fake_stream_socket.h" -#include "net/base/io_buffer.h" -#include "net/base/ip_endpoint.h" -#include "net/base/net_errors.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -namespace { - -const char kIpAddress1[] = "192.168.0.1"; -const uint16_t kPort1 = 10001; -const char kIpAddress2[] = "192.168.0.2"; -const uint16_t kPort2 = 10002; - -net::IPAddress IpLiteralToIpAddress(const std::string& ip_literal) { - net::IPAddress ip_address; - CHECK(ip_address.AssignFromIPLiteral(ip_literal)); - return ip_address; -} - -void Callback(int error_code) {} - -} // namespace - -class FakeStreamSocketTest : public ::testing::Test { - public: - FakeStreamSocketTest() - : endpoint_1_(IpLiteralToIpAddress(kIpAddress1), kPort1), - socket_1_(endpoint_1_), - endpoint_2_(IpLiteralToIpAddress(kIpAddress2), kPort2), - socket_2_(endpoint_2_) {} - ~FakeStreamSocketTest() override {} - - base::test::TaskEnvironment task_environment_; - net::IPEndPoint endpoint_1_; - FakeStreamSocket socket_1_; - net::IPEndPoint endpoint_2_; - FakeStreamSocket socket_2_; -}; - -TEST_F(FakeStreamSocketTest, GetLocalAddress) { - net::IPEndPoint local_address; - ASSERT_EQ(net::OK, socket_1_.GetLocalAddress(&local_address)); - EXPECT_EQ(endpoint_1_, local_address); -} - -TEST_F(FakeStreamSocketTest, GetPeerAddressWithoutPeer) { - net::IPEndPoint peer_address; - EXPECT_EQ(net::ERR_SOCKET_NOT_CONNECTED, - socket_1_.GetPeerAddress(&peer_address)); -} - -TEST_F(FakeStreamSocketTest, GetPeerAddressWithPeer) { - socket_1_.SetPeer(&socket_2_); - socket_2_.SetPeer(&socket_1_); - net::IPEndPoint peer_address; - ASSERT_EQ(net::OK, socket_1_.GetPeerAddress(&peer_address)); - EXPECT_EQ(endpoint_2_, peer_address); -} - -TEST_F(FakeStreamSocketTest, ReadAndWriteWithoutPeer) { - auto io_buffer = base::MakeRefCounted(1); - EXPECT_EQ(net::ERR_IO_PENDING, - socket_1_.Read(io_buffer.get(), 1, base::BindOnce(&Callback))); - EXPECT_EQ(net::ERR_SOCKET_NOT_CONNECTED, - socket_1_.Write(io_buffer.get(), 1, base::BindOnce(&Callback), - TRAFFIC_ANNOTATION_FOR_TESTS)); -} - -TEST_F(FakeStreamSocketTest, ReadAndWriteWithPeer) { - socket_1_.SetPeer(&socket_2_); - socket_2_.SetPeer(&socket_1_); - const std::string kData("DATA"); - auto send_buffer = base::MakeRefCounted(kData); - ASSERT_EQ( - static_cast(kData.size()), - socket_1_.Write(send_buffer.get(), kData.size(), - base::BindOnce(&Callback), TRAFFIC_ANNOTATION_FOR_TESTS)); - auto receive_buffer = - base::MakeRefCounted(kData.size()); - ASSERT_EQ(static_cast(kData.size()), - socket_2_.Read(receive_buffer.get(), kData.size(), - base::BindOnce(&Callback))); - EXPECT_EQ(0, std::memcmp(kData.data(), receive_buffer->data(), kData.size())); -} - -TEST_F(FakeStreamSocketTest, ReadAndWritePending) { - socket_1_.SetPeer(&socket_2_); - socket_2_.SetPeer(&socket_1_); - const std::string kData("DATA"); - auto receive_buffer = - base::MakeRefCounted(kData.size()); - ASSERT_EQ(net::ERR_IO_PENDING, - socket_2_.Read(receive_buffer.get(), kData.size(), - base::BindOnce(&Callback))); - auto send_buffer = base::MakeRefCounted(kData); - ASSERT_EQ( - static_cast(kData.size()), - socket_1_.Write(send_buffer.get(), kData.size(), - base::BindOnce(&Callback), TRAFFIC_ANNOTATION_FOR_TESTS)); - EXPECT_EQ(0, std::memcmp(kData.data(), receive_buffer->data(), kData.size())); -} - -TEST_F(FakeStreamSocketTest, ReadAndWriteLargeData) { - socket_1_.SetPeer(&socket_2_); - socket_2_.SetPeer(&socket_1_); - // Send 1 MB of data between sockets. - const std::string kData("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"); - auto send_buffer = base::MakeRefCounted(kData); - const int kWriteCount = 1024 * 1024 / kData.size(); - for (int i = 0; i < kWriteCount; i++) { - ASSERT_EQ(static_cast(kData.size()), - socket_1_.Write(send_buffer.get(), kData.size(), - base::BindOnce(&Callback), - TRAFFIC_ANNOTATION_FOR_TESTS)); - } - auto receive_buffer = base::MakeRefCounted(1024); - for (int i = 0; i < 1024; i++) { - ASSERT_EQ(1024, socket_2_.Read(receive_buffer.get(), 1024, - base::BindOnce(&Callback))); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/io_buffer_pool.cc chromium-132.0.6834.159/chromecast/net/io_buffer_pool.cc --- chromium-132.0.6834.110/chromecast/net/io_buffer_pool.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/io_buffer_pool.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,285 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/io_buffer_pool.h" - -#include - -#include "base/bits.h" -#include "base/memory/aligned_memory.h" -#include "base/memory/raw_ptr.h" -#include "base/synchronization/lock.h" - -namespace chromecast { - -// The IOBufferPool allocates IOBuffers and the associated data as a single -// contiguous buffer. The buffer is laid out like this: -// |------------Wrapper----------|---data area---| -// |--IOBuffer--|--Internal ptr--|---data area---| -// -// The contiguous buffer is allocated as a character array, and then a Wrapper -// instance is placement-newed into it. We return a pointer to the IOBuffer -// within the Wrapper. -// -// When the IOBuffer is deleted (in operator delete), we get a pointer to the -// beginning of storage for the IOBuffer, which is the same memory location -// as the Wrapper instance (since the Wrapper has no vtable or base class, this -// should be true for any compiler). We can therefore cast the "deleted" -// pointer to a Wrapper* and then reclaim the buffer. -// -// All the actual data and logic for the buffer pool is held in the Internal -// class, which is refcounted with 1 ref for the IOBufferPool owner, and 1 ref -// for each buffer currently in use (ie, not in the free list). The Internal -// instance is only deleted when its internal refcount drops to 0; this allows -// buffers allocated from the pool to be safely used and deleted even after the -// pool has been destroyed. -// -// Note that locking in the Internal methods is optional since it is only needed -// when threadsafe operation is requested. - -class IOBufferPool::Internal { - public: - Internal(size_t data_area_size, size_t max_buffers, bool threadsafe); - - Internal(const Internal&) = delete; - Internal& operator=(const Internal&) = delete; - - size_t num_allocated() const { - base::AutoLockMaybe lock(lock_ptr_.get()); - return num_allocated_; - } - - size_t num_free() const { - base::AutoLockMaybe lock(lock_ptr_.get()); - return num_free_; - } - - void Preallocate(size_t num_buffers); - - void OwnerDestroyed(); - - scoped_refptr GetBuffer(); - - private: - class Buffer; - class Wrapper; - union Storage; - - static constexpr size_t kAlignment = 16; - - static Storage* AllocateStorageUnionAndDataArea(size_t data_area_size); - static char* DataAreaFromStorageUnion(Storage* ptr); - - ~Internal(); - - void Reclaim(Wrapper* wrapper); - - const size_t data_area_size_; - const size_t max_buffers_; - - mutable base::Lock lock_; - const raw_ptr lock_ptr_; - - raw_ptr free_buffers_; - size_t num_allocated_; - size_t num_free_; - - int refs_; -}; - -class IOBufferPool::Internal::Buffer : public net::IOBuffer { - public: - Buffer(char* data, size_t size) - : net::IOBuffer(base::make_span(data, size)) {} - - Buffer(const Buffer&) = delete; - Buffer& operator=(const Buffer&) = delete; - - private: - friend class Wrapper; - - ~Buffer() override = default; - static void operator delete(void* ptr); -}; - -class IOBufferPool::Internal::Wrapper { - public: - Wrapper(char* data, size_t size, IOBufferPool::Internal* pool) - : buffer_(data, size), pool_(pool) {} - - Wrapper(const Wrapper&) = delete; - Wrapper& operator=(const Wrapper&) = delete; - - ~Wrapper() = delete; - static void operator delete(void*) = delete; - - Buffer* buffer() { return &buffer_; } - - void Reclaim() { pool_->Reclaim(this); } - - private: - Buffer buffer_; - IOBufferPool::Internal* const pool_; -}; - -union IOBufferPool::Internal::Storage { - Storage* next; // Pointer to next free buffer. - Wrapper wrapper; -}; - -void IOBufferPool::Internal::Buffer::operator delete(void* ptr) { - Wrapper* wrapper = reinterpret_cast(ptr); - wrapper->Reclaim(); -} - -IOBufferPool::Internal::Internal(size_t data_area_size, - size_t max_buffers, - bool threadsafe) - : data_area_size_(data_area_size), - max_buffers_(max_buffers), - lock_ptr_(threadsafe ? &lock_ : nullptr), - free_buffers_(nullptr), - num_allocated_(0), - num_free_(0), - refs_(1) { // 1 ref for the owner. -} - -IOBufferPool::Internal::~Internal() { - while (free_buffers_) { - char* data = reinterpret_cast(free_buffers_.get()); - free_buffers_ = free_buffers_->next; - base::AlignedFree(data); - } -} - -// Allocates aligned space for a `union Storage` plus an additional data -// area of `data_area_size` bytes with the same alignment. -// static -IOBufferPool::Internal::Storage* -IOBufferPool::Internal::AllocateStorageUnionAndDataArea(size_t data_area_size) { - size_t kAlignedStorageSize = base::bits::AlignUp(sizeof(Storage), kAlignment); - return reinterpret_cast( - base::AlignedAlloc(kAlignedStorageSize + data_area_size, kAlignment)); -} - -// Returns a pointer to the data area that follows a `union Storage`. -// static -char* IOBufferPool::Internal::DataAreaFromStorageUnion( - IOBufferPool::Internal::Storage* ptr) { - size_t kAlignedStorageSize = base::bits::AlignUp(sizeof(Storage), kAlignment); - return reinterpret_cast(ptr) + kAlignedStorageSize; -} - -void IOBufferPool::Internal::Preallocate(size_t num_buffers) { - // We assume that this is uncontended in normal usage, so just lock for the - // entire method. - base::AutoLockMaybe lock(lock_ptr_.get()); - if (num_buffers > max_buffers_) { - num_buffers = max_buffers_; - } - if (num_allocated_ >= num_buffers) { - return; - } - size_t num_extra_buffers = num_buffers - num_allocated_; - num_free_ += num_extra_buffers; - num_allocated_ += num_extra_buffers; - while (num_extra_buffers > 0) { - Storage* storage = AllocateStorageUnionAndDataArea(data_area_size_); - storage->next = free_buffers_; - free_buffers_ = storage; - - --num_extra_buffers; - } - // No need to add refs here, since the newly allocated buffers are not in use. -} - -void IOBufferPool::Internal::OwnerDestroyed() { - bool deletable; - { - base::AutoLockMaybe lock(lock_ptr_.get()); - --refs_; // Remove the owner's ref. - deletable = (refs_ == 0); - } - - if (deletable) { - delete this; - } -} - -scoped_refptr IOBufferPool::Internal::GetBuffer() { - Storage* ptr = nullptr; - - { - base::AutoLockMaybe lock(lock_ptr_.get()); - if (free_buffers_) { - ptr = free_buffers_; - free_buffers_ = free_buffers_->next; - --num_free_; - } else { - if (num_allocated_ == max_buffers_) - return nullptr; - ++num_allocated_; - } - ++refs_; // Add a ref for the now in-use buffer. - } - - if (!ptr) { - ptr = AllocateStorageUnionAndDataArea(data_area_size_); - } - - char* data_area = DataAreaFromStorageUnion(ptr); - Wrapper* wrapper = - new (static_cast(ptr)) Wrapper(data_area, data_area_size_, this); - return scoped_refptr(wrapper->buffer()); -} - -void IOBufferPool::Internal::Reclaim(Wrapper* wrapper) { - Storage* storage = reinterpret_cast(wrapper); - bool deletable; - { - base::AutoLockMaybe lock(lock_ptr_.get()); - storage->next = free_buffers_; - free_buffers_ = storage; - ++num_free_; - --refs_; // Remove a ref since this buffer is no longer in use. - deletable = (refs_ == 0); - } - - if (deletable) { - delete this; - } -} - -IOBufferPool::IOBufferPool(size_t buffer_size, - size_t max_buffers, - bool threadsafe) - : buffer_size_(buffer_size), - max_buffers_(max_buffers), - threadsafe_(threadsafe), - internal_(new Internal(buffer_size_, max_buffers_, threadsafe_)) {} - -IOBufferPool::IOBufferPool(size_t buffer_size) - : IOBufferPool(buffer_size, static_cast(-1)) {} - -IOBufferPool::~IOBufferPool() { - internal_->OwnerDestroyed(); -} - -size_t IOBufferPool::NumAllocatedForTesting() const { - return internal_->num_allocated(); -} - -size_t IOBufferPool::NumFreeForTesting() const { - return internal_->num_free(); -} - -void IOBufferPool::Preallocate(size_t num_buffers) { - internal_->Preallocate(num_buffers); -} - -scoped_refptr IOBufferPool::GetBuffer() { - return internal_->GetBuffer(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/io_buffer_pool.h chromium-132.0.6834.159/chromecast/net/io_buffer_pool.h --- chromium-132.0.6834.110/chromecast/net/io_buffer_pool.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/io_buffer_pool.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_NET_IO_BUFFER_POOL_H_ -#define CHROMECAST_NET_IO_BUFFER_POOL_H_ - -#include - -#include "base/memory/raw_ptr.h" -#include "base/memory/ref_counted.h" -#include "net/base/io_buffer.h" - -namespace chromecast { - -// Buffer pool to allocate ::net::IOBuffers of a constant size. When a buffer -// from this pool is destroyed, it is returned to the pool to be reused (rather -// than constantly reallocating memory). If the buffer is destroyed after the -// pool has been destroyed, the buffer's memory will be freed correctly. -class IOBufferPool : public base::RefCountedThreadSafe { - public: - // |buffer_size| is the usable size of each buffer that will be returned - // by GetBuffer(). |max_buffers| is the maximum number of buffers that this - // pool will allocate. If |threadsafe| is true then the pool and any buffers - // allocated from it may be used safely on any thread; otherwise all access - // to pool and buffers must be made on the creating sequence. - IOBufferPool(size_t buffer_size, size_t max_buffers, bool threadsafe = false); - // If |max_buffers| is not specified, the maximum value of size_t is used. - explicit IOBufferPool(size_t buffer_size); - - IOBufferPool(const IOBufferPool&) = delete; - IOBufferPool& operator=(const IOBufferPool&) = delete; - - size_t buffer_size() const { return buffer_size_; } - size_t max_buffers() const { return max_buffers_; } - bool threadsafe() const { return threadsafe_; } - - // Ensures that at least |num_buffers| are allocated. If |num_buffers| is - // greater than |max_buffers|, makes sure that |max_buffers| buffers have been - // allocated. - void Preallocate(size_t num_buffers); - - // Returns an IOBuffer from the pool, or |nullptr| if there are no buffers in - // the pool and |max buffers| has been reached. The pool does not keep any - // references to the buffer. It is safe to use the returned buffer after the - // pool has been destroyed; if the buffer is destroyed after the pool is - // destroyed, the buffer's memory will be freed correctly. - scoped_refptr GetBuffer(); - - // Returns the number of buffers that have ever been allocated by the pool. - size_t NumAllocatedForTesting() const; - // Returns the number of buffers that are currently free in the pool. - size_t NumFreeForTesting() const; - - private: - class Internal; - - friend class base::RefCountedThreadSafe; - ~IOBufferPool(); - - const size_t buffer_size_; - const size_t max_buffers_; - const bool threadsafe_; - raw_ptr internal_; // Manages its own lifetime. -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_IO_BUFFER_POOL_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/io_buffer_pool_unittest.cc chromium-132.0.6834.159/chromecast/net/io_buffer_pool_unittest.cc --- chromium-132.0.6834.110/chromecast/net/io_buffer_pool_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/io_buffer_pool_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,113 +0,0 @@ -// 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 "chromecast/net/io_buffer_pool.h" - -#include "base/memory/ref_counted.h" -#include "net/base/io_buffer.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -namespace { -const size_t kDefaultBufferSize = 256; -} // namespace - -TEST(IOBufferPoolTest, ZeroMaxBuffers) { - auto pool = base::MakeRefCounted(kDefaultBufferSize, 0); - EXPECT_EQ(nullptr, pool->GetBuffer()); - EXPECT_EQ(kDefaultBufferSize, pool->buffer_size()); - EXPECT_EQ(0u, pool->max_buffers()); - EXPECT_EQ(0u, pool->NumAllocatedForTesting()); - EXPECT_EQ(0u, pool->NumFreeForTesting()); -} - -TEST(IOBufferPoolTest, OneMaxBuffer) { - auto pool = base::MakeRefCounted(kDefaultBufferSize, 1); - scoped_refptr buffer = pool->GetBuffer(); - EXPECT_NE(nullptr, buffer.get()); - EXPECT_EQ(nullptr, pool->GetBuffer()); - EXPECT_EQ(1u, pool->max_buffers()); - EXPECT_EQ(1u, pool->NumAllocatedForTesting()); - EXPECT_EQ(0u, pool->NumFreeForTesting()); -} - -TEST(IOBufferPoolTest, SeveralMaxBuffers) { - auto pool = base::MakeRefCounted(kDefaultBufferSize, 4); - scoped_refptr buffer1 = pool->GetBuffer(); - scoped_refptr buffer2 = pool->GetBuffer(); - scoped_refptr buffer3 = pool->GetBuffer(); - scoped_refptr buffer4 = pool->GetBuffer(); - EXPECT_NE(nullptr, buffer1.get()); - EXPECT_NE(nullptr, buffer2.get()); - EXPECT_NE(nullptr, buffer3.get()); - EXPECT_NE(nullptr, buffer4.get()); - EXPECT_EQ(nullptr, pool->GetBuffer()); - EXPECT_EQ(4u, pool->max_buffers()); - EXPECT_EQ(4u, pool->NumAllocatedForTesting()); - EXPECT_EQ(0u, pool->NumFreeForTesting()); -} - -TEST(IOBufferPoolTest, Reclaim) { - auto pool = base::MakeRefCounted(kDefaultBufferSize, 3); - scoped_refptr buffer1 = pool->GetBuffer(); - scoped_refptr buffer2 = pool->GetBuffer(); - scoped_refptr buffer3 = pool->GetBuffer(); - EXPECT_NE(nullptr, buffer1.get()); - EXPECT_NE(nullptr, buffer2.get()); - EXPECT_NE(nullptr, buffer3.get()); - EXPECT_EQ(3u, pool->NumAllocatedForTesting()); - EXPECT_EQ(0u, pool->NumFreeForTesting()); - buffer1 = nullptr; - EXPECT_EQ(3u, pool->NumAllocatedForTesting()); - EXPECT_EQ(1u, pool->NumFreeForTesting()); - buffer2 = nullptr; - EXPECT_EQ(3u, pool->NumAllocatedForTesting()); - EXPECT_EQ(2u, pool->NumFreeForTesting()); - buffer3 = nullptr; - EXPECT_EQ(3u, pool->NumAllocatedForTesting()); - EXPECT_EQ(3u, pool->NumFreeForTesting()); - buffer1 = pool->GetBuffer(); - EXPECT_EQ(3u, pool->NumAllocatedForTesting()); - EXPECT_EQ(2u, pool->NumFreeForTesting()); -} - -TEST(IOBufferPoolTest, DestroyBufferAfterPool) { - auto pool = base::MakeRefCounted(kDefaultBufferSize, 3); - scoped_refptr buffer1 = pool->GetBuffer(); - scoped_refptr buffer2 = pool->GetBuffer(); - EXPECT_NE(nullptr, buffer1.get()); - EXPECT_NE(nullptr, buffer2.get()); - EXPECT_EQ(2u, pool->NumAllocatedForTesting()); - EXPECT_EQ(0u, pool->NumFreeForTesting()); - buffer1 = nullptr; - EXPECT_EQ(2u, pool->NumAllocatedForTesting()); - EXPECT_EQ(1u, pool->NumFreeForTesting()); - - pool = nullptr; - buffer2 = nullptr; // Expect no crash and no memory errors. -} - -TEST(IOBufferPoolTest, Preallocate) { - auto pool = base::MakeRefCounted(kDefaultBufferSize, 3); - pool->Preallocate(8); - - EXPECT_EQ(3u, pool->max_buffers()); - EXPECT_EQ(3u, pool->NumAllocatedForTesting()); - EXPECT_EQ(3u, pool->NumFreeForTesting()); - - scoped_refptr buffer1 = pool->GetBuffer(); - scoped_refptr buffer2 = pool->GetBuffer(); - scoped_refptr buffer3 = pool->GetBuffer(); - - EXPECT_NE(nullptr, buffer1.get()); - EXPECT_NE(nullptr, buffer2.get()); - EXPECT_NE(nullptr, buffer3.get()); - EXPECT_EQ(nullptr, pool->GetBuffer()); - - EXPECT_EQ(3u, pool->NumAllocatedForTesting()); - EXPECT_EQ(0u, pool->NumFreeForTesting()); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/mock_stream_socket.cc chromium-132.0.6834.159/chromecast/net/mock_stream_socket.cc --- chromium-132.0.6834.110/chromecast/net/mock_stream_socket.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/mock_stream_socket.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/mock_stream_socket.h" - -#include "net/base/io_buffer.h" -#include "net/base/net_errors.h" -#include "net/socket/next_proto.h" -#include "net/socket/socket_tag.h" -#include "net/traffic_annotation/network_traffic_annotation.h" - -using ::testing::Invoke; -using ::testing::Return; -using ::testing::ReturnRef; -using ::testing::_; - -namespace chromecast { - -MockStreamSocket::MockStreamSocket() { - // Set default return values. - ON_CALL(*this, Read(_, _, _)).WillByDefault(Return(net::ERR_IO_PENDING)); - ON_CALL(*this, Write(_, _, _, _)) - .WillByDefault(Invoke( - [](net::IOBuffer* buf, int buf_len, - net::CompletionOnceCallback callback, - const net::NetworkTrafficAnnotationTag& traffic_annotation) { - return buf_len; - })); - ON_CALL(*this, NetLog()).WillByDefault(ReturnRef(net_log_)); - ON_CALL(*this, GetNegotiatedProtocol()) - .WillByDefault(Return(net::NextProto())); -} - -MockStreamSocket::~MockStreamSocket() {} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/mock_stream_socket.h chromium-132.0.6834.159/chromecast/net/mock_stream_socket.h --- chromium-132.0.6834.110/chromecast/net/mock_stream_socket.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/mock_stream_socket.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_NET_MOCK_STREAM_SOCKET_H_ -#define CHROMECAST_NET_MOCK_STREAM_SOCKET_H_ - -#include - -#include "net/base/completion_once_callback.h" -#include "net/log/net_log_with_source.h" -#include "net/socket/stream_socket.h" -#include "net/traffic_annotation/network_traffic_annotation.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { - -// Google Mock implementation of StreamSocket. -class MockStreamSocket : public net::StreamSocket { - public: - MockStreamSocket(); - - MockStreamSocket(const MockStreamSocket&) = delete; - MockStreamSocket& operator=(const MockStreamSocket&) = delete; - - ~MockStreamSocket() override; - - MOCK_METHOD3(Read, int(net::IOBuffer*, int, net::CompletionOnceCallback)); - MOCK_METHOD4(Write, - int(net::IOBuffer*, - int, - net::CompletionOnceCallback, - const net::NetworkTrafficAnnotationTag&)); - MOCK_METHOD1(SetReceiveBufferSize, int(int32_t)); - MOCK_METHOD1(SetSendBufferSize, int(int32_t)); - MOCK_METHOD1(Connect, int(net::CompletionOnceCallback)); - MOCK_METHOD0(Disconnect, void()); - MOCK_CONST_METHOD0(IsConnected, bool()); - MOCK_CONST_METHOD0(IsConnectedAndIdle, bool()); - MOCK_CONST_METHOD1(GetPeerAddress, int(net::IPEndPoint*)); - MOCK_CONST_METHOD1(GetLocalAddress, int(net::IPEndPoint*)); - MOCK_CONST_METHOD0(NetLog, const net::NetLogWithSource&()); - MOCK_CONST_METHOD0(WasEverUsed, bool()); - MOCK_CONST_METHOD0(UsingTCPFastOpen, bool()); - MOCK_CONST_METHOD0(GetNegotiatedProtocol, net::NextProto()); - MOCK_METHOD1(GetSSLInfo, bool(net::SSLInfo*)); - MOCK_CONST_METHOD0(GetTotalReceivedBytes, int64_t()); - MOCK_METHOD1(ApplySocketTag, void(const net::SocketTag&)); - - private: - net::NetLogWithSource net_log_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_MOCK_STREAM_SOCKET_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/net_switches.cc chromium-132.0.6834.159/chromecast/net/net_switches.cc --- chromium-132.0.6834.110/chromecast/net/net_switches.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/net_switches.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -// 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 "chromecast/net/net_switches.h" - -namespace switches { - -// Url for network connectivity checking. Default is -// "https://clients3.google.com/generate_204". -const char kConnectivityCheckUrl[] = "connectivity-check-url"; - -// List of network interfaces to ignore. Ignored interfaces will not be used -// for network connectivity. -const char kNetifsToIgnore[] = "netifs-to-ignore"; - -} // namespace switches diff -Nru chromium-132.0.6834.110/chromecast/net/net_switches.h chromium-132.0.6834.159/chromecast/net/net_switches.h --- chromium-132.0.6834.110/chromecast/net/net_switches.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/net_switches.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// 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. - -#ifndef CHROMECAST_NET_NET_SWITCHES_H_ -#define CHROMECAST_NET_NET_SWITCHES_H_ - -namespace switches { - -extern const char kConnectivityCheckUrl[]; -extern const char kNetifsToIgnore[]; - -} // namespace switches - -#endif // CHROMECAST_NET_NET_SWITCHES_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/net_util_cast.cc chromium-132.0.6834.159/chromecast/net/net_util_cast.cc --- chromium-132.0.6834.110/chromecast/net/net_util_cast.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/net_util_cast.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// 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 "chromecast/net/net_util_cast.h" - -#include "base/command_line.h" -#include "base/strings/string_split.h" -#include "chromecast/base/cast_sys_info_util.h" -#include "chromecast/net/net_switches.h" -#include "chromecast/public/cast_sys_info.h" - -namespace chromecast { - -std::unordered_set GetIgnoredInterfaces() { - std::unordered_set ignored_interfaces; - std::unique_ptr sys_info = CreateSysInfo(); - if (!sys_info->GetApInterface().empty()) - ignored_interfaces.insert(sys_info->GetApInterface()); - - // Add interfaces from "netif-to-ignore" switch. - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - base::CommandLine::StringType netifs_to_ignore_str = - command_line->GetSwitchValueNative(switches::kNetifsToIgnore); - for (const std::string& netif : base::SplitString( - netifs_to_ignore_str, ",", base::TRIM_WHITESPACE, - base::SPLIT_WANT_ALL)) - ignored_interfaces.insert(netif); - - return ignored_interfaces; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/net_util_cast.h chromium-132.0.6834.159/chromecast/net/net_util_cast.h --- chromium-132.0.6834.110/chromecast/net/net_util_cast.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/net_util_cast.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// 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. - -#ifndef CHROMECAST_NET_NET_UTIL_CAST_H_ -#define CHROMECAST_NET_NET_UTIL_CAST_H_ - -#include -#include - -namespace chromecast { - -// Gets the list of interfaces that should be ignored. The interfaces returned -// by this function will not be used to connect to the internet. -std::unordered_set GetIgnoredInterfaces(); - -} // namespace chromecast - -#endif // CHROMECAST_NET_NET_UTIL_CAST_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/network_change_notifier_factory_cast.cc chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_cast.cc --- chromium-132.0.6834.110/chromecast/net/network_change_notifier_factory_cast.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_cast.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// 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 "chromecast/net/network_change_notifier_factory_cast.h" - -#include "chromecast/net/net_util_cast.h" -#include "net/base/network_change_notifier_linux.h" - -namespace chromecast { - -std::unique_ptr -NetworkChangeNotifierFactoryCast::CreateInstanceWithInitialTypes( - net::NetworkChangeNotifier::ConnectionType /*initial_type*/, - net::NetworkChangeNotifier::ConnectionSubtype /*initial_subtype*/) { - // Caller assumes ownership. - return std::make_unique( - GetIgnoredInterfaces()); -} - -NetworkChangeNotifierFactoryCast::~NetworkChangeNotifierFactoryCast() = default; - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/network_change_notifier_factory_cast.h chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_cast.h --- chromium-132.0.6834.110/chromecast/net/network_change_notifier_factory_cast.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_cast.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// 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. - -#ifndef CHROMECAST_NET_NETWORK_CHANGE_NOTIFIER_FACTORY_CAST_H_ -#define CHROMECAST_NET_NETWORK_CHANGE_NOTIFIER_FACTORY_CAST_H_ - -#include "base/compiler_specific.h" -#include "net/base/network_change_notifier_factory.h" - -namespace chromecast { - -class NetworkChangeNotifierFactoryCast - : public net::NetworkChangeNotifierFactory { - public: - NetworkChangeNotifierFactoryCast() = default; - - NetworkChangeNotifierFactoryCast(const NetworkChangeNotifierFactoryCast&) = - delete; - NetworkChangeNotifierFactoryCast& operator=( - const NetworkChangeNotifierFactoryCast&) = delete; - - ~NetworkChangeNotifierFactoryCast() override; - - // net::NetworkChangeNotifierFactory implementation: - std::unique_ptr CreateInstanceWithInitialTypes( - net::NetworkChangeNotifier::ConnectionType /*initial_type*/, - net::NetworkChangeNotifier::ConnectionSubtype /*initial_subtype*/) - override; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_NETWORK_CHANGE_NOTIFIER_FACTORY_CAST_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/network_change_notifier_factory_fuchsia.cc chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_fuchsia.cc --- chromium-132.0.6834.110/chromecast/net/network_change_notifier_factory_fuchsia.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_fuchsia.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/network_change_notifier_factory_fuchsia.h" - -#include "base/command_line.h" -#include "chromecast/base/chromecast_switches.h" -#include "net/base/network_change_notifier_fuchsia.h" - -namespace chromecast { - -std::unique_ptr -NetworkChangeNotifierFactoryFuchsia::CreateInstanceWithInitialTypes( - net::NetworkChangeNotifier::ConnectionType /*initial_type*/, - net::NetworkChangeNotifier::ConnectionSubtype /*initial_subtype*/) { - auto require_wlan = GetSwitchValueBoolean(switches::kRequireWlan, false); - - // Caller assumes ownership. - return std::make_unique(require_wlan); -} - -NetworkChangeNotifierFactoryFuchsia::NetworkChangeNotifierFactoryFuchsia() = - default; -NetworkChangeNotifierFactoryFuchsia::~NetworkChangeNotifierFactoryFuchsia() = - default; - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/network_change_notifier_factory_fuchsia.h chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_fuchsia.h --- chromium-132.0.6834.110/chromecast/net/network_change_notifier_factory_fuchsia.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/network_change_notifier_factory_fuchsia.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_NET_NETWORK_CHANGE_NOTIFIER_FACTORY_FUCHSIA_H_ -#define CHROMECAST_NET_NETWORK_CHANGE_NOTIFIER_FACTORY_FUCHSIA_H_ - -#include "net/base/network_change_notifier_factory.h" - -namespace chromecast { - -class NetworkChangeNotifierFactoryFuchsia - : public net::NetworkChangeNotifierFactory { - public: - NetworkChangeNotifierFactoryFuchsia(); - - NetworkChangeNotifierFactoryFuchsia( - const NetworkChangeNotifierFactoryFuchsia&) = delete; - NetworkChangeNotifierFactoryFuchsia& operator=( - const NetworkChangeNotifierFactoryFuchsia&) = delete; - - ~NetworkChangeNotifierFactoryFuchsia() override; - - // net::NetworkChangeNotifierFactory implementation: - std::unique_ptr CreateInstanceWithInitialTypes( - net::NetworkChangeNotifier::ConnectionType /*initial_type*/, - net::NetworkChangeNotifier::ConnectionSubtype /*initial_subtype*/) - override; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_NETWORK_CHANGE_NOTIFIER_FACTORY_FUCHSIA_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/small_message_socket.cc chromium-132.0.6834.159/chromecast/net/small_message_socket.cc --- chromium-132.0.6834.110/chromecast/net/small_message_socket.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/small_message_socket.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,491 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/small_message_socket.h" - -#include -#include - -#include -#include - -#include "base/check_op.h" -#include "base/containers/span_writer.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/numerics/byte_conversions.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/net/io_buffer_pool.h" -#include "net/base/net_errors.h" -#include "net/socket/socket.h" - -namespace chromecast { - -namespace { - -// Maximum number of times to read/write in a loop before reposting on the -// run loop (to allow other tasks to run). -const int kMaxIOLoop = 5; - -const int kDefaultBufferSize = 2048; - -constexpr size_t kMax2ByteSize = std::numeric_limits::max(); - -} // namespace - -SmallMessageSocket::BufferWrapper::BufferWrapper() = default; -SmallMessageSocket::BufferWrapper::~BufferWrapper() { - // The `data_` pointer in the base class is pointing into the buffer in the - // `buffer_` field. Stop pointing into the field before its buffer is freed. - data_ = nullptr; -} - -void SmallMessageSocket::BufferWrapper::SetUnderlyingBuffer( - scoped_refptr buffer, - size_t capacity) { - CHECK_LE(capacity, static_cast(buffer->size())); - - buffer_ = std::move(buffer); - used_ = 0; - capacity_ = capacity; - - size_ = capacity_; - data_ = buffer_->data(); -} - -scoped_refptr -SmallMessageSocket::BufferWrapper::TakeUnderlyingBuffer() { - return std::move(buffer_); -} - -void SmallMessageSocket::BufferWrapper::ClearUnderlyingBuffer() { - data_ = nullptr; - buffer_.reset(); -} - -void SmallMessageSocket::BufferWrapper::DidConsume(size_t bytes) { - CHECK(buffer_); - CHECK_LE(bytes, static_cast(size_)); - - size_ -= bytes; - used_ += bytes; - data_ += bytes; - CHECK_EQ(data_, buffer_->data() + used_); -} - -char* SmallMessageSocket::BufferWrapper::StartOfBuffer() const { - CHECK(buffer_); - return buffer_->data(); -} - -base::span SmallMessageSocket::BufferWrapper::used_span() const { - CHECK(buffer_); - return base::span(buffer_->bytes(), used_); -} - -SmallMessageSocket::SmallMessageSocket(Delegate* delegate, - std::unique_ptr socket) - : delegate_(delegate), - socket_(std::move(socket)), - task_runner_(base::SequencedTaskRunner::GetCurrentDefault()), - write_storage_(base::MakeRefCounted()), - write_buffer_(base::MakeRefCounted()), - read_storage_(base::MakeRefCounted()), - read_buffer_(base::MakeRefCounted()), - weak_factory_(this) { - DCHECK(delegate_); - write_storage_->SetCapacity(kDefaultBufferSize); - read_storage_->SetCapacity(kDefaultBufferSize); -} - -SmallMessageSocket::~SmallMessageSocket() = default; - -void SmallMessageSocket::UseBufferPool( - scoped_refptr buffer_pool) { - DCHECK(buffer_pool); - if (buffer_pool_) { - // Replace existing buffer pool. No need to copy data out of existing buffer - // since it will remain valid until we are done using it. - buffer_pool_ = std::move(buffer_pool); - return; - } - - buffer_pool_ = std::move(buffer_pool); - if (!in_message_) { - ActivateBufferPool(read_storage_->span_before_offset()); - } -} - -void SmallMessageSocket::ActivateBufferPool( - base::span current_data) { - // Copy any already-read data into a new buffer for pool-based operation. - DCHECK(buffer_pool_); - DCHECK(!in_message_); - - const size_t current_size = current_data.size(); - scoped_refptr<::net::IOBuffer> new_buffer; - size_t new_buffer_size; - if (current_size <= buffer_pool_->buffer_size()) { - new_buffer = buffer_pool_->GetBuffer(); - CHECK(new_buffer); - new_buffer_size = buffer_pool_->buffer_size(); - } else { - new_buffer = - base::MakeRefCounted<::net::IOBufferWithSize>(current_size * 2); - new_buffer_size = current_size * 2; - } - base::as_writable_bytes(new_buffer->span()).copy_prefix_from(current_data); - - read_buffer_->SetUnderlyingBuffer(std::move(new_buffer), new_buffer_size); - read_buffer_->DidConsume(current_size); -} - -void SmallMessageSocket::RemoveBufferPool() { - if (!buffer_pool_) { - return; - } - - if (static_cast(read_storage_->capacity()) < read_buffer_->used()) { - read_storage_->SetCapacity(read_buffer_->used()); - } - base::span used_span = read_buffer_->used_span(); - read_storage_->everything().copy_prefix_from(used_span); - read_storage_->set_offset(used_span.size()); - - buffer_pool_.reset(); -} - -void* SmallMessageSocket::PrepareSend(size_t message_size) { - if (write_buffer_->size()) { - send_blocked_ = true; - return nullptr; - } - size_t bytes_for_size = SizeDataBytes(message_size); - - write_storage_->set_offset(0); - const size_t total_size = bytes_for_size + message_size; - // TODO(lethalantidote): Remove cast once capacity converted to size_t. - if (static_cast(write_storage_->capacity()) < total_size) { - write_storage_->SetCapacity(total_size); - } - - write_buffer_->SetUnderlyingBuffer(write_storage_, total_size); - auto span = base::as_writable_bytes(write_buffer_->span()); - WriteSizeData(span, message_size); - return span.subspan(bytes_for_size).data(); -} - -bool SmallMessageSocket::SendBuffer(scoped_refptr data, - size_t size) { - if (write_buffer_->size()) { - send_blocked_ = true; - return false; - } - - write_buffer_->SetUnderlyingBuffer(std::move(data), size); - Send(); - return true; -} - -// static -size_t SmallMessageSocket::SizeDataBytes(size_t message_size) { - return (message_size < kMax2ByteSize ? 2 : 6); -} - -// static -size_t SmallMessageSocket::WriteSizeData(base::span buf, - size_t message_size) { - base::SpanWriter writer(buf); - if (message_size < kMax2ByteSize) { - writer.WriteU16BigEndian(static_cast(message_size)); - } else { - writer.WriteU16BigEndian(base::checked_cast(kMax2ByteSize)); - writer.WriteU32BigEndian( - // NOTE: This may truncate the message_size. - static_cast(message_size)); - } - return buf.size() - writer.remaining(); -} - -void SmallMessageSocket::Send() { - for (int i = 0; i < kMaxIOLoop; ++i) { - int result = - socket_->Write(write_buffer_.get(), write_buffer_->size(), - base::BindOnce(&SmallMessageSocket::OnWriteComplete, - base::Unretained(this)), - MISSING_TRAFFIC_ANNOTATION); - if (!HandleWriteResult(result)) { - return; - } - } - - task_runner_->PostTask(FROM_HERE, base::BindOnce(&SmallMessageSocket::Send, - weak_factory_.GetWeakPtr())); -} - -void SmallMessageSocket::OnWriteComplete(int result) { - if (HandleWriteResult(result)) { - Send(); - } -} - -bool SmallMessageSocket::HandleWriteResult(int result) { - if (result == net::ERR_IO_PENDING) { - return false; - } - if (result <= 0) { - // Post a task rather than just calling OnError(), to avoid calling - // OnError() - // synchronously. - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&SmallMessageSocket::OnError, - weak_factory_.GetWeakPtr(), result)); - return false; - } - - write_buffer_->DidConsume(result); - if (write_buffer_->size()) { - return true; - } - - write_buffer_->ClearUnderlyingBuffer(); - if (send_blocked_) { - send_blocked_ = false; - delegate_->OnSendUnblocked(); - } - return false; -} - -void SmallMessageSocket::OnError(int error) { - delegate_->OnError(error); -} - -void SmallMessageSocket::ReceiveMessages() { - // Post a task rather than just calling Read(), to avoid calling delegate - // methods from within this method. - task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&SmallMessageSocket::ReceiveMessagesSynchronously, - weak_factory_.GetWeakPtr())); -} - -void SmallMessageSocket::ReceiveMessagesSynchronously() { - if ((buffer_pool_ && HandleCompletedMessageBuffers()) || - (!buffer_pool_ && HandleCompletedMessages())) { - Read(); - } -} - -void SmallMessageSocket::Read() { - // Read in a loop for a few times while data is immediately available. - // This improves average packet receive delay as compared to always posting a - // new task for each call to Read(). - for (int i = 0; i < kMaxIOLoop; ++i) { - net::IOBuffer* buffer; - int size; - if (buffer_pool_) { - buffer = read_buffer_.get(); - size = read_buffer_->size(); - } else { - buffer = read_storage_.get(); - size = read_storage_->RemainingCapacity(); - } - int read_result = - socket()->Read(buffer, size, - base::BindOnce(&SmallMessageSocket::OnReadComplete, - base::Unretained(this))); - - if (!HandleReadResult(read_result)) { - return; - } - } - - task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&SmallMessageSocket::Read, weak_factory_.GetWeakPtr())); -} - -void SmallMessageSocket::OnReadComplete(int result) { - if (HandleReadResult(result)) { - Read(); - } -} - -bool SmallMessageSocket::HandleReadResult(int result) { - if (result == net::ERR_IO_PENDING) { - return false; - } - - if (result == 0 || result == net::ERR_CONNECTION_CLOSED) { - delegate_->OnEndOfStream(); - return false; - } - - if (result < 0) { - delegate_->OnError(result); - return false; - } - - if (buffer_pool_) { - read_buffer_->DidConsume(result); - return HandleCompletedMessageBuffers(); - } else { - read_storage_->set_offset(read_storage_->offset() + result); - return HandleCompletedMessages(); - } -} - -// static -bool SmallMessageSocket::ReadSize(char* ptr, - size_t bytes_read, - size_t& data_offset, - size_t& message_size) { - if (bytes_read < sizeof(uint16_t)) { - return false; - } - - // TODO(crbug.com/40284755): This span is not safely constructed and is likely - // incorrect for some callers. ReadSize() should receive a span instead of the - // unbounded pointer `ptr`. We use up to bytes from the pointer below, so we - // unsoundly claim that the span has 6 bytes here. - auto span = UNSAFE_TODO(base::as_bytes(base::span(ptr, 6u))); - - uint16_t first_size = base::numerics::U16FromBigEndian(span.first<2u>()); - span = span.subspan(sizeof(uint16_t)); - data_offset = sizeof(uint16_t); - if (first_size < kMax2ByteSize) { - message_size = first_size; - } else { - if (bytes_read < sizeof(uint16_t) + sizeof(uint32_t)) { - return false; - } - uint32_t real_size = base::numerics::U32FromBigEndian(span.first<4u>()); - span = span.subspan(sizeof(uint32_t)); - data_offset += sizeof(uint32_t); - message_size = real_size; - } - return true; -} - -bool SmallMessageSocket::HandleCompletedMessages() { - DCHECK(!buffer_pool_); - bool keep_reading = true; - base::span bytes_read = read_storage_->span_before_offset(); - while (keep_reading) { - size_t data_offset; - size_t message_size; - if (!ReadSize(base::as_writable_chars(bytes_read).data(), bytes_read.size(), - data_offset, message_size)) { - break; - } - size_t total_size = data_offset + message_size; - - if (static_cast(read_storage_->capacity()) < total_size) { - if (bytes_read != read_storage_->span_before_offset()) { - read_storage_->everything().copy_prefix_from(bytes_read); - read_storage_->set_offset(bytes_read.size()); - } - read_storage_->SetCapacity(total_size); - return true; - } - - if (bytes_read.size() < total_size) { - break; // Haven't received the full message yet. - } - - // Take a weak pointer in case OnMessage() causes this to be deleted. - auto self = weak_factory_.GetWeakPtr(); - in_message_ = true; - auto data = - base::as_writable_chars(bytes_read.subspan(data_offset, message_size)); - keep_reading = delegate_->OnMessage(data.data(), data.size()); - if (!self) { - return false; - } - in_message_ = false; - - bytes_read = bytes_read.subspan(total_size); - - if (buffer_pool_) { - // A buffer pool was added within OnMessage(). - ActivateBufferPool(bytes_read); - return (keep_reading ? HandleCompletedMessageBuffers() : false); - } - } - - if (bytes_read != read_storage_->span_before_offset()) { - read_storage_->everything().copy_prefix_from(bytes_read); - read_storage_->set_offset(bytes_read.size()); - } - - return keep_reading; -} - -bool SmallMessageSocket::HandleCompletedMessageBuffers() { - DCHECK(buffer_pool_); - size_t bytes_read; - while ((bytes_read = read_buffer_->used())) { - size_t data_offset; - size_t message_size; - if (!ReadSize(read_buffer_->StartOfBuffer(), bytes_read, data_offset, - message_size)) { - break; - } - size_t total_size = data_offset + message_size; - - if (read_buffer_->capacity() < total_size) { - // Current buffer is not big enough. - auto new_buffer = - base::MakeRefCounted<::net::IOBufferWithSize>(total_size); - memcpy(new_buffer->data(), read_buffer_->StartOfBuffer(), bytes_read); - read_buffer_->SetUnderlyingBuffer(std::move(new_buffer), total_size); - read_buffer_->DidConsume(bytes_read); - return true; - } - - if (bytes_read < total_size) { - break; // Haven't received the full message yet. - } - - auto old_buffer = read_buffer_->TakeUnderlyingBuffer(); - auto new_buffer = buffer_pool_->GetBuffer(); - CHECK(new_buffer); - size_t new_buffer_size = buffer_pool_->buffer_size(); - size_t extra_size = bytes_read - total_size; - if (extra_size > 0) { - // Copy extra data to new buffer. - if (extra_size > buffer_pool_->buffer_size()) { - new_buffer = base::MakeRefCounted<::net::IOBufferWithSize>(extra_size); - new_buffer_size = extra_size; - } - memcpy(new_buffer->data(), old_buffer->data() + total_size, extra_size); - } - read_buffer_->SetUnderlyingBuffer(std::move(new_buffer), new_buffer_size); - read_buffer_->DidConsume(extra_size); - - // Take a weak pointer in case OnMessageBuffer() causes this to be deleted. - auto self = weak_factory_.GetWeakPtr(); - bool keep_reading = - delegate_->OnMessageBuffer(std::move(old_buffer), total_size); - if (!self || !keep_reading) { - return false; - } - if (!buffer_pool_) { - // The buffer pool was removed within OnMessageBuffer(). - return HandleCompletedMessages(); - } - } - - return true; -} - -bool SmallMessageSocket::Delegate::OnMessageBuffer( - scoped_refptr buffer, - size_t size) { - size_t offset = SizeDataBytes(size); - return OnMessage(buffer->data() + offset, size - offset); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/small_message_socket.h chromium-132.0.6834.159/chromecast/net/small_message_socket.h --- chromium-132.0.6834.110/chromecast/net/small_message_socket.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/small_message_socket.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,211 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_NET_SMALL_MESSAGE_SOCKET_H_ -#define CHROMECAST_NET_SMALL_MESSAGE_SOCKET_H_ - -#include - -#include "base/containers/span.h" -#include "base/memory/raw_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "net/base/io_buffer.h" - -namespace base { -class SequencedTaskRunner; -} // namespace base - -namespace net { -class Socket; -} // namespace net - -namespace chromecast { -class IOBufferPool; - -// Sends messages over a Socket. All methods must be called on the same -// sequence. Any of the delegate methods can destroy this object if desired. -class SmallMessageSocket { - public: - class Delegate { - public: - // Called when sending becomes possible again, if a previous attempt to send - // was rejected. - virtual void OnSendUnblocked() {} - - // Called when an unrecoverable error occurs while sending or receiving. Is - // only called asynchronously. - virtual void OnError(int error) {} - - // Called when the end of stream has been read. No more data will be - // received. - virtual void OnEndOfStream() {} - - // Called when a message has been received and there is no buffer pool. The - // |data| buffer contains |size| bytes of data. Return |true| to continue - // reading messages after OnMessage() returns. - virtual bool OnMessage(char* data, size_t size) = 0; - - // Called when a message has been received. The |buffer| contains |size| - // bytes of data, which includes the first 2 (or 6) bytes which are the size - // in network byte order. Note that these 2/6 bytes are not included in - // OnMessage()! Return |true| to continue receiving messages. - // Note: if the first 2 bytes are 0xffff, then the following 4 bytes are the - // size in network byte order (in which case, the offset to the message data - // is 6 bytes). - virtual bool OnMessageBuffer(scoped_refptr buffer, - size_t size); - - protected: - virtual ~Delegate() = default; - }; - - SmallMessageSocket(Delegate* delegate, std::unique_ptr socket); - - SmallMessageSocket(const SmallMessageSocket&) = delete; - SmallMessageSocket& operator=(const SmallMessageSocket&) = delete; - - virtual ~SmallMessageSocket(); - - net::Socket* socket() const { return socket_.get(); } - base::SequencedTaskRunner* task_runner() const { return task_runner_.get(); } - IOBufferPool* buffer_pool() const { return buffer_pool_.get(); } - - // Adds a |buffer_pool| used to allocate buffers to receive messages into; - // received messages are passed to OnMessageBuffer(). If a message would be - // too big to fit in a pool-provided buffer, a dynamically allocated IOBuffer - // will be used instead for that message. - void UseBufferPool(scoped_refptr buffer_pool); - - // Removes the buffer pool; subsequent received messages will be passed to - // OnMessage(). - void RemoveBufferPool(); - - // Prepares a buffer to send a message of the given |message_size|. Returns - // nullptr if sending is not allowed right now (ie, another send is currently - // in progress). Otherwise, returns a buffer at least large enough to contain - // |message_size| bytes. The caller should fill in the buffer as desired and - // then call Send() to send the finished message. - // If nullptr is returned, then OnSendUnblocked() will be called once sending - // is possible again. - // - // TODO(crbug.com/40284755): This method should return a span of size - // `message_size` instead of a pointer. - void* PrepareSend(size_t message_size); - void Send(); - - // Sends an already-prepared buffer of data, if possible. The first part of - // the buffer should contain the message size information as written by - // WriteSizeData(). Returns true if the buffer will be sent; returns false if - // sending is not allowed right now (ie, another send is currently in - // progress). If false is returned, then OnSendUnblocked() will be called once - // sending is possible again. - bool SendBuffer(scoped_refptr data, size_t size); - - // Returns the number of bytes used for size information for the given message - // size. - static size_t SizeDataBytes(size_t message_size); - - // Writes the necessary |message_size| information into `buf`. This can be - // used to prepare a buffer for SendBuffer(). Note that if `message_size` is - // greater than or equal to 0xffff, the message size data will take up 6 - // bytes, and the `buf` will need to be large enough. Returns the number of - // bytes written (= SizeDataBytes(message_size)). - static size_t WriteSizeData(base::span buf, size_t message_size); - - // Reads the message size from a |ptr| which contains |bytes_read| of data. - // Returns |false| if there was not enough data to read a valid size. - static bool ReadSize(char* ptr, - size_t bytes_read, - size_t& data_offset, - size_t& message_size); - - // Enables receiving messages from the stream. Messages will be received and - // passed to OnMessage() until either an error occurs, the end of stream is - // reached, or OnMessage() returns false. If OnMessage() returns false, you - // may call ReceiveMessages() to start receiving again. OnMessage() will not - // be called synchronously from within this method (it always posts a task). - void ReceiveMessages(); - - // Same as ReceiveMessages(), but OnMessage() may be called synchronously. - // This is more efficient because it doesn't post a task to ensure - // asynchronous reads. - void ReceiveMessagesSynchronously(); - - private: - friend class SmallMessageSocketTest; - - // This class wraps the IOBuffer and controls its range to point into - // `buffer_` but allowing it to be a subset of `buffer_` that can shrink as - // bytes are consumed from the front. The base IOBuffer is passed in from - // SetUnderlyingBuffer. - class BufferWrapper : public net::IOBuffer { - public: - BufferWrapper(); - - // Set the base buffer. `capacity` is the total size of `base`. - void SetUnderlyingBuffer(scoped_refptr base, - size_t capacity); - scoped_refptr TakeUnderlyingBuffer(); - void ClearUnderlyingBuffer(); - - // Offset the next available bytes in the buffer. - void DidConsume(size_t bytes); - - // A pointer to the very start of the buffer. The `span()` returned will - // move as DidConsume() is called and moves the start of the buffer forward. - // But this will always return the absolute beginning of the buffer. - // TODO(328018028): This should return a span. - char* StartOfBuffer() const; - - size_t used() const { return used_; } - size_t capacity() const { return capacity_; } - - base::span used_span() const; - - private: - ~BufferWrapper() override; - - // The buffer that actually holds the memory. - scoped_refptr buffer_; - - // Size of the used bytes in previous operations. - size_t used_ = 0; - - // Total size of `buffer_`. - size_t capacity_ = 0; - }; - - void OnWriteComplete(int result); - bool HandleWriteResult(int result); - void OnError(int error); - - void Read(); - void OnReadComplete(int result); - bool HandleReadResult(int result); - bool HandleCompletedMessages(); - bool HandleCompletedMessageBuffers(); - void ActivateBufferPool(base::span current_data); - - const raw_ptr delegate_; - const std::unique_ptr socket_; - const scoped_refptr task_runner_; - - const scoped_refptr write_storage_; - const scoped_refptr write_buffer_; - bool send_blocked_ = false; - - const scoped_refptr read_storage_; - - scoped_refptr buffer_pool_; - const scoped_refptr read_buffer_; - - bool in_message_ = false; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_SMALL_MESSAGE_SOCKET_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/small_message_socket_unittest.cc chromium-132.0.6834.159/chromecast/net/small_message_socket_unittest.cc --- chromium-132.0.6834.110/chromecast/net/small_message_socket_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/small_message_socket_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,355 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/small_message_socket.h" - -#include -#include -#include - -#include "base/big_endian.h" -#include "base/test/task_environment.h" -#include "chromecast/net/fake_stream_socket.h" -#include "chromecast/net/io_buffer_pool.h" -#include "net/base/io_buffer.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -namespace { - -constexpr size_t kDefaultMessageSize = 256; -constexpr size_t kLargeMessageSize = 100000; - -const char kIpAddress1[] = "192.168.0.1"; -const uint16_t kPort1 = 10001; -const char kIpAddress2[] = "192.168.0.2"; -const uint16_t kPort2 = 10002; - -net::IPAddress IpLiteralToIpAddress(const std::string& ip_literal) { - net::IPAddress ip_address; - CHECK(ip_address.AssignFromIPLiteral(ip_literal)); - return ip_address; -} - -void SetData(base::span buffer) { - for (size_t i = 0u; i < buffer.size(); ++i) { - buffer[i] = static_cast(i); - } -} - -void CheckData(base::span buffer) { - for (size_t i = 0u; i < buffer.size(); ++i) { - EXPECT_EQ(buffer[i], static_cast(i)); - } -} - -class TestSocket : public SmallMessageSocket::Delegate { - public: - explicit TestSocket(std::unique_ptr socket) - : socket_(this, std::move(socket)) {} - - ~TestSocket() override = default; - - void UseBufferPool() { - buffer_pool_ = base::MakeRefCounted(kDefaultMessageSize + - sizeof(uint16_t)); - socket_.UseBufferPool(buffer_pool_); - } - void SwapPoolUse(bool swap) { swap_pool_use_ = swap; } - - void* PrepareSend(int message_size) { - return socket_.PrepareSend(message_size); - } - void Send() { socket_.Send(); } - bool SendBuffer(scoped_refptr data, int size) { - return socket_.SendBuffer(std::move(data), size); - } - - void SendData(size_t size) { - size_t data_offset = SmallMessageSocket::SizeDataBytes(size); - auto buffer = - base::MakeRefCounted(data_offset + size); - ASSERT_EQ(buffer->span().size(), size + data_offset); - size_t written = SmallMessageSocket::WriteSizeData( - base::as_writable_bytes(buffer->span()), size); - ASSERT_EQ(written, data_offset); - SetData(base::as_writable_chars(buffer->span().subspan(data_offset))); - SendBuffer(std::move(buffer), data_offset + size); - } - - void ReceiveMessages() { socket_.ReceiveMessages(); } - - size_t last_message_size() const { - DCHECK(!message_history_.empty()); - return message_history_[message_history_.size() - 1]; - } - - const std::vector& message_history() const { - return message_history_; - } - - IOBufferPool* buffer_pool() const { return buffer_pool_.get(); } - SmallMessageSocket* socket() { return &socket_; } - - private: - void OnError(int error) override { NOTREACHED(); } - - bool OnMessage(char* data, size_t size) override { - message_history_.push_back(size); - CheckData( - // TODO(crbug.com/40284755): OnMessage() should receive a span. - UNSAFE_TODO(base::span(data, size))); - if (swap_pool_use_) { - UseBufferPool(); - } - return true; - } - - bool OnMessageBuffer(scoped_refptr buffer, - size_t size) override { - size_t data_offset; - size_t message_size; - bool read_ok = SmallMessageSocket::ReadSize(buffer->data(), size, - data_offset, message_size); - EXPECT_TRUE(read_ok); - if (!read_ok) { - return false; - } - EXPECT_EQ(message_size, size - data_offset); - message_history_.push_back(message_size); - CheckData( - base::as_chars(buffer->span().subspan(data_offset, message_size))); - if (swap_pool_use_) { - socket_.RemoveBufferPool(); - buffer_pool_ = nullptr; - } - return true; - } - - SmallMessageSocket socket_; - std::vector message_history_; - scoped_refptr buffer_pool_; - bool swap_pool_use_ = false; -}; - -} // namespace - -class SmallMessageSocketTest : public ::testing::Test { - public: - SmallMessageSocketTest() { - auto fake1 = std::make_unique( - net::IPEndPoint(IpLiteralToIpAddress(kIpAddress1), kPort1)); - auto fake2 = std::make_unique( - net::IPEndPoint(IpLiteralToIpAddress(kIpAddress2), kPort2)); - fake1->SetPeer(fake2.get()); - fake2->SetPeer(fake1.get()); - fake1->SetBadSenderMode(true); - fake2->SetBadSenderMode(true); - - socket_1_ = std::make_unique(std::move(fake1)); - socket_2_ = std::make_unique(std::move(fake2)); - } - - ~SmallMessageSocketTest() override = default; - - protected: - static scoped_refptr - CreateBufferWrapper() { - return base::MakeRefCounted(); - } - - base::test::TaskEnvironment task_environment_; - - std::unique_ptr socket_1_; - std::unique_ptr socket_2_; -}; - -TEST_F(SmallMessageSocketTest, SendAndReceive) { - socket_2_->ReceiveMessages(); - socket_1_->SendData(kDefaultMessageSize); - task_environment_.RunUntilIdle(); - EXPECT_EQ(socket_2_->last_message_size(), kDefaultMessageSize); -} - -TEST_F(SmallMessageSocketTest, SendAndReceiveLarge) { - size_t message_size = kLargeMessageSize; - socket_2_->ReceiveMessages(); - for (int i = 0; i < 5; ++i) { - socket_1_->SendData(message_size); - task_environment_.RunUntilIdle(); - EXPECT_EQ(socket_2_->last_message_size(), message_size); - - socket_1_->SendData(kDefaultMessageSize); - task_environment_.RunUntilIdle(); - EXPECT_EQ(socket_2_->last_message_size(), kDefaultMessageSize); - - --message_size; - } -} - -TEST_F(SmallMessageSocketTest, PrepareSendAndReceive) { - char* buffer = - static_cast(socket_1_->PrepareSend(kDefaultMessageSize)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize))); - socket_2_->ReceiveMessages(); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - EXPECT_EQ(socket_2_->last_message_size(), kDefaultMessageSize); -} - -TEST_F(SmallMessageSocketTest, MultipleMessages) { - char* buffer = static_cast(socket_1_->PrepareSend(kLargeMessageSize)); - - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kLargeMessageSize))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - buffer = - static_cast(socket_1_->PrepareSend(kDefaultMessageSize * 2 + 1)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize * 2 + 1))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - buffer = static_cast(socket_1_->PrepareSend(kDefaultMessageSize - 5)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize - 5))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - socket_2_->ReceiveMessages(); - task_environment_.RunUntilIdle(); - - ASSERT_EQ(socket_2_->message_history().size(), 3u); - EXPECT_EQ(socket_2_->message_history()[0], kLargeMessageSize); - EXPECT_EQ(socket_2_->message_history()[1], kDefaultMessageSize * 2 + 1); - EXPECT_EQ(socket_2_->message_history()[2], kDefaultMessageSize - 5); -} - -TEST_F(SmallMessageSocketTest, BufferSendAndReceive) { - socket_1_->UseBufferPool(); - socket_2_->UseBufferPool(); - socket_2_->ReceiveMessages(); - socket_1_->SendData(kDefaultMessageSize); - task_environment_.RunUntilIdle(); - EXPECT_EQ(socket_2_->last_message_size(), kDefaultMessageSize); - EXPECT_GT(socket_2_->buffer_pool()->NumAllocatedForTesting(), 0u); - EXPECT_GT(socket_2_->buffer_pool()->NumFreeForTesting(), 0u); -} - -TEST_F(SmallMessageSocketTest, SendLargerThanPoolBufferSize) { - socket_1_->UseBufferPool(); - socket_2_->UseBufferPool(); - char* buffer = static_cast(socket_1_->PrepareSend(kLargeMessageSize)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kLargeMessageSize))); - socket_2_->ReceiveMessages(); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - EXPECT_EQ(socket_2_->last_message_size(), kLargeMessageSize); -} - -TEST_F(SmallMessageSocketTest, BufferMultipleMessages) { - socket_1_->UseBufferPool(); - socket_2_->UseBufferPool(); - char* buffer = - static_cast(socket_1_->PrepareSend(kDefaultMessageSize - 1)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize - 1))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - buffer = static_cast(socket_1_->PrepareSend(kLargeMessageSize)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kLargeMessageSize))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - buffer = static_cast(socket_1_->PrepareSend(kDefaultMessageSize - 5)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize - 5))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - buffer = static_cast(socket_1_->PrepareSend(kDefaultMessageSize)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - socket_2_->ReceiveMessages(); - task_environment_.RunUntilIdle(); - - ASSERT_EQ(socket_2_->message_history().size(), 4u); - EXPECT_EQ(socket_2_->message_history()[0], kDefaultMessageSize - 1); - EXPECT_EQ(socket_2_->message_history()[1], kLargeMessageSize); - EXPECT_EQ(socket_2_->message_history()[2], kDefaultMessageSize - 5); - EXPECT_EQ(socket_2_->message_history()[3], kDefaultMessageSize); -} - -TEST_F(SmallMessageSocketTest, SwapPoolUse) { - socket_2_->SwapPoolUse(true); - char* buffer = - static_cast(socket_1_->PrepareSend(kDefaultMessageSize * 2 + 1)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize * 2 + 1))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - buffer = static_cast(socket_1_->PrepareSend(kDefaultMessageSize - 5)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize - 5))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - buffer = static_cast(socket_1_->PrepareSend(kDefaultMessageSize)); - SetData( - // TODO(crbug.com/40284755): PrepareSend() should return a span. - UNSAFE_TODO(base::span(buffer, kDefaultMessageSize))); - socket_1_->Send(); - task_environment_.RunUntilIdle(); - - socket_2_->ReceiveMessages(); - task_environment_.RunUntilIdle(); - - ASSERT_EQ(socket_2_->message_history().size(), 3u); - EXPECT_EQ(socket_2_->message_history()[0], kDefaultMessageSize * 2 + 1); - EXPECT_EQ(socket_2_->message_history()[1], kDefaultMessageSize - 5); - EXPECT_EQ(socket_2_->message_history()[2], kDefaultMessageSize); -} - -TEST_F(SmallMessageSocketTest, BufferWrapper) { - auto buffer = base::MakeRefCounted(10); - base::span buffer_data = base::as_chars(buffer->span()); - auto wrapper = CreateBufferWrapper(); - wrapper->SetUnderlyingBuffer(std::move(buffer), 9); - EXPECT_EQ(wrapper->data(), &buffer_data[0u]); - EXPECT_EQ(wrapper->size(), 9); - EXPECT_EQ(wrapper->capacity(), 9u); - EXPECT_EQ(wrapper->used(), 0u); - EXPECT_EQ(wrapper->StartOfBuffer(), &buffer_data[0u]); - - wrapper->DidConsume(3); - EXPECT_EQ(wrapper->data(), &buffer_data[3u]); - EXPECT_EQ(wrapper->size(), 6); - EXPECT_EQ(wrapper->capacity(), 9u); - EXPECT_EQ(wrapper->used(), 3u); - EXPECT_EQ(wrapper->StartOfBuffer(), &buffer_data[0u]); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/socket_util.cc chromium-132.0.6834.159/chromecast/net/socket_util.cc --- chromium-132.0.6834.110/chromecast/net/socket_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/socket_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/net/socket_util.h" - -#include - -#include - -#include "base/logging.h" -#include "net/base/net_errors.h" -#include "net/base/sockaddr_storage.h" -#include "net/socket/socket_posix.h" -#include "net/socket/stream_socket.h" -#include "net/socket/unix_domain_client_socket_posix.h" - -namespace chromecast { - -bool CreateUnnamedSocketPair(base::ScopedFD* fd1, base::ScopedFD* fd2) { - int raw_socks[2]; - if (socketpair(AF_UNIX, SOCK_STREAM, 0, raw_socks) == -1) { - return false; - } - fd1->reset(raw_socks[0]); - fd2->reset(raw_socks[1]); - return true; -} - -std::unique_ptr AdoptUnnamedSocketHandle( - base::ScopedFD socket_fd) { - if (!socket_fd.is_valid()) { - LOG(ERROR) << "Received invalid socket descriptor: " << socket_fd.get(); - return nullptr; - } - - net::SockaddrStorage address; - auto socket_posix = std::make_unique(); - if (socket_posix->AdoptConnectedSocket(socket_fd.release(), address) != - net::OK) { - LOG(ERROR) << "Cannot adopt connected socket."; - return nullptr; - } - return std::make_unique(std::move(socket_posix)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/socket_util.h chromium-132.0.6834.159/chromecast/net/socket_util.h --- chromium-132.0.6834.110/chromecast/net/socket_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/socket_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_NET_SOCKET_UTIL_H_ -#define CHROMECAST_NET_SOCKET_UTIL_H_ - -#include - -#include "base/files/scoped_file.h" - -namespace net { -class StreamSocket; -} // namespace net - -namespace chromecast { - -// Creates a socket pair and returns true if succeeded. -bool CreateUnnamedSocketPair(base::ScopedFD* fd1, base::ScopedFD* fd2); - -// Returns a net::StreamSocket wrapping the |socket_fd|. -// Note: nullptr will be returned if |socket_fd| is invalid or an error occurred -// when adopting the socket descriptor. -std::unique_ptr AdoptUnnamedSocketHandle( - base::ScopedFD socket_fd); - -} // namespace chromecast - -#endif // CHROMECAST_NET_SOCKET_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/time_sync_tracker.cc chromium-132.0.6834.159/chromecast/net/time_sync_tracker.cc --- chromium-132.0.6834.110/chromecast/net/time_sync_tracker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/time_sync_tracker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// 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 "chromecast/net/time_sync_tracker.h" - -namespace chromecast { - -TimeSyncTracker::TimeSyncTracker() {} - -TimeSyncTracker::~TimeSyncTracker() = default; - -void TimeSyncTracker::AddObserver(Observer* observer) { - observer_list_.AddObserver(observer); -} - -void TimeSyncTracker::RemoveObserver(Observer* observer) { - observer_list_.RemoveObserver(observer); -} - -void TimeSyncTracker::Notify() { - for (Observer& observer : observer_list_) { - observer.OnTimeSynced(); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/time_sync_tracker.h chromium-132.0.6834.159/chromecast/net/time_sync_tracker.h --- chromium-132.0.6834.110/chromecast/net/time_sync_tracker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/time_sync_tracker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// 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. - -#ifndef CHROMECAST_NET_TIME_SYNC_TRACKER_H_ -#define CHROMECAST_NET_TIME_SYNC_TRACKER_H_ - -#include "base/observer_list.h" -#include "base/observer_list_types.h" - -namespace chromecast { - -// Tracks whether or not time has synced on the device. -// -// In cases where general network connectivity does not include whether or not -// time has synced, this class provides that information. -class TimeSyncTracker { - public: - class Observer : public base::CheckedObserver { - public: - virtual void OnTimeSynced() = 0; - - protected: - Observer() {} - ~Observer() override = default; - }; - - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - // Returns if the time has been synced. - virtual bool IsTimeSynced() const = 0; - - protected: - TimeSyncTracker(); - virtual ~TimeSyncTracker(); - - // Notifies observer that time has been synced. - void Notify(); - - private: - base::ObserverList observer_list_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_TIME_SYNC_TRACKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/net/time_sync_tracker_fuchsia.cc chromium-132.0.6834.159/chromecast/net/time_sync_tracker_fuchsia.cc --- chromium-132.0.6834.110/chromecast/net/time_sync_tracker_fuchsia.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/time_sync_tracker_fuchsia.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// 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 "chromecast/net/time_sync_tracker_fuchsia.h" - -#include -#include - -#include "base/fuchsia/fuchsia_logging.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/task/current_thread.h" -#include "base/time/time.h" - -namespace chromecast { -namespace { - -zx_handle_t GetUtcClockHandle() { - zx_handle_t clock_handle = zx_utc_reference_get(); - DCHECK(clock_handle != ZX_HANDLE_INVALID); - return clock_handle; -} - -} // namespace - -TimeSyncTrackerFuchsia::TimeSyncTrackerFuchsia() - : utc_clock_(GetUtcClockHandle()), time_watch_(FROM_HERE) { - base::CurrentIOThread::Get()->WatchZxHandle( - utc_clock_->get(), false /* persistent */, ZX_USER_SIGNAL_0, &time_watch_, - this); -} - -TimeSyncTrackerFuchsia::~TimeSyncTrackerFuchsia() = default; - -void TimeSyncTrackerFuchsia::OnZxHandleSignalled(zx_handle_t handle, - zx_signals_t signals) { - VLOG(1) << " Time is externally synced."; - is_time_synced_ = true; - Notify(); -} - -bool TimeSyncTrackerFuchsia::IsTimeSynced() const { - return is_time_synced_; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/net/time_sync_tracker_fuchsia.h chromium-132.0.6834.159/chromecast/net/time_sync_tracker_fuchsia.h --- chromium-132.0.6834.110/chromecast/net/time_sync_tracker_fuchsia.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/net/time_sync_tracker_fuchsia.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// 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. - -#ifndef CHROMECAST_NET_TIME_SYNC_TRACKER_FUCHSIA_H_ -#define CHROMECAST_NET_TIME_SYNC_TRACKER_FUCHSIA_H_ - -#include - -#include "base/message_loop/message_pump_for_io.h" -#include "chromecast/net/time_sync_tracker.h" - -namespace chromecast { - -class TimeSyncTrackerFuchsia : public TimeSyncTracker, - public base::MessagePumpForIO::ZxHandleWatcher { - public: - explicit TimeSyncTrackerFuchsia(); - TimeSyncTrackerFuchsia(const TimeSyncTrackerFuchsia&) = delete; - TimeSyncTrackerFuchsia& operator=(const TimeSyncTrackerFuchsia&) = delete; - ~TimeSyncTrackerFuchsia() override; - - // TimeSyncTracker implementation: - bool IsTimeSynced() const final; - - private: - // ZxHandleWatcher implementation: - void OnZxHandleSignalled(zx_handle_t handle, zx_signals_t signals) final; - - zx::unowned_clock utc_clock_; - bool is_time_synced_ = false; - - base::MessagePumpForIO::ZxHandleWatchController time_watch_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_NET_TIME_SYNC_TRACKER_FUCHSIA_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/DEPS chromium-132.0.6834.159/chromecast/public/DEPS --- chromium-132.0.6834.110/chromecast/public/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -include_rules = [ - # chromecast/public should not depend on anything Chromium specific - # Disallow all chromium-wide dependencies listed in chromium/src/DEPS. - "-base", - "-build", - "-ipc", - "-testing", - "-url", -] diff -Nru chromium-132.0.6834.110/chromecast/public/avsettings.h chromium-132.0.6834.159/chromecast/public/avsettings.h --- chromium-132.0.6834.110/chromecast/public/avsettings.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/avsettings.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,408 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_AVSETTINGS_H_ -#define CHROMECAST_PUBLIC_AVSETTINGS_H_ - -#include - -#include -#include - -#include "chromecast_export.h" -#include "output_restrictions.h" -#include "task_runner.h" - -namespace chromecast { - -// Pure abstract interface to get and set media-related information. Each -// platform must provide its own implementation. -// All functions except constructor and destructor are called in one thread. -// All delegate functions can be called by platform implementation on any -// threads, for example, created by platform implementation internally. -class AvSettings { - public: - // Defines whether or not the cast receiver is the current active source of - // the screen. If the device is connected to HDMI sinks, it may be unknown. - // GENERATED_JAVA_ENUM_PACKAGE: com.google.android.apps.mediashell.avsettings - enum ActiveState { - UNKNOWN, - STANDBY, // Screen is off - INACTIVE, // Screen is on, but cast receiver is not active - ACTIVE, // Screen is on and cast receiver is active - }; - - // Audio codec supported by the device (or HDMI sink). - // GENERATED_JAVA_ENUM_PACKAGE: com.google.android.apps.mediashell.avsettings - enum AudioCodec { - AC3 = 1 << 0, - DTS = 1 << 1, - DTS_HD = 1 << 2, - EAC3 = 1 << 3, - LPCM = 1 << 4, - MPEG_H_AUDIO = 1 << 5, - - // All known audio codecs. - ALL = AC3 | DTS | DTS_HD | EAC3 | LPCM | MPEG_H_AUDIO - }; - - // Defines the type of audio volume control of the device. - // GENERATED_JAVA_ENUM_PACKAGE: com.google.android.apps.mediashell.avsettings - enum AudioVolumeControlType { - UNKNOWN_VOLUME, - - // MASTER_VOLUME: Devices of CEC audio controls is a master volume system, - // i.e the system volume is changed, but not attenuated, - // e.g. normal TVs, audio devices. - MASTER_VOLUME, - - // ATTENUATION_VOLUME: Devices which do not do CEC audio controls, - // e.g. Chromecast. - ATTENUATION_VOLUME, - - // FIXED_VOLUME: Devices which have fixed volume, e.g. Nexus Player. - FIXED_VOLUME, - }; - - enum class HdmiContentType { - NO_DATA_TYPE, - GAME_TYPE, - }; - - // Defines the status of platform wake-on-cast feature. - enum WakeOnCastStatus { - WAKE_ON_CAST_UNKNOWN, // Should only been used very rarely when platform - // has error to get the status. - WAKE_ON_CAST_NOT_SUPPORTED, // Platform doesn't support wake-on-cast. - WAKE_ON_CAST_DISABLED, - WAKE_ON_CAST_ENABLED, - }; - - // GENERATED_JAVA_ENUM_PACKAGE: com.google.android.apps.mediashell.avsettings - enum Event { - // This event shall be fired whenever the active state is changed including - // when the screen turned on, when the cast receiver (or the device where - // cast receiver is running on) became the active input source, or after a - // call to TurnActive() or TurnStandby(). - // WakeSystem() may change the active state depending on implementation. - // On this event, GetActiveState() will be called on the thread where - // Initialize() was called. - ACTIVE_STATE_CHANGED = 0, - - // This event shall be fired whenever the audio codecs supported by the - // device (or HDMI sinks connected to the device) are changed. - // On this event, GetAudioCodecsSupported(), GetMaxAudioChannels(), and - // GetSpatialRenderingAudioCodecs() be called on the thread where - // Initialize() was called. - AUDIO_CODECS_SUPPORTED_CHANGED = 2, - - // This event shall be fired whenever the screen information of the device - // (or HDMI sinks connected to the device) are changed including screen - // resolution, HDCP version and supported EOTFs. - // On this event, GetScreenResolution(), GetHDCPVersion() and - // GetSupportedEotfs(), GetScreenWidthMm(), GetScreenHeightMm() will be - // called on the thread where Initialize() was called. - SCREEN_INFO_CHANGED = 3, - - // This event should be fired whenever the active output restrictions on the - // device outputs change. On this event, GetOutputRestrictions() will be - // called on the thread where Initialize() was called. - OUTPUT_RESTRICTIONS_CHANGED = 4, - - // This event shall be fired whenever the type of volume control provided - // by the device is changed, for e.g., when the device is connected or - // disconnected to HDMI sinks - AUDIO_VOLUME_CONTROL_TYPE_CHANGED = 5, - - // This event shall be fired whenever wake-on-cast status is changed by - // platform. - WAKE_ON_CAST_CHANGED = 6, - - // This event shall be fired whenever the volume step interval provided - // by the device is changed, for e.g. when connecting to an AVR setup - // where step interval should be 1%. - AUDIO_VOLUME_STEP_INTERVAL_CHANGED = 7, - - // This event shall be fired whenever the HDR output type changes. - // On this event, GetHdrOutputType() will be called on the thread where - // Initialize() was called. - HDR_OUTPUT_TYPE_CHANGED = 8, - - // This event should be fired when the device is connected to HDMI sinks. - HDMI_CONNECTED = 100, - - // This event should be fired when the device is disconnected to HDMI sinks. - HDMI_DISCONNECTED = 101, - - // This event should be fired when an HDMI error occurs. - HDMI_ERROR = 102, - - // This event should be fired when the display brightness is changed. - DISPLAY_BRIGHTNESS_CHANGED = 200, - }; - - // Delegate to inform the caller events. As a subclass of TaskRunner, - // AvSettings implementation can post tasks to the thread where Initialize() - // was called. - class Delegate : public TaskRunner { - public: - // This may be invoked to posts a task to the thread where Initialize() was - // called. - bool PostTask(Task* task, uint64_t delay_ms) override = 0; - - // This must be invoked to fire an event when one of the conditions - // described above (Event) happens. - virtual void OnMediaEvent(Event event) = 0; - - // This should be invoked when a key is pressed. - // |key_code| is a CEC code defined in User Control Codes table of the CEC - // specification (CEC Table 30 in the HDMI 1.4a specification). - virtual void OnKeyPressed(int key_code) = 0; - - // This should be invoked when a key is released. - virtual void OnKeyReleased(int key_code) = 0; - - protected: - ~Delegate() override {} - }; - - virtual ~AvSettings() {} - - // Initializes avsettings and starts delivering events to |delegate|. - // |delegate| must not be null. - virtual void Initialize(Delegate* delegate) = 0; - - // Finalizes avsettings. It must assume |delegate| passed to Initialize() is - // invalid after this call and stop delivering events. - virtual void Finalize() = 0; - - // Returns current active state. - virtual ActiveState GetActiveState() = 0; - - // Turns the screen on. Sets the active input to the cast receiver iff - // switch_to_cast == true. - // If successful, it must return true and fire ACTIVE_STATE_CHANGED. - virtual bool TurnActive(bool switch_to_cast) = 0; - - // Turns the screen off (or stand-by). If the device is connecting to HDMI - // sinks, broadcasts a CEC standby message on the HDMI control bus to put all - // sink devices (TV, AVR) into a standby state. - // If successful, it must return true and fire ACTIVE_STATE_CHANGED. - virtual bool TurnStandby() = 0; - - // Requests the system where cast receiver is running on to be kept awake for - // |time_ms|. If the system is already being kept awake, the period should be - // extended from |time_ms| in the future. - // It will be called when cast senders discover the cast receiver while the - // system is in a stand-by mode (or a deeper sleeping/dormant mode depending - // on the system). To respond to cast senders' requests, cast receiver needs - // the system awake for given amount of time. The system should not turn - // screen on. - // Returns true if successful. - virtual bool KeepSystemAwake(int time_ms) = 0; - - // Sets screen (backlight) brightness. - // |brightness|: Range is 0.0 (off) to 1.0 (max). - // |smooth|: If true, will gradually change brightness in a ramp. If true and - // unsupported, returns false and does nothing. If false, sets brightness - // immediately. If another ramp is already in progress, it is cancelled and a - // new one is started from the current brightness of the display. - // If the implementation rounds to discrete values, it should round up so that - // non-0 |brightness| values don't turn off the display. - // Returns false if set fails. Returns true otherwise. - // Not all displays support this function. - static CHROMECAST_EXPORT bool SetDisplayBrightness(float brightness, - bool smooth) - __attribute__((weak)); - - // Gets the current screen (backlight) brightness. - // |brightness|: Range is 0.0 (off) to 1.0 (max). - // Returns false and does not modify |brightness| if get fails. - // Returns true and sets |brightness| to the current brightness otherwise. - // Not all displays support this function. - static CHROMECAST_EXPORT bool GetDisplayBrightness(float* brightness) - __attribute__((weak)); - - // Gets the nits output by the display at 100% brightness. - // |nits|: The maximum brightness in nits. - // Returns false and does not modify |nits| if get fails. - // Returns true and sets |nits| on success. - // Not all displays support this function. - static CHROMECAST_EXPORT bool GetDisplayMaxBrightnessNits(float* nits) - __attribute__((weak)); - - // Set Hdmi content type. Return false if such operation fails. The operation - // fails if unexpected errors occur, or if the desired |content_type| is not - // supported by Hdmi sink, in which case implementation shall return false - // without actually setting the content type. - // This function should only be implemented on HDMI platforms. - static CHROMECAST_EXPORT bool SetHdmiContentType(HdmiContentType content_type) - __attribute__((weak)); - - // Gets the HDMI latency in microseconds. - // Returns valid values when HDMI is connected. - // Returns 0 when HDMI is not connected or when the latency cannot be - // measured. - // This function should only be implemented on HDMI platforms. - static CHROMECAST_EXPORT int GetHdmiLatencyUs() __attribute__((weak)); - - // Gets the EDID ID string. - // Returns the valid EDID ID when HDMI is connected. - // Returns an empty string when HDMI is not connected or when the EDID info - // cannot be correctly parsed. - // This function should only be implemented on HDMI platforms. - static CHROMECAST_EXPORT std::string GetEdidId() __attribute__((weak)); - - // Returns true if this is an HDMI platform. - // This function should only be implemented on HDMI platforms. - static CHROMECAST_EXPORT bool IsHdmiPlatform() __attribute__((weak)); - - // Returns the type of volume control, i.e. MASTER_VOLUME, FIXED_VOLUME or - // ATTENUATION_VOLUME. For example, normal TVs, devices of CEC audio - // controls, and audio devices are master volume systems. The counter - // examples are Chromecast (which doesn't do CEC audio controls) and - // Nexus Player which is fixed volume. - virtual AudioVolumeControlType GetAudioVolumeControlType() = 0; - - // Retrieves the volume step interval in range [0.0, 1.0] that specifies how - // much volume to change per step, e.g. 0.05 = 5%. Returns true if a valid - // interval is specified by platform; returns false if interval should defer - // to default values. - // - // Current default volume step intervals per control type are as follows: - // - MASTER_VOLUME: 0.05 (5%) - // - ATTENUATION_VOLUME: 0.02 (2%) - // - FIXED_VOLUME: 0.01 (1%) - // - UNKNOWN_VOLUME: 0.01 (1%) - virtual bool GetAudioVolumeStepInterval(float* step_inteval) = 0; - - // Gets audio codecs supported by the device (or HDMI sinks). - // The result is an integer of OR'ed AudioCodec values. - virtual int GetAudioCodecsSupported() = 0; - - // Returns a bitmap of audio codecs that the device (or HDMI sinks) can - // render spatially. - static CHROMECAST_EXPORT int GetSpatialRenderingAudioCodecs() - __attribute__((weak)); - - // Gets maximum number of channels for given audio codec, |codec|. - virtual int GetMaxAudioChannels(AudioCodec codec) = 0; - - // Retrieves the resolution of screen of the device (or HDMI sinks). - // Returns true if it gets resolution successfully. - virtual bool GetScreenResolution(int* width, int* height) = 0; - - // Retrieves the refresh rate of screen of the device (or HDMI sinks) in - // millihertz. - // Returns true if it gets refresh rate successfully. - // TODO(jiaqih): Update to virtual function in next API update. - static CHROMECAST_EXPORT bool GetRefreshRateMillihertz(int* refresh_rate) - __attribute__((weak)); - - // Returns the current HDCP version multiplied by ten (so, for example, for - // HDCP 2.2 the return value is 22). The return value should by 0 if HDCP is - // not supported. Or TV_PLATFORM_NO_HDCP for platforms like CastTV that - // support equivalent content protection without HDCP. - enum { TV_PLATFORM_NO_HDCP = 99 }; - virtual int GetHDCPVersion() = 0; - - // Supported Electro-Optical Transfer Function (EOTF) reported by the device. - // The values are according to Table 8 in CTA-861.3 (formerly CEA-861.3). - // GENERATED_JAVA_ENUM_PACKAGE: com.google.android.apps.mediashell.avsettings - enum Eotf { - EOTF_SDR = 1 << 0, - EOTF_HDR = 1 << 1, - EOTF_SMPTE_ST_2084 = 1 << 2, - EOTF_HLG = 1 << 3, - }; - - // Returns a set of flags, defined in the Eotf enum above, indicating support - // of different EOTFs by the device or HDMI sink. - virtual int GetSupportedEotfs() = 0; - - enum DolbyVisionCapFlags { - DOLBY_SUPPORTED = 1 << 0, - DOLBY_4K_P60_SUPPORTED = 1 << 1, - DOLBY_422_12BIT_SUPPORTED = 1 << 2, - }; - - // Returns a set of flags, defined in the DolbyVisionCapFlags enum above, - // indicating support for DolbyVision and various DV-related features. - virtual int GetDolbyVisionFlags() = 0; - - // Returns physical screen size in millimeters. - virtual int GetScreenWidthMm() = 0; - virtual int GetScreenHeightMm() = 0; - - // If supported, retrieves the restrictions active on the device outputs (as - // specified by the PlayReady CDM; see output_restrictions.h). If reporting - // output restrictions is unsupported, should return false. - virtual bool GetOutputRestrictions( - OutputRestrictions* output_restrictions) = 0; - - // If supported, sets which output restrictions should be active on the device - // (as specified by the PlayReady CDM; see output_restrictions.h). The device - // should try to apply these restrictions and fire OUTPUT_RESTRICTIONS_CHANGED - // if they result in a change of active restrictions. - virtual void ApplyOutputRestrictions( - const OutputRestrictions& restrictions) = 0; - - // Returns current Wake-On-Cast status from platform. - virtual WakeOnCastStatus GetWakeOnCastStatus() = 0; - - // Enables/Disables Wake-On-Cast status. - // Returns false if failed or not supported. - virtual bool EnableWakeOnCast(bool enabled) = 0; - - // Supported HDR output modes. - // GENERATED_JAVA_ENUM_PACKAGE: com.google.android.apps.mediashell.avsettings - enum HdrOutputType { - HDR_OUTPUT_SDR, // not HDR - HDR_OUTPUT_HDR, // HDR with static metadata - HDR_OUTPUT_DOLBYVISION // DolbyVision output - }; - - // Gets the current HDR output type. - virtual HdrOutputType GetHdrOutputType() = 0; - - // Sets the HDMI video mode according to the given parameters: - // |allow_4k|: if false, the resolution set will not be a 4K resolution. - // |optimize_for_fps|: *Attempts* to pick a refresh rate optimal for the - // given content frame rate. |optimize_for_fps| is expressed as framerate - // * 100. I.e. 24hz -> 2400, 23.98hz -> 2398, etc. Values <= 0 are ignored. - // |output_type|: if set to HDR_OUTPUT_DOLBYVISION, the video mode set will - // be a DV supported resolution. If set to HDR_OUTPUT_HDR, the video mode set - // will be a 10-bit or greater video mode. - // - // Returns: - // - true if HDMI video mode change is beginning. Caller should wait for - // SCREEN_INFO_CHANGED event for mode change to complete. - // - false if no HDMI video mode change has begun. This could be because - // HDMI is disconnected, or the current resolution is already good for the - // given parameters, or no valid resolution with the given parameters is - // found (ie. setting require_dolby_vision/require_hdr to true when the - // sink doesn't support those features). - // - // Non-HDMI devices should return false. - virtual bool SetHdmiVideoMode(bool allow_4k, - int optimize_for_fps, - HdrOutputType output_type) = 0; - - // Returns true if the HDMI sink supports the specified HDR output type in - // the current HDMI mode. Returns false otherwise. - // - // Non-HDMI devices should return false. - virtual bool IsHdrOutputSupportedByCurrentHdmiVideoMode( - HdrOutputType output_type) = 0; -}; - -// Entrypoint for overridable AvSettings shared library. -class CHROMECAST_EXPORT AvSettingsShlib { - public: - static AvSettings* Create(const std::vector& argv); -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_AVSETTINGS_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/bluetooth/bluetooth_types.h chromium-132.0.6834.159/chromecast/public/bluetooth/bluetooth_types.h --- chromium-132.0.6834.110/chromecast/public/bluetooth/bluetooth_types.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/bluetooth/bluetooth_types.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_BLUETOOTH_BLUETOOTH_TYPES_H_ -#define CHROMECAST_PUBLIC_BLUETOOTH_BLUETOOTH_TYPES_H_ - -#include -#include - -namespace chromecast { -namespace bluetooth_v2_shlib { - -static constexpr size_t kAddrLen = 6; -static constexpr size_t kUuidLen = 16; -using Addr = std::array; // Little endian -using Uuid = std::array; // Big endian - -} // namespace bluetooth_v2_shlib -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_BLUETOOTH_BLUETOOTH_TYPES_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/bluetooth/gatt.h chromium-132.0.6834.159/chromecast/public/bluetooth/gatt.h --- chromium-132.0.6834.110/chromecast/public/bluetooth/gatt.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/bluetooth/gatt.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,390 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_BLUETOOTH_GATT_H_ -#define CHROMECAST_PUBLIC_BLUETOOTH_GATT_H_ - -#include - -#include "bluetooth_types.h" -#include "chromecast_export.h" - -namespace chromecast { -namespace bluetooth_v2_shlib { - -// GATT (Generic Attributes) is the primary mechanism in BLE (Bluetooth Low -// Energy) for transmiting data. -class CHROMECAST_EXPORT Gatt { - public: - // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html - enum Permissions : uint16_t { - PERMISSION_NONE = 0, - PERMISSION_READ = 1 << 0, - PERMISSION_READ_ENCRYPTED = 1 << 1, - PERMISSION_READ_ENCRYPTED_MITM = 1 << 2, - PERMISSION_WRITE = 1 << 4, - PERMISSION_WRITE_ENCRYPTED = 1 << 5, - PERMISSION_WRITE_ENCRYPTED_MITM = 1 << 6, - PERMISSION_WRITE_SIGNED = 1 << 7, - PERMISSION_WRITE_SIGNED_MITM = 1 << 8, - }; - - // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html - enum Properties : uint8_t { - PROPERTY_NONE = 0, - PROPERTY_BROADCAST = 1 << 0, - PROPERTY_READ = 1 << 1, - PROPERTY_WRITE_NO_RESPONSE = 1 << 2, - PROPERTY_WRITE = 1 << 3, - PROPERTY_NOTIFY = 1 << 4, - PROPERTY_INDICATE = 1 << 5, - PROPERTY_SIGNED_WRITE = 1 << 6, - PROPERTY_EXTENDED_PROPS = 1 << 7, - }; - - // https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html - enum WriteType : uint8_t { - WRITE_TYPE_NONE = 0, - WRITE_TYPE_NO_RESPONSE = 1 << 0, - WRITE_TYPE_DEFAULT = 1 << 1, - WRITE_TYPE_SIGNED = 1 << 2, - }; - - // Core 4.2 Vol3 part F 3.4.1.1 Error Response - enum class Status { - NONE = 0, - INVALID_HANDLE = 0x01, - READ_NOT_PERMITTED = 0x02, - WRITE_NOT_PERMITTED = 0x03, - INVALID_PDU = 0x04, - INSUFFICIENT_AUTHEN = 0x05, - REQUEST_NOT_SUPPORTED = 0x06, - INVALID_OFFSET = 0x07, - INSUFFICIENT_AUTHOR = 0x08, - PREP_QUEUE_FULL = 0x09, - ATTRIBUTE_NOT_FOUND = 0x0a, - ATTRIBUTE_NOT_LONG = 0x0b, - INSUFFICIENT_KEY_SIZE = 0x0c, - INVALID_ATTRIBUTE_LENGTH = 0x0d, - UNLIKELY = 0x0e, - INSUFFICIENT_ENCR = 0x0f, - UNSUPPORTED_GRP_TYPE = 0x10, - INSUFFICIENT_RESOURCES = 0x11, - CCCD_IMPROPERLY_CONFIGURED = 0xFD, - PROCEDURE_IN_PROGRESS = 0xFE, - OUT_OF_RANGE = 0xFF - }; - - // Attributes that describe a characteristic value. - struct Descriptor { - Uuid uuid; - uint16_t handle; - Permissions permissions; - }; - - // Attribute types that contain a single logical value. - struct Characteristic { - Characteristic(); - Characteristic(const Characteristic& other); - ~Characteristic(); - - Uuid uuid; - uint16_t handle; - Permissions permissions; - Properties properties; - std::vector descriptors; - }; - - // Services are collections of characteristics and relationships to other - // services that encapsulate the behavior of part of a device. - struct Service { - Service(); - Service(const Service& other); - ~Service(); - Uuid uuid; - uint16_t handle; - bool primary; - std::vector characteristics; - std::vector included_services; - }; - - // The GATT client role is when a device connects to a remote GATT server. - class Client { - public: - // See frameworks/base/core/java/android/bluetooth/BluetoothGatt.java - // AUTHENTICATION_{NONE,NO_MITM,MITM} - enum AuthReq : int32_t { - AUTH_REQ_INVALID = -1, - AUTH_REQ_NONE = 0, - AUTH_REQ_NO_MITM = 1, - AUTH_REQ_MITM = 2, - - AUTH_REQ_MAX = AUTH_REQ_MITM, - }; - - enum class Transport { - kAuto, - kBrEdr, - kLe, - }; - - // These callbacks may be on any thead. - class Delegate { - public: - // Called when the connection changes. - virtual void OnConnectChanged(const Addr& addr, - bool status, - bool connected) = 0; - - // Called when the bonding state changes. - virtual void OnBondChanged(const Addr& addr, - bool status, - bool bonded) = 0; - - // Called on a Characteristic value notification. - virtual void OnNotification(const Addr& addr, - uint16_t handle, - const std::vector& value) = 0; - - // Called in response to ReadCharacteristic. - virtual void OnCharacteristicReadResponse( - const Addr& addr, - bool status, - uint16_t handle, - const std::vector& value) = 0; - - // Called in response to WriteCharacteristic. - virtual void OnCharacteristicWriteResponse(const Addr& addr, - bool status, - uint16_t handle) = 0; - - // Called in response to ReadDescriptor. - virtual void OnDescriptorReadResponse( - const Addr& addr, - bool status, - uint16_t handle, - const std::vector& value) = 0; - - // Called in response to WriteDescriptor. - virtual void OnDescriptorWriteResponse(const Addr& addr, - bool status, - uint16_t handle) = 0; - - // Called in response to ReadRemoteRssi. - virtual void OnReadRemoteRssi(const Addr& addr, - bool status, - int rssi) = 0; - - // Called when the connection MTU changes. - virtual void OnMtuChanged(const Addr& addr, bool status, int mtu) = 0; - - // Called when the service list is obtained. - virtual void OnGetServices(const Addr& addr, - const std::vector& services) = 0; - - // Called when services are removed. - virtual void OnServicesRemoved(const Addr& addr, - uint16_t start_handle, - uint16_t end_handle) = 0; - - // Called when services are added. - virtual void OnServicesAdded(const Addr& addr, - const std::vector& services) = 0; - - virtual ~Delegate() = default; - }; - - // Returns true if GATT client profile is supported. - static bool IsSupported(); - static void SetDelegate(Delegate* delegate); - - // Create a connection to remote device |addr| using |transport|. - static bool Connect(const Addr& addr, Transport transport); - - // Remove connection to remote device |addr|. - static bool Disconnect(const Addr& addr); - - // Create bond to remote device |addr|. - static bool CreateBond(const Addr& addr); - - // Remove bond to remote device |addr|. - static bool RemoveBond(const Addr& addr); - - // Read |characteristic| from remote device |addr|. If |auth_req| is - // AUTH_REQ_INVALID, this function will automatically retry stronger - // authentications on failure. - static bool ReadCharacteristic(const Addr& addr, - const Characteristic& characteristic, - AuthReq auth_req); - - // Write |characteristic| on remote device |addr| with |write_type|. If - // |auth_req| is AUTH_REQ_INVALID, this function will automatically retry - // stronger authentications on failure. - static bool WriteCharacteristic(const Addr& addr, - const Characteristic& characteristic, - AuthReq auth_req, - WriteType write_type, - const std::vector& value); - - // Read |descriptor| from remote device |addr|. If |auth_req| is - // AUTH_REQ_INVALID, this function will automatically retry stronger - // authentications on failure. - static bool ReadDescriptor(const Addr& addr, - const Descriptor& descriptor, - AuthReq auth_req); - - // Write |descriptor| on remote device |addr|. If |auth_req| is - // AUTH_REQ_INVALID, this function will automatically retry stronger - // authentications on failure. - static bool WriteDescriptor(const Addr& addr, - const Descriptor& descriptor, - AuthReq auth_req, - const std::vector& value); - - // Register or deregister for notifications of |characteristic| on device - // |addr|. - static bool SetCharacteristicNotification( - const Addr& addr, - const Characteristic& characteristic, - bool enable); - - // Read the RSSI of remote device with |addr| - static bool ReadRemoteRssi(const Addr& addr); - - // Request |mtu| on the connection with device |addr|. - static bool RequestMtu(const Addr& addr, int mtu); - - // Update connection parameters with device |addr|. - static bool ConnectionParameterUpdate(const Addr& addr, - int min_interval, - int max_interval, - int latency, - int timeout); - - // Retrieve the list of services on device |addr|. They will be returned in - // the callback |OnGetServices|. - static bool GetServices(const Addr& addr); - - // Clear pending connect request of remote device with |addr|. - static bool ClearPendingConnect(const Addr& addr) __attribute__((__weak__)); - - // Clear pending disconnect request of remote device with |addr|. - static bool ClearPendingDisconnect(const Addr& addr) - __attribute__((__weak__)); - }; - - // GATT Server role. Devices must implement the GATT server role in order to - // support Cast BLE setup. - class Server { - public: - class Delegate { - public: - // Called when a client connects or disconnects. - virtual void OnConnectionStateChanged(const Addr& addr, - bool connected) = 0; - - // Called when a service was added. |success| is false if it failed to add - // the service. - virtual void OnServiceAdded(bool success, const Service& service) = 0; - - // Called when a client requests a read on a characteristic. - virtual void OnCharacteristicReadRequest(const Addr& addr, - int request_id, - uint16_t handle, - int offset, - bool is_long) = 0; - - // Called when a client requests a write on a characteristic. - virtual void OnCharacteristicWriteRequest( - const Addr& addr, - int request_id, - uint16_t handle, - int offset, - bool is_prepare_write, - bool need_response, - const std::vector& value) = 0; - - // Called when a client requests a read on a descriptor. - virtual void OnDescriptorReadRequest(const Addr& addr, - int request_id, - uint16_t handle, - int offset, - bool is_long) = 0; - - // Called when a client requests a write on a descriptor. - virtual void OnDescriptorWriteRequest( - const Addr& addr, - int request_id, - uint16_t handle, - int offset, - bool is_prepare_write, - bool need_response, - const std::vector& value) = 0; - - // Called when a client performs a prepared write operation. If - // |is_execute| is false, then it clears the currently pending prepared - // write. - virtual void OnExecuteWriteRequest(const Addr& addr, - int request_id, - bool is_execute) = 0; - - // Called when SendNotification is complete. |success| is false if it - // failed. - virtual void OnNotificationSent(const Addr& addr, bool success) = 0; - - virtual ~Delegate() = default; - }; - - // Returns true if this interface is implemented. - static bool IsSupported(); - - static void SetDelegate(Delegate* delegate); - - // Add |Service| to this GATT Server. On completion, OnServiceAdded will be - // called. - static bool AddService(const Service& service); - - // Send a response to any of the callbacks with a |request_id| above. - static bool SendResponse(const Addr& addr, - int request_id, - Status status, - int offset, - const std::vector& value); - - // Send a characteristic value notification. - static bool SendNotification(const Addr& addr, - int handle, - bool confirm, - const std::vector& value); - }; -}; - -// Work around '[chromium-style] Complex class/struct needs an explicit -// out-of-line constructor.' -inline Gatt::Characteristic::Characteristic() = default; -inline Gatt::Characteristic::Characteristic(const Characteristic& other) = - default; -inline Gatt::Characteristic::~Characteristic() = default; - -inline Gatt::Service::Service() = default; -inline Gatt::Service::Service(const Service& other) = default; -inline Gatt::Service::~Service() = default; - -inline bool operator==(const Gatt::Descriptor& lhs, - const Gatt::Descriptor& rhs) { - return lhs.uuid == rhs.uuid && lhs.handle == rhs.handle && - lhs.permissions == rhs.permissions; -} - -inline bool operator==(const Gatt::Characteristic& lhs, - const Gatt::Characteristic& rhs) { - return lhs.uuid == rhs.uuid && lhs.handle == rhs.handle && - lhs.permissions == rhs.permissions && - lhs.properties == rhs.properties && lhs.descriptors == rhs.descriptors; -} - -} // namespace bluetooth_v2_shlib -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_BLUETOOTH_GATT_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/bluetooth/le_scanner.h chromium-132.0.6834.159/chromecast/public/bluetooth/le_scanner.h --- chromium-132.0.6834.110/chromecast/public/bluetooth/le_scanner.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/bluetooth/le_scanner.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_BLUETOOTH_LE_SCANNER_H_ -#define CHROMECAST_PUBLIC_BLUETOOTH_LE_SCANNER_H_ - -#include -#include - -#include "bluetooth_types.h" -#include "chromecast_export.h" - -namespace chromecast { -namespace bluetooth_v2_shlib { - -// Interface for BLE Scanner. -class CHROMECAST_EXPORT LeScanner { - public: - struct ScanResult { - ScanResult(Addr addr, const std::vector& adv_data, int rssi); - ScanResult(const ScanResult& other); - ~ScanResult(); - - const Addr addr; - const std::vector adv_data; - const int rssi; - }; - - class Delegate { - public: - virtual void OnScanResult(const ScanResult& scan_result) = 0; - - virtual ~Delegate() = default; - }; - - // Returns true if this interface is implemented. - static bool IsSupported(); - static void SetDelegate(Delegate* delegate); - - static bool StartScan(); - static bool StopScan(); - - static bool SetScanParameters(int scan_interval_ms, int scan_window_ms) - __attribute__((__weak__)); -}; - -inline LeScanner::ScanResult::ScanResult(Addr addr, const std::vector& adv_data, int rssi) : addr(std::move(addr)), adv_data(adv_data), rssi(rssi) {} -inline LeScanner::ScanResult::ScanResult(const LeScanner::ScanResult& other) = - default; -inline LeScanner::ScanResult::~ScanResult() = default; - -} // namespace bluetooth_v2_shlib -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_BLUETOOTH_LE_SCANNER_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/cast_egl_platform.h chromium-132.0.6834.159/chromecast/public/cast_egl_platform.h --- chromium-132.0.6834.110/chromecast/public/cast_egl_platform.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/cast_egl_platform.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_CAST_EGL_PLATFORM_H_ -#define CHROMECAST_PUBLIC_CAST_EGL_PLATFORM_H_ - -namespace chromecast { - -struct Size; - -// Interface representing all the hardware-specific elements of an Ozone -// implementation for Cast. Supply an implementation of this interface -// to OzonePlatformCast to create a complete Ozone implementation. -class CastEglPlatform { - public: - typedef void* (*GLGetProcAddressProc)(const char* name); - typedef void* NativeDisplayType; - typedef void* NativeWindowType; - - virtual ~CastEglPlatform() {} - - // Returns an array of EGL properties, which can be used in any EGL function - // used to select a display configuration. Note that all properties should be - // immediately followed by the corresponding desired value and array should be - // terminated with EGL_NONE. Ownership of the array is not transferred to - // caller. desired_list contains list of desired EGL properties and values. - virtual const int* GetEGLSurfaceProperties(const int* desired_list) = 0; - - // InitializeHardware is called once (before creating display type or window) - // and must return false on failure. - virtual bool InitializeHardware() = 0; - - // These three are called once after hardware is successfully initialized. - // The implementation must load the libraries containing EGL and GLES2 - // bindings (return the pointer obtained from dlopen). It must also supply - // a function pointer to eglGetProcAddress or equivalent. - virtual void* GetEglLibrary() = 0; - virtual void* GetGles2Library() = 0; - virtual GLGetProcAddressProc GetGLProcAddressProc() = 0; - - // Creates an EGLNativeDisplayType. Called once when initializing display. - virtual NativeDisplayType CreateDisplayType(const Size& size) = 0; - - // Creates an EGLNativeWindow using previously-created DisplayType. Called - // once when initializing display. - virtual NativeWindowType CreateWindow(NativeDisplayType display_type, - const Size& size) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_CAST_EGL_PLATFORM_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/cast_egl_platform_shlib.h chromium-132.0.6834.159/chromecast/public/cast_egl_platform_shlib.h --- chromium-132.0.6834.110/chromecast/public/cast_egl_platform_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/cast_egl_platform_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_CAST_EGL_PLATFORM_SHLIB_H_ -#define CHROMECAST_PUBLIC_CAST_EGL_PLATFORM_SHLIB_H_ - -#include -#include - -#include "chromecast_export.h" - -namespace chromecast { - -class CastEglPlatform; - -// Entry point for loading CastEglPlatform from shared library. -class CHROMECAST_EXPORT CastEglPlatformShlib { - public: - static CastEglPlatform* Create(const std::vector& argv); -}; - -} - -#endif // CHROMECAST_PUBLIC_CAST_EGL_PLATFORM_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/cast_media_shlib.h chromium-132.0.6834.159/chromecast/public/cast_media_shlib.h --- chromium-132.0.6834.110/chromecast/public/cast_media_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/cast_media_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_CAST_MEDIA_SHLIB_H_ -#define CHROMECAST_PUBLIC_CAST_MEDIA_SHLIB_H_ - -#include - -#include -#include -#include -#include -#include - -#include "chromecast_export.h" -#include "volume_control.h" - -namespace chromecast { -namespace media { - -enum SampleFormat : int; - -class MediaPipelineBackend; -struct MediaPipelineDeviceParams; -class VideoPlane; - -// Provides access to platform-specific media systems and hardware resources. -// In cast_shell, all usage is from the browser process. An implementation is -// assumed to be in an uninitialized state initially. When uninitialized, no -// API calls will be made except for Initialize, which brings the implementation -// into an initialized state. A call to Finalize returns the implementation to -// its uninitialized state. The implementation must support multiple -// transitions between these states, to support resource grant/revoke events and -// also to allow multiple unit tests to bring up the media systems in isolation -// from other tests. -class CHROMECAST_EXPORT CastMediaShlib { - public: - using ResultCallback = - std::function; - - // Initializes platform-specific media systems. Only called when in an - // uninitialized state. - static void Initialize(const std::vector& argv); - - // Tears down platform-specific media systems and returns to the uninitialized - // state. The implementation must release all media-related hardware - // resources. - static void Finalize(); - - // Gets the VideoPlane instance for managing the hardware video plane. - // While an implementation is in an initialized state, this function may be - // called at any time. The VideoPlane object must be destroyed in Finalize. - static VideoPlane* GetVideoPlane(); - - // Creates a media pipeline backend. Called in the browser process for each - // media pipeline and raw audio stream. The caller owns the returned - // MediaPipelineBackend instance. - static MediaPipelineBackend* CreateMediaPipelineBackend( - const MediaPipelineDeviceParams& params); - - // Fetches the renderer clock rate (Hz). - static double GetMediaClockRate(); - - // Fetches the granularity of clock rate adjustments. - static double MediaClockRatePrecision(); - - // Fetches the possible range of clock rate adjustments. - static void MediaClockRateRange(double* minimum_rate, double* maximum_rate); - - // Sets the renderer clock rate (Hz). - static bool SetMediaClockRate(double new_rate); - - // Tests if the implementation supports renderer clock rate adjustments. - static bool SupportsMediaClockRateChange(); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_CAST_MEDIA_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/cast_sys_info.h chromium-132.0.6834.159/chromecast/public/cast_sys_info.h --- chromium-132.0.6834.110/chromecast/public/cast_sys_info.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/cast_sys_info.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_CAST_SYS_INFO_H_ -#define CHROMECAST_PUBLIC_CAST_SYS_INFO_H_ - -#include -#include - -#include "chromecast_export.h" - -namespace chromecast { - -// Pure abstract interface for system information which is accessed by other -// processes as well as cast_shell browser process. All information should be -// immutable. -// It should be possible to instantiate multiple instances of CastSysInfo and -// should be able to be instantiated at any point in the startup process. Other -// processes must be able to create an instance of CastSysInfo. -class CastSysInfo { - public: - enum BuildType { - BUILD_ENG, - BUILD_BETA, - BUILD_PRODUCTION, - }; - - virtual ~CastSysInfo() {} - - // Returns the system build type. - virtual BuildType GetBuildType() = 0; - // Returns release channel of system. - virtual std::string GetSystemReleaseChannel() = 0; - // Returns serial number of the device. - virtual std::string GetSerialNumber() = 0; - // Returns product code name of the device. - virtual std::string GetProductName() = 0; - // Returns product sku code name of the device. - static CHROMECAST_EXPORT std::string GetProductSkuName( - CastSysInfo* cast_sys_info) __attribute__((__weak__)); - - // Returns model name of device (eg: Chromecast, Nexus Player, ...). - virtual std::string GetDeviceModel() = 0; - // Returns the board's name. - virtual std::string GetBoardName() = 0; - // Returns the revision of board (eg: 514, ...). - virtual std::string GetBoardRevision() = 0; - // Returns device manufacturer (eg: Google, ...). - virtual std::string GetManufacturer() = 0; - // Returns the system's build number (eg: 100, 20000 ...). - // This describes system version which may be different with - // CAST_BUILD_NUMBER. - virtual std::string GetSystemBuildNumber() = 0; - // Returns signing epoch time. - static CHROMECAST_EXPORT std::string GetSigningEpoch() - __attribute__((__weak__)); - - // Returns default country and locale baked from the factory. - virtual std::string GetFactoryCountry() = 0; - - // Returns arbitrary number of factory locales, should return {"en-US"} if no - // locales are configured. - virtual std::vector GetFactoryLocaleList() = 0; - - // Returns the name of the wifi interface used to connect to the internet. - virtual std::string GetWifiInterface() = 0; - // Returns the name of the software AP interface. - virtual std::string GetApInterface() = 0; - - // Returns the setup SSID suffix to use, if configured, an empty string - // otherwise. - virtual std::string GetProductSsidSuffix() = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_CAST_SYS_INFO_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/cast_sys_info_shlib.h chromium-132.0.6834.159/chromecast/public/cast_sys_info_shlib.h --- chromium-132.0.6834.110/chromecast/public/cast_sys_info_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/cast_sys_info_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_CAST_SYS_INFO_SHLIB_H_ -#define CHROMECAST_PUBLIC_CAST_SYS_INFO_SHLIB_H_ - -#include -#include - -#include "chromecast_export.h" - -namespace chromecast { - -class CastSysInfo; - -class CHROMECAST_EXPORT CastSysInfoShlib { - public: - // Returns a instance of CastSysInfo for the platform from a shared library. - // Caller will take ownership of returned pointer. - static CastSysInfo* Create(const std::vector& argv); -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_CAST_SYS_INFO_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/chromecast_export.h chromium-132.0.6834.159/chromecast/public/chromecast_export.h --- chromium-132.0.6834.110/chromecast/public/chromecast_export.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/chromecast_export.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_CHROMECAST_EXPORT_H_ -#define CHROMECAST_PUBLIC_CHROMECAST_EXPORT_H_ - -// Export attribute for classes that are exposed in shared libraries, -// allowing OEM partners to replace with their own implementations. -#define CHROMECAST_EXPORT __attribute__((visibility("default"))) - -#endif // CHROMECAST_PUBLIC_CHROMECAST_EXPORT_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/graphics_properties_shlib.h chromium-132.0.6834.159/chromecast/public/graphics_properties_shlib.h --- chromium-132.0.6834.110/chromecast/public/graphics_properties_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/graphics_properties_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_GRAPHICS_PROPERTIES_SHLIB_H_ -#define CHROMECAST_PUBLIC_GRAPHICS_PROPERTIES_SHLIB_H_ - -#include -#include - -#include "chromecast_export.h" - -namespace chromecast { - -class CHROMECAST_EXPORT GraphicsPropertiesShlib { - public: - // Optional resolutions that cast_shell queries for. 720p (1280x720) is - // assumed to be supported. - enum Resolution { - k1080p, // 1920x1080 - kUHDTV // 3840x2160 - }; - - // Returns whether or not the given display resolution is supported. - // Called in the browser process; command line args are provided. - static bool IsSupported(Resolution resolution, - const std::vector& argv); -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_GRAPHICS_PROPERTIES_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/graphics_types.h chromium-132.0.6834.159/chromecast/public/graphics_types.h --- chromium-132.0.6834.110/chromecast/public/graphics_types.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/graphics_types.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_GRAPHICS_TYPES_H_ -#define CHROMECAST_PUBLIC_GRAPHICS_TYPES_H_ - -namespace chromecast { - -struct Rect { - Rect(int w, int h) : x(0), y(0), width(w), height(h) {} - Rect(int arg_x, int arg_y, int w, int h) - : x(arg_x), y(arg_y), width(w), height(h) {} - - int x; - int y; - int width; - int height; -}; - -struct RectF { - RectF(float w, float h) : x(0), y(0), width(w), height(h) {} - RectF(float arg_x, float arg_y, float w, float h) - : x(arg_x), y(arg_y), width(w), height(h) {} - - float x; - float y; - float width; - float height; -}; - -struct Size { - Size(int w, int h) : width(w), height(h) {} - - int width; - int height; -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_GRAPHICS_TYPES_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/audio_post_processor2_shlib.h chromium-132.0.6834.159/chromecast/public/media/audio_post_processor2_shlib.h --- chromium-132.0.6834.110/chromecast/public/media/audio_post_processor2_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/audio_post_processor2_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,133 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_MEDIA_AUDIO_POST_PROCESSOR2_SHLIB_H_ -#define CHROMECAST_PUBLIC_MEDIA_AUDIO_POST_PROCESSOR2_SHLIB_H_ - -#include - -#include "volume_control.h" - -// Plugin interface for audio DSP modules. -// This is applicable only to audio CMA backends (Alsa, Fuscia). -// -// Please refer to -// chromecast/media/cma/backend/post_processors/governor_shlib.cc -// as an example for new code, but OEM's implementations should not have any -// Chromium dependencies. -// -// Please refer to -// chromecast/media/cma/backend/post_processors/post_processor_wrapper.h for an -// example of how to port an existing AudioPostProcessor to AudioPostProcessor2 -// -// Notes on PostProcessors that have a different number of in/out channels: -// * PostProcessor authors are free to define their channel order; Cast will -// simply pass this data to subsequent PostProcessors and MixerOutputStream. -// * Channel selection for stereo pairs will occur after the "mix" group, so -// devices that support stereo pairs should only change the number of -// in the "linearize" group of cast_audio.json. - -namespace chromecast { -namespace media { - -// Interface for AudioPostProcessors used for applying DSP in StreamMixer. -class AudioPostProcessor2 { - public: - struct Config { - int output_sample_rate; // The output sample rate for this processor. - int system_output_sample_rate; // The system (hardware) output sample rate. - // The number of output frames expected from ProcessFrames(). - int output_frames_per_write; - }; - - struct Metadata { - // The maximum volume multiplier applied to the current buffer, in dBFS. - float volume_dbfs; - - // The (max) current target volume multiplier that we are slewing towards. - float target_volume_dbfs; - - // The system volume applied to the stream (normalized to 0-1). Equivalent - // to DbFSToVolume(volume_dbfs). - float system_volume; - }; - - struct Status { - int input_sample_rate = -1; - int output_channels = -1; - - // The group delay, measured in frames at the input sample rate. See - // chromecast/media/cma/backend/post_processors/post_processor_unittest.cc - // for how this is tested. - int rendering_delay_frames = 0; - - // The number of input frames of silence it will take for the processor to - // come to rest after playing out audio. - // In the case of an FIR filter, this is the length of the FIR kernel. - // In the case of IIR filters, this should be calculated as the number of - // frames for the output to decay to 10% (5 time constants). - // When inputs are paused, at least |GetRingingTimeInFrames()| of - // silence will be passed through the processor. - int ringing_time_frames = 0; - - // The data buffer in which the last output from ProcessFrames() was stored. - // This will never be called before ProcessFrames(). - // This data location should be valid until ProcessFrames() is called - // again. - // The data returned by GetOutputBuffer() should not be modified by this - // instance until the next call to ProcessFrames(). - // If |channels_in| >= |channels_out|, this may be |data| from the - // last call to ProcessFrames(). - // If |channels_in| < |channels_out|, this PostProcessor is responsible for - // allocating an output buffer. - // If PostProcessor owns |output_buffer|, it must ensure that the memory - // is valid until the next call to ProcessFrames() or destruction. - float* output_buffer = nullptr; - }; - - virtual ~AudioPostProcessor2() = default; - - // Sets the Config of the processor. - // Returns |false| if the processor cannot support |config| - virtual bool SetConfig(const Config& config) = 0; - - // Returns the processor's generated settings. Post processors should keep - // an up-to-date Status as a member variable. - virtual const Status& GetStatus() = 0; - - // Processes audio frames from |data|. - // This will never be called before SetOutputSampleRate(). - // ProcessFrames may overwrite |data|, in which case GetOutputBuffer() should - // return |data|. - // |data| will be 32-bit interleaved float with |channels_in| channels. - // ProcessFrames must produce an equal duration of audio as was input, - // allowing for sample rate / channel count changes. If the output data - // will take up equal or less space than the input data, ProcessFrames() - // should overwrite the input data and store a pointer to |data| in |Status|. - // Otherwise, the Processor should allocate and own its own output buffer. - virtual void ProcessFrames(float* data, int frames, Metadata* metadata) = 0; - - // Sends a message to the PostProcessor. Implementations are responsible - // for the format and parsing of messages. - // Returns |true| if the message was accepted or |false| if the message could - // not be applied (i.e. invalid parameter, format error, parameter out of - // range, etc). - // If the PostProcessor can/will not be updated at runtime, this can be - // implemented as "return false;" - virtual bool UpdateParameters(const std::string& message) = 0; - - // Sets content type to the PostProcessor so it could change processing - // settings accordingly. - virtual void SetContentType(AudioContentType content_type) {} - - // Called when device is playing as part of a stereo pair. - // |channel| is the playout channel on this device (0 for left, 1 for right). - // or -1 if the device is not part of a stereo pair. - virtual void SetPlayoutChannel(int channel) {} -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_AUDIO_POST_PROCESSOR2_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/audio_post_processor_shlib.h chromium-132.0.6834.159/chromecast/public/media/audio_post_processor_shlib.h --- chromium-132.0.6834.110/chromecast/public/media/audio_post_processor_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/audio_post_processor_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_MEDIA_AUDIO_POST_PROCESSOR_SHLIB_H_ -#define CHROMECAST_PUBLIC_MEDIA_AUDIO_POST_PROCESSOR_SHLIB_H_ - -#include -#include - -#include "chromecast_export.h" -#include "volume_control.h" - -namespace chromecast { -namespace media { -class AudioPostProcessor; -} // namespace media -} // namespace chromecast - -// Creates an AudioPostProcessor. -// This is applicable only to Alsa CMA backend. -// Please refer to -// chromecast/media/cma/backend/post_processors/governor_shlib.cc -// as an example, but OEM's implementations should not have any -// Chromium dependencies. -// Called from StreamMixerAlsa when shared objects are listed in -// /etc/cast_audio.json -// AudioPostProcessors are created on startup and only destroyed/reset -// if the output sample rate changes. -extern "C" CHROMECAST_EXPORT chromecast::media::AudioPostProcessor* -AudioPostProcessorShlib_Create(const std::string& config, int channels); - -namespace chromecast { -namespace media { - -// The maximum amount of data that will ever be processed in one call. -const int kMaxAudioWriteTimeMilliseconds = 20; - -// Interface for AudioPostProcessors used for applying DSP in StreamMixerAlsa. -class AudioPostProcessor { - public: - // Updates the sample rate of the processor. - // Returns |false| if the processor cannot support |sample_rate| - // Returning false will result in crashing cast_shell. - virtual bool SetSampleRate(int sample_rate) = 0; - - // Processes audio frames from |data|, overwriting contents. - // |data| will always be 32-bit interleaved float. - // |frames| is the number of audio frames in data and is - // always non-zero and less than or equal to 20ms of audio. - // AudioPostProcessor must always provide |frames| frames of data back - // (may output 0’s) - // |system_volume| is the Cast Volume applied to the stream - // (normalized to 0-1). It is the same as the cast volume set via alsa. - // |volume_dbfs| is the actual attenuation in dBFS (-inf to 0), equivalent to - // VolumeMap::VolumeToDbFS(|volume|). - // AudioPostProcessor should assume that volume has already been applied. - // Returns the current rendering delay of the filter in frames, - // or negative if an error occurred during processing. - // If an error occurred during processing, |data| should be unchanged. - virtual int ProcessFrames(float* data, - int frames, - float system_volume, - float volume_dbfs) = 0; - - // Returns the number of frames of silence it will take for the - // processor to come to rest. - // This may be the actual number of frames stored, - // or may be calculated from internal resonators or similar. - // When inputs are paused, at least this |GetRingingTimeInFrames()| of - // silence will be passed through the processor. - // This is not expected to be real-time; - // It should only change when SetSampleRate is called. - virtual int GetRingingTimeInFrames() = 0; - - // Sends a message to the PostProcessor. Implementations are responsible - // for the format and parsing of messages. - // OEM's do not need to implement this method. - virtual void UpdateParameters(const std::string& message) {} - - // Set content type to the PostProcessor so it could change processing - // settings accordingly. - virtual void SetContentType(AudioContentType content_type) {} - - // Called when device is playing as part of a stereo pair. - // |channel| is the playout channel on this device (0 for left, 1 for right). - // or -1 if the device is not part of a stereo pair. - virtual void SetPlayoutChannel(int channel) {} - - virtual ~AudioPostProcessor() = default; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_AUDIO_POST_PROCESSOR_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/cast_decoder_buffer.h chromium-132.0.6834.159/chromecast/public/media/cast_decoder_buffer.h --- chromium-132.0.6834.110/chromecast/public/media/cast_decoder_buffer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/cast_decoder_buffer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_CAST_DECODER_BUFFER_H_ -#define CHROMECAST_PUBLIC_MEDIA_CAST_DECODER_BUFFER_H_ - -#include -#include - -#include "stream_id.h" - -namespace chromecast { -namespace media { - -class CastDecryptConfig; -class DecryptContext; - -// CastDecoderBuffer provides an interface for passing a single frame of audio -// or video data to the pipeline backend. End-of-stream is indicated by passing -// a frame where end_of_stream() returns true. -// The buffer's lifetime is managed by the caller code - it MUST NOT be -// deleted by the MediaPipelineBackend implementation, and MUST NOT be -// dereferenced after completion of buffer push (i.e. -// kBufferSuccess/kBufferFailure for synchronous completion, OnPushComplete -// for kBufferPending case). -// TODO(halliwell): consider renaming functions here to camel case. -class CastDecoderBuffer { - public: - virtual ~CastDecoderBuffer() {} - - // Returns the stream id of this decoder buffer. - virtual StreamId stream_id() const = 0; - - // Returns the PTS of the frame in microseconds. - virtual int64_t timestamp() const = 0; - - // Gets the frame data. - virtual const uint8_t* data() const = 0; - - // Returns the size of the frame in bytes. - virtual size_t data_size() const = 0; - - // Returns the decrypt configuration. - // Returns nullptr if and only if the buffer is unencrypted. - virtual const CastDecryptConfig* decrypt_config() const = 0; - - // Returns the decrypt context. Returns nullptr if and only if the buffer is - // unencrypted. - virtual DecryptContext* decrypt_context() const = 0; - - // Indicates if this is a special frame that indicates the end of the stream. - // If true, functions to access the frame content cannot be called. - virtual bool end_of_stream() const = 0; - - // Indicates if this is a key frame. Only relevant to buffers containing video - // data. - virtual bool is_key_frame() const = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_CAST_DECODER_BUFFER_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/cast_decrypt_config.h chromium-132.0.6834.159/chromecast/public/media/cast_decrypt_config.h --- chromium-132.0.6834.110/chromecast/public/media/cast_decrypt_config.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/cast_decrypt_config.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_CAST_DECRYPT_CONFIG_H_ -#define CHROMECAST_PUBLIC_MEDIA_CAST_DECRYPT_CONFIG_H_ - -#include -#include -#include - -namespace chromecast { -namespace media { - -// Specification of whether and how the stream is encrypted (in whole or part). -// -// Algorithm and mode that was used to encrypt the stream. -enum class EncryptionScheme { kUnencrypted, kAesCtr, kAesCbc }; - -// CENC 3rd Edition adds pattern encryption, through two new protection -// schemes: 'cens' (with AES-CTR) and 'cbcs' (with AES-CBC). -// The pattern applies independently to each 'encrypted' part of the frame (as -// defined by the relevant subsample entries), and reduces further the -// actual encryption applied through a repeating pattern of (encrypt:skip) -// 16 byte blocks. For example, in a (1:9) pattern, the first block is -// encrypted, and the next nine are skipped. This pattern is applied -// repeatedly until the end of the last 16-byte block in the subsample. -// Any remaining bytes are left clear. -// If either of encrypt_blocks or skip_blocks is 0, pattern encryption is -// disabled. -struct EncryptionPattern { - EncryptionPattern() = default; - EncryptionPattern(uint32_t encrypt_blocks, uint32_t skip_blocks); - bool IsInEffect() const; - - uint32_t encrypt_blocks = 0; - uint32_t skip_blocks = 0; -}; - -inline EncryptionPattern::EncryptionPattern(uint32_t encrypt_blocks, - uint32_t skip_blocks) - : encrypt_blocks(encrypt_blocks), skip_blocks(skip_blocks) {} - -inline bool EncryptionPattern::IsInEffect() const { - return encrypt_blocks != 0 && skip_blocks != 0; -} - -// The Common Encryption spec provides for subsample encryption, where portions -// of a sample are set in cleartext. A SubsampleEntry specifies the number of -// clear and encrypted bytes in each subsample. For decryption, all of the -// encrypted bytes in a sample should be considered a single logical stream, -// regardless of how they are divided into subsamples, and the clear bytes -// should not be considered as part of decryption. This is logically equivalent -// to concatenating all 'cypher_bytes' portions of subsamples, decrypting that -// result, and then copying each byte from the decrypted block over the -// position of the corresponding encrypted byte. -struct SubsampleEntry { - SubsampleEntry() : clear_bytes(0), cypher_bytes(0) {} - SubsampleEntry(uint32_t clear_bytes, uint32_t cypher_bytes) - : clear_bytes(clear_bytes), cypher_bytes(cypher_bytes) {} - uint32_t clear_bytes; - uint32_t cypher_bytes; -}; - -// Contains all metadata needed to decrypt a media sample. -class CastDecryptConfig { - public: - virtual ~CastDecryptConfig() = default; - - // Returns the ID for this sample's decryption key. - virtual const std::string& key_id() const = 0; - - // Returns the initialization vector as defined by the encryption format. - virtual const std::string& iv() const = 0; - - // Returns the encryption pattern for current sample. - virtual const EncryptionPattern& pattern() const = 0; - - // Returns the clear and encrypted portions of the sample as described above. - virtual const std::vector& subsamples() const = 0; - - // Returns the encryption scheme for this sample. - virtual EncryptionScheme encryption_scheme() const = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_CAST_DECRYPT_CONFIG_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/cast_key_status.h chromium-132.0.6834.159/chromecast/public/media/cast_key_status.h --- chromium-132.0.6834.110/chromecast/public/media/cast_key_status.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/cast_key_status.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_CAST_KEY_STATUS_H_ -#define CHROMECAST_PUBLIC_MEDIA_CAST_KEY_STATUS_H_ - -namespace chromecast { -namespace media { - -// Status of encryption key. See EME spec for details: -// https://w3c.github.io/encrypted-media/ - not all key status values -// are supported currently. -enum CastKeyStatus { KEY_STATUS_USABLE = 0, KEY_STATUS_EXPIRED }; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_CAST_KEY_STATUS_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/cast_key_system.h chromium-132.0.6834.159/chromecast/public/media/cast_key_system.h --- chromium-132.0.6834.110/chromecast/public/media/cast_key_system.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/cast_key_system.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_CAST_KEY_SYSTEM_H_ -#define CHROMECAST_PUBLIC_MEDIA_CAST_KEY_SYSTEM_H_ - -namespace chromecast { -namespace media { - -// Specifies the encryption key system used by a given buffer. -// TODO(yucliu): Remove KEY_SYSTEM_CLEAR_KEY in next 3P Linux Update. -enum CastKeySystem { - KEY_SYSTEM_NONE = 0, - KEY_SYSTEM_CLEAR_KEY, - KEY_SYSTEM_PLAYREADY, - KEY_SYSTEM_WIDEVINE -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_CAST_KEY_SYSTEM_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/decoder_config.h chromium-132.0.6834.159/chromecast/public/media/decoder_config.h --- chromium-132.0.6834.110/chromecast/public/media/decoder_config.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/decoder_config.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,411 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_DECODER_CONFIG_H_ -#define CHROMECAST_PUBLIC_MEDIA_DECODER_CONFIG_H_ - -#include - -#include - -#include "cast_decrypt_config.h" -#include "stream_id.h" - -namespace chromecast::media { - -// Maximum audio bytes per sample. -static const int kMaxBytesPerSample = 4; - -// Maximum audio sampling rate. -static const int kMaxSampleRate = 192000; - -// TODO(guohuideng): change at least AudioCodec and SampleFormat to enum class. -enum AudioCodec : int { - kAudioCodecUnknown = 0, - kCodecAAC, - kCodecMP3, - kCodecPCM, - kCodecPCM_S16BE, - kCodecVorbis, - kCodecOpus, - kCodecEAC3, - kCodecAC3, - kCodecDTS, - kCodecFLAC, - kCodecMpegHAudio, - kCodecDTSXP2, - kCodecDTSE, - - kAudioCodecMin = kAudioCodecUnknown, - kAudioCodecMax = kCodecDTSE, -}; - -enum class ChannelLayout { - UNSUPPORTED, - - // Front C - MONO, - - // Front L, Front R - STEREO, - - // Front L, Front R, Front C, LFE, Side L, Side R - SURROUND_5_1, - - // Actual channel layout is specified in the bitstream and the actual channel - // count is unknown at Chromium media pipeline level (useful for audio - // pass-through mode). - BITSTREAM, - - // Channels are not explicitly mapped to speakers. - DISCRETE, - - // Max value, must always equal the largest entry ever logged. - MAX_LAST = DISCRETE, -}; - -// Internal chromecast apps use this to decide on channel_layout. -inline ChannelLayout ChannelLayoutFromChannelNumber(int channel_number) { - switch (channel_number) { - case 1: - return ChannelLayout::MONO; - case 2: - return ChannelLayout::STEREO; - case 6: - return ChannelLayout::SURROUND_5_1; - default: - return ChannelLayout::UNSUPPORTED; - } -} - -enum SampleFormat : int { - kUnknownSampleFormat = 0, - kSampleFormatU8, // Unsigned 8-bit w/ bias of 128. - kSampleFormatS16, // Signed 16-bit. - kSampleFormatS32, // Signed 32-bit. - kSampleFormatF32, // Float 32-bit. - kSampleFormatPlanarS16, // Signed 16-bit planar. - kSampleFormatPlanarF32, // Float 32-bit planar. - kSampleFormatPlanarS32, // Signed 32-bit planar. - kSampleFormatS24, // Signed 24-bit. - kSampleFormatPlanarU8, // Unsigned 8-bit w/ bias of 128 planar. - - kSampleFormatMin = kUnknownSampleFormat, - kSampleFormatMax = kSampleFormatPlanarU8, -}; - -enum VideoCodec : int { - kVideoCodecUnknown = 0, - kCodecH264, - kCodecVC1, - kCodecMPEG2, - kCodecMPEG4, - kCodecTheora, - kCodecVP8, - kCodecVP9, - kCodecHEVC, - kCodecDolbyVisionH264, - kCodecDolbyVisionHEVC, - kCodecAV1, - - kVideoCodecMin = kVideoCodecUnknown, - kVideoCodecMax = kCodecAV1, -}; - -// Profile for Video codec. -enum VideoProfile : int { - kVideoProfileUnknown = 0, - kH264Baseline, - kH264Main, - kH264Extended, - kH264High, - kH264High10, - kH264High422, - kH264High444Predictive, - kH264ScalableBaseline, - kH264ScalableHigh, - kH264StereoHigh, - kH264MultiviewHigh, - kVP8ProfileAny, - kVP9Profile0, - kVP9Profile1, - kVP9Profile2, - kVP9Profile3, - kDolbyVisionProfile0, - kDolbyVisionProfile5, - kDolbyVisionProfile7, - kHEVCMain, - kHEVCMain10, - kHEVCMainStillPicture, - kAV1ProfileMain, - kAV1ProfileHigh, - kAV1ProfilePro, - kDolbyVisionProfile8, - kDolbyVisionProfile9, - kHEVCRext, - kHEVCHighThroughput, - kHEVCMultiviewMain, - kHEVCScalableMain, - kHEVC3dMain, - kHEVCScreenExtended, - kHEVCScalableRext, - kHEVCHighThroughputScreenExtended, - kVVCProfileMain10, - kVVCProfileMain12, - kVVCProfileMain12Intra, - kVVCProfileMultilayerMain10, - kVVCProfileMain10444, - kVVCProfileMain12444, - kVVCProfileMain16444, - kVVCProfileMain12444Intra, - kVVCProfileMain16444Intra, - kVVCProfileMultilayerMain10444, - kVVCProfileMain10Still, - kVVCProfileMain12Still, - kVVCProfileMain10444Still, - kVVCProfileMain12444Still, - kVVCProfileMain16444Still, - - kVideoProfileMin = kVideoProfileUnknown, - kVideoProfileMax = kVVCProfileMain16444Still, -}; - -struct CodecProfileLevel { - VideoCodec codec; - VideoProfile profile; - int level; -}; - -// ---- Begin copy/paste from //media/base/video_color_space.h ---- -// Described in ISO 23001-8:2016 - -// Table 2 -enum class PrimaryID : uint8_t { - INVALID = 0, - BT709 = 1, - UNSPECIFIED = 2, - BT470M = 4, - BT470BG = 5, - SMPTE170M = 6, - SMPTE240M = 7, - FILM = 8, - BT2020 = 9, - SMPTEST428_1 = 10, - SMPTEST431_2 = 11, - SMPTEST432_1 = 12, - EBU_3213_E = 22 -}; - -// Table 3 -enum class TransferID : uint8_t { - INVALID = 0, - BT709 = 1, - UNSPECIFIED = 2, - GAMMA22 = 4, - GAMMA28 = 5, - SMPTE170M = 6, - SMPTE240M = 7, - LINEAR = 8, - LOG = 9, - LOG_SQRT = 10, - IEC61966_2_4 = 11, - BT1361_ECG = 12, - IEC61966_2_1 = 13, - BT2020_10 = 14, - BT2020_12 = 15, - SMPTEST2084 = 16, - SMPTEST428_1 = 17, - - // Not yet standardized - ARIB_STD_B67 = 18, // AKA hybrid-log gamma, HLG. -}; - -// Table 4 -enum class MatrixID : uint8_t { - RGB = 0, - BT709 = 1, - UNSPECIFIED = 2, - FCC = 4, - BT470BG = 5, - SMPTE170M = 6, - SMPTE240M = 7, - YCOCG = 8, - BT2020_NCL = 9, - BT2020_CL = 10, - YDZDX = 11, - INVALID = 255, -}; -// ---- End copy/pasted from media/base/video_color_space.h ---- - -// This corresponds to the WebM Range enum which is part of WebM color data -// (see http://www.webmproject.org/docs/container/#Range). -// H.264 only uses a bool, which corresponds to the LIMITED/FULL values. -// ---- Begin copy/paste from //ui/gfx/color_space.h ---- -enum class RangeID : int8_t { - INVALID = 0, - // Limited Rec. 709 color range with RGB values ranging from 16 to 235. - LIMITED = 1, - // Full RGB color range with RGB values from 0 to 255. - FULL = 2, - // Range is defined by TransferID/MatrixID. - DERIVED = 3, - LAST = DERIVED -}; -// ---- Begin copy/paste from //ui/gfx/color_space.h ---- - -// ---- Begin copy/paste from //ui/gfx/hdr_metadata.h ---- -// SMPTE ST 2086 color volume metadata. -struct ColorVolumeMetadata { - float primary_r_chromaticity_x = 0; - float primary_r_chromaticity_y = 0; - float primary_g_chromaticity_x = 0; - float primary_g_chromaticity_y = 0; - float primary_b_chromaticity_x = 0; - float primary_b_chromaticity_y = 0; - float white_point_chromaticity_x = 0; - float white_point_chromaticity_y = 0; - float luminance_max = 0; - float luminance_min = 0; - - ColorVolumeMetadata(); - ColorVolumeMetadata(const ColorVolumeMetadata& rhs); - ColorVolumeMetadata& operator=(const ColorVolumeMetadata& rhs); -}; - -// HDR metadata common for HDR10 and WebM/VP9-based HDR formats. -struct HDRMetadata { - ColorVolumeMetadata color_volume_metadata; - unsigned max_content_light_level = 0; - unsigned max_frame_average_light_level = 0; - - HDRMetadata(); - HDRMetadata(const HDRMetadata& rhs); - HDRMetadata& operator=(const HDRMetadata& rhs); -}; - -inline ColorVolumeMetadata::ColorVolumeMetadata() = default; -inline ColorVolumeMetadata::ColorVolumeMetadata(const ColorVolumeMetadata&) = - default; -inline ColorVolumeMetadata& ColorVolumeMetadata::operator=( - const ColorVolumeMetadata&) = default; - -inline HDRMetadata::HDRMetadata() = default; -inline HDRMetadata::HDRMetadata(const HDRMetadata&) = default; -inline HDRMetadata& HDRMetadata::operator=(const HDRMetadata&) = default; -// ---- End copy/paste from //ui/gfx/hdr_metadata.h ---- - -constexpr int kChannelAll = -1; - -// TODO(erickung): Remove constructor once CMA backend implementation doesn't -// create a new object to reset the configuration and use IsValidConfig() to -// determine if the configuration is still valid or not. -struct AudioConfig { - AudioConfig(); - AudioConfig(const AudioConfig& other); - ~AudioConfig(); - - bool is_encrypted() const { - return encryption_scheme != EncryptionScheme::kUnencrypted; - } - - // Stream id. - StreamId id = StreamId::kPrimary; - // Audio codec. - AudioCodec codec = AudioCodec::kAudioCodecUnknown; - // Audio channel layout. - ChannelLayout channel_layout = ChannelLayout::UNSUPPORTED; - // The format of each audio sample. - SampleFormat sample_format = SampleFormat::kUnknownSampleFormat; - // Number of bytes in each channel. - int bytes_per_channel = 0; - // Number of channels in this audio stream. - int channel_number = 0; - // Number of audio samples per second. - int samples_per_second = 0; - // Extra data buffer for certain codec initialization. - std::vector extra_data; - // Encryption scheme (if any) used for the content. - EncryptionScheme encryption_scheme = EncryptionScheme::kUnencrypted; - // Hardware AV sync flag. - bool use_hw_av_sync = false; - // The session id which the Android AudioTrack will be attached to. If not - // valid, a new one will be atomically generated by the Android system. - // For Cast Connect Multizone use case, if the app uses hardware av sync, - // mediashell will get the id of the media session opened by the app. - int audio_track_session_id = 0; -}; - -inline AudioConfig::AudioConfig() = default; -inline AudioConfig::AudioConfig(const AudioConfig& other) = default; -inline AudioConfig::~AudioConfig() = default; - -// TODO(erickung): Remove constructor once CMA backend implementation does't -// create a new object to reset the configuration and use IsValidConfig() to -// determine if the configuration is still valid or not. -struct VideoConfig { - VideoConfig(); - VideoConfig(const VideoConfig& other); - ~VideoConfig(); - - bool is_encrypted() const { - return encryption_scheme != EncryptionScheme::kUnencrypted; - } - - // Stream Id. - StreamId id = StreamId::kPrimary; - // Video codec. - VideoCodec codec = VideoCodec::kVideoCodecUnknown; - // Video codec profile. - VideoProfile profile = VideoProfile::kVideoProfileUnknown; - // Video codec level. - uint32_t codec_profile_level = 0; - // Additional video config for the video stream if available. Consumers of - // this structure should make an explicit copy of |additional_config| if it - // will be used after SetConfig() finishes. - VideoConfig* additional_config = nullptr; - // Extra data buffer for certain codec initialization. - std::vector extra_data; - // Encryption scheme (if any) used for the content. - EncryptionScheme encryption_scheme = EncryptionScheme::kUnencrypted; - - // ColorSpace info - PrimaryID primaries = PrimaryID::UNSPECIFIED; - TransferID transfer = TransferID::UNSPECIFIED; - MatrixID matrix = MatrixID::UNSPECIFIED; - RangeID range = RangeID::INVALID; - - bool have_hdr_metadata = false; - HDRMetadata hdr_metadata; - - // Info about the width and height, in pixels. - int width = 0; - int height = 0; -}; - -inline VideoConfig::VideoConfig() = default; -inline VideoConfig::VideoConfig(const VideoConfig& other) = default; -inline VideoConfig::~VideoConfig() = default; - -inline bool IsValidConfig(const AudioConfig& config) { - return config.codec >= kAudioCodecMin && config.codec <= kAudioCodecMax && - config.codec != kAudioCodecUnknown && - config.channel_layout != ChannelLayout::UNSUPPORTED && - config.sample_format >= kSampleFormatMin && - config.sample_format <= kSampleFormatMax && - ((config.sample_format != kUnknownSampleFormat && - config.channel_number > 0 && config.bytes_per_channel > 0 && - config.bytes_per_channel <= kMaxBytesPerSample) || - config.channel_layout == ChannelLayout::BITSTREAM) && - config.samples_per_second > 0 && - config.samples_per_second <= kMaxSampleRate; -} - -inline bool IsValidConfig(const VideoConfig& config) { - return config.codec >= kVideoCodecMin && config.codec <= kVideoCodecMax && - config.codec != kVideoCodecUnknown; -} - -} // namespace chromecast::media - -#endif // CHROMECAST_PUBLIC_MEDIA_DECODER_CONFIG_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/decrypt_context.h chromium-132.0.6834.159/chromecast/public/media/decrypt_context.h --- chromium-132.0.6834.110/chromecast/public/media/decrypt_context.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/decrypt_context.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_DECRYPT_CONTEXT_H_ -#define CHROMECAST_PUBLIC_MEDIA_DECRYPT_CONTEXT_H_ - -#include - -#include "cast_key_system.h" - -namespace chromecast { -namespace media { -class CastDecoderBuffer; - -// Provides the information needed to decrypt frames. -class DecryptContext { - public: - virtual ~DecryptContext() {} - - // Get the key system to use for decryption. - virtual CastKeySystem GetKeySystem() = 0; - - // Decrypts the given buffer. Returns true/false for success/failure. - // - // |opaque_handle| is a handle to the secure memory, which is only accessible - // by TEE. - // - // The decrypted data will be of size |buffer.size()| and there must be - // enough space in |opaque_handle| to store that data. - // - // If non-zero, |data_offset| specifies an offset to be applied to - // |opaque_handle| before the decrypted data is written. - virtual bool Decrypt(CastDecoderBuffer* buffer, - uint8_t* opaque_handle, - size_t data_offset) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_DECRYPT_CONTEXT_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/external_audio_decoder.h chromium-132.0.6834.159/chromecast/public/media/external_audio_decoder.h --- chromium-132.0.6834.110/chromecast/public/media/external_audio_decoder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/external_audio_decoder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_EXTERNAL_AUDIO_DECODER_H_ -#define CHROMECAST_PUBLIC_MEDIA_EXTERNAL_AUDIO_DECODER_H_ - -#include - -#include "cast_decoder_buffer.h" -#include "chromecast_export.h" -#include "decoder_config.h" - -namespace chromecast { -namespace media { - -// The external audio decoder is an optional dynamically-loaded shared library. -// The library is loaded as "libcast_external_decoder.so" from the cast_shell -// shared library search path. See below for the functions that the library -// must export. - -// Interface for additional audio decoder functionality. ExternalAudioDecoder -// always decodes to planar float format. -class ExternalAudioDecoder { - public: - class Delegate { - public: - // Allocates a buffer to write decoded audio into. The caller may write - // up to |bytes| bytes of decoded audio into the returned buffer, in the - // desired output format. To avoid memory leaks, OnDecodedBuffer() must be - // called for every allocated buffer. It is an error to call AllocateBuffer - // twice in a row without calling OnDecodedBuffer() in between. - virtual void* AllocateBuffer(size_t bytes) = 0; - - // Informs the delegate that |decoded_size_bytes| of decoded audio data have - // been written into the buffer most recently returned by AllocateBuffer(). - // |decoded_size_bytes| may be 0. |config| is the config of the decoded - // audio. It is assumed that the config is the same for all - // OnDecodedBuffer() calls that occur within a single call to - // ExternalAudioDecoder::Decode(), but the config may change between calls - // to Decode(). Decoded audio must be in planar float format. - virtual void OnDecodedBuffer(size_t decoded_size_bytes, - const AudioConfig& config) = 0; - - protected: - virtual ~Delegate() = default; - }; - - // Returns the expected number of channels in the decoded audio. This is - // called immediately after construction. Returns 0 if the number of channels - // is not known. - virtual int GetNumOutputChannels() = 0; - - // Decodes an audio buffer. The implementation of this method should call - // the delegate's AllocateBuffer() method to allocate a buffer, write some - // decoded data to the buffer, and then call the delegate's OnDecodedBuffer() - // method. This may be done 0 or more times per call to Decode(). All delegate - // methods must be called synchronously from within Decode(). Returns |false| - // if an error occurred while decoding. - virtual bool Decode(const CastDecoderBuffer& buffer) = 0; - - protected: - virtual ~ExternalAudioDecoder() = default; -}; - -// The external decoder library must export the following functions: - -// Returns |true| if |config| is supported by the external decoder library, -// |false| otherwise. An ExternalAudioDecoder instance will be created for any -// stream where |true| is returned for the config. -extern "C" CHROMECAST_EXPORT bool ExternalAudioDecoder_IsSupportedConfig( - const AudioConfig& config); - -// Creates an external audio decoder. The |delegate| is guaranteed to outlive -// the returned decoder instance. The returned decoder will be deleted by -// calling ExternalAudioDecoder_DeleteDecoder(). -extern "C" CHROMECAST_EXPORT ExternalAudioDecoder* -ExternalAudioDecoder_CreateDecoder(ExternalAudioDecoder::Delegate* delegate, - const AudioConfig& config); - -// Deletes an external audio decoder. -extern "C" CHROMECAST_EXPORT void ExternalAudioDecoder_DeleteDecoder( - ExternalAudioDecoder* decoder); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_EXTERNAL_AUDIO_DECODER_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/external_audio_pipeline_shlib.h chromium-132.0.6834.159/chromecast/public/media/external_audio_pipeline_shlib.h --- chromium-132.0.6834.110/chromecast/public/media/external_audio_pipeline_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/external_audio_pipeline_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,190 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_MEDIA_EXTERNAL_AUDIO_PIPELINE_SHLIB_H_ -#define CHROMECAST_PUBLIC_MEDIA_EXTERNAL_AUDIO_PIPELINE_SHLIB_H_ - -#include -#include - -#include "cast_media_shlib.h" -#include "chromecast_export.h" -#include "media_pipeline_backend.h" -#include "mixer_output_stream.h" - -namespace chromecast { -namespace media { - -class CHROMECAST_EXPORT ExternalAudioPipelineShlib { - public: - // Represents a media input source of the external media pipeline. - enum class MediaInputSource { - UNKNOWN_INPUT_SOURCE, - HDMI, - AIRPLAY, - }; - - // Represents a media playback state of the external media pipeline. - enum class MediaPlaybackState { - UNKNOWN_STATE, - STOPPED, - PAUSED, - PLAYING, - }; - - // Observer for reporting requests for media volume change/muting from the - // external media pipeline. The external pipeline should communicate the media - // volume change requests through this observer and otherwise shouldn't change - // the media volume in any way. Cast pipeline will call - // SetExternalMediaVolume/SetExternalMediaMuted to actually change the volume - // of the external media. The external pipeline must only apply the received - // volume to the external (non-Cast) audio. It specifically must not be - // applied to the mixer output stream. The received volume should also not be - // reported again through this observer. - class ExternalMediaVolumeChangeRequestObserver { - public: - // Called by the external pipeline to request a media volume change by the - // cast pipeline. - virtual void OnVolumeChangeRequest(float new_volume) = 0; - - // Called by the external pipeline to request muting/unmuting media volume - // by the cast pipeline. - virtual void OnMuteChangeRequest(bool new_muted) = 0; - - protected: - virtual ~ExternalMediaVolumeChangeRequestObserver() = default; - }; - - // Media metadata which can be acquired from the external pipeline. - struct ExternalMediaMetadata { - ExternalMediaMetadata(); - ExternalMediaMetadata(const ExternalMediaMetadata& other); - ~ExternalMediaMetadata(); - - std::string title; - std::string artist; - std::string album; - std::string genre; - int track_num = -1; - MediaInputSource source = MediaInputSource::HDMI; - std::string source_description; - MediaPlaybackState state = MediaPlaybackState::UNKNOWN_STATE; - }; - - // Observer for reporting media metadata change from the external media - // pipeline, e.g., title, artist, input source, play back state, and etc. - class ExternalMediaMetadataChangeObserver { - public: - // Called when media metadata is updated. - virtual void OnExternalMediaMetadataChanged( - const ExternalMediaMetadata& metadata) = 0; - - protected: - virtual ~ExternalMediaMetadataChangeObserver() = default; - }; - - // Observer for audio loopback data. - class LoopbackAudioObserver { - public: - // Called whenever audio data is about to be output. The |timestamp| is the - // estimated time in microseconds (relative to CLOCK_MONOTONIC_RAW) that - // the audio will actually be output. |length| is the length of the audio - // |data| in bytes. The format of the data is given by |sample_format| and - // |num_channels|. - // This method may be called by any thread, and MUST not block or take very - // much time (to avoid audio underruns). - virtual void OnLoopbackAudio(int64_t timestamp, - SampleFormat sample_format, - int sample_rate, - int num_channels, - uint8_t* data, - int length) = 0; - - // Called if the loopback data is not continuous (ie, does not accurately - // represent the actual output) for any reason. For example, if there is an - // output underflow, or if output is disabled due to no output streams. - // This method could be called from any thread. - virtual void OnLoopbackInterrupted() = 0; - - // Called once this observer has been fully removed by a call to - // RemoveLoopbackAudioObserver(). After this is called, no more calls to - // OnLoopbackAudio() or OnLoopbackInterrupted() will be made for this - // observer unless it is added again. This method could be called from any - // thread. - virtual void OnRemoved() = 0; - - protected: - virtual ~LoopbackAudioObserver() {} - }; - - // Returns whether this shlib is supported. If this returns true, it indicates - // that the platform uses an external audio pipeline that needs to be combined - // with Cast's media pipeline. - static bool IsSupported(); - - // Adds an external media volume observer. - static void AddExternalMediaVolumeChangeRequestObserver( - ExternalMediaVolumeChangeRequestObserver* observer); - - // Removes an external media volume observer. After this is called, the - // implementation must not call any more methods on the observer. - static void RemoveExternalMediaVolumeChangeRequestObserver( - ExternalMediaVolumeChangeRequestObserver* observer); - - // Sets the effective volume that the external pipeline must apply. The volume - // must be applied only to external (non-Cast) audio. Cast audio must never - // be affected. The pipeline should not report it back through the volume - // observer. The volume |level| is in the range [0.0, 1.0]. - static void SetExternalMediaVolume(float level); - - // Sets the effective muted state that the external pipeline must apply. The - // mute state must be applied only to external (non-Cast) audio. Cast audio - // must never be affected. The pipeline should not report this state back - // through the volume observer. - static void SetExternalMediaMuted(bool muted); - - // Adds a loopback audio observer. An observer will not be added more than - // once without being removed first. - static void AddExternalLoopbackAudioObserver(LoopbackAudioObserver* observer); - - // Removes a loopback audio observer. An observer will not be removed unless - // it was previously added, and will not be removed more than once without - // being added again first. - // Once the observer is fully removed (ie. once it is certain that - // OnLoopbackAudio() will not be called again for the observer), the - // observer's OnRemoved() method must be called. The OnRemoved() method must - // be called once for each time that RemoveLoopbackAudioObserver() is called - // for a given observer, even if the observer was not added. The - // implementation may call OnRemoved() from any thread. - // This function is optional to implement. - static void RemoveExternalLoopbackAudioObserver( - LoopbackAudioObserver* observer); - - // Adds an external media metadata observer. - static void AddExternalMediaMetadataChangeObserver( - ExternalMediaMetadataChangeObserver* observer); - - // Removes an external media volume observer. After this is called, the - // implementation must not call any more methods on the observer. - static void RemoveExternalMediaMetadataChangeObserver( - ExternalMediaMetadataChangeObserver* observer); - - // Returns an instance of MixerOutputStream from the shared library. - // Caller will take ownership of the returned pointer. - static std::unique_ptr CreateMixerOutputStream(); -}; - -inline ExternalAudioPipelineShlib::ExternalMediaMetadata:: - ExternalMediaMetadata() = default; - -inline ExternalAudioPipelineShlib::ExternalMediaMetadata::ExternalMediaMetadata( - const ExternalMediaMetadata& other) = default; - -inline ExternalAudioPipelineShlib::ExternalMediaMetadata:: - ~ExternalMediaMetadata() = default; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_EXTERNAL_AUDIO_PIPELINE_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/media_capabilities_shlib.h chromium-132.0.6834.159/chromecast/public/media/media_capabilities_shlib.h --- chromium-132.0.6834.110/chromecast/public/media/media_capabilities_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/media_capabilities_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_MEDIA_MEDIA_CAPABILITIES_SHLIB_H_ -#define CHROMECAST_PUBLIC_MEDIA_MEDIA_CAPABILITIES_SHLIB_H_ - -#include "chromecast_export.h" -#include "decoder_config.h" - -namespace chromecast { -namespace media { - -// Interface for specifying platform media capabilities. It allows for more -// detailed information to be provided by the platform compared to the previous -// MediaCodecSupportShlib interface. -class CHROMECAST_EXPORT MediaCapabilitiesShlib { - public: - // Return true if the current platform supports the given combination of video - // codec, profile and level. For a list of supported codecs and profiles see - // decoder_config.h. The level value is codec specific. For H.264 and VP9 the - // level value is multiplied by ten, i.e. level=51 corresponds to level 5.1 - // For HEVC the level value is multiplied by 30, to match level_idc value in - // HEVC bitstream. So for HEVC level=153 corresponds to level 5.1 - static bool IsSupportedVideoConfig(VideoCodec codec, - VideoProfile profile, - int level); - - // Return true if the platform supports the given audio |config|. - static bool IsSupportedAudioConfig(const AudioConfig& config); - - // Return true if the platform is able to decode and display the video stream - // smoothly with requested codec, profile, visible size and framerate. - CHROMECAST_EXPORT static bool CanPlayVideoSmoothly(VideoCodec codec, - VideoProfile profile, - int width, - int height, - double framerate) - __attribute__((weak)); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_MEDIA_CAPABILITIES_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/media_pipeline_backend.h chromium-132.0.6834.159/chromecast/public/media/media_pipeline_backend.h --- chromium-132.0.6834.110/chromecast/public/media/media_pipeline_backend.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/media_pipeline_backend.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,404 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_MEDIA_PIPELINE_BACKEND_H_ -#define CHROMECAST_PUBLIC_MEDIA_MEDIA_PIPELINE_BACKEND_H_ - -#include - -#include - -#include "cast_key_status.h" -#include "chromecast_export.h" -#include "decoder_config.h" - -namespace chromecast { -class TaskRunner; -struct Size; - -namespace media { -class CastDecoderBuffer; - -// Interface for platform-specific output of media. -// A new MediaPipelineBackend will be instantiated for each media player -// instance and raw audio stream. If a backend has both video and audio -// decoders, they must be synchronized. -// If more backends are requested than the platform supports, the unsupported -// extra backends may return nullptr for CreateAudioDecoder/CreateVideoDecoder. -// The basic usage pattern is: -// * Decoder objects created and delegates set, then Initialize called -// * Start/Stop/Pause/Resume used to manage playback state -// * Decoder objects are used to pass actual stream data buffers -// * Backend must make appropriate callbacks on the provided Delegate -// All functions will be called on the media thread. Delegate callbacks -// must be made on this thread also (using provided TaskRunner if necessary). -class MediaPipelineBackend { - public: - // Return code for PushBuffer - enum BufferStatus { - kBufferSuccess, - kBufferFailed, - kBufferPending, - }; - - class Decoder { - public: - using BufferStatus = MediaPipelineBackend::BufferStatus; - - // Delegate methods must be called on the main CMA thread. - class Delegate { - public: - using BufferStatus = MediaPipelineBackend::BufferStatus; - - // See comments on PushBuffer. Must not be called with kBufferPending. - virtual void OnPushBufferComplete(BufferStatus status) = 0; - - // Must be called after an end-of-stream buffer has been rendered (ie, the - // last real buffer has been sent to the output hardware). - virtual void OnEndOfStream() = 0; - - // May be called if a decoder error occurs. No more calls to PushBuffer() - // should be made after this is called. - virtual void OnDecoderError() = 0; - - // Must be called when a decryption key status changes. - virtual void OnKeyStatusChanged(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) = 0; - - // Must be called when video resolution change is detected by the decoder. - // Only relevant for video decoders. - virtual void OnVideoResolutionChanged(const Size& size) = 0; - - protected: - virtual ~Delegate() {} - }; - - // Provides the delegate for this decoder. Called once before the backend - // is initialized; is never called after the backend is initialized. - virtual void SetDelegate(Delegate* delegate) = 0; - - // Pushes a buffer of data for decoding and output. If the implementation - // cannot push the buffer now, it must store the buffer, return - // |kBufferPending| and execute the push at a later time when it becomes - // possible to do so. The implementation must then invoke - // Delegate::OnPushBufferComplete once the push has been completed. Pushing - // a pending buffer should be aborted if Stop is called; - // OnPushBufferComplete need not be invoked in this case. - // If |kBufferPending| is returned, the pipeline will stop pushing any - // further buffers until OnPushBufferComplete is invoked. - // OnPushBufferComplete should be only be invoked to indicate completion of - // a pending buffer push - not for the immediate |kBufferSuccess| return - // case. - // The buffer's lifetime is managed by the caller code - it MUST NOT be - // deleted by the MediaPipelineBackend implementation, and MUST NOT be - // dereferenced after completion of buffer push (i.e. - // returning kBufferSuccess/kBufferFailure for synchronous completion, - // calling OnPushBufferComplete() for kBufferPending case). - virtual BufferStatus PushBuffer(CastDecoderBuffer* buffer) = 0; - - protected: - virtual ~Decoder() {} - }; - - class AudioDecoder : public Decoder { - public: - // Info on pipeline latency: amount of data in pipeline not rendered yet, - // and timestamp of system clock (must be CLOCK_MONOTONIC_RAW) at which - // delay measurement was taken. Both times in microseconds. - struct RenderingDelay { - RenderingDelay() - : delay_microseconds(0), timestamp_microseconds(INT64_MIN) {} - RenderingDelay(int64_t delay_microseconds_in, - int64_t timestamp_microseconds_in) - : delay_microseconds(delay_microseconds_in), - timestamp_microseconds(timestamp_microseconds_in) {} - int64_t delay_microseconds; - int64_t timestamp_microseconds; - }; - - // Statistics (computed since last call to backend Start). - struct Statistics { - // Reported as webkitAudioBytesDecoded. Counts number of source bytes - // decoded (not decoder output bytes). - uint64_t decoded_bytes; - }; - - // Android AudioTrack timestamp information. - struct AudioTrackTimestamp { - AudioTrackTimestamp() - : audio_track_frame_position(0), - audio_track_frame_position_without_silence(0), - audio_track_nano_time(INT64_MIN) {} - AudioTrackTimestamp(int64_t audio_track_frame_position_in, - int64_t audio_track_frame_position_without_silence_in, - int64_t audio_track_nano_time_in) - : audio_track_frame_position(audio_track_frame_position_in), - audio_track_frame_position_without_silence( - audio_track_frame_position_without_silence_in), - audio_track_nano_time(audio_track_nano_time_in) {} - // Position in frames relative to start of an assumed audio stream in the - // Android AudioTrack. - int64_t audio_track_frame_position; - // Position in frames relative to start of an assumed audio stream in the - // Android AudioTrack, excluding frames of silence buffers which don't - // have timestamps. - int64_t audio_track_frame_position_without_silence; - // Time associated with the frame in the Android audio pipeline. - int64_t audio_track_nano_time; - }; - - // Provides the audio configuration. Called once before the backend is - // initialized, and again any time the configuration changes (in any state). - // Note that SetConfig() may be called before SetDelegate() is called. - // Returns true if the configuration is a supported configuration. - virtual bool SetConfig(const AudioConfig& config) = 0; - - // Sets the volume multiplier for this audio stream. - // The multiplier is in the range [0.0, 1.0]. If not called, a default - // multiplier of 1.0 is assumed. Returns true if successful. - // Only called after the backend has been initialized. - virtual bool SetVolume(float multiplier) = 0; - - // Returns the pipeline latency: i.e. the amount of data - // in the pipeline that have not been rendered yet, in microseconds. - // Returns a RenderingDelay.timestamp = INT64_MIN if the latency is not - // available. - // Only called when the backend is playing. - virtual RenderingDelay GetRenderingDelay() = 0; - - // Returns the playback statistics since last call to backend Start. Only - // called when playing or paused. - virtual void GetStatistics(Statistics* statistics) = 0; - - // Returns the Android AudioTrack timestamp information. - // Returns a AudioTrackTimestamp.audio_track_nano_time = INT64_MIN if the - // timestamp is not available. - virtual AudioTrackTimestamp GetAudioTrackTimestamp() = 0; - - // Returns the streaming start threshold of the current audio track. - // Returns zero if the start threshold is not available. - virtual int GetStartThresholdInFrames() = 0; - - // Returns the minimum amount of audio data buffered (in microseconds) - // necessary to prevent underrun for the given |config|; ie, if the - // rendering delay falls below this value, then underrun may occur. - static int64_t GetMinimumBufferedTime(const AudioConfig& config) - __attribute__((__weak__)); - - // Returns true if the audio decoder requires that encrypted buffers be - // decrypted before being passed to PushBuffer(). - CHROMECAST_EXPORT static bool RequiresDecryption() - __attribute__((__weak__)); - - protected: - ~AudioDecoder() override {} - }; - - class VideoDecoder : public Decoder { - public: - // Statistics (computed since last call to backend Start). - struct Statistics { - // Counts number of source bytes decoded (not decoder output). - uint64_t decoded_bytes; // Reported as webkitVideoBytesDecoded. - uint64_t decoded_frames; // Reported as webkitDecodedFrames. - uint64_t dropped_frames; // Reported as webkitDroppedFrames. - }; - - // FrameDisplayInfoDelegate methods must be called on the main CMA thread. - class FrameDisplayInfoDelegate { - public: - // OnFrameDisplayed is called either when the frame is displayed - // successfully (with valid |display_time|), or when the frame is dropped - // but it's meant to displayed(with |display_time|==INT64_MIN). - // If a pushed frame is repeated on screen, OnFrameDisplayed() is called - // only once. - // For this API to work properly, the pts fields in CastDecoderBuffer must - // be unique. - virtual void OnFrameDisplayed( - int64_t push_time, // Time when the frame is pushed to backend, - // in microseconds, relative to - // CLOCK_MONOTONIC or CLOCK_MONOTONIC_RAW. - // When it's not available it's INT64_MIN. - int64_t display_time, // Time when the frame is displayed on screen, - // in microseconds, relative to - // CLOCK_MONOTONIC or CLOCK_MONOTONIC_RAW. - // If it's INT64_MIN, the frame is not - // displayed but dropped. - int64_t pts // The |timestamp| within the CastDecoderBuffer that's - // pushed to backend, in microseconds. - ) = 0; - - protected: - virtual ~FrameDisplayInfoDelegate() = default; - }; - - // Provides the video configuration. Called once with the configuration for - // the primary stream before the backend is initialized, and the - // configuration may contain a pointer to additional configuration for a - // secondary stream. Called again with the configuration for either the - // primary or secondary stream when either changes after the backend is - // initialized. - // Note that SetConfig() may be called before SetDelegate() is called. - // Returns true if the configuration is a supported configuration. - virtual bool SetConfig(const VideoConfig& config) = 0; - - // Returns the playback statistics since last call to backend Start. Only - // called when playing or paused. - virtual void GetStatistics(Statistics* statistics) = 0; - - // Register |frame_display_info_delegate| on |video_decoder| to receive - // OnFrameDisplayed. - // TODO(guohuideng): make this a virtual method on VideoDecoder at next API - // update. - CHROMECAST_EXPORT static void SetFrameDisplayInfoDelegate( - FrameDisplayInfoDelegate* frame_display_info_delegate, - VideoDecoder* video_decoder) __attribute__((weak)); - - // The optional APIs below are for low latency playback performance - // improvement and they are only available and sensible on very limited - // implementations. Only intended users should be concerned with them. - - // Get number of frames available for display in last Vsync, in - // |num_of_frames_available_last_vsync|. It returns false if it fails. - CHROMECAST_EXPORT static bool GetNumberOfFramesAvailableLastVsync( - uint32_t* num_of_frames_available_last_vsync, - VideoDecoder* video_decoder) __attribute__((weak)); - // Get number of frames pushed but not decoded yet, in - // |num_of_frames_enqueued_pre_decode|. It returns false if it fails. - CHROMECAST_EXPORT static bool GetNumberOfFramesEnqueuedPreDecode( - uint32_t* num_of_frames_enqueued_pre_decode, - VideoDecoder* video_decoder) __attribute__((weak)); - // Change the max number of frames that output module would hold before it - // drops frame. It returns false if it fails. - CHROMECAST_EXPORT static bool SetFreeRunDropThreshold( - uint32_t free_run_drop_threshold, - VideoDecoder* video_decoder) __attribute__((weak)); - // Set max output buffer count at post decoding stage. It returns false if - // it fails. - CHROMECAST_EXPORT static bool SetMaxOutputBufferCount( - uint32_t max_output_buffer_count, - VideoDecoder* video_decoder) __attribute__((weak)); - - protected: - ~VideoDecoder() override {} - }; - - // This is created/deleted on media thread. All the methods and delegate - // methods should be called on media thread. - class AudioDecryptor { - public: - using BufferStatus = MediaPipelineBackend::BufferStatus; - - // Delegate methods must be called on media thread. - class Delegate { - public: - // Called to indicate decryptor can accept more buffers, after - // PushBufferForDecrypt returns |kBufferPending|. - virtual void OnPushBufferForDecryptComplete(BufferStatus status) = 0; - - // Must be called for each pushed buffer (both clear and encrypted). - // Returns false if decryption fails, e.g. license policy violation. - virtual void OnDecryptComplete(bool success) = 0; - - protected: - virtual ~Delegate() = default; - }; - - // Aborts all the pending operations once the object is deleted. - virtual ~AudioDecryptor() = default; - - // Provides delegate for this decryptor. Called once before any other APIs. - virtual void SetDelegate(Delegate* delegate) = 0; - - // Pushes a buffer of data for decrypting. Decrypted data will be put in - // |output|. Implementation MUST check the license policy before returning - // the clear buffer back. - // - // Similar to Decoder::PushBuffer, implementation can return - // |kBufferPending| to stop caller from pushing more buffers. See comments - // of Decoder::PushBuffer for more details on buffer pushing. - // - // Implementation must invoke Delegate::OnDecryptComplete once data is - // decrypted. Both encrypted and clear buffers will be pushed. - // Implementation should call the delegate methods in the same sequence as - // pushing buffer. - // - // Once EOS buffer is pushed, implementation should decrypt and return all - // the buffers. - // - // |buffer| and |output| are owned by caller. Caller must not destroy them - // until Delegate::OnDecryptComplete is called. |output| must be long - // enough to hold clear data. |output| may overlap with the memory carried - // by |buffer|. The size of decrypted data should be same as encrypted data. - virtual BufferStatus PushBufferForDecrypt(CastDecoderBuffer* buffer, - uint8_t* output) = 0; - }; - - virtual ~MediaPipelineBackend() {} - - // Creates a new AudioDecoder attached to this pipeline. MediaPipelineBackend - // maintains ownership of the decoder object (and must not delete before it's - // destroyed). Will be called zero or more times, all calls made before - // Initialize. May return nullptr if the platform implementation cannot - // support any additional simultaneous playback at this time. - virtual AudioDecoder* CreateAudioDecoder() = 0; - - // Creates a new VideoDecoder attached to this pipeline. MediaPipelineBackend - // maintains ownership of the decoder object (and must not delete before it's - // destroyed). Will be called zero or more times, all calls made before - // Initialize. Note: Even if your backend only supports audio, you must - // provide a default implementation of VideoDecoder; one way to do this is to - // inherit from MediaPipelineBackendDefault. May return nullptr if the - // platform implementation cannot support any additional simultaneous playback - // at this time. - virtual VideoDecoder* CreateVideoDecoder() = 0; - - // Initializes the backend. This will be called once, after Decoder creation - // but before all other functions. Hardware resources for all decoders should - // be acquired here. Backend is then considered in Initialized state. - // Returns false for failure. - virtual bool Initialize() = 0; - - // Places pipeline into playing state. Playback will start at given time once - // buffers are pushed. Called only when in Initialized state. |start_pts| is - // the start playback timestamp in microseconds. - virtual bool Start(int64_t start_pts) = 0; - - // Returns pipeline to 'Initialized' state. May be called while playing or - // paused. Buffers cannot be pushed in Initialized state. - virtual void Stop() = 0; - - // Pauses media playback. Called only when in playing state. - virtual bool Pause() = 0; - - // Resumes media playback. Called only when in paused state. - virtual bool Resume() = 0; - - // Gets the current playback timestamp in microseconds. Only called when in - // the "playing" or "paused" states. Returns INT64_MIN if the PTS is not - // available. - virtual int64_t GetCurrentPts() = 0; - - // Sets the playback rate. |rate| > 0. If this is not called, a default rate - // of 1.0 is assumed. Returns true if successful. Only called when in - // the "playing" or "paused" states. - virtual bool SetPlaybackRate(float rate) = 0; - - // Creates a new AudioDecryptor for extracting clear audio buffers. Caller - // owns the object. This will be called multiple times on media thread. When - // the object is deleted, the implementation should abort all the pending - // operations. - // This function is optional. The correct implementation must return a valid - // object. Platforms which support standard CDM decryption APIs do not need to - // implement this function. - CHROMECAST_EXPORT static AudioDecryptor* CreateAudioDecryptor( - EncryptionScheme scheme, - TaskRunner* task_runner) __attribute__((weak)); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_MEDIA_PIPELINE_BACKEND_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/media_pipeline_device_params.h chromium-132.0.6834.159/chromecast/public/media/media_pipeline_device_params.h --- chromium-132.0.6834.110/chromecast/public/media/media_pipeline_device_params.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/media_pipeline_device_params.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,192 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_MEDIA_MEDIA_PIPELINE_DEVICE_PARAMS_H_ -#define CHROMECAST_PUBLIC_MEDIA_MEDIA_PIPELINE_DEVICE_PARAMS_H_ - -#include - -#include -#include - -#include "chromecast/public/volume_control.h" - -namespace service_manager { -class Connector; -} // namespace service_manager - -namespace chromecast { -class TaskRunner; - -namespace media { - -enum class AudioChannel { - kAll = 0, - kLeft = 1, - kRight = 2, -}; - -// Supplies creation parameters to platform-specific pipeline backend. -struct MediaPipelineDeviceParams { - enum MediaSyncType { - // Default operation, synchronize playback using PTS with higher latency. - kModeSyncPts = 0, - // With this mode, synchronization is disabled and audio/video frames are - // rendered "right away": - // - for audio, frames are still rendered based on the sampling frequency - // - for video, frames are rendered as soon as available at the output of - // the video decoder. - // The assumption is that no B frames are used when synchronization is - // disabled, otherwise B frames would always be skipped. - kModeIgnorePts = 1, - // In addition to the constraints above, also do not wait for vsync. - kModeIgnorePtsAndVSync = 2, - // Almost same as kModeSyncPts except two things: - // 1. When pushing silence to the backend decoder, set an invalid timestamp - // to the silence buffer. We always play the silence, but if the stream uses - // hardware av sync mode, the invalid timestamp will not be used to do av - // sync. - // 2. When pushing non-silence buffers, do not adjust the timestamp. When - // calculating the rendering delay, the silence buffer will be counted. But - // when calculating the current playback position of the real audio data, - // buffers without timestamp, like silence buffer, will not be counted. - kModeApkSyncPts = 3, - }; - - enum AudioStreamType { - // "Real" audio stream. If this stream underruns, all audio output may pause - // until more real stream data is available. - kAudioStreamNormal = 0, - // Sound-effects audio stream. May be interrupted if a real audio stream - // is created with a different sample rate. Underruns on an effects stream - // do not affect output of real audio streams. - kAudioStreamSoundEffects = 1, - }; - - MediaPipelineDeviceParams(); - - // TODO(guohuideng): Get rid of these excessive number of constructors, using - // default arguments. - MediaPipelineDeviceParams(TaskRunner* task_runner_in, - AudioContentType content_type_in, - const std::string& device_id_in); - - MediaPipelineDeviceParams(MediaSyncType sync_type_in, - TaskRunner* task_runner_in, - AudioContentType content_type_in, - const std::string& device_id_in); - - MediaPipelineDeviceParams(MediaSyncType sync_type_in, - AudioStreamType audio_type_in, - TaskRunner* task_runner_in, - AudioContentType content_type_in, - const std::string& device_id_in); - - MediaPipelineDeviceParams(const MediaPipelineDeviceParams& other); - MediaPipelineDeviceParams& operator=(const MediaPipelineDeviceParams& other); - MediaPipelineDeviceParams(MediaPipelineDeviceParams&& other); - MediaPipelineDeviceParams& operator=(MediaPipelineDeviceParams&& other); - - MediaSyncType sync_type = kModeSyncPts; - AudioStreamType audio_type = kAudioStreamNormal; - - // This flag matters only when the implementation of - // CastMediaShlib::CreateMediaPipelineBackend(...) can return multiple kinds - // of CastMediaShlib::MediaPipelineBackend. When this flag is true, - // CastMediaShlib::CreateMediaPipelineBackend(...) should return a backend - // that supports pass-through audio if it is possible. - bool pass_through_audio_support_desired = false; - - // task_runner allows backend implementations to post tasks to the media - // thread. Since all calls from cast_shell into the backend are made on - // the media thread, this may simplify thread management and safety for - // some backends. - TaskRunner* task_runner = nullptr; - - // This field is deprecated. - // - // TODO(yucliu): Remove this field. - service_manager::Connector* connector = nullptr; - - // Identifies the content type for volume control. - AudioContentType content_type = AudioContentType::kMedia; - std::string device_id; - - // ID of the current session. - std::string session_id; - - // This field is deprecated and ignored. - bool multiroom = false; - - // Audio channel this device is playing. - AudioChannel audio_channel = AudioChannel::kAll; - - // This field is deprecated and ignored. - int64_t output_delay_us = 0; -}; - -inline MediaPipelineDeviceParams::MediaPipelineDeviceParams() = default; - -inline MediaPipelineDeviceParams::MediaPipelineDeviceParams( - TaskRunner* task_runner_in, - AudioContentType content_type_in, - const std::string& device_id_in) - : task_runner(task_runner_in), - content_type(content_type_in), - device_id(device_id_in) {} - -inline MediaPipelineDeviceParams::MediaPipelineDeviceParams( - MediaSyncType sync_type_in, - TaskRunner* task_runner_in, - AudioContentType content_type_in, - const std::string& device_id_in) - : sync_type(sync_type_in), - task_runner(task_runner_in), - content_type(content_type_in), - device_id(device_id_in) {} - -inline MediaPipelineDeviceParams::MediaPipelineDeviceParams( - MediaSyncType sync_type_in, - AudioStreamType audio_type_in, - TaskRunner* task_runner_in, - AudioContentType content_type_in, - const std::string& device_id_in) - : sync_type(sync_type_in), - audio_type(audio_type_in), - task_runner(task_runner_in), - content_type(content_type_in), - device_id(device_id_in) {} - -inline MediaPipelineDeviceParams::MediaPipelineDeviceParams( - const MediaPipelineDeviceParams& other) = default; - -inline MediaPipelineDeviceParams& MediaPipelineDeviceParams::operator=( - const MediaPipelineDeviceParams& other) = default; - -inline MediaPipelineDeviceParams::MediaPipelineDeviceParams( - MediaPipelineDeviceParams&& other) = default; - -inline MediaPipelineDeviceParams& MediaPipelineDeviceParams::operator=( - MediaPipelineDeviceParams&& other) = default; - -inline std::ostream& operator<<(std::ostream& os, AudioChannel audio_channel) { - switch (audio_channel) { - case AudioChannel::kAll: - os << "all"; - return os; - case AudioChannel::kLeft: - os << "left"; - return os; - case AudioChannel::kRight: - os << "right"; - return os; - } - os << "unknown"; - return os; -} - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_MEDIA_PIPELINE_DEVICE_PARAMS_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/mixer_output_stream.h chromium-132.0.6834.159/chromecast/public/media/mixer_output_stream.h --- chromium-132.0.6834.110/chromecast/public/media/mixer_output_stream.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/mixer_output_stream.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_MEDIA_MIXER_OUTPUT_STREAM_H_ -#define CHROMECAST_PUBLIC_MEDIA_MIXER_OUTPUT_STREAM_H_ - -#include - -#include "media_pipeline_backend.h" - -namespace chromecast { -namespace media { - -// Interface for output audio stream. Used by the mixer to play mixed stream. -class MixerOutputStream { - public: - static constexpr int kInvalidSampleRate = 0; - - // Creates a default MixerOutputStream. - static std::unique_ptr Create(); - - virtual ~MixerOutputStream() {} - - // Start the stream. Caller must call GetSampleRate() to get the actual sample - // rate selected for the stream. It may be different from - // |requested_sample_rate|, e.g. if IsFixedSampleRate() is true, or the device - // doesn't support |requested_sample_rate|. - virtual bool Start(int requested_sample_rate, int channels) = 0; - - // Returns number of channels expected to be passed to Write(). - virtual int GetNumChannels() = 0; - - // Returns current sample rate. - virtual int GetSampleRate() = 0; - - // Returns current rendering delay for the stream. - virtual MediaPipelineBackend::AudioDecoder::RenderingDelay - GetRenderingDelay() = 0; - - // Returns the optimal number of frames to pass to Write(). For ALSA, this is - // the period size. - virtual int OptimalWriteFramesCount() = 0; - - // |data_size| is size of |data|. Should be divided by number of channels - // to get number of frames. - // The current implementation of the mixer relies on ALSA specific behavior - // where Write blocks if there is not enough space in the buffer. Until - // this is changed other implementation must follow the same behavior. - virtual bool Write(const float* data, - int data_size, - bool* out_playback_interrupted) = 0; - - // Stops the stream. After being stopped the stream can be restarted by - // calling Start(). - virtual void Stop() = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_MIXER_OUTPUT_STREAM_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/media/stream_id.h chromium-132.0.6834.159/chromecast/public/media/stream_id.h --- chromium-132.0.6834.110/chromecast/public/media/stream_id.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/media/stream_id.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_MEDIA_STREAM_ID_H_ -#define CHROMECAST_PUBLIC_MEDIA_STREAM_ID_H_ - -namespace chromecast { -namespace media { - -enum StreamId { - kPrimary = 0, - kSecondary -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_MEDIA_STREAM_ID_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/osd_plane.h chromium-132.0.6834.159/chromecast/public/osd_plane.h --- chromium-132.0.6834.110/chromecast/public/osd_plane.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/osd_plane.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_OSD_PLANE_H_ -#define CHROMECAST_PUBLIC_OSD_PLANE_H_ - -namespace chromecast { - -class OsdSurface; -struct Rect; -struct Size; - -// Abstract graphics plane for OSD, to be implemented in platform-specific way. -// Platform must composite this plane on top of main (GL-based) graphics plane. -class OsdPlane { - public: - virtual ~OsdPlane() {} - - // Creates a surface for offscreen drawing. - virtual OsdSurface* CreateSurface(const Size& size) = 0; - - // Sets a clip rectangle, client should call before drawing to back buffer - // to specify the area they intend to draw on. Platforms may reduce memory - // usage by only allocating back buffer to cover this area. Areas outside - // clip rectangle must display as fully transparent. In particular, setting - // an empty clip rectangle and calling Flip should clear the plane. - // |osd_res| gives the resolution of the full OSD plane, i.e. |rect| is - // a subrectangle of this area. |output_scale| specifies the current scaling - // from |osd_res| to output screen resolution. - virtual void SetClipRectangle(const Rect& rect, - const Size& osd_res, - float output_scale) = 0; - - // Gets the current back buffer surface. Valid until next call to Flip or - // SetClipRectangle. - virtual OsdSurface* GetBackBuffer() = 0; - - // Presents current back buffer to screen. - virtual void Flip() = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_OSD_PLANE_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/osd_plane_shlib.h chromium-132.0.6834.159/chromecast/public/osd_plane_shlib.h --- chromium-132.0.6834.110/chromecast/public/osd_plane_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/osd_plane_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_OSD_PLANE_SHLIB_H_ -#define CHROMECAST_PUBLIC_OSD_PLANE_SHLIB_H_ - -#include -#include - -#include "chromecast_export.h" - -namespace chromecast { - -class OsdPlane; - -// Entry point for loading OsdPlane from shared library. -class CHROMECAST_EXPORT OsdPlaneShlib { - public: - static OsdPlane* Create(const std::vector& argv); -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_OSD_PLANE_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/osd_surface.h chromium-132.0.6834.159/chromecast/public/osd_surface.h --- chromium-132.0.6834.110/chromecast/public/osd_surface.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/osd_surface.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_OSD_SURFACE_H_ -#define CHROMECAST_PUBLIC_OSD_SURFACE_H_ - -namespace chromecast { - -struct Rect; -struct Size; - -// Provides simple API (copy bitmap, blit, composite and fill) for drawing -// OSD graphics on OsdPlane. Hardware-specific implementation should be -// instantiated by OsdPlane. -class OsdSurface { - public: - struct Point { - Point(int arg_x, int arg_y) : x(arg_x), y(arg_y) {} - - const int x; - const int y; - }; - - virtual ~OsdSurface() {} - - // Blits(fast copy) bitmap from a surface. Copies |src_rect| area of surface - // |dst_point| of this surface. - virtual void Blit(OsdSurface* src_surface, - const Rect& src_rect, - const Point& dst_point) = 0; - - // Composites ARGB values of |src_surface| on top of this surface. It is NOT - // copy. Used when displaying OSD images on same plane. - virtual void Composite(OsdSurface* src_surface, - const Rect& src_rect, - const Point& dst_point) = 0; - - // Copies |damage_rect| area of src bitmap into |dst_point| of this surface. - // It is similar to Blit() except that it accepts arbitrary bitmap pointer - // instead of surface. - virtual void CopyBitmap(char* src_bitmap, - const Rect& src_rect, - const Rect& damage_rect, - const Point& dst_point) = 0; - - // Fills |rect| area of surface with |argb| value. - virtual void Fill(const Rect& rect, int argb) = 0; - - // Returns the dimensions of the surface. - virtual const Size& size() const = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_OSD_SURFACE_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/output_restrictions.h chromium-132.0.6834.159/chromecast/public/output_restrictions.h --- chromium-132.0.6834.110/chromecast/public/output_restrictions.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/output_restrictions.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,97 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_OUTPUT_RESTRICTIONS_H_ -#define CHROMECAST_PUBLIC_OUTPUT_RESTRICTIONS_H_ - -namespace chromecast { - -// The below values were adapted from the msdn article on Output Protection -// Levels: https://msdn.microsoft.com/en-us/library/dn468832.aspx - -// Restrictions supported/applied to Uncompressed Digital Audio outputs, e.g. -// HDMI, DisplayPort, MHL. -class UncompressedDigitalAudio { - public: - enum Restrictions { - // HDCP protection. - kHdcp = 1, - // HDCP protection *or* SCMS Copy Never protection. - kHdcpOrScmsCopyNever = 1 << 1, - // Disable the output so that content is not sent to it. - kDisableOutput = 1 << 2, - }; -}; - -// Restrictions supported/applied to Compressed Digital Audio outputs, e.g. -// HDMI, DisplayPort, MHL. -class CompressedDigitalAudio { - public: - enum Restrictions { - // HDCP protection *or* SCMS Copy Never protection. - kHdcpOrScmsCopyNever = 1, - // HDCP protection. - kHdcp = 1 << 1, - // Disable the output so that content is not sent to it. - kDisableOutput = 1 << 2, - }; -}; - -// Restrictions supported/applied to Analog TV outputs, e.g. Component, -// Composite, VGA. -class AnalogVideo { - public: - enum Restrictions { - // Content is constrainted to 520,000 pixels of effective resolution. - kConstrainOutputToSd = 1, - // CGMS-A Copy Never protection. - kCgmsACopyNever = 1 << 1, - // Macrovision APC Automatic Gain Control and Color Stripe protection. - kAgcAndColorStripe = 1 << 2, - // Disable the output so that content is not sent to it. - kDisableOutput = 1 << 3, - }; -}; - -// Restrictions supported/applied to Uncompressed Digital Video outputs, e.g. -// HDMI, DVI, DisplayPort, MHL. -class UncompressedDigitalVideo { - public: - enum Restrictions { - // HDCP protection. - kHdcp = 1, - // Disable the output so that content is not sent to it. - kDisableOutput = 1 << 2, - }; -}; - -// Represents either a set of supported OutputRestrictions, or a set of -// OutputRestrictions to be applied. -struct OutputRestrictions { - OutputRestrictions() - : uncompressed_digital_audio_mask(0), - compressed_digital_audio_mask(0), - analog_video_mask(0), - uncompressed_digital_video_mask(0) {} - - // A bitmask of UncompressedDigitalAudio restrictions, indicating either - // supported or required restrictions. - int uncompressed_digital_audio_mask; - - // A bitmask of CompressedDigitalAudio restrictions, indicating either - // supported or required restrictions. - int compressed_digital_audio_mask; - - // A bitmask of Analog TV restrictions, indicating either supported or - // required restrictions. - int analog_video_mask; - - // A bitmask of UncompressedDigitalVideo restrictions, indicating either - // supported or required restrictions. - int uncompressed_digital_video_mask; -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_OUTPUT_RESTRICTIONS_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/reboot_shlib.h chromium-132.0.6834.159/chromecast/public/reboot_shlib.h --- chromium-132.0.6834.110/chromecast/public/reboot_shlib.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/reboot_shlib.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,187 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_REBOOT_SHLIB_H_ -#define CHROMECAST_PUBLIC_REBOOT_SHLIB_H_ - -#include -#include - -#include "chromecast_export.h" - -namespace chromecast { - -// All methods in the RebootShlib interface can be called from any thread. -class CHROMECAST_EXPORT RebootShlib { - public: - // GENERATED_JAVA_ENUM_PACKAGE: com.google.android.apps.cast - enum RebootSource { - // A default value to use if the source of a reboot is not known. - UNKNOWN = 0, - - // A reboot that wasn't device-initiated (e.g. power cycle). - FORCED = 1, - - // A reboot triggered by the setup API that was not an FDR or an OTA. - // This is a user initiated reboot attempt. - API = 2, - - // An automatic reboot of the device that happens once a day. - NIGHTLY = 3, - - // A reboot caused by an OTA/update related source. - // Note: Calling RebootNow(RebootSource::OTA) does not imply that - // an OTA must happen upon reboot; it is simply an indicator that a reboot - // request is coming from an OTA-related source. - // Only if SetOtaForNextReboot() has been called must reboot to result - // in an OTA update. - OTA = 4, - - // A reboot caused by a watchdog process, which generally indicates - // a device malfunction of some sort. - WATCHDOG = 5, - - // A reboot triggered by the Cast ProcessManager, which monitors various - // cast services and will cause a reboot if critical services are failing. - PROCESS_MANAGER = 6, - - // A reboot triggered by the Cast CrashUploader, which is responsible for - // handling crash reports and will cause a reboot if a high crash rate is - // detected. - CRASH_UPLOADER = 7, - - // A reboot caused by an FDR related source. - // Note: Calling RebootNow(RebootSource::FDR) does not imply that - // an FDR must happen upon reboot; it is simply an indicator that a reboot - // request is coming from an FDR-related source. - // Only if SetFdrForNextReboot() has been called must reboot to result - // in an OTA update. - FDR = 8, - - // A reboot caused by hardware watchdog. This requires additional - // information from the SoC. Otherwise, it can be categorized as forced. - HW_WATCHDOG = 9, - - // A reboot caused by other software reason that is not listed above. - SW_OTHER = 10, - - // A reboot caused by overheat. - OVERHEAT = 11, - - // The device got into a state such that it needs to regenerate the cloud - // device id. - REGENERATE_CLOUD_ID = 12, - - // A reboot is triggered due to successive OOM events. - REPEATED_OOM = 13, - - // A reboot is triggered when the utility process is found to be in - // crash loop. - UTILITY_PROCESS_CRASH = 14, - - // Restart of the Cast component following a graceful teardown, e.g., - // intended by the platform. Device has not rebooted. This only makes sense - // on platforms that allow a component restart without a full device reboot. - GRACEFUL_RESTART = 15, - - // Restart of the Cast component following an ungraceful teardown, e.g., - // a crash.. Device has not rebooted. This only makes sense on platforms - // that allow a component restart without a full device reboot. - UNGRACEFUL_RESTART = 16, - - // A dirty reboot is triggered due to multiple services are affected by - // bugs. In that case, business logic can't proceed and busy references - // can't be trusted, so a dirty reboot will be executed. - MULTI_SERVICE_BUG = 17, - - // Intentional shutdown by power manager of battery powered devices. - POWER_MANAGER_SHUTDOWN = 18, - - // Restart of the Cast component to apply changes due to an experiment flag - // value change. This is only used to handle flag changes that would be more - // risky to attempt without a full process restart. Very few experiments - // trigger this path. - EXPERIMENT_CHANGE = 19, - - // A reboot is triggered when the anomaly detection service detects a - // system-level anomaly and needs to recover from it with restarting the - // Cast component. - ANOMALY = 20, - - // A reboot is triggered when the kernel panics. - KERNEL_PANIC = 21, - }; - - // Initializes any platform-specific reboot systems. - static void Initialize(const std::vector& argv); - - // Tears down and uninitializes any platform-specific reboot systems. - static void Finalize(); - - // Returns whether this shlib is supported. If this returns true, it - // indicates that IsRebootSourceSupported will be true for at least one - // RebootSource. - static bool IsSupported(); - - // Indicates if a particular RebootSource is supported. If |reboot_source| - // is supported, calling RebootNow(|reboot_source|) should cause the system - // to reboot as soon as possible. - static bool IsRebootSourceSupported(RebootSource reboot_source); - - // Causes the system to reboot as soon as possible if the supplied - // |reboot_source| is supported. - // Returns true if the reboot is expected to succeed. - // Returns false if there is an error during reboot attempt (or the - // |reboot_source| is not supported). - // - // NOTE: RebootNow(RebootSource::FDR) does NOT require an FDR to occur upon - // reboot. An FDR is only required to occur upon reboot if - // IsFdrForNextRebootSupported() returns true and SetFdrForNextReboot() - // has been called. If SetFdrForNextReboot() has been called, then a reboot - // must result in an FDR regardless of the RebootSource passed to RebootNow. - // - // NOTE: RebootNow(RebootSource::OTA) does NOT require an OTA to occur upon - // reboot. An OTA is only required to occur upon reboot if - // IsOtaForNextRebootSupported() returns true and SetOtaForNextReboot() - // has been called. If SetOtaForNextReboot() has been called, then a reboot - // must result in an OTA regardless of the RebootSource passed to RebootNow. - static bool RebootNow(RebootSource reboot_source); - - // Indicates if FDR (Factory Data Reset) on next reboot is supported. - // NOTE: This is independent from IsRebootSourceSupported(RebootSource::FDR). - // If IsFdrForNextRebootSupported() returns true and SetFdrForNextReboot() - // has been called, then the device must do an FDR upon reboot, regardless - // of the type of reboot (including power cycle). - static bool IsFdrForNextRebootSupported(); - - // If IsFdrSupported() returns true, then calling SetFdrForNextReboot() - // must result in FDR occuring upon the next reboot (regardless of the - // RebootSource or cause of reboot). - static void SetFdrForNextReboot(); - - // Indicates if updates (also known as OTAs) on next reboot are supported. - // NOTE: This is independent from IsRebootSourceSupported(RebootSource::OTA). - // If IsOtaForNextRebootSupported() returns true and SetOtaForNextReboot() - // has been called, then the device must do an OTA upon reboot, regardless - // of the type of reboot (including power cycle). - static bool IsOtaForNextRebootSupported(); - - // If IsOtaSupported() returns true, then calling SetOtaForNextReboot() - // must result in any available OTA update getting applied upon the next - // reboot (regardless of the RebootSource or cause of reboot). - static void SetOtaForNextReboot(); - - // If IsClearOtaFromNextRebootSupported() returns true and - // ClearOtaForNextReboot() has been called, then the device will cancel any - // pending OTA waiting to be applied. - static bool IsClearOtaForNextRebootSupported(); - - // If IsClearOtaForNextRebootSupported() returns true then calling - // ClearOtaForNextReboot voids any prior call to SetOtaForNextReboot. - static void ClearOtaForNextReboot(); -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_REBOOT_SHLIB_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/task_runner.h chromium-132.0.6834.159/chromecast/public/task_runner.h --- chromium-132.0.6834.110/chromecast/public/task_runner.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/task_runner.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_TASK_RUNNER_H_ -#define CHROMECAST_PUBLIC_TASK_RUNNER_H_ - -#include - -namespace chromecast { - -// Provides a way for vendor libraries to run code on a specific thread. -// For example, cast_shell supplies an implementation of this interface through -// media APIs (see MediaPipelineDeviceParams) to allow media backends to -// schedule tasks to be run on the media thread. -class TaskRunner { - public: - // Subclass and implement 'Run' to supply code to be run by PostTask or - // PostDelayedTask. They both take ownership of the Task object passed in - // and will delete after running the Task. - class Task { - public: - virtual ~Task() {} - virtual void Run() = 0; - }; - - // This class is intended for use with base callback type. A template has been - // used to avoid introducing a hard dependency on Chromium base. It is used to - // convert a chromium-style callback to a Task as defined above. - template - class CallbackTask : public Task { - public: - CallbackTask(T callback) : callback_(std::move(callback)) {} - - ~CallbackTask() override = default; - - private: - // TaskRunner::Task overrides: - void Run() override { std::move(callback_).Run(); } - - T callback_; - }; - - // Posts a task to the thread's task queue. Delay of 0 could mean task - // runs immediately (within the call to PostTask, if it's called on the - // target thread) but there also could be some delay (the task could be added - // to target thread's task queue). - virtual bool PostTask(Task* task, uint64_t delay_milliseconds) = 0; - - protected: - virtual ~TaskRunner() {} -}; - -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_TASK_RUNNER_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/video_plane.h chromium-132.0.6834.159/chromecast/public/video_plane.h --- chromium-132.0.6834.110/chromecast/public/video_plane.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/video_plane.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// 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. - -#ifndef CHROMECAST_PUBLIC_VIDEO_PLANE_H_ -#define CHROMECAST_PUBLIC_VIDEO_PLANE_H_ - -namespace chromecast { -struct RectF; - -namespace media { - -class VideoPlane { - public: - // List of possible hardware transforms that can be applied to video. - // Rotations are anticlockwise. - enum Transform { - TRANSFORM_NONE, - ROTATE_90, - ROTATE_180, - ROTATE_270, - FLIP_HORIZONTAL, - FLIP_VERTICAL, - }; - - // List of supported coordinates for VideoPlane. kScreen represents screen - // coordinates, meaning coordinates relative to the physical screen - // resolution. kGraphics represents coordinates relative to the graphics - // resolution. - enum Coordinates { - kScreen, - kGraphics, - }; - - virtual ~VideoPlane() {} - - // Updates the video plane geometry. - // |screen_rect| specifies the rectangle that the video should occupy, - // in the coordinates specified by GetVideoPlaneCoordinates. If that function - // is not defined, defaults to using screen resolution coordinates. - // |transform| specifies how the video should be transformed within that - // rectangle. - virtual void SetGeometry(const RectF& screen_rect, Transform transform) = 0; - - // Returns the coordinate system to be used when passing coordinates to - // VideoPlane::SetGeometry. If this is not defined, defaults to screen - // coordinates. - static Coordinates GetCoordinates() __attribute__((weak)); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_VIDEO_PLANE_H_ diff -Nru chromium-132.0.6834.110/chromecast/public/volume_control.h chromium-132.0.6834.159/chromecast/public/volume_control.h --- chromium-132.0.6834.110/chromecast/public/volume_control.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/public/volume_control.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,159 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_PUBLIC_VOLUME_CONTROL_H_ -#define CHROMECAST_PUBLIC_VOLUME_CONTROL_H_ - -#include -#include -#include - -#include "chromecast_export.h" - -namespace chromecast { -namespace media { - -// Audio content types for volume control. Each content type has a separate -// volume and mute state. -// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chromecast.media -enum class AudioContentType { - kMedia, // Normal audio playback; also used for system sound effects. - kAlarm, // Alarm sounds. - kCommunication, // Voice communication, eg assistant TTS. - kOther, // No content type volume control (only per-stream control). - kNumTypes, // Not a valid type; should always be last in the enum. -}; - -inline std::ostream& operator<<(std::ostream& os, AudioContentType audio_type) { - switch (audio_type) { - case AudioContentType::kMedia: - return os << "MEDIA"; - case AudioContentType::kAlarm: - return os << "ALARM"; - case AudioContentType::kCommunication: - return os << "COMMUNICATION"; - case AudioContentType::kOther: - return os << "OTHER"; - default: - return os << "Add a new entry above, otherwise kNumTypes is not a valid " - "type."; - } -} - -// Different sources of volume changes. Used to change behaviour (eg feedback -// sounds) based on the source. -enum class VolumeChangeSource { - kUser, // User-initiated volume change. - kAutomatic, // Automatic volume change, no user involvement. - kAutoWithFeedback, // Automatic volume change, but we still want to have - // volume feedback UX. - kUserWithNoAudioFeedback, // User-initiated change, but audible feedback is - // disabled. -}; - -inline std::ostream& operator<<(std::ostream& os, - VolumeChangeSource vol_change_source) { - switch (vol_change_source) { - case VolumeChangeSource::kUser: - return os << "USER"; - case VolumeChangeSource::kAutomatic: - return os << "AUTOMATIC"; - case VolumeChangeSource::kAutoWithFeedback: - return os << "AUTO_WITH_FEEDBACK"; - case VolumeChangeSource::kUserWithNoAudioFeedback: - return os << "USER_NO_AUDIO_FEEDBACK"; - } -} - -// Observer for volume/mute state changes. This is useful to detect volume -// changes that occur outside of cast_shell. Add/RemoveVolumeObserver() must not -// be called synchronously from OnVolumeChange() or OnMuteChange(). Note that -// no volume/mute changes will occur for AudioContentType::kOther, so no -// observer methods will be called with that type. -class VolumeObserver { - public: - // Called whenever the volume changes for a given stream |type|. May be called - // on an arbitrary thread. - virtual void OnVolumeChange(VolumeChangeSource source, - AudioContentType type, - float new_volume) = 0; - - // Called whenever the mute state changes for a given stream |type|. May be - // called on an arbitrary thread. - virtual void OnMuteChange(VolumeChangeSource source, - AudioContentType type, - bool new_muted) = 0; - - protected: - virtual ~VolumeObserver() = default; -}; - -// Volume control is initialized once when cast_shell starts up, and finalized -// on shutdown. Revoking resources has no effect on volume control. All volume -// control methods are called on the same thread that calls Initialize(). -class CHROMECAST_EXPORT VolumeControl { - public: - // Initializes platform-specific volume control. Only called when volume - // control is in an uninitialized state. The implementation of this method - // should load previously set volume and mute states from persistent storage, - // so that the volume and mute are preserved across reboots. - static void Initialize(const std::vector& argv); - - // Tears down platform-specific volume control and returns to the - // uninitialized state. - static void Finalize(); - - // Adds a volume observer. - static void AddVolumeObserver(VolumeObserver* observer); - // Removes a volume observer. After this is called, the implementation must - // not call any more methods on the observer. - static void RemoveVolumeObserver(VolumeObserver* observer); - - // Gets/sets the output volume for a given audio stream |type|. The volume - // |level| is in the range [0.0, 1.0]. AudioContentType::kOther is not a valid - // |type| for these methods. - static float GetVolume(AudioContentType type); - static void SetVolume(VolumeChangeSource source, - AudioContentType type, - float level); - - // Sets a multiplier on the attenuation level for a given audio stream type. - // Used for stereo pair balance. - static void SetVolumeMultiplier(AudioContentType type, float multiplier) - __attribute__((weak)); - - // Gets/sets the mute state for a given audio stream |type|. - // AudioContentType::kOther is not a valid |type| for these methods. - static bool IsMuted(AudioContentType type); - static void SetMuted(VolumeChangeSource source, - AudioContentType type, - bool muted); - - // Limits the output volume for a given stream |type| to no more than |limit|. - // This does not affect the logical volume for the stream type; the volume - // returned by GetVolume() should not change, and no OnVolumeChange() event - // should be sent to observers. AudioContentType::kOther is not a valid |type| - // for this method. - static void SetOutputLimit(AudioContentType type, float limit); - - // Called to enable power save mode when no audio is being played - // (|power_save_on| will be true in this case), and to disable power save mode - // when audio playback resumes (|power_save_on| will be false). - // NOTE: This is optional (therefore a weak symbol) because most platforms - // do not have any need to implement it. - static void SetPowerSaveMode(bool power_save_on) __attribute__((weak)); - - // Converts a volume level in the range [0.0, 1.0] to/from a volume in dB. - // The volume in dB should be full-scale (so a volume level of 1.0 would be - // 0.0 dBFS, and any lower volume level would be negative). - // NOTE: Unlike the other VolumeControl methods, these may be called before - // Initialize() or after Finalize(). May be called from multiple processes. - static float VolumeToDbFS(float volume); - static float DbFSToVolume(float dbfs); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_PUBLIC_VOLUME_CONTROL_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/DEPS chromium-132.0.6834.159/chromecast/renderer/DEPS --- chromium-132.0.6834.110/chromecast/renderer/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -include_rules = [ - "+chromecast/browser/mojom", - "+chromecast/common", - "+chromecast/crash", - "+chromecast/media", - "+components/cast_receiver/renderer", - "+components/cdm/renderer", - "+components/guest_view/renderer", - "+components/media_control/renderer", - "+components/media_control/mojom", - "+components/network_hints/renderer", - "+components/on_load_script_injector/renderer", - "+components/url_rewrite/common", - "+components/url_rewrite/renderer", - "+components/version_info", - "+content/public/common", - "+content/public/renderer", - "+gin", - "+media/base", - "+media/media_buildflags.h", - "+media/remoting/receiver_controller.h", - "+media/remoting/stream_provider.h", - "+media/renderers", - "+mojo/public", - "+base/strings/escape.h", - "+net/http/http_request_headers.h", - "+net/base/net_errors.h", - "+net/base/url_util.h", - "+services/network/public/cpp", - "+services/service_manager/public", - "+third_party/blink/public", - "+v8", -] diff -Nru chromium-132.0.6834.110/chromecast/renderer/OWNERS chromium-132.0.6834.159/chromecast/renderer/OWNERS --- chromium-132.0.6834.110/chromecast/renderer/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -seantopping@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/renderer/activity_filtering_websocket_handshake_throttle.cc chromium-132.0.6834.159/chromecast/renderer/activity_filtering_websocket_handshake_throttle.cc --- chromium-132.0.6834.110/chromecast/renderer/activity_filtering_websocket_handshake_throttle.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/activity_filtering_websocket_handshake_throttle.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// 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 "chromecast/renderer/activity_filtering_websocket_handshake_throttle.h" - -#include "base/strings/stringprintf.h" -#include "third_party/blink/public/platform/web_string.h" -#include "url/gurl.h" - -namespace chromecast { - -ActivityFilteringWebSocketHandshakeThrottle:: - ActivityFilteringWebSocketHandshakeThrottle(ActivityUrlFilter* filter) - : url_filter_(filter) {} - -ActivityFilteringWebSocketHandshakeThrottle:: - ~ActivityFilteringWebSocketHandshakeThrottle() = default; - -void ActivityFilteringWebSocketHandshakeThrottle::ThrottleHandshake( - const blink::WebURL& url, - const blink::WebSecurityOrigin& creator_origin, - const blink::WebSecurityOrigin& isolated_world_origin, - blink::WebSocketHandshakeThrottle::OnCompletion completion_callback) { - GURL gurl = GURL(url); - - // Pass through allowed URLs, block otherwise. - if (url_filter_->UrlMatchesWhitelist(gurl)) { - std::move(completion_callback).Run(std::nullopt); - return; - } - - std::move(completion_callback) - .Run(blink::WebString::FromUTF8(base::StringPrintf( - "WebSocket connection to %s is blocked", gurl.spec().c_str()))); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/activity_filtering_websocket_handshake_throttle.h chromium-132.0.6834.159/chromecast/renderer/activity_filtering_websocket_handshake_throttle.h --- chromium-132.0.6834.110/chromecast/renderer/activity_filtering_websocket_handshake_throttle.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/activity_filtering_websocket_handshake_throttle.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// 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. - -#ifndef CHROMECAST_RENDERER_ACTIVITY_FILTERING_WEBSOCKET_HANDSHAKE_THROTTLE_H_ -#define CHROMECAST_RENDERER_ACTIVITY_FILTERING_WEBSOCKET_HANDSHAKE_THROTTLE_H_ - -#include "chromecast/common/activity_url_filter.h" -#include "third_party/blink/public/platform/web_url.h" -#include "third_party/blink/public/platform/websocket_handshake_throttle.h" - -namespace chromecast { - -// This class implements the WebSocketHandshakeThrottle class as a facility -// to block WebSocket connection establishment. Specifically, -// blink::Platform::CreateWebSocketHandshakeThrottle() is called when a -// WebSocket handshake is started. If -// ActivityFilteringWebSocketHandshakeThrottle is installed, the -// ThrottleHandshake() will be called on the handshake. If the URL is not -// whitelisted, the handshake will be aborted, and a connection error will be -// reported to Javascript. -class ActivityFilteringWebSocketHandshakeThrottle - : public blink::WebSocketHandshakeThrottle { - public: - explicit ActivityFilteringWebSocketHandshakeThrottle( - ActivityUrlFilter* filter); - - ActivityFilteringWebSocketHandshakeThrottle( - const ActivityFilteringWebSocketHandshakeThrottle&) = delete; - ActivityFilteringWebSocketHandshakeThrottle& operator=( - const ActivityFilteringWebSocketHandshakeThrottle&) = delete; - - ~ActivityFilteringWebSocketHandshakeThrottle() override; - - // blink::WebSocketHandshakeThrottle implementation: - void ThrottleHandshake(const blink::WebURL& url, - const blink::WebSecurityOrigin& creator_origin, - const blink::WebSecurityOrigin& isolated_world_origin, - blink::WebSocketHandshakeThrottle::OnCompletion - completion_callback) override; - - private: - ActivityUrlFilter* const url_filter_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_ACTIVITY_FILTERING_WEBSOCKET_HANDSHAKE_THROTTLE_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/assistant_bindings.cc chromium-132.0.6834.159/chromecast/renderer/assistant_bindings.cc --- chromium-132.0.6834.110/chromecast/renderer/assistant_bindings.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/assistant_bindings.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,169 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/assistant_bindings.h" - -#include "base/check.h" -#include "base/json/json_reader.h" -#include "base/json/json_writer.h" -#include "base/logging.h" -#include "base/stl_util.h" -#include "base/time/time.h" -#include "content/public/renderer/render_frame.h" -#include "content/public/renderer/render_thread.h" -#include "third_party/blink/public/platform/browser_interface_broker_proxy.h" -#include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h" -#include "third_party/blink/public/web/web_local_frame.h" - -namespace chromecast { -namespace shell { - -namespace { - -const int kMaxMessageQueueSize = 50; -static const int64_t kDelayBetweenReconnectionInMillis = 100; - -const char kSetAssistantMessageHandlerMethodName[] = - "setAssistantMessageHandler"; -const char kSendAssistantRequestMethodName[] = "sendAssistantRequest"; - -} // namespace - -AssistantBindings::AssistantBindings(content::RenderFrame* frame, - const base::Value::Dict& feature_config) - : CastBinding(frame), - feature_config_(feature_config.Clone()), - message_client_binding_(this), - weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); -} - -AssistantBindings::~AssistantBindings() {} - -void AssistantBindings::OnMessage(base::Value message) { - if (assistant_message_handler_.IsEmpty()) { - return; - } - - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = web_frame->MainWorldScriptContext(); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - - v8::Local handler = v8::Local::New( - isolate, std::move(assistant_message_handler_)); - - std::string json; - base::JSONWriter::Write(message, &json); - v8::Local message_val = - gin::Converter::ToV8(isolate, json); - - v8::Local argv[] = {message_val}; - web_frame->CallFunctionEvenIfScriptDisabled(handler, context->Global(), - std::size(argv), argv); - - assistant_message_handler_ = - v8::UniquePersistent(isolate, handler); -} - -void AssistantBindings::Install(v8::Local cast_platform, - v8::Isolate* isolate) { - DVLOG(1) << "Installing AssistantBindings"; - - InstallBinding(isolate, cast_platform, kSetAssistantMessageHandlerMethodName, - &AssistantBindings::SetAssistantMessageHandler, - base::Unretained(this)); - InstallBinding(isolate, cast_platform, kSendAssistantRequestMethodName, - &AssistantBindings::SendAssistantRequest, - base::Unretained(this)); -} - -void AssistantBindings::SetAssistantMessageHandler( - v8::Local assistant_message_handler) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - assistant_message_handler_ = - v8::UniquePersistent(isolate, assistant_message_handler); - ReconnectMessagePipe(); -} - -void AssistantBindings::SendAssistantRequest(const std::string& request) { - if (assistant_message_handler_.IsEmpty()) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - isolate->ThrowException( - v8::String::NewFromUtf8(isolate, - "Error: assistant message handler is not set.", - v8::NewStringType::kInternalized) - .ToLocalChecked()); - return; - } - if (!message_pipe_.is_bound()) { - if (v8_to_assistant_queue_.size() < kMaxMessageQueueSize) { - v8_to_assistant_queue_.push_back(request); - } else { - LOG(WARNING) << "Messages sending to assistant overflow, will drop " - "upcoming messages"; - } - return; - } - - v8_to_assistant_queue_.push_back(request); - FlushV8ToAssistantQueue(); -} - -void AssistantBindings::ReconnectMessagePipe() { - if (message_client_binding_.is_bound()) - message_client_binding_.reset(); - if (message_pipe_.is_bound()) - message_pipe_.reset(); - LOG(INFO) << "Creating message pipe"; - const std::string* app_id = feature_config_.FindString("app_id"); - DCHECK(app_id) << "Couldn't get app_id from feature config"; - GetMojoInterface()->CreateMessagePipe( - *app_id, message_client_binding_.BindNewPipeAndPassRemote(), - message_pipe_.BindNewPipeAndPassReceiver()); - - reconnect_assistant_timer_.Stop(); -} - -void AssistantBindings::OnAssistantConnectionError() { - LOG(WARNING) << "Disconnected from assistant. Will reconnect every " - << kDelayBetweenReconnectionInMillis << " milliseconds"; - assistant_.reset(); - reconnect_assistant_timer_.Start( - FROM_HERE, base::Milliseconds(kDelayBetweenReconnectionInMillis), this, - &AssistantBindings::ReconnectMessagePipe); -} - -void AssistantBindings::FlushV8ToAssistantQueue() { - DCHECK(message_pipe_.is_bound()); - - for (auto& request : v8_to_assistant_queue_) { - auto value = base::JSONReader::Read(request); - if (!value) { - LOG(ERROR) << "Unable to parse Assistant message JSON."; - continue; - } - message_pipe_->SendMessage(std::move(*value)); - } - v8_to_assistant_queue_.clear(); -} - -const mojo::Remote& -AssistantBindings::GetMojoInterface() { - if (!assistant_.is_bound()) { - render_frame()->GetBrowserInterfaceBroker().GetInterface( - assistant_.BindNewPipeAndPassReceiver()); - assistant_.set_disconnect_handler(base::BindOnce( - &AssistantBindings::OnAssistantConnectionError, weak_this_)); - } - return assistant_; -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/assistant_bindings.h chromium-132.0.6834.159/chromecast/renderer/assistant_bindings.h --- chromium-132.0.6834.110/chromecast/renderer/assistant_bindings.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/assistant_bindings.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_ASSISTANT_BINDINGS_H_ -#define CHROMECAST_RENDERER_ASSISTANT_BINDINGS_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "base/timer/timer.h" -#include "chromecast/common/mojom/assistant_messenger.mojom.h" -#include "chromecast/renderer/native_bindings_helper.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" - -namespace chromecast { -namespace shell { - -// When enabled, these bindings can be used to open a message channel with the -// Assistant. These bindings are only enabled for a small set of first-party -// apps. -class AssistantBindings : public CastBinding, - public chromecast::mojom::AssistantMessageClient { - public: - AssistantBindings(content::RenderFrame* frame, - const base::Value::Dict& feature_config); - ~AssistantBindings() override; - AssistantBindings(const AssistantBindings&) = delete; - AssistantBindings& operator=(const AssistantBindings&) = delete; - - private: - friend class ::chromecast::CastBinding; - - // chromecast::mojom::AssistantMessageClient implementation: - void OnMessage(base::Value message) override; - - // CastBinding implementation: - void Install(v8::Local cast_platform, - v8::Isolate* isolate) override; - - // Binding methods - void SetAssistantMessageHandler( - v8::Local assistant_message_handler); - void SendAssistantRequest(const std::string& request); - - void ReconnectMessagePipe(); - void OnAssistantConnectionError(); - - void FlushV8ToAssistantQueue(); - - const mojo::Remote& - GetMojoInterface(); - - base::RepeatingTimer reconnect_assistant_timer_; - mojo::Remote assistant_; - base::Value::Dict feature_config_; - - mojo::Receiver - message_client_binding_; - mojo::Remote message_pipe_; - std::vector v8_to_assistant_queue_; - - v8::UniquePersistent assistant_message_handler_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_ASSISTANT_BINDINGS_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_activity_url_filter_manager.cc chromium-132.0.6834.159/chromecast/renderer/cast_activity_url_filter_manager.cc --- chromium-132.0.6834.110/chromecast/renderer/cast_activity_url_filter_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_activity_url_filter_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,110 +0,0 @@ -// 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 "chromecast/renderer/cast_activity_url_filter_manager.h" - -#include -#include - -#include "base/functional/bind.h" -#include "base/logging.h" -#include "content/public/renderer/render_frame.h" -#include "third_party/blink/public/web/web_local_frame.h" - -namespace chromecast { - -CastActivityUrlFilterManager::UrlFilterReceiver::UrlFilterReceiver( - content::RenderFrame* render_frame, - base::OnceCallback on_removed_callback) - : content::RenderFrameObserver(render_frame), - on_removed_callback_(std::move(on_removed_callback)), - weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); - render_frame->GetAssociatedInterfaceRegistry() - ->AddInterface( - base::BindRepeating( - &CastActivityUrlFilterManager::UrlFilterReceiver:: - OnActivityUrlFilterConfigurationAssociatedRequest, - weak_this_)); -} - -CastActivityUrlFilterManager::UrlFilterReceiver::~UrlFilterReceiver() { - std::move(on_removed_callback_).Run(); -} - -bool CastActivityUrlFilterManager::UrlFilterReceiver:: - OnAssociatedInterfaceRequestForFrame( - const std::string& interface_name, - mojo::ScopedInterfaceEndpointHandle* handle) { - return associated_interfaces_.TryBindInterface(interface_name, handle); -} - -void CastActivityUrlFilterManager::UrlFilterReceiver::OnDestruct() { - delete this; -} - -void CastActivityUrlFilterManager::UrlFilterReceiver::SetFilter( - chromecast::mojom::ActivityUrlFilterCriteriaPtr filter_criteria) { - if (filter_criteria->criteria.empty()) - return; - - url_filter_ = std::make_unique(filter_criteria->criteria); -} - -void CastActivityUrlFilterManager::UrlFilterReceiver:: - OnActivityUrlFilterConfigurationAssociatedRequest( - mojo::PendingAssociatedReceiver< - chromecast::mojom::ActivityUrlFilterConfiguration> receiver) { - receivers_.Add(this, std::move(receiver)); -} - -ActivityUrlFilter* -CastActivityUrlFilterManager::UrlFilterReceiver::GetUrlFilter() { - return url_filter_.get(); -} - -CastActivityUrlFilterManager::CastActivityUrlFilterManager() - : weak_factory_(this) { - weak_this_ = weak_factory_.GetWeakPtr(); -} - -CastActivityUrlFilterManager::~CastActivityUrlFilterManager() = default; - -ActivityUrlFilter* -CastActivityUrlFilterManager::GetActivityUrlFilterForRenderFrameToken( - const blink::LocalFrameToken& frame_token) { - const auto& it = activity_url_filters_.find(frame_token); - if (it == activity_url_filters_.end()) - return nullptr; - - return it->second->GetUrlFilter(); -} - -void CastActivityUrlFilterManager::OnRenderFrameCreated( - content::RenderFrame* render_frame) { - auto frame_token = render_frame->GetWebFrame()->GetLocalFrameToken(); - - // Lifetime is tied to |render_frame| via content::RenderFrameObserver. - auto* filter_receiver = new CastActivityUrlFilterManager::UrlFilterReceiver( - render_frame, - base::BindOnce(&CastActivityUrlFilterManager::OnRenderFrameRemoved, - weak_this_, frame_token)); - - auto result = activity_url_filters_.emplace(frame_token, filter_receiver); - - if (!result.second) - LOG(ERROR) - << "A URL filter for Activity already exists for Render frame token " - << frame_token; -} - -void CastActivityUrlFilterManager::OnRenderFrameRemoved( - const blink::LocalFrameToken& frame_token) { - const auto& it = activity_url_filters_.find(frame_token); - - if (it != activity_url_filters_.end()) - activity_url_filters_.erase(it); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_activity_url_filter_manager.h chromium-132.0.6834.159/chromecast/renderer/cast_activity_url_filter_manager.h --- chromium-132.0.6834.110/chromecast/renderer/cast_activity_url_filter_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_activity_url_filter_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// 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. - -#ifndef CHROMECAST_RENDERER_CAST_ACTIVITY_URL_FILTER_MANAGER_H_ -#define CHROMECAST_RENDERER_CAST_ACTIVITY_URL_FILTER_MANAGER_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "chromecast/common/activity_url_filter.h" -#include "chromecast/common/mojom/activity_url_filter.mojom.h" -#include "content/public/renderer/render_frame_observer.h" -#include "mojo/public/cpp/bindings/associated_receiver_set.h" -#include "mojo/public/cpp/bindings/pending_associated_receiver.h" -#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" -#include "third_party/blink/public/common/tokens/tokens.h" - -namespace chromecast { - -// This class accepts strings that represent URL filter criteria from -// the browser through mojo, and constructs the URL matcher that filters -// web requests. -class CastActivityUrlFilterManager { - public: - CastActivityUrlFilterManager(); - - CastActivityUrlFilterManager(const CastActivityUrlFilterManager&) = delete; - CastActivityUrlFilterManager& operator=(const CastActivityUrlFilterManager&) = - delete; - - ~CastActivityUrlFilterManager(); - - // Returns nullptr if no Activity URL filter exists for the render frame. - ActivityUrlFilter* GetActivityUrlFilterForRenderFrameToken( - const blink::LocalFrameToken& frame_token); - - void OnRenderFrameCreated(content::RenderFrame* render_frame); - void OnRenderFrameRemoved(const blink::LocalFrameToken& frame_token); - - private: - class UrlFilterReceiver - : public content::RenderFrameObserver, - public chromecast::mojom::ActivityUrlFilterConfiguration { - public: - explicit UrlFilterReceiver(content::RenderFrame* render_frame, - base::OnceCallback on_removed_callback); - - UrlFilterReceiver(const UrlFilterReceiver&) = delete; - UrlFilterReceiver& operator=(const UrlFilterReceiver&) = delete; - - ~UrlFilterReceiver() override; - - // mojom::ActivityUrlFilterConfiguration implementation: - void SetFilter( - chromecast::mojom::ActivityUrlFilterCriteriaPtr filter) override; - - ActivityUrlFilter* GetUrlFilter(); - - private: - // content::RenderFrameObserver implementation: - bool OnAssociatedInterfaceRequestForFrame( - const std::string& interface_name, - mojo::ScopedInterfaceEndpointHandle* handle) override; - void OnDestruct() override; - - void OnActivityUrlFilterConfigurationAssociatedRequest( - mojo::PendingAssociatedReceiver< - chromecast::mojom::ActivityUrlFilterConfiguration> receiver); - - std::unique_ptr url_filter_; - - blink::AssociatedInterfaceRegistry associated_interfaces_; - mojo::AssociatedReceiverSet< - chromecast::mojom::ActivityUrlFilterConfiguration> - receivers_; - - base::OnceCallback on_removed_callback_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; - }; - - base::flat_map - activity_url_filters_; - - base::WeakPtr weak_this_; - base::WeakPtrFactory weak_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_CAST_ACTIVITY_URL_FILTER_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_content_renderer_client.cc chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client.cc --- chromium-132.0.6834.110/chromecast/renderer/cast_content_renderer_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,361 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/cast_content_renderer_client.h" - -#include -#include - -#include "base/command_line.h" -#include "base/feature_list.h" -#include "base/strings/string_number_conversions.h" -#include "base/task/sequenced_task_runner.h" -#include "build/build_config.h" -#include "chromecast/base/bitstream_audio_codecs.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/base/chromecast_switches.h" -#include "chromecast/common/cors_exempt_headers.h" -#include "chromecast/crash/app_state_tracker.h" -#include "chromecast/media/base/media_codec_support.h" -#include "chromecast/media/base/supported_codec_profile_levels_memo.h" -#include "chromecast/public/media/media_capabilities_shlib.h" -#include "chromecast/renderer/cast_url_loader_throttle_provider.h" -#include "chromecast/renderer/cast_websocket_handshake_throttle_provider.h" -#include "chromecast/renderer/media/key_systems_cast.h" -#include "chromecast/renderer/media/media_caps_observer_impl.h" -#include "components/cast_receiver/renderer/public/content_renderer_client_mixins.h" -#include "components/media_control/renderer/media_playback_options.h" -#include "components/network_hints/renderer/web_prescient_networking_impl.h" -#include "components/on_load_script_injector/renderer/on_load_script_injector.h" -#include "components/url_rewrite/common/url_request_rewrite_rules.h" -#include "content/public/common/content_switches.h" -#include "content/public/renderer/render_frame.h" -#include "content/public/renderer/render_thread.h" -#include "media/base/audio_parameters.h" -#include "media/base/key_system_info.h" -#include "media/base/media.h" -#include "media/base/remoting_constants.h" -#include "media/remoting/receiver_controller.h" -#include "media/remoting/stream_provider.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "services/network/public/cpp/is_potentially_trustworthy.h" -#include "third_party/blink/public/platform/browser_interface_broker_proxy.h" -#include "third_party/blink/public/platform/web_runtime_features.h" -#include "third_party/blink/public/web/web_frame_widget.h" -#include "third_party/blink/public/web/web_security_policy.h" -#include "third_party/blink/public/web/web_settings.h" -#include "third_party/blink/public/web/web_view.h" - -#if BUILDFLAG(IS_ANDROID) -#include "base/android/bundle_utils.h" -#include "chromecast/media/audio/cast_audio_device_factory.h" -#include "components/cdm/renderer/key_system_support_update.h" -#include "media/base/android/media_codec_util.h" -#else -#include "chromecast/renderer/memory_pressure_observer_impl.h" -#endif // BUILDFLAG(IS_ANDROID) - -namespace chromecast { -namespace shell { -namespace { -bool IsSupportedBitstreamAudioCodecHelper(::media::AudioCodec codec, int mask) { - return (codec == ::media::AudioCodec::kAC3 && - (kBitstreamAudioCodecAc3 & mask)) || - (codec == ::media::AudioCodec::kEAC3 && - (kBitstreamAudioCodecEac3 & mask)) || - (codec == ::media::AudioCodec::kDTS && - (kBitstreamAudioCodecDts & mask)) || - (codec == ::media::AudioCodec::kDTSXP2 && - (kBitstreamAudioCodecDtsXP2 & mask)) || - (codec == ::media::AudioCodec::kMpegHAudio && - (kBitstreamAudioCodecMpegHAudio & mask)); -} -} // namespace - -#if BUILDFLAG(IS_ANDROID) -// Audio renderer algorithm maximum capacity. 5s buffer is already large enough, -// we don't need a larger capacity. Otherwise audio renderer will double the -// buffer size when underrun happens, which will cause the playback paused to -// wait long time for enough buffers. -constexpr base::TimeDelta kAudioRendererMaxCapacity = base::Seconds(5); -// Audio renderer algorithm starting capacity. Configure large enough to -// prevent underrun. -constexpr base::TimeDelta kAudioRendererStartingCapacity = base::Seconds(5); -constexpr base::TimeDelta kAudioRendererStartingCapacityEncrypted = - base::Seconds(5); -#endif // BUILDFLAG(IS_ANDROID) - -CastContentRendererClient::CastContentRendererClient() - : cast_receiver_mixins_(cast_receiver::ContentRendererClientMixins::Create( - base::BindRepeating(&IsCorsExemptHeader))), - supported_profiles_( - std::make_unique()), - activity_url_filter_manager_( - std::make_unique()) { -#if BUILDFLAG(IS_ANDROID) - // Registers a custom content::AudioDeviceFactory - cast_audio_device_factory_ = - std::make_unique(); -#endif // BUILDFLAG(IS_ANDROID) -} - -CastContentRendererClient::~CastContentRendererClient() = default; - -void CastContentRendererClient::RenderThreadStarted() { - // Register as observer for media capabilities - content::RenderThread* thread = content::RenderThread::Get(); - mojo::Remote media_caps; - thread->BindHostReceiver(media_caps.BindNewPipeAndPassReceiver()); - mojo::PendingRemote proxy; - media_caps_observer_.reset( - new media::MediaCapsObserverImpl(&proxy, supported_profiles_.get())); - media_caps->AddObserver(std::move(proxy)); - -#if !BUILDFLAG(IS_ANDROID) - // Register to observe memory pressure changes - mojo::Remote - memory_pressure_controller; - thread->BindHostReceiver( - memory_pressure_controller.BindNewPipeAndPassReceiver()); - mojo::PendingRemote - memory_pressure_proxy; - memory_pressure_observer_.reset( - new MemoryPressureObserverImpl(&memory_pressure_proxy)); - memory_pressure_controller->AddObserver(std::move(memory_pressure_proxy)); -#endif - - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - - std::string last_launched_app = - command_line->GetSwitchValueNative(switches::kLastLaunchedApp); - if (!last_launched_app.empty()) - AppStateTracker::SetLastLaunchedApp(last_launched_app); - - std::string previous_app = - command_line->GetSwitchValueNative(switches::kPreviousApp); - if (!previous_app.empty()) - AppStateTracker::SetPreviousApp(previous_app); -} - -void CastContentRendererClient::RenderFrameCreated( - content::RenderFrame* render_frame) { - DCHECK(render_frame); - - cast_receiver_mixins_->RenderFrameCreated(*render_frame); - - // Lifetime is tied to |render_frame| via content::RenderFrameObserver. - if (render_frame->IsMainFrame()) { - main_frame_feature_manager_on_associated_interface_ = - new FeatureManagerOnAssociatedInterface(render_frame); - } else { - new FeatureManagerOnAssociatedInterface(render_frame); - } - - if (!app_media_capabilities_observer_receiver_.is_bound()) { - mojo::Remote app_media_capabilities; - render_frame->GetBrowserInterfaceBroker().GetInterface( - app_media_capabilities.BindNewPipeAndPassReceiver()); - app_media_capabilities->AddObserver( - app_media_capabilities_observer_receiver_.BindNewPipeAndPassRemote()); - } - - activity_url_filter_manager_->OnRenderFrameCreated(render_frame); -} - -void CastContentRendererClient::RunScriptsAtDocumentStart( - content::RenderFrame* render_frame) {} - -void CastContentRendererClient::RunScriptsAtDocumentEnd( - content::RenderFrame* render_frame) {} - -std::unique_ptr<::media::KeySystemSupportRegistration> -CastContentRendererClient::GetSupportedKeySystems( - content::RenderFrame* render_frame, - ::media::GetSupportedKeySystemsCB cb) { -#if BUILDFLAG(IS_ANDROID) - return cdm::GetSupportedKeySystemsUpdates(render_frame, - /*can_persist_data=*/true, - std::move(cb)); -#else - ::media::KeySystemInfos key_systems; - media::AddChromecastKeySystems(&key_systems, - false /* enable_persistent_license_support */); - std::move(cb).Run(std::move(key_systems)); - return nullptr; -#endif // BUILDFLAG(IS_ANDROID) -} - -bool CastContentRendererClient::IsDecoderSupportedAudioType( - const ::media::AudioType& type) { -#if BUILDFLAG(IS_ANDROID) - if (type.spatial_rendering) - return false; - - // No ATV device we know of has (E)AC3 decoder, so it relies on the audio sink - // device. - if (type.codec == ::media::AudioCodec::kEAC3) { - return kBitstreamAudioCodecEac3 & - supported_bitstream_audio_codecs_info_.codecs; - } - if (type.codec == ::media::AudioCodec::kAC3) { - return kBitstreamAudioCodecAc3 & - supported_bitstream_audio_codecs_info_.codecs; - } - if (type.codec == ::media::AudioCodec::kDTS) { - return kBitstreamAudioCodecDts & - supported_bitstream_audio_codecs_info_.codecs; - } - if (type.codec == ::media::AudioCodec::kDTSXP2) { - return kBitstreamAudioCodecDtsXP2 & - supported_bitstream_audio_codecs_info_.codecs; - } - if (type.codec == ::media::AudioCodec::kMpegHAudio) { - return kBitstreamAudioCodecMpegHAudio & - supported_bitstream_audio_codecs_info_.codecs; - } - - return ::media::IsDefaultDecoderSupportedAudioType(type); -#else - if (type.profile == ::media::AudioCodecProfile::kXHE_AAC) - return false; - - // If the HDMI sink supports bitstreaming the codec, then the vendor backend - // does not need to support it. - if (CheckSupportedBitstreamAudioCodec(type.codec, type.spatial_rendering)) - return true; - - media::AudioCodec codec = media::ToCastAudioCodec(type.codec); - // Cast platform implements software decoding of Opus and FLAC, so only PCM - // support is necessary in order to support Opus and FLAC. - if (codec == media::kCodecOpus || codec == media::kCodecFLAC) - codec = media::kCodecPCM; - - media::AudioConfig cast_audio_config; - cast_audio_config.codec = codec; - return media::MediaCapabilitiesShlib::IsSupportedAudioConfig( - cast_audio_config); -#endif -} - -bool CastContentRendererClient::IsDecoderSupportedVideoType( - const ::media::VideoType& type) { - // TODO(servolk): make use of eotf. - - // TODO(crbug.com/40124585): Check attached screen for support of - // type.hdr_metadata_type. - if (type.hdr_metadata_type != ::gfx::HdrMetadataType::kNone) { - NOTIMPLEMENTED() << "HdrMetadataType support signaling not implemented."; - return false; - } - -#if BUILDFLAG(IS_ANDROID) - return supported_profiles_->IsSupportedVideoConfig( - media::ToCastVideoCodec(type.codec, type.profile), - media::ToCastVideoProfile(type.profile), type.level); -#else - return media::MediaCapabilitiesShlib::IsSupportedVideoConfig( - media::ToCastVideoCodec(type.codec, type.profile), - media::ToCastVideoProfile(type.profile), type.level); -#endif -} - -bool CastContentRendererClient::IsSupportedBitstreamAudioCodec( - ::media::AudioCodec codec) { - return IsSupportedBitstreamAudioCodecHelper( - codec, supported_bitstream_audio_codecs_info_.codecs); -} - -bool CastContentRendererClient::CheckSupportedBitstreamAudioCodec( - ::media::AudioCodec codec, - bool check_spatial_rendering) { - if (!IsSupportedBitstreamAudioCodec(codec)) - return false; - - if (!check_spatial_rendering) - return true; - - return IsSupportedBitstreamAudioCodecHelper( - codec, supported_bitstream_audio_codecs_info_.spatial_rendering); -} - -std::unique_ptr -CastContentRendererClient::CreatePrescientNetworking( - content::RenderFrame* render_frame) { - return std::make_unique( - render_frame); -} - -bool CastContentRendererClient::DeferMediaLoad( - content::RenderFrame* render_frame, - bool render_frame_has_played_media_before, - base::OnceClosure closure) { - return cast_receiver_mixins_->DeferMediaLoad(*render_frame, - std::move(closure)); -} - -std::unique_ptr<::media::Demuxer> -CastContentRendererClient::OverrideDemuxerForUrl( - content::RenderFrame* render_frame, - const GURL& url, - scoped_refptr task_runner) { - if (render_frame->GetRenderFrameMediaPlaybackOptions() - .is_remoting_renderer_enabled() && - url.SchemeIs(::media::remoting::kRemotingScheme)) { - return std::make_unique<::media::remoting::StreamProvider>( - ::media::remoting::ReceiverController::GetInstance(), task_runner); - } - return nullptr; -} - -bool CastContentRendererClient::IsIdleMediaSuspendEnabled() { - return false; -} - -void CastContentRendererClient:: - SetRuntimeFeaturesDefaultsBeforeBlinkInitialization() { - // Allow HtmlMediaElement.volume to be greater than 1, for normalization. - blink::WebRuntimeFeatures::EnableFeatureFromString( - "MediaElementVolumeGreaterThanOne", true); - // Settings for ATV (Android defaults are not what we want). - blink::WebRuntimeFeatures::EnableMediaControlsOverlayPlayButton(false); -} - -void CastContentRendererClient::OnSupportedBitstreamAudioCodecsChanged( - const BitstreamAudioCodecsInfo& info) { - supported_bitstream_audio_codecs_info_ = info; -} - -std::unique_ptr -CastContentRendererClient::CreateWebSocketHandshakeThrottleProvider() { - return std::make_unique( - activity_url_filter_manager_.get()); -} - -std::unique_ptr -CastContentRendererClient::CreateURLLoaderThrottleProvider( - blink::URLLoaderThrottleProviderType type) { - auto throttle_provider = std::make_unique( - type, activity_url_filter_manager()); - return cast_receiver_mixins_->ExtendURLLoaderThrottleProvider( - std::move(throttle_provider)); -} - -std::optional<::media::AudioRendererAlgorithmParameters> -CastContentRendererClient::GetAudioRendererAlgorithmParameters( - ::media::AudioParameters audio_parameters) { -#if BUILDFLAG(IS_ANDROID) - ::media::AudioRendererAlgorithmParameters parameters; - parameters.max_capacity = kAudioRendererMaxCapacity; - parameters.starting_capacity = kAudioRendererStartingCapacity; - parameters.starting_capacity_for_encrypted = - kAudioRendererStartingCapacityEncrypted; - return std::optional<::media::AudioRendererAlgorithmParameters>(parameters); -#else - return std::nullopt; -#endif -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_content_renderer_client.h chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client.h --- chromium-132.0.6834.110/chromecast/renderer/cast_content_renderer_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,128 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_CAST_CONTENT_RENDERER_CLIENT_H_ -#define CHROMECAST_RENDERER_CAST_CONTENT_RENDERER_CLIENT_H_ - -#include -#include - -#include "base/task/sequenced_task_runner.h" -#include "build/build_config.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/common/mojom/application_media_capabilities.mojom.h" -#include "chromecast/renderer/cast_activity_url_filter_manager.h" -#include "chromecast/renderer/feature_manager_on_associated_interface.h" -#include "content/public/renderer/content_renderer_client.h" -#include "media/base/audio_codecs.h" -#include "media/base/audio_parameters.h" -#include "media/base/key_systems_support_registration.h" -#include "mojo/public/cpp/bindings/receiver.h" - -namespace cast_receiver { -class ContentRendererClientMixins; -} // namespace cast_receiver - -namespace chromecast { -class MemoryPressureObserverImpl; -namespace media { -class MediaCapsObserverImpl; -class SupportedCodecProfileLevelsMemo; - -#if BUILDFLAG(IS_ANDROID) -class CastAudioDeviceFactory; -#endif // BUILDFLAG(IS_ANDROID) -} - -namespace shell { - -class CastContentRendererClient - : public content::ContentRendererClient, - public mojom::ApplicationMediaCapabilitiesObserver { - public: - // Creates an implementation of CastContentRendererClient. Platform should - // link in an implementation as needed. - static std::unique_ptr Create(); - - CastContentRendererClient(const CastContentRendererClient&) = delete; - CastContentRendererClient& operator=(const CastContentRendererClient&) = - delete; - - ~CastContentRendererClient() override; - - // ContentRendererClient implementation: - void RenderThreadStarted() override; - void RenderFrameCreated(content::RenderFrame* render_frame) override; - void RunScriptsAtDocumentStart(content::RenderFrame* render_frame) override; - void RunScriptsAtDocumentEnd(content::RenderFrame* render_frame) override; - std::unique_ptr<::media::KeySystemSupportRegistration> GetSupportedKeySystems( - content::RenderFrame* render_frame, - ::media::GetSupportedKeySystemsCB cb) override; - bool IsDecoderSupportedAudioType(const ::media::AudioType& type) override; - bool IsDecoderSupportedVideoType(const ::media::VideoType& type) override; - bool IsSupportedBitstreamAudioCodec(::media::AudioCodec codec) override; - std::unique_ptr CreatePrescientNetworking( - content::RenderFrame* render_frame) override; - bool DeferMediaLoad(content::RenderFrame* render_frame, - bool render_frame_has_played_media_before, - base::OnceClosure closure) override; - std::unique_ptr<::media::Demuxer> OverrideDemuxerForUrl( - content::RenderFrame* render_frame, - const GURL& url, - scoped_refptr task_runner) override; - bool IsIdleMediaSuspendEnabled() override; - void SetRuntimeFeaturesDefaultsBeforeBlinkInitialization() override; - std::unique_ptr - CreateWebSocketHandshakeThrottleProvider() override; - std::unique_ptr - CreateURLLoaderThrottleProvider( - blink::URLLoaderThrottleProviderType type) override; - std::optional<::media::AudioRendererAlgorithmParameters> - GetAudioRendererAlgorithmParameters( - ::media::AudioParameters audio_parameters) override; - - protected: - CastContentRendererClient(); - - CastActivityUrlFilterManager* activity_url_filter_manager() { - return activity_url_filter_manager_.get(); - } - - // TODO(guohuideng): Move |feature_manager_on_associated_interface_| to - // private when we can. - FeatureManagerOnAssociatedInterface* - main_frame_feature_manager_on_associated_interface_{nullptr}; - - private: - // mojom::ApplicationMediaCapabilitiesObserver implementation: - void OnSupportedBitstreamAudioCodecsChanged( - const BitstreamAudioCodecsInfo& info) override; - - bool CheckSupportedBitstreamAudioCodec(::media::AudioCodec codec, - bool check_spatial_rendering); - - std::unique_ptr - cast_receiver_mixins_; - - std::unique_ptr media_caps_observer_; - std::unique_ptr supported_profiles_; - mojo::Receiver - app_media_capabilities_observer_receiver_{this}; -#if !BUILDFLAG(IS_ANDROID) - std::unique_ptr memory_pressure_observer_; -#endif - -#if BUILDFLAG(IS_ANDROID) - std::unique_ptr cast_audio_device_factory_; -#endif - - BitstreamAudioCodecsInfo supported_bitstream_audio_codecs_info_; - - std::unique_ptr activity_url_filter_manager_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_CAST_CONTENT_RENDERER_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_content_renderer_client_simple.cc chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client_simple.cc --- chromium-132.0.6834.110/chromecast/renderer/cast_content_renderer_client_simple.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_content_renderer_client_simple.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// 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 "chromecast/renderer/cast_content_renderer_client.h" - -#include - -#include "base/memory/ptr_util.h" - -namespace chromecast { -namespace shell { - -// static -std::unique_ptr CastContentRendererClient::Create() { - return base::WrapUnique(new CastContentRendererClient()); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_content_settings_client.cc chromium-132.0.6834.159/chromecast/renderer/cast_content_settings_client.cc --- chromium-132.0.6834.110/chromecast/renderer/cast_content_settings_client.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_content_settings_client.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/cast_content_settings_client.h" - -#include "base/strings/strcat.h" -#include "content/public/renderer/render_frame.h" -#include "content/public/renderer/render_thread.h" -#include "third_party/blink/public/platform/web_url.h" -#include "third_party/blink/public/web/web_local_frame.h" - -namespace chromecast { - -CastContentSettingsClient::CastContentSettingsClient( - content::RenderFrame* render_frame, - const std::string& app_id, - bool allow_insecure_content) - : content::RenderFrameObserver(render_frame), - app_id_(app_id), - allow_insecure_content_(allow_insecure_content) { - render_frame->GetWebFrame()->SetContentSettingsClient(this); - content::RenderThread::Get()->BindHostReceiver( - metrics_helper_remote_.BindNewPipeAndPassReceiver()); -} - -CastContentSettingsClient::~CastContentSettingsClient() {} - -void CastContentSettingsClient::OnDestruct() { - delete this; -} - -bool CastContentSettingsClient::AllowRunningInsecureContent( - bool enabled_per_settings, - const blink::WebURL& url) { - ReportRendererFeatureUse(app_id_, "ActiveInsecureContent"); - return allow_insecure_content_; -} - -void CastContentSettingsClient::PassiveInsecureContentFound( - const blink::WebURL&) { - ReportRendererFeatureUse(app_id_, "PassiveInsecureContent"); -} - -bool CastContentSettingsClient::ShouldAutoupgradeMixedContent() { - ReportRendererFeatureUse(app_id_, "DisableAutoUpgradeMixedContent"); - return !allow_insecure_content_; -} - -void CastContentSettingsClient::ReportRendererFeatureUse( - const std::string& app_id, - const std::string& feature_name) { - std::string event = - base::StrCat({"Cast.Platform.RendererFeatureUse.", feature_name}); - metrics_helper_remote_->RecordApplicationEvent(app_id, - /*session_id=*/"", - /*sdk_version=*/"", event); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_content_settings_client.h chromium-132.0.6834.159/chromecast/renderer/cast_content_settings_client.h --- chromium-132.0.6834.110/chromecast/renderer/cast_content_settings_client.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_content_settings_client.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_CAST_CONTENT_SETTINGS_CLIENT_H_ -#define CHROMECAST_RENDERER_CAST_CONTENT_SETTINGS_CLIENT_H_ - -#include "chromecast/common/mojom/metrics_helper.mojom.h" -#include "content/public/renderer/render_frame_observer.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "third_party/blink/public/platform/web_content_settings_client.h" - -namespace chromecast { - -// Chromecast implementation of blink::WebContentSettingsClient. -class CastContentSettingsClient : public content::RenderFrameObserver, - public blink::WebContentSettingsClient { - public: - CastContentSettingsClient(content::RenderFrame* render_view, - const std::string& app_id, - bool allow_insecure_content); - CastContentSettingsClient(const CastContentSettingsClient&) = delete; - CastContentSettingsClient& operator=(const CastContentSettingsClient&) = - delete; - - private: - ~CastContentSettingsClient() override; - - // content::RenderFrameObserver implementation. - void OnDestruct() override; - - // blink::WebContentSettingsClient implementation. - bool AllowRunningInsecureContent(bool enabled_per_settings, - const blink::WebURL& url) override; - void PassiveInsecureContentFound(const blink::WebURL&) override; - bool ShouldAutoupgradeMixedContent() override; - - void ReportRendererFeatureUse(const std::string& app_id, - const std::string& feature_name); - - const std::string app_id_; - const bool allow_insecure_content_; - // TODO(b/150022618): Add decisions from Cast service to control the - // availibilitiy of the Renderer features. - - mojo::Remote metrics_helper_remote_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_CAST_CONTENT_SETTINGS_CLIENT_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_demo_bindings.cc chromium-132.0.6834.159/chromecast/renderer/cast_demo_bindings.cc --- chromium-132.0.6834.110/chromecast/renderer/cast_demo_bindings.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_demo_bindings.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,388 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/cast_demo_bindings.h" - -#include - -#include "base/check.h" -#include "base/task/sequenced_task_runner.h" -#include "content/public/renderer/render_frame.h" -#include "content/public/renderer/v8_value_converter.h" -#include "third_party/blink/public/platform/browser_interface_broker_proxy.h" -#include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h" -#include "third_party/blink/public/web/web_local_frame.h" - -namespace chromecast { -namespace shell { - -namespace { -const int64_t kDelayBetweenReconnectionInMillis = 100; - -const char kDemoObjectName[] = "demo"; - -const char kRecordEventName[] = "recordEvent"; -const char kSetRetailerName[] = "setRetailer"; -const char kSetStoreIdName[] = "setStoreId"; -const char kGetRetailerName[] = "getRetailer"; -const char kGetStoreIdName[] = "getStoreId"; -const char kSetDefaultVolumeName[] = "setDefaultVolume"; -const char kGetDefaultVolumeName[] = "getDefaultVolume"; -const char kApplyDefaultVolumeName[] = "applyDefaultVolume"; -const char kSetWifiConnectionName[] = "setWifiConnection"; -const char kGetAvailableWifiNetworksName[] = "getAvailableWifiNetworks"; -const char kGetWifiConnectionStateName[] = "getWifiConnectionState"; -const char kRegisterVolumeChangeHandlerName[] = "registerVolumeChangeHandler"; -const char kPersistLocalStorageName[] = "persistLocalStorage"; - -const char kSetVolumeName[] = "setVolume"; -} // namespace - -CastDemoBindings::CastDemoBindings(content::RenderFrame* render_frame) - : CastBinding(render_frame), binding_(this), weak_factory_(this) {} - -CastDemoBindings::~CastDemoBindings() {} - -void CastDemoBindings::Install(v8::Local cast_platform, - v8::Isolate* isolate) { - v8::Local demo_object = - EnsureObjectExists(isolate, cast_platform, kDemoObjectName); - - InstallBinding(isolate, demo_object, kRecordEventName, - &CastDemoBindings::RecordEvent, base::Unretained(this)); - InstallBinding(isolate, demo_object, kSetRetailerName, - &CastDemoBindings::SetRetailerName, base::Unretained(this)); - InstallBinding(isolate, demo_object, kSetStoreIdName, - &CastDemoBindings::SetStoreId, base::Unretained(this)); - InstallBinding(isolate, demo_object, kGetRetailerName, - &CastDemoBindings::GetRetailerName, base::Unretained(this)); - InstallBinding(isolate, demo_object, kGetStoreIdName, - &CastDemoBindings::GetStoreId, base::Unretained(this)); - InstallBinding(isolate, demo_object, kSetDefaultVolumeName, - &CastDemoBindings::SetDefaultVolumeLevel, - base::Unretained(this)); - InstallBinding(isolate, demo_object, kGetDefaultVolumeName, - &CastDemoBindings::GetDefaultVolumeLevel, - base::Unretained(this)); - InstallBinding(isolate, demo_object, kApplyDefaultVolumeName, - &CastDemoBindings::ApplyDefaultVolume, base::Unretained(this)); - InstallBinding(isolate, demo_object, kSetWifiConnectionName, - &CastDemoBindings::SetWifiCredentials, base::Unretained(this)); - InstallBinding(isolate, demo_object, kGetAvailableWifiNetworksName, - &CastDemoBindings::GetAvailableWifiNetworks, - base::Unretained(this)); - InstallBinding(isolate, demo_object, kGetWifiConnectionStateName, - &CastDemoBindings::GetConnectionStatus, - base::Unretained(this)); - InstallBinding(isolate, demo_object, kRegisterVolumeChangeHandlerName, - &CastDemoBindings::SetVolumeChangeHandler, - base::Unretained(this)); - InstallBinding(isolate, demo_object, kPersistLocalStorageName, - &CastDemoBindings::PersistLocalStorage, - base::Unretained(this)); - - InstallBinding(isolate, demo_object, kSetVolumeName, - &CastDemoBindings::SetVolume, base::Unretained(this)); -} - -void CastDemoBindings::RecordEvent(const std::string& event_name, - v8::Local v8_data) { - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - v8::Isolate* v8_isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope v8_handle_scope(v8_isolate); - v8::Local v8_context = web_frame->MainWorldScriptContext(); - v8::Context::Scope v8_context_scope(v8_context); - - std::unique_ptr v8_converter = - content::V8ValueConverter::Create(); - v8_converter->SetDateAllowed(true); - v8_converter->SetRegExpAllowed(true); - std::unique_ptr data_ptr = - v8_converter->FromV8Value(v8_data, v8_context); - - base::Value data; - if (data_ptr) { - data = base::Value::FromUniquePtrValue(std::move(data_ptr)); - } - GetCastDemo()->RecordEvent(event_name, std::move(data)); -} - -void CastDemoBindings::SetRetailerName(const std::string& retailer_name) { - GetCastDemo()->SetRetailerName(retailer_name); -} - -void CastDemoBindings::SetStoreId(const std::string& store_id) { - GetCastDemo()->SetStoreId(store_id); -} - -v8::Local CastDemoBindings::GetRetailerName() { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - auto context = isolate->GetCurrentContext(); - v8::Local resolver = - v8::Promise::Resolver::New(context).ToLocalChecked(); - v8::Global unique_resolver = - v8::Global(isolate, resolver); - v8::Global persisted_context = - v8::Global(isolate, context); - - GetCastDemo()->GetRetailerName(base::BindOnce( - &CastDemoBindings::OnGetRetailerName, base::Unretained(this), - std::move(unique_resolver), std::move(persisted_context))); - return resolver->GetPromise(); -} - -void CastDemoBindings::OnGetRetailerName( - v8::Global resolver, - v8::Global original_context, - const std::string& retailer_name) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = original_context.Get(isolate); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - - resolver.Get(isolate) - ->Resolve(context, gin::ConvertToV8(isolate, retailer_name)) - .ToChecked(); -} - -v8::Local CastDemoBindings::GetStoreId() { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - auto context = isolate->GetCurrentContext(); - v8::Local resolver = - v8::Promise::Resolver::New(context).ToLocalChecked(); - v8::Global unique_resolver = - v8::Global(isolate, resolver); - v8::Global persisted_context = - v8::Global(isolate, context); - - GetCastDemo()->GetStoreId( - base::BindOnce(&CastDemoBindings::OnGetStoreId, base::Unretained(this), - std::move(unique_resolver), std::move(persisted_context))); - return resolver->GetPromise(); -} - -void CastDemoBindings::OnGetStoreId(v8::Global resolver, - v8::Global original_context, - const std::string& store_id) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = original_context.Get(isolate); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - - resolver.Get(isolate) - ->Resolve(context, gin::ConvertToV8(isolate, store_id)) - .ToChecked(); -} - -void CastDemoBindings::SetVolume(float level) { - // This method is deprecated. Provide a workable implementation to support - // development using old content. - SetDefaultVolumeLevel(level); - ApplyDefaultVolume(); -} - -void CastDemoBindings::SetDefaultVolumeLevel(float level) { - GetCastDemo()->SetDefaultVolumeLevel(level); -} - -v8::Local CastDemoBindings::GetDefaultVolumeLevel() { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - auto context = isolate->GetCurrentContext(); - v8::Local resolver = - v8::Promise::Resolver::New(context).ToLocalChecked(); - v8::Global unique_resolver = - v8::Global(isolate, resolver); - v8::Global persisted_context = - v8::Global(isolate, context); - - GetCastDemo()->GetDefaultVolumeLevel(base::BindOnce( - &CastDemoBindings::OnGetDefaultVolumeLevel, base::Unretained(this), - std::move(unique_resolver), std::move(persisted_context))); - return resolver->GetPromise(); -} - -void CastDemoBindings::OnGetDefaultVolumeLevel( - v8::Global resolver, - v8::Global original_context, - float level) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = original_context.Get(isolate); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - - resolver.Get(isolate) - ->Resolve(context, gin::ConvertToV8(isolate, level)) - .ToChecked(); -} - -void CastDemoBindings::ApplyDefaultVolume() { - GetCastDemo()->ApplyDefaultVolume(); -} - -void CastDemoBindings::SetWifiCredentials(const std::string& ssid, - const std::string& psk) { - GetCastDemo()->SetWifiCredentials(ssid, psk); -} - -v8::Local CastDemoBindings::GetAvailableWifiNetworks() { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - auto context = isolate->GetCurrentContext(); - v8::Local resolver = - v8::Promise::Resolver::New(context).ToLocalChecked(); - v8::Global unique_resolver = - v8::Global(isolate, resolver); - v8::Global persisted_context = - v8::Global(isolate, context); - - GetCastDemo()->GetAvailableWifiNetworks(base::BindOnce( - &CastDemoBindings::OnGetAvailableWifiNetworks, base::Unretained(this), - std::move(unique_resolver), std::move(persisted_context))); - return resolver->GetPromise(); -} - -void CastDemoBindings::OnGetAvailableWifiNetworks( - v8::Global resolver, - v8::Global original_context, - base::Value network_list) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = original_context.Get(isolate); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - - std::unique_ptr v8_converter = - content::V8ValueConverter::Create(); - v8::Local v8_value = - v8_converter->ToV8Value(network_list, context); - - resolver.Get(isolate) - ->Resolve(context, gin::ConvertToV8(isolate, v8_value)) - .ToChecked(); -} - -v8::Local CastDemoBindings::GetConnectionStatus() { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - auto context = isolate->GetCurrentContext(); - v8::Local resolver = - v8::Promise::Resolver::New(context).ToLocalChecked(); - v8::Global unique_resolver = - v8::Global(isolate, resolver); - v8::Global persisted_context = - v8::Global(isolate, context); - - GetCastDemo()->GetConnectionStatus(base::BindOnce( - &CastDemoBindings::OnGetConnectionStatus, base::Unretained(this), - std::move(unique_resolver), std::move(persisted_context))); - return resolver->GetPromise(); -} - -void CastDemoBindings::OnGetConnectionStatus( - v8::Global resolver, - v8::Global original_context, - base::Value status) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = original_context.Get(isolate); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - - std::unique_ptr v8_converter = - content::V8ValueConverter::Create(); - v8::Local v8_value = v8_converter->ToV8Value(status, context); - - resolver.Get(isolate) - ->Resolve(context, gin::ConvertToV8(isolate, v8_value)) - .ToChecked(); -} - -void CastDemoBindings::SetVolumeChangeHandler( - v8::Local volume_change_handler) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - volume_change_handler_ = - v8::UniquePersistent(isolate, volume_change_handler); -} - -void CastDemoBindings::VolumeChanged(float level) { - if (volume_change_handler_.IsEmpty()) { - return; - } - - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = web_frame->MainWorldScriptContext(); - v8::Context::Scope context_scope(context); - v8::Local handler = - v8::Local::New(isolate, std::move(volume_change_handler_)); - - auto args = - v8::to_array>({gin::ConvertToV8(isolate, level)}); - - v8::MaybeLocal maybe_result = - handler->Call(context, context->Global(), args.size(), args.data()); - - volume_change_handler_ = v8::UniquePersistent(isolate, handler); - - v8::Local result; - std::ignore = maybe_result.ToLocal(&result); -} - -void CastDemoBindings::PersistLocalStorage() { - GetCastDemo()->PersistLocalStorage(); -} - -void CastDemoBindings::ReconnectMojo() { - render_frame()->GetBrowserInterfaceBroker().GetInterface( - cast_demo_.BindNewPipeAndPassReceiver()); - DCHECK(cast_demo_.is_bound()); - cast_demo_.set_disconnect_handler(base::BindOnce( - &CastDemoBindings::OnMojoConnectionError, base::Unretained(this))); - - if (binding_.is_bound()) { - binding_.reset(); - } - - mojo::PendingRemote pending_remote; - binding_.Bind(pending_remote.InitWithNewPipeAndPassReceiver()); - cast_demo_->AddVolumeChangeObserver(std::move(pending_remote)); -} - -void CastDemoBindings::OnMojoConnectionError() { - LOG(WARNING) << "Disconnected from Demo Mojo. Will retry every " - << kDelayBetweenReconnectionInMillis << " milliseconds."; - base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&CastDemoBindings::ReconnectMojo, - weak_factory_.GetWeakPtr()), - base::Milliseconds(kDelayBetweenReconnectionInMillis)); -} - -const mojo::Remote& CastDemoBindings::GetCastDemo() { - if (!cast_demo_.is_bound()) { - ReconnectMojo(); - } - return cast_demo_; -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_demo_bindings.h chromium-132.0.6834.159/chromecast/renderer/cast_demo_bindings.h --- chromium-132.0.6834.110/chromecast/renderer/cast_demo_bindings.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_demo_bindings.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,97 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_CAST_DEMO_BINDINGS_H_ -#define CHROMECAST_RENDERER_CAST_DEMO_BINDINGS_H_ - -#include - -#include "base/memory/weak_ptr.h" -#include "chromecast/common/mojom/cast_demo.mojom.h" -#include "chromecast/renderer/native_bindings_helper.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "v8/include/v8.h" - -namespace chromecast { -namespace shell { - -// Enabled only when the device is in demonstration mode. This is only enabled -// for the demonstration JS app. -class CastDemoBindings : public CastBinding, - public mojom::CastDemoVolumeChangeObserver { - public: - explicit CastDemoBindings(content::RenderFrame* render_frame); - CastDemoBindings(const CastDemoBindings&) = delete; - CastDemoBindings& operator=(const CastDemoBindings&) = delete; - - private: - friend class CastBinding; - - ~CastDemoBindings() override; - - // CastBinding implementation: - void Install(v8::Local cast_platform, - v8::Isolate* isolate) override; - - // Methods to be called from v8: (See mojom for details) - void RecordEvent(const std::string& event_name, v8::Local data); - void SetRetailerName(const std::string& retailer_name); - void SetStoreId(const std::string& store_id); - v8::Local GetRetailerName(); - v8::Local GetStoreId(); - void SetDefaultVolumeLevel(float level); - v8::Local GetDefaultVolumeLevel(); - void ApplyDefaultVolume(); - void SetWifiCredentials(const std::string& ssid, const std::string& psk); - v8::Local GetAvailableWifiNetworks(); - v8::Local GetConnectionStatus(); - void SetVolumeChangeHandler(v8::Local volume_change_handler); - void PersistLocalStorage(); - - // Deprecated - void SetVolume(float level); - - // Methods to return values to v8: - void OnGetRetailerName(v8::Global resolver, - v8::Global original_context, - const std::string& retailer_name); - void OnGetStoreId(v8::Global resolver, - v8::Global original_context, - const std::string& store_id); - void OnGetDefaultVolumeLevel(v8::Global resolver, - v8::Global original_context, - float level); - void OnGetAvailableWifiNetworks(v8::Global resolver, - v8::Global original_context, - base::Value network_list); - void OnGetConnectionStatus(v8::Global resolver, - v8::Global original_context, - base::Value status); - - // mojom::CastDemoVolumeChangeObserver implementation: - void VolumeChanged(float level) override; - - void ReconnectMojo(); - void OnMojoConnectionError(); - - // Returns a reference to |cast_demo_|, and binds it to a mojo pipe if - // necessary. - const mojo::Remote& GetCastDemo(); - - // The pointer to the remote mojom::CastDemo interface. Do not access this - // member directly; instead, use GetCastDemo(). - mojo::Remote cast_demo_; - - mojo::Receiver binding_; - - v8::UniquePersistent volume_change_handler_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_CAST_DEMO_BINDINGS_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_url_loader_throttle_provider.cc chromium-132.0.6834.159/chromecast/renderer/cast_url_loader_throttle_provider.cc --- chromium-132.0.6834.110/chromecast/renderer/cast_url_loader_throttle_provider.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_url_loader_throttle_provider.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ -// 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 "chromecast/renderer/cast_url_loader_throttle_provider.h" - -#include -#include - -#include "base/functional/callback.h" -#include "base/memory/ptr_util.h" -#include "chromecast/common/activity_filtering_url_loader_throttle.h" -#include "chromecast/renderer/cast_activity_url_filter_manager.h" -#include "components/url_rewrite/common/url_loader_throttle.h" -#include "third_party/blink/public/common/loader/url_loader_throttle.h" - -namespace chromecast { - -CastURLLoaderThrottleProvider::CastURLLoaderThrottleProvider( - blink::URLLoaderThrottleProviderType type, - CastActivityUrlFilterManager* url_filter_manager) - : type_(type), cast_activity_url_filter_manager_(url_filter_manager) { - DETACH_FROM_SEQUENCE(sequence_checker_); -} - -CastURLLoaderThrottleProvider::~CastURLLoaderThrottleProvider() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -CastURLLoaderThrottleProvider::CastURLLoaderThrottleProvider( - const chromecast::CastURLLoaderThrottleProvider& other) - : type_(other.type_), - cast_activity_url_filter_manager_( - other.cast_activity_url_filter_manager_) { - DETACH_FROM_SEQUENCE(sequence_checker_); -} - -std::unique_ptr -CastURLLoaderThrottleProvider::Clone() { - return base::WrapUnique(new CastURLLoaderThrottleProvider(*this)); -} - -blink::WebVector> -CastURLLoaderThrottleProvider::CreateThrottles( - base::optional_ref local_frame_token, - const network::ResourceRequest& request) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - blink::WebVector> throttles; - - if (cast_activity_url_filter_manager_ && local_frame_token.has_value()) { - auto* activity_url_filter = cast_activity_url_filter_manager_ - ->GetActivityUrlFilterForRenderFrameToken( - local_frame_token.value()); - if (activity_url_filter) { - throttles.emplace_back( - std::make_unique( - activity_url_filter)); - } - } - - return throttles; -} - -void CastURLLoaderThrottleProvider::SetOnline(bool is_online) {} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_url_loader_throttle_provider.h chromium-132.0.6834.159/chromecast/renderer/cast_url_loader_throttle_provider.h --- chromium-132.0.6834.110/chromecast/renderer/cast_url_loader_throttle_provider.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_url_loader_throttle_provider.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_CAST_URL_LOADER_THROTTLE_PROVIDER_H_ -#define CHROMECAST_RENDERER_CAST_URL_LOADER_THROTTLE_PROVIDER_H_ - -#include -#include - -#include "base/functional/callback_forward.h" -#include "base/memory/scoped_refptr.h" -#include "base/sequence_checker.h" -#include "third_party/blink/public/platform/url_loader_throttle_provider.h" - -namespace chromecast { -class CastActivityUrlFilterManager; - -class CastURLLoaderThrottleProvider : public blink::URLLoaderThrottleProvider { - public: - CastURLLoaderThrottleProvider( - blink::URLLoaderThrottleProviderType type, - CastActivityUrlFilterManager* url_filter_manager); - ~CastURLLoaderThrottleProvider() override; - CastURLLoaderThrottleProvider& operator=( - const CastURLLoaderThrottleProvider&) = delete; - - // blink::URLLoaderThrottleProvider implementation: - std::unique_ptr Clone() override; - blink::WebVector> CreateThrottles( - base::optional_ref local_frame_token, - const network::ResourceRequest& request) override; - void SetOnline(bool is_online) override; - - private: - // This copy constructor works in conjunction with Clone(), not intended for - // general use. - CastURLLoaderThrottleProvider(const CastURLLoaderThrottleProvider& other); - - blink::URLLoaderThrottleProviderType type_; - CastActivityUrlFilterManager* const cast_activity_url_filter_manager_; - - SEQUENCE_CHECKER(sequence_checker_); -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_CAST_URL_LOADER_THROTTLE_PROVIDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_websocket_handshake_throttle_provider.cc chromium-132.0.6834.159/chromecast/renderer/cast_websocket_handshake_throttle_provider.cc --- chromium-132.0.6834.110/chromecast/renderer/cast_websocket_handshake_throttle_provider.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_websocket_handshake_throttle_provider.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// 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 "chromecast/renderer/cast_websocket_handshake_throttle_provider.h" - -#include "base/feature_list.h" -#include "base/memory/ptr_util.h" -#include "base/task/single_thread_task_runner.h" -#include "chromecast/renderer/activity_filtering_websocket_handshake_throttle.h" -#include "services/network/public/cpp/features.h" - -namespace chromecast { - -CastWebSocketHandshakeThrottleProvider::CastWebSocketHandshakeThrottleProvider( - CastActivityUrlFilterManager* url_filter_manager) - : cast_activity_url_filter_manager_(url_filter_manager) { - DCHECK(url_filter_manager); - DETACH_FROM_THREAD(thread_checker_); -} - -CastWebSocketHandshakeThrottleProvider:: - ~CastWebSocketHandshakeThrottleProvider() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); -} - -CastWebSocketHandshakeThrottleProvider::CastWebSocketHandshakeThrottleProvider( - const chromecast::CastWebSocketHandshakeThrottleProvider& other) - : cast_activity_url_filter_manager_( - other.cast_activity_url_filter_manager_) { - DETACH_FROM_THREAD(thread_checker_); -} - -std::unique_ptr -CastWebSocketHandshakeThrottleProvider::Clone( - scoped_refptr task_runner) { - return base::WrapUnique(new CastWebSocketHandshakeThrottleProvider(*this)); -} - -std::unique_ptr -CastWebSocketHandshakeThrottleProvider::CreateThrottle( - base::optional_ref local_frame_token, - scoped_refptr task_runner) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - if (!local_frame_token.has_value()) { - return nullptr; - } - - auto* activity_url_filter = - cast_activity_url_filter_manager_ - ->GetActivityUrlFilterForRenderFrameToken(local_frame_token.value()); - if (!activity_url_filter) - return nullptr; - - return std::make_unique( - activity_url_filter); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_websocket_handshake_throttle_provider.h chromium-132.0.6834.159/chromecast/renderer/cast_websocket_handshake_throttle_provider.h --- chromium-132.0.6834.110/chromecast/renderer/cast_websocket_handshake_throttle_provider.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_websocket_handshake_throttle_provider.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -// 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. - -#ifndef CHROMECAST_RENDERER_CAST_WEBSOCKET_HANDSHAKE_THROTTLE_PROVIDER_H_ -#define CHROMECAST_RENDERER_CAST_WEBSOCKET_HANDSHAKE_THROTTLE_PROVIDER_H_ - -#include - -#include "base/task/single_thread_task_runner.h" -#include "base/threading/thread_checker.h" -#include "chromecast/renderer/cast_activity_url_filter_manager.h" -#include "third_party/blink/public/platform/websocket_handshake_throttle_provider.h" - -namespace chromecast { - -// This class allows cast_shell to provide a WebSocketHandshakeThrottle -// implementation to delay or block WebSocket handshakes. -// This must be constructed on the render thread, and then used and destructed -// on a single thread, which can be different from the render thread. -class CastWebSocketHandshakeThrottleProvider - : public blink::WebSocketHandshakeThrottleProvider { - public: - explicit CastWebSocketHandshakeThrottleProvider( - CastActivityUrlFilterManager* url_filter_manager); - - CastWebSocketHandshakeThrottleProvider& operator=( - const CastWebSocketHandshakeThrottleProvider&) = delete; - - ~CastWebSocketHandshakeThrottleProvider() override; - - // blink::WebSocketHandshakeThrottleProvider implementation: - std::unique_ptr Clone( - scoped_refptr task_runner) override; - std::unique_ptr CreateThrottle( - base::optional_ref local_frame_token, - scoped_refptr task_runner) override; - - private: - // This copy constructor works in conjunction with Clone(), not intended for - // general use. - CastWebSocketHandshakeThrottleProvider( - const CastWebSocketHandshakeThrottleProvider& other); - - CastActivityUrlFilterManager* const cast_activity_url_filter_manager_; - - THREAD_CHECKER(thread_checker_); -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_CAST_WEBSOCKET_HANDSHAKE_THROTTLE_PROVIDER_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_window_manager_bindings.cc chromium-132.0.6834.159/chromecast/renderer/cast_window_manager_bindings.cc --- chromium-132.0.6834.110/chromecast/renderer/cast_window_manager_bindings.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_window_manager_bindings.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,342 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/cast_window_manager_bindings.h" - -#include -#include - -#include "base/check.h" -#include "build/build_config.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/common/feature_constants.h" -#include "chromecast/common/mojom/gesture.mojom.h" -#include "chromecast/renderer/feature_manager.h" -#include "content/public/renderer/render_frame.h" -#include "gin/data_object_builder.h" -#include "third_party/blink/public/platform/browser_interface_broker_proxy.h" -#include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h" -#include "third_party/blink/public/web/web_local_frame.h" -#include "third_party/blink/public/web/web_view.h" - -namespace chromecast { -namespace shell { - -namespace { - -const char kBindingsObjectName[] = "windowManager"; -const char kOnBackGestureName[] = "onBackGesture"; -const char kOnBackGestureProgressName[] = "onBackGestureProgress"; -const char kOnBackGestureCancelName[] = "onBackGestureCancel"; -const char kOnTopDragGestureDoneName[] = "onTopDragGestureDone"; -const char kOnTopDragGestureProgressName[] = "onTopDragGestureProgress"; -const char kOnRightDragGestureDoneName[] = "onRightDragGestureDone"; -const char kOnRightDragGestureProgressName[] = "onRightDragGestureProgress"; -const char kOnTapGestureName[] = "onTapGesture"; -const char kOnTapDownGestureName[] = "onTapDownGesture"; -const char kCanGoBackName[] = "canGoBack"; -const char kCanTopDragName[] = "canTopDrag"; -const char kCanRightDragName[] = "canRightDrag"; -const char kMinimize[] = "minimize"; -const char kMaximize[] = "maximize"; - -#if !BUILDFLAG(IS_ANDROID) -const char kDisplayControlsName[] = "displayControls"; -#endif - -void OnGestureSourceDisconnectionError() { - LOG(ERROR) << "Connection error talking to system gesture source."; -} - -void OnWindowDisconnect() { - LOG(ERROR) << "Connection error talking to platform activity."; -} - -} // namespace - -CastWindowManagerBindings::CastWindowManagerBindings( - content::RenderFrame* render_frame, - const FeatureManager* feature_manager) - : CastBinding(render_frame), - feature_manager_(feature_manager), - handler_receiver_(this) { - DCHECK(feature_manager_); -} - -CastWindowManagerBindings::~CastWindowManagerBindings() {} - -void CastWindowManagerBindings::Install(v8::Local cast_platform, - v8::Isolate* isolate) { - if (feature_manager_->FeatureEnabled(feature::kEnableSystemGestures)) { - v8::Local windowManagerObject = - EnsureObjectExists(isolate, cast_platform, kBindingsObjectName); - - // On back bindings. - InstallBinding(isolate, windowManagerObject, kCanGoBackName, - &CastWindowManagerBindings::SetCanGoBack, - base::Unretained(this)); - InstallBinding(isolate, windowManagerObject, kOnBackGestureName, - &CastWindowManagerBindings::SetV8Callback, - base::Unretained(this), &on_back_gesture_callback_); - InstallBinding(isolate, windowManagerObject, kOnBackGestureProgressName, - &CastWindowManagerBindings::SetV8Callback, - base::Unretained(this), &on_back_gesture_progress_callback_); - InstallBinding(isolate, windowManagerObject, kOnBackGestureCancelName, - &CastWindowManagerBindings::SetV8Callback, - base::Unretained(this), &on_back_gesture_cancel_callback_); - - // Top drag bindings. - InstallBinding(isolate, windowManagerObject, kCanTopDragName, - &CastWindowManagerBindings::SetCanTopDrag, - base::Unretained(this)); - InstallBinding(isolate, windowManagerObject, kOnTopDragGestureDoneName, - &CastWindowManagerBindings::SetV8Callback, - base::Unretained(this), &on_top_drag_gesture_done_callback_); - InstallBinding(isolate, windowManagerObject, kOnTopDragGestureProgressName, - &CastWindowManagerBindings::SetV8Callback, - base::Unretained(this), - &on_top_drag_gesture_progress_callback_); - - // Right drag bindings. - InstallBinding(isolate, windowManagerObject, kCanRightDragName, - &CastWindowManagerBindings::SetCanRightDrag, - base::Unretained(this)); - InstallBinding(isolate, windowManagerObject, kOnRightDragGestureDoneName, - &CastWindowManagerBindings::SetV8Callback, - base::Unretained(this), - &on_right_drag_gesture_done_callback_); - InstallBinding( - isolate, windowManagerObject, kOnRightDragGestureProgressName, - &CastWindowManagerBindings::SetV8Callback, base::Unretained(this), - &on_right_drag_gesture_progress_callback_); - - // 'Tap' bindings. - InstallBinding(isolate, windowManagerObject, kOnTapGestureName, - &CastWindowManagerBindings::SetV8Callback, - base::Unretained(this), &on_tap_gesture_callback_); - InstallBinding(isolate, windowManagerObject, kOnTapDownGestureName, - &CastWindowManagerBindings::SetV8Callback, - base::Unretained(this), &on_tap_down_gesture_callback_); - } - if (feature_manager_->FeatureEnabled(feature::kEnableWindowControls)) { - v8::Local windowManagerObject = - EnsureObjectExists(isolate, cast_platform, kBindingsObjectName); - - InstallBinding(isolate, windowManagerObject, kMaximize, - &CastWindowManagerBindings::Show, base::Unretained(this)); - InstallBinding(isolate, windowManagerObject, kMinimize, - &CastWindowManagerBindings::Hide, base::Unretained(this)); - } -} - -v8::Local CastWindowManagerBindings::SetV8Callback( - v8::UniquePersistent* callback_function, - v8::Local callback) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - - *callback_function = v8::UniquePersistent(isolate, callback); - - return v8::Undefined(isolate); -} - -void CastWindowManagerBindings::Show() { - BindWindow(); - window_->Show(); -} - -void CastWindowManagerBindings::Hide() { - BindWindow(); - window_->Hide(); -} - -void CastWindowManagerBindings::SetCanGoBack(bool can_go_back) { - BindGestureSource(); - gesture_source_->SetCanGoBack(can_go_back); -} - -void CastWindowManagerBindings::SetCanTopDrag(bool can_top_drag) { - BindGestureSource(); - gesture_source_->SetCanTopDrag(can_top_drag); -} - -void CastWindowManagerBindings::SetCanRightDrag(bool can_right_drag) { - BindGestureSource(); - gesture_source_->SetCanRightDrag(can_right_drag); -} - -void CastWindowManagerBindings::OnTouchInputSupportSet( - PersistedResolver resolver, - PersistedContext original_context, - bool resolve_promise, - bool display_controls) { - DVLOG(2) << __FUNCTION__; - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = original_context.Get(isolate); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - - if (resolve_promise) { - resolver.Get(isolate) - ->Resolve(context, - -#if !BUILDFLAG(IS_ANDROID) - gin::DataObjectBuilder(isolate) - .Set(kDisplayControlsName, display_controls) - .Build() -#else - v8::Undefined(isolate) -#endif - ) - .ToChecked(); - } else { - resolver.Get(isolate)->Reject(context, v8::Undefined(isolate)).ToChecked(); - } -} - -void CastWindowManagerBindings::BindGestureSource() { - if (gesture_source_.is_bound() && gesture_source_.is_connected()) - return; - gesture_source_.reset(); - render_frame()->GetBrowserInterfaceBroker().GetInterface( - gesture_source_.BindNewPipeAndPassReceiver()); - gesture_source_.set_disconnect_handler( - base::BindRepeating(&OnGestureSourceDisconnectionError)); - handler_receiver_.reset(); - gesture_source_->Subscribe(handler_receiver_.BindNewPipeAndPassRemote()); -} - -void CastWindowManagerBindings::BindWindow() { - if (window_.is_bound() && window_.is_connected()) - return; - window_.reset(); - render_frame()->GetBrowserInterfaceBroker().GetInterface( - window_.BindNewPipeAndPassReceiver()); - window_.set_disconnect_handler(base::BindRepeating(&OnWindowDisconnect)); -} - -void CastWindowManagerBindings::InvokeV8Callback( - v8::UniquePersistent* callback_function) { - if (callback_function->IsEmpty()) { - return; - } - - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = web_frame->MainWorldScriptContext(); - v8::Context::Scope context_scope(context); - v8::Local handler = - v8::Local::New(isolate, std::move(*callback_function)); - - v8::MaybeLocal maybe_result = - handler->Call(context, context->Global(), 0, nullptr); - - *callback_function = v8::UniquePersistent(isolate, handler); - - v8::Local result; - std::ignore = maybe_result.ToLocal(&result); -} - -void CastWindowManagerBindings::InvokeV8Callback( - v8::UniquePersistent* callback_function, - const gfx::Point& touch_location) { - if (callback_function->IsEmpty()) { - return; - } - - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = web_frame->MainWorldScriptContext(); - v8::Context::Scope context_scope(context); - v8::Local handler = - v8::Local::New(isolate, std::move(*callback_function)); - - v8::Local touch_x = v8::Integer::New(isolate, touch_location.x()); - v8::Local touch_y = v8::Integer::New(isolate, touch_location.y()); - - auto args = v8::to_array>({touch_x, touch_y}); - - v8::MaybeLocal maybe_result = - handler->Call(context, context->Global(), args.size(), args.data()); - - *callback_function = v8::UniquePersistent(isolate, handler); - - v8::Local result; - std::ignore = maybe_result.ToLocal(&result); -} - -void CastWindowManagerBindings::OnBackGesture( - ::chromecast::mojom::GestureHandler::OnBackGestureCallback callback) { - // Note: Can't use InvokeV8Callback here because of the OnBackGestureCallback - // argument. So we have this boilerplate here until we can get rid of the - // unused callback argument. - if (on_back_gesture_callback_.IsEmpty()) { - std::move(callback).Run(false); - return; - } - - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = web_frame->MainWorldScriptContext(); - v8::Context::Scope context_scope(context); - v8::Local handler = v8::Local::New( - isolate, std::move(on_back_gesture_callback_)); - auto result = handler->Call(context, context->Global(), 0, nullptr); - - on_back_gesture_callback_ = - v8::UniquePersistent(isolate, handler); - if (result.IsEmpty()) { - LOG(ERROR) << "No value from callback execution; "; - std::move(callback).Run(false); - return; - } - - auto callback_return_value = result.ToLocalChecked(); - bool return_boolean = callback_return_value->BooleanValue(isolate); - std::move(callback).Run(return_boolean); -} - -void CastWindowManagerBindings::OnBackGestureProgress( - const gfx::Point& touch_location) { - InvokeV8Callback(&on_back_gesture_progress_callback_, touch_location); -} - -void CastWindowManagerBindings::OnBackGestureCancel() { - InvokeV8Callback(&on_back_gesture_cancel_callback_); -} - -void CastWindowManagerBindings::OnTopDragGestureDone() { - InvokeV8Callback(&on_top_drag_gesture_done_callback_); -} - -void CastWindowManagerBindings::OnTopDragGestureProgress( - const gfx::Point& touch_location) { - InvokeV8Callback(&on_top_drag_gesture_progress_callback_, touch_location); -} - -void CastWindowManagerBindings::OnRightDragGestureDone() { - InvokeV8Callback(&on_right_drag_gesture_done_callback_); -} - -void CastWindowManagerBindings::OnRightDragGestureProgress( - const gfx::Point& touch_location) { - InvokeV8Callback(&on_right_drag_gesture_progress_callback_, touch_location); -} - -void CastWindowManagerBindings::OnTapGesture() { - InvokeV8Callback(&on_tap_gesture_callback_); -} - -void CastWindowManagerBindings::OnTapDownGesture() { - InvokeV8Callback(&on_tap_down_gesture_callback_); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/cast_window_manager_bindings.h chromium-132.0.6834.159/chromecast/renderer/cast_window_manager_bindings.h --- chromium-132.0.6834.110/chromecast/renderer/cast_window_manager_bindings.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/cast_window_manager_bindings.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_CAST_WINDOW_MANAGER_BINDINGS_H_ -#define CHROMECAST_RENDERER_CAST_WINDOW_MANAGER_BINDINGS_H_ - -#include "base/memory/ptr_util.h" -#include "chromecast/browser/mojom/cast_content_window.mojom.h" -#include "chromecast/common/mojom/activity_window.mojom.h" -#include "chromecast/common/mojom/gesture.mojom.h" -#include "chromecast/renderer/native_bindings_helper.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "v8/include/v8.h" - -namespace chromecast { - -class FeatureManager; - -namespace shell { - -// Renderer side implementation of cast system gesture. -// Implements the mojo service which receives notification of gesture events, -// and also sets up the JS callback bindings to application code. -class CastWindowManagerBindings : public CastBinding, - public ::chromecast::mojom::GestureHandler { - public: - CastWindowManagerBindings(content::RenderFrame* render_frame, - const FeatureManager* feature_manager); - CastWindowManagerBindings(const CastWindowManagerBindings&) = delete; - CastWindowManagerBindings& operator=(const CastWindowManagerBindings&) = - delete; - - // ::chromecast::mojom::GestureHandler implementation: - void OnBackGesture(OnBackGestureCallback callback) override; - void OnBackGestureProgress(const gfx::Point& touch_location) override; - void OnBackGestureCancel() override; - void OnTopDragGestureProgress(const gfx::Point& touch_location) override; - void OnTopDragGestureDone() override; - void OnRightDragGestureProgress(const gfx::Point& touch_location) override; - void OnRightDragGestureDone() override; - void OnTapGesture() override; - void OnTapDownGesture() override; - - private: - friend class CastBinding; - - ~CastWindowManagerBindings() override; - - // Typedefs for v8 objects that need to run between tasks. - // v8::Global has move semantics, it does not imply unique ownership over an - // v8 object. You can create multiple v8::Globals from the same v8::Local. - using PersistedContext = v8::Global; - using PersistedResolver = v8::Global; - - v8::Local SetV8Callback( - v8::UniquePersistent* callback_function, - v8::Local callback); - void InvokeV8Callback(v8::UniquePersistent* callback_function); - void InvokeV8Callback(v8::UniquePersistent* callback_function, - const gfx::Point& touch_location); - - // CastBinding implementation: - void Install(v8::Local cast_platform, - v8::Isolate* isolate) override; - - void BindGestureSource(); - void BindWindow(); - - void Show(); - void Hide(); - void SetCanGoBack(bool can_go_back); - void SetCanTopDrag(bool can_top_drag); - void SetCanRightDrag(bool can_right_drag); - - void OnTouchInputSupportSet(PersistedResolver resolver, - PersistedContext original_context, - bool resolve_promise, - bool display_controls); - - const FeatureManager* feature_manager_; - - mojo::Remote<::chromecast::mojom::GestureSource> gesture_source_; - mojo::Remote<::chromecast::mojom::ActivityWindow> window_; - - // Receiver handle bound to self. - mojo::Receiver<::chromecast::mojom::GestureHandler> handler_receiver_; - - v8::UniquePersistent on_back_gesture_callback_; - v8::UniquePersistent on_back_gesture_progress_callback_; - v8::UniquePersistent on_back_gesture_cancel_callback_; - - v8::UniquePersistent on_top_drag_gesture_done_callback_; - v8::UniquePersistent on_top_drag_gesture_progress_callback_; - - v8::UniquePersistent on_right_drag_gesture_done_callback_; - v8::UniquePersistent on_right_drag_gesture_progress_callback_; - - v8::UniquePersistent on_tap_gesture_callback_; - - v8::UniquePersistent on_tap_down_gesture_callback_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_CAST_WINDOW_MANAGER_BINDINGS_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/feature_manager.cc chromium-132.0.6834.159/chromecast/renderer/feature_manager.cc --- chromium-132.0.6834.110/chromecast/renderer/feature_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/feature_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,180 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/feature_manager.h" - -#include -#include -#include -#include - -#include "base/check.h" -#include "base/containers/contains.h" -#include "base/logging.h" -#include "base/not_fatal_until.h" -#include "base/values.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/common/feature_constants.h" -#include "chromecast/renderer/assistant_bindings.h" -#include "chromecast/renderer/cast_demo_bindings.h" -#include "chromecast/renderer/cast_window_manager_bindings.h" -#include "chromecast/renderer/settings_ui_bindings.h" -#include "content/public/renderer/render_frame.h" -#include "content/public/renderer/render_frame_media_playback_options.h" -#include "services/network/public/cpp/is_potentially_trustworthy.h" -#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" -#include "third_party/blink/public/platform/web_runtime_features.h" -#include "third_party/blink/public/platform/web_security_origin.h" -#include "third_party/blink/public/platform/web_string.h" -#include "third_party/blink/public/web/web_local_frame.h" -#include "third_party/blink/public/web/web_security_policy.h" - -namespace chromecast { - -FeatureManager::FeatureManager(content::RenderFrame* render_frame) - : content::RenderFrameObserver(render_frame), - configured_(false), - can_install_bindings_(false), - dev_origin_(GURL()), - secure_origin_set_(false) { - registry_.AddInterface(base::BindRepeating( - &FeatureManager::OnFeatureManagerRequest, base::Unretained(this))); -} - -FeatureManager::~FeatureManager() {} - -void FeatureManager::OnInterfaceRequestForFrame( - const std::string& interface_name, - mojo::ScopedMessagePipeHandle* interface_pipe) { - registry_.TryBindInterface(interface_name, interface_pipe); -} - -void FeatureManager::OnDestruct() { - delete this; -} - -void FeatureManager::DidClearWindowObject() { - can_install_bindings_ = true; - if (!configured_) - return; - - EnableBindings(); -} - -void FeatureManager::ConfigureFeatures( - std::vector features) { - if (configured_) - return; - configured_ = true; - for (auto& feature : features) { - // If we want to add enabled/disabled status to FeaturePtr, we can overlap - // previous setting via [] operator - features_map_[feature->name] = std::move(feature); - } - - ConfigureFeaturesInternal(); - - if (!can_install_bindings_) - return; - EnableBindings(); -} - -void FeatureManager::ConfigureFeaturesInternal() { - if (FeatureEnabled(feature::kEnableDevMode)) { - const base::Value::Dict& dev_mode_config = - (features_map_.find(feature::kEnableDevMode)->second)->config; - const std::string* dev_mode_origin = - dev_mode_config.FindString(feature::kDevModeOrigin); - DCHECK(dev_mode_origin); - dev_origin_ = GURL(*dev_mode_origin); - DCHECK(dev_origin_.is_valid()); - } - - if (FeatureEnabled(feature::kDisableBackgroundSuspend)) { - auto options = render_frame()->GetRenderFrameMediaPlaybackOptions(); - options.is_background_suspend_enabled = false; - render_frame()->SetRenderFrameMediaPlaybackOptions(options); - } - - // Call feature-specific functions. - SetupAdditionalSecureOrigin(); - - // Disable timer throttling for background tabs before the frame is painted. - if (FeatureEnabled(feature::kDisableBackgroundTabTimerThrottle)) { - blink::WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(false); - } - if (FeatureEnabled(feature::kEnableSettingsUiMojo)) { - v8_bindings_.insert(new shell::SettingsUiBindings(render_frame())); - } - - // Window manager bindings will install themselves depending on the specific - // feature flags enabled, so we pass the feature manager through to let it - // decide. - v8_bindings_.insert( - new shell::CastWindowManagerBindings(render_frame(), this)); - if (FeatureEnabled(feature::kEnableDemoStandaloneMode)) { - v8_bindings_.insert(new shell::CastDemoBindings(render_frame())); - } - - if (FeatureEnabled(feature::kEnableAssistantMessagePipe)) { - auto& feature = GetFeature(feature::kEnableAssistantMessagePipe); - v8_bindings_.insert( - new shell::AssistantBindings(render_frame(), feature->config)); - } -} - -void FeatureManager::EnableBindings() { - LOG(INFO) << "Enabling bindings: " << *this; - for (auto* binding : v8_bindings_) { - binding->TryInstall(); - } -} - -void FeatureManager::OnFeatureManagerRequest( - mojo::PendingReceiver request) { - bindings_.Add(this, std::move(request)); -} - -bool FeatureManager::FeatureEnabled(const std::string& feature) const { - return base::Contains(features_map_, feature); -} - -const chromecast::shell::mojom::FeaturePtr& FeatureManager::GetFeature( - const std::string& feature) const { - auto itor = features_map_.find(feature); - CHECK(itor != features_map_.end(), base::NotFatalUntil::M130); - return itor->second; -} - -void FeatureManager::SetupAdditionalSecureOrigin() { - if (!dev_origin_.is_valid()) { - return; - } - - // Secure origin should be only set once, otherwise it will cause CHECK - // failure when race between origin safelist changing and thread creation - // happens (b/63583734). - if (secure_origin_set_) { - return; - } - - secure_origin_set_ = true; - - LOG(INFO) << "Treat origin " << dev_origin_ << " as secure origin"; - - blink::WebSecurityPolicy::AddSchemeToSecureContextSafelist( - blink::WebString::FromASCII(dev_origin_.scheme())); - - network::SecureOriginAllowlist::GetInstance().SetAuxiliaryAllowlist( - dev_origin_.spec(), nullptr); -} - -std::ostream& operator<<(std::ostream& os, const FeatureManager& features) { - for (auto& feature : features.features_map_) { - os << feature.first << " "; - } - return os; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/feature_manager.h chromium-132.0.6834.159/chromecast/renderer/feature_manager.h --- chromium-132.0.6834.110/chromecast/renderer/feature_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/feature_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_FEATURE_MANAGER_H_ -#define CHROMECAST_RENDERER_FEATURE_MANAGER_H_ - -#include -#include -#include -#include - -#include "base/containers/flat_set.h" -#include "base/values.h" -#include "chromecast/common/mojom/feature_manager.mojom.h" -#include "chromecast/renderer/native_bindings_helper.h" -#include "content/public/renderer/render_frame_observer.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "services/service_manager/public/cpp/binder_registry.h" -#include "url/gurl.h" - -namespace chromecast { - -// Receives messages from the browser process to enable/disable Cast -// application-facing features. Features usually have an associated V8 binding -// which exposes a platform capability to the app. -class FeatureManager : public content::RenderFrameObserver, - public shell::mojom::FeatureManager { - public: - explicit FeatureManager(content::RenderFrame* render_frame); - FeatureManager(const FeatureManager&) = delete; - FeatureManager& operator=(const FeatureManager&) = delete; - ~FeatureManager() override; - - const GURL& dev_origin() const { return dev_origin_; } - bool configured() const { return configured_; } - - bool FeatureEnabled(const std::string& feature) const; - - const chromecast::shell::mojom::FeaturePtr& GetFeature( - const std::string& feature) const; - - friend std::ostream& operator<<(std::ostream& os, - const FeatureManager& features); - - protected: - // Allows a derived class to add its own features at the end of - // mojom::FeatureManager::ConfigureFeatures(). - virtual void ConfigureFeaturesInternal(); - - // Map for storing enabled features, name -> FeaturePtr. - using FeaturesMap = - std::map; - FeaturesMap features_map_; - - base::flat_set v8_bindings_; - - private: - // content::RenderFrameObserver implementation: - void OnInterfaceRequestForFrame( - const std::string& interface_name, - mojo::ScopedMessagePipeHandle* interface_pipe) override; - void DidClearWindowObject() override; - void OnDestruct() override; - - // shell::mojom::FeatureManager implementation - void ConfigureFeatures( - std::vector features) override; - - // Bind the incoming request with this implementation - void OnFeatureManagerRequest( - mojo::PendingReceiver request); - - void EnableBindings(); - void SetupAdditionalSecureOrigin(); - - // Flag for when the configuration message is received from the browser. - bool configured_; - bool can_install_bindings_; - - // Origin enabled for development - GURL dev_origin_; - bool secure_origin_set_; - - service_manager::BinderRegistry registry_; - - mojo::ReceiverSet bindings_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_FEATURE_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/feature_manager_on_associated_interface.cc chromium-132.0.6834.159/chromecast/renderer/feature_manager_on_associated_interface.cc --- chromium-132.0.6834.110/chromecast/renderer/feature_manager_on_associated_interface.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/feature_manager_on_associated_interface.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/feature_manager_on_associated_interface.h" - -#include "base/check.h" -#include "base/logging.h" -#include "base/values.h" -#include "chromecast/base/cast_features.h" -#include "chromecast/common/feature_constants.h" -#include "chromecast/renderer/cast_content_settings_client.h" -#include "content/public/renderer/render_frame.h" - -namespace chromecast { -FeatureManagerOnAssociatedInterface::FeatureManagerOnAssociatedInterface( - content::RenderFrame* render_frame) - : FeatureManager(render_frame) {} - -FeatureManagerOnAssociatedInterface::~FeatureManagerOnAssociatedInterface() {} - -void FeatureManagerOnAssociatedInterface::ConfigureFeaturesInternal() { - FeatureManager::ConfigureFeaturesInternal(); - - if (FeatureEnabled(feature::kEnableTrackControlAppRendererFeatureUse)) { - std::string app_id("MissingAppId"); - auto& feature = - GetFeature(feature::kEnableTrackControlAppRendererFeatureUse); - const std::string* app_id_received = - feature->config.FindString(feature::kKeyAppId); - if (app_id_received) { - app_id = *app_id_received; - } else { - LOG(ERROR) << __func__ << " failed to receive valid app_id"; - } - bool allow_insecure_content = true; - // Lifetime is tied to |render_frame| via content::RenderFrameObserver. - new CastContentSettingsClient(render_frame(), app_id, - allow_insecure_content); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/feature_manager_on_associated_interface.h chromium-132.0.6834.159/chromecast/renderer/feature_manager_on_associated_interface.h --- chromium-132.0.6834.110/chromecast/renderer/feature_manager_on_associated_interface.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/feature_manager_on_associated_interface.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_FEATURE_MANAGER_ON_ASSOCIATED_INTERFACE_H_ -#define CHROMECAST_RENDERER_FEATURE_MANAGER_ON_ASSOCIATED_INTERFACE_H_ - -#include -#include - -#include "chromecast/renderer/feature_manager.h" -#include "content/public/renderer/render_frame_observer.h" -#include "mojo/public/cpp/bindings/associated_receiver_set.h" -#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" - -namespace chromecast { - -// Similar to the internal FeatureManager, but it's attached to associated -// interface to ensure the actions are taken before the webpage is loaded. -// TODO(b/187758538): Refactor this class with the internal FeatureManager. The -// most likely result is we upstream and merge the internal FeatureManager to -// this class and rename this class to FeatureManager. -class FeatureManagerOnAssociatedInterface : public FeatureManager { - public: - explicit FeatureManagerOnAssociatedInterface( - content::RenderFrame* render_frame); - FeatureManagerOnAssociatedInterface( - const FeatureManagerOnAssociatedInterface&) = delete; - FeatureManagerOnAssociatedInterface& operator=( - const FeatureManagerOnAssociatedInterface&) = delete; - ~FeatureManagerOnAssociatedInterface() override; - - private: - // FeautreManager implementation: - void ConfigureFeaturesInternal() override; - - // Bind the incoming request with this implementation - void OnFeatureManagerAssociatedRequest( - mojo::PendingAssociatedReceiver - pending_receiver); - - // Flag for when the configuration message is received from the browser. - bool configured_; - - // Map for storing enabled features, name -> FeaturePtr. - using FeaturesMap = - std::map; - FeaturesMap features_map_; - - blink::AssociatedInterfaceRegistry registry_; - mojo::AssociatedReceiverSet receivers_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_FEATURE_MANAGER_ON_ASSOCIATED_INTERFACE_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/media/DEPS chromium-132.0.6834.159/chromecast/renderer/media/DEPS --- chromium-132.0.6834.110/chromecast/renderer/media/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/media/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -include_rules = [ - "+mojo/public", - "+third_party/widevine/cdm/buildflags.h", - "+ui/gfx/geometry", -] diff -Nru chromium-132.0.6834.110/chromecast/renderer/media/key_systems_cast.cc chromium-132.0.6834.159/chromecast/renderer/media/key_systems_cast.cc --- chromium-132.0.6834.110/chromecast/renderer/media/key_systems_cast.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/media/key_systems_cast.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/media/key_systems_cast.h" - -#include -#include - -#include "base/check.h" -#include "base/command_line.h" -#include "build/build_config.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/media/base/key_systems_common.h" -#include "media/base/content_decryption_module.h" -#include "media/base/eme_constants.h" -#include "media/base/key_system_info.h" -#include "media/media_buildflags.h" -#include "third_party/widevine/cdm/buildflags.h" - -#if BUILDFLAG(ENABLE_WIDEVINE) -#include "components/cdm/renderer/widevine_key_system_info.h" -#endif - -using ::media::CdmSessionType; -using ::media::EmeConfig; -using ::media::EmeConfigRuleState; -using ::media::EmeFeatureSupport; -using ::media::EmeInitDataType; -using ::media::EmeMediaType; -using ::media::EncryptionScheme; -using ::media::SupportedCodecs; - -namespace chromecast { -namespace media { -namespace { - -#if BUILDFLAG(USE_CHROMECAST_CDMS) || BUILDFLAG(ENABLE_LIBRARY_CDMS) -SupportedCodecs GetCastEmeSupportedCodecs() { - SupportedCodecs codecs = ::media::EME_CODEC_AAC | ::media::EME_CODEC_AVC1 | - ::media::EME_CODEC_VP9_PROFILE0 | - ::media::EME_CODEC_VP9_PROFILE2 | - ::media::EME_CODEC_VP8; - -#if !BUILDFLAG(DISABLE_SECURE_FLAC_OPUS_DECODING) - codecs |= ::media::EME_CODEC_FLAC | ::media::EME_CODEC_OPUS; -#endif // BUILDFLAG(DISABLE_SECURE_FLAC_OPUS_DECODING) - -#if BUILDFLAG(ENABLE_PLATFORM_HEVC) - codecs |= ::media::EME_CODEC_HEVC_PROFILE_MAIN; - codecs |= ::media::EME_CODEC_HEVC_PROFILE_MAIN10; -#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC) - -#if BUILDFLAG(ENABLE_PLATFORM_DOLBY_VISION) - codecs |= ::media::EME_CODEC_DOLBY_VISION_AVC; -#if BUILDFLAG(ENABLE_PLATFORM_HEVC) - codecs |= ::media::EME_CODEC_DOLBY_VISION_HEVC; -#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC) -#endif // BUILDFLAG(ENABLE_PLATFORM_DOLBY_VISION) - -#if BUILDFLAG(ENABLE_PLATFORM_AC3_EAC3_AUDIO) - codecs |= ::media::EME_CODEC_AC3 | ::media::EME_CODEC_EAC3; -#endif // BUILDFLAG(ENABLE_PLATFORM_AC3_EAC3_AUDIO) - -#if BUILDFLAG(ENABLE_PLATFORM_DTS_AUDIO) - codecs |= ::media::EME_CODEC_DTS | ::media::EME_CODEC_DTSE | - ::media::EME_CODEC_DTSXP2; -#endif // BUILDFLAG(ENABLE_PLATFORM_DTS_AUDIO) - -#if BUILDFLAG(ENABLE_PLATFORM_MPEG_H_AUDIO) - codecs |= ::media::EME_CODEC_MPEG_H_AUDIO; -#endif // BUILDFLAG(ENABLE_PLATFORM_MPEG_H_AUDIO) - - return codecs; -} - -void AddCmaKeySystems(::media::KeySystemInfos* key_system_infos, - bool enable_persistent_license_support) { - // |codecs| may not be used if Widevine and Playready aren't supported. - [[maybe_unused]] SupportedCodecs codecs = GetCastEmeSupportedCodecs(); - -#if BUILDFLAG(ENABLE_WIDEVINE) - using Robustness = cdm::WidevineKeySystemInfo::Robustness; - - const base::flat_set kEncryptionSchemes = { - EncryptionScheme::kCenc, EncryptionScheme::kCbcs}; - - const base::flat_set kSessionTypes = { - CdmSessionType::kTemporary, CdmSessionType::kPersistentLicense}; - - key_system_infos->emplace_back(new cdm::WidevineKeySystemInfo( - codecs, // Regular codecs. - kEncryptionSchemes, // Encryption schemes. - kSessionTypes, // Session types. - codecs, // Hardware secure codecs. - kEncryptionSchemes, // Hardware secure encryption schemes. - kSessionTypes, // Hardware secure session types. - Robustness::HW_SECURE_CRYPTO, // Max audio robustness. - Robustness::HW_SECURE_ALL, // Max video robustness. - // Note: On Chromecast, all CDMs may have persistent state. - EmeFeatureSupport::ALWAYS_ENABLED, // Persistent state. - EmeFeatureSupport::ALWAYS_ENABLED)); // Distinctive identifier. -#endif // BUILDFLAG(ENABLE_WIDEVINE) -} -#endif // BUILDFLAG(USE_CHROMECAST_CDMS) || BUILDFLAG(ENABLE_LIBRARY_CDMS) - -} // namespace - -void AddChromecastKeySystems( - ::media::KeySystemInfos* key_system_infos, - bool enable_persistent_license_support) { -#if BUILDFLAG(USE_CHROMECAST_CDMS) || BUILDFLAG(ENABLE_LIBRARY_CDMS) - AddCmaKeySystems(key_system_infos, enable_persistent_license_support); -#endif // BUILDFLAG(USE_CHROMECAST_CDMS) || BUILDFLAG(ENABLE_LIBRARY_CDMS) -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/media/key_systems_cast.h chromium-132.0.6834.159/chromecast/renderer/media/key_systems_cast.h --- chromium-132.0.6834.110/chromecast/renderer/media/key_systems_cast.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/media/key_systems_cast.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_MEDIA_KEY_SYSTEMS_CAST_H_ -#define CHROMECAST_RENDERER_MEDIA_KEY_SYSTEMS_CAST_H_ - -#include "media/base/key_system_info.h" - -namespace chromecast { -namespace media { - -void AddChromecastKeySystems(::media::KeySystemInfos* key_system_infos, - bool enable_persistent_license_support); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_MEDIA_KEY_SYSTEMS_CAST_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/media/media_caps_observer_impl.cc chromium-132.0.6834.159/chromecast/renderer/media/media_caps_observer_impl.cc --- chromium-132.0.6834.110/chromecast/renderer/media/media_caps_observer_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/media/media_caps_observer_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/media/media_caps_observer_impl.h" - -#include "chromecast/media/base/supported_codec_profile_levels_memo.h" -#include "chromecast/public/media/decoder_config.h" - -namespace chromecast { -namespace media { - -MediaCapsObserverImpl::MediaCapsObserverImpl( - mojo::PendingRemote* proxy, - SupportedCodecProfileLevelsMemo* supported_profiles) - : supported_profiles_(supported_profiles), - receiver_(this, proxy->InitWithNewPipeAndPassReceiver()) {} - -MediaCapsObserverImpl::~MediaCapsObserverImpl() = default; - -void MediaCapsObserverImpl::AddSupportedCodecProfileLevel( - mojom::CodecProfileLevelPtr codec_profile_level) { - CodecProfileLevel converted_codec_profile_level( - {static_cast(codec_profile_level->codec), - static_cast(codec_profile_level->profile), - codec_profile_level->level}); - supported_profiles_->AddSupportedCodecProfileLevel( - converted_codec_profile_level); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/media/media_caps_observer_impl.h chromium-132.0.6834.159/chromecast/renderer/media/media_caps_observer_impl.h --- chromium-132.0.6834.110/chromecast/renderer/media/media_caps_observer_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/media/media_caps_observer_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_MEDIA_MEDIA_CAPS_OBSERVER_IMPL_H_ -#define CHROMECAST_RENDERER_MEDIA_MEDIA_CAPS_OBSERVER_IMPL_H_ - -#include "chromecast/common/mojom/media_caps.mojom.h" -#include "chromecast/media/base/supported_codec_profile_levels_memo.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver.h" - -namespace chromecast { -namespace media { - -class MediaCapsObserverImpl : public mojom::MediaCapsObserver { - public: - MediaCapsObserverImpl(mojo::PendingRemote* proxy, - SupportedCodecProfileLevelsMemo* supported_profiles); - - MediaCapsObserverImpl(const MediaCapsObserverImpl&) = delete; - MediaCapsObserverImpl& operator=(const MediaCapsObserverImpl&) = delete; - - ~MediaCapsObserverImpl() override; - - private: - void AddSupportedCodecProfileLevel( - mojom::CodecProfileLevelPtr codec_profile_level) override; - - SupportedCodecProfileLevelsMemo* supported_profiles_; - mojo::Receiver receiver_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_MEDIA_MEDIA_CAPS_OBSERVER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/memory_pressure_observer_impl.cc chromium-132.0.6834.159/chromecast/renderer/memory_pressure_observer_impl.cc --- chromium-132.0.6834.110/chromecast/renderer/memory_pressure_observer_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/memory_pressure_observer_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/memory_pressure_observer_impl.h" - -#include "base/memory/memory_pressure_listener.h" - -namespace chromecast { - -MemoryPressureObserverImpl::MemoryPressureObserverImpl( - mojo::PendingRemote* observer) - : receiver_(this, observer->InitWithNewPipeAndPassReceiver()) {} - -MemoryPressureObserverImpl::~MemoryPressureObserverImpl() = default; - -void MemoryPressureObserverImpl::MemoryPressureLevelChanged( - int32_t pressure_level) { - base::MemoryPressureListener::NotifyMemoryPressure( - static_cast( - pressure_level)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/memory_pressure_observer_impl.h chromium-132.0.6834.159/chromecast/renderer/memory_pressure_observer_impl.h --- chromium-132.0.6834.110/chromecast/renderer/memory_pressure_observer_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/memory_pressure_observer_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_MEMORY_PRESSURE_OBSERVER_IMPL_H_ -#define CHROMECAST_RENDERER_MEMORY_PRESSURE_OBSERVER_IMPL_H_ - -#include "chromecast/common/mojom/memory_pressure.mojom.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver.h" - -namespace chromecast { - -class MemoryPressureObserverImpl : public mojom::MemoryPressureObserver { - public: - MemoryPressureObserverImpl( - mojo::PendingRemote* observer); - - MemoryPressureObserverImpl(const MemoryPressureObserverImpl&) = delete; - MemoryPressureObserverImpl& operator=(const MemoryPressureObserverImpl&) = - delete; - - ~MemoryPressureObserverImpl() override; - - private: - void MemoryPressureLevelChanged(int32_t pressure_level) override; - - mojo::Receiver receiver_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_MEMORY_PRESSURE_OBSERVER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/native_bindings_helper.cc chromium-132.0.6834.159/chromecast/renderer/native_bindings_helper.cc --- chromium-132.0.6834.110/chromecast/renderer/native_bindings_helper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/native_bindings_helper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/native_bindings_helper.h" - -#include "base/logging.h" -#include "content/public/renderer/render_frame.h" -#include "gin/converter.h" -#include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h" -#include "third_party/blink/public/web/web_local_frame.h" - -namespace chromecast { - -namespace { -const char kCastObjectName[] = "cast"; -const char kCastPlatformObjectKey[] = "__platform__"; -} // namespace - -v8::Local GetOrCreateCastPlatformObject( - v8::Isolate* isolate, - v8::Local global) { - v8::Local cast = - EnsureObjectExists(isolate, global, kCastObjectName); - return EnsureObjectExists(isolate, cast, kCastPlatformObjectKey); -} - -v8::Local EnsureObjectExists(v8::Isolate* isolate, - v8::Local parent, - const std::string& key) { - v8::Local context = isolate->GetCurrentContext(); - v8::MaybeLocal child = - parent->Get(context, gin::StringToV8(isolate, key)); - v8::Local child_local; - v8::Local child_object; - if (child.ToLocal(&child_local) && child_local->IsObject() && - child_local->ToObject(context).ToLocal(&child_object)) - return child_object; - - if (!child_local.IsEmpty() && !child_local->IsUndefined()) - LOG(WARNING) << "Overwriting non-empty non-object with key " << key; - - v8::Local new_child_object = v8::Object::New(isolate); - v8::Maybe result = - parent->Set(context, gin::StringToSymbol(isolate, key), new_child_object); - if (result.IsNothing() || !result.FromJust()) - LOG(ERROR) << "Failed to set new object with key " << key; - - return new_child_object; -} - -CastBinding::CastBinding(content::RenderFrame* render_frame) - : content::RenderFrameObserver(render_frame) {} - -CastBinding::~CastBinding() {} - -void CastBinding::DidClearWindowObject() { - TryInstall(); -} - -void CastBinding::OnDestruct() { - delete this; -} - -void CastBinding::TryInstall() { - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - if (!web_frame) - return; - - v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - if (!isolate) - return; - - // The HandleScope must be created before MainWorldScriptContext is called. - v8::HandleScope handle_scope(isolate); - v8::Local context = web_frame->MainWorldScriptContext(); - v8::MicrotasksScope microtasks(context, - v8::MicrotasksScope::kDoNotRunMicrotasks); - if (context.IsEmpty()) - return; - - v8::Context::Scope context_scope(context); - v8::Local global = context->Global(); - v8::Local cast_platform = - GetOrCreateCastPlatformObject(isolate, global); - Install(cast_platform, isolate); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/native_bindings_helper.h chromium-132.0.6834.159/chromecast/renderer/native_bindings_helper.h --- chromium-132.0.6834.110/chromecast/renderer/native_bindings_helper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/native_bindings_helper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_NATIVE_BINDINGS_HELPER_H_ -#define CHROMECAST_RENDERER_NATIVE_BINDINGS_HELPER_H_ - -#include - -#include "base/functional/bind.h" -#include "content/public/renderer/render_frame_observer.h" -#include "gin/function_template.h" -#include "v8/include/v8.h" -namespace content { -class RenderFrame; -} - -namespace chromecast { - -// Returns the reference to "cast.__platform__", creating it if necessary. -v8::Local GetOrCreateCastPlatformObject( - v8::Isolate* isolate, - v8::Local global); - -// Returns parent[key], creating it as a v8::Object if necessary. This will -// aggressively overwrite things that are not objects. -v8::Local EnsureObjectExists(v8::Isolate* isolate, - v8::Local parent, - const std::string& key); - -// Binds |method| and |args| into a JS function named |method_name| which will -// be attached to |parent_object|. Return the bound function to caller. -template -v8::Local InstallBinding(v8::Isolate* isolate, - v8::Local parent_object, - std::string method_name, - Functor method, - Args&&... args) { - v8::Local temp(gin::CreateFunctionTemplate( - isolate, base::BindRepeating(method, std::forward(args)...))); - v8::Local func = - temp->GetFunction(isolate->GetCurrentContext()).ToLocalChecked(); - v8::Maybe result = parent_object->Set( - isolate->GetCurrentContext(), - gin::StringToSymbol(isolate, std::move(method_name)), func); - if (result.IsNothing() || !result.FromJust()) - LOG(ERROR) << "Failed to install binging for method " << method_name; - - return func; -} - -// Template for managing the lifetime of a cast_shell binding. Derive from -// from CastBinding and the class will be destroyed when the frame is -// destroyed. -class CastBinding : public content::RenderFrameObserver { - public: - CastBinding(const CastBinding&) = delete; - CastBinding& operator=(const CastBinding&) = delete; - - void TryInstall(); - - protected: - explicit CastBinding(content::RenderFrame* render_frame); - ~CastBinding() override; - - // content::RenderFrameObserver implementation: - void DidClearWindowObject() final; - void OnDestruct() final; - - // Adds function bindings to the cast.__platform__ object. - // The function can be called multiple times, sub classes should make sure - // the binding is updated in every call. - virtual void Install(v8::Local cast_platform, - v8::Isolate* isolate) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_NATIVE_BINDINGS_HELPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/queryable_data_store.cc chromium-132.0.6834.159/chromecast/renderer/queryable_data_store.cc --- chromium-132.0.6834.110/chromecast/renderer/queryable_data_store.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/queryable_data_store.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/queryable_data_store.h" - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/task/task_runner.h" -#include "base/values.h" -#include "chromecast/common/queryable_data.h" -#include "content/public/renderer/render_thread.h" - -namespace chromecast { - -QueryableDataStore::QueryableDataStore( - const scoped_refptr render_main_thread) - : render_main_thread_(std::move(render_main_thread)) {} - -QueryableDataStore::~QueryableDataStore() {} - -void QueryableDataStore::Set(const std::string& key, base::Value value) { - render_main_thread_->PostTask( - FROM_HERE, base::BindOnce(&QueryableData::RegisterQueryableValue, key, - std::move(value))); -} - -void QueryableDataStore::BindQueryableDataStoreReceiver( - mojo::PendingReceiver receiver) { - queryable_data_receivers_.Add(this, std::move(receiver)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/queryable_data_store.h chromium-132.0.6834.159/chromecast/renderer/queryable_data_store.h --- chromium-132.0.6834.110/chromecast/renderer/queryable_data_store.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/queryable_data_store.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_QUERYABLE_DATA_STORE_H_ -#define CHROMECAST_RENDERER_QUERYABLE_DATA_STORE_H_ - -#include - -#include "base/memory/ref_counted.h" -#include "chromecast/common/mojom/queryable_data_store.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/receiver_set.h" - -namespace base { -class Value; -class TaskRunner; -} // namespace base - -namespace chromecast { - -// This class is used to sync queryable data on the renderer thread based on -// messages from the browser process. -class QueryableDataStore : public shell::mojom::QueryableDataStore { - public: - explicit QueryableDataStore( - const scoped_refptr render_main_thread); - - QueryableDataStore(const QueryableDataStore&) = delete; - QueryableDataStore& operator=(const QueryableDataStore&) = delete; - - ~QueryableDataStore() override; - - void BindQueryableDataStoreReceiver( - mojo::PendingReceiver receiver); - - private: - // shell::mojom::QueryableDataStore implementation: - void Set(const std::string& key, base::Value value) override; - - const scoped_refptr render_main_thread_; - - mojo::ReceiverSet queryable_data_receivers_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_QUERYABLE_DATA_STORE_H_ diff -Nru chromium-132.0.6834.110/chromecast/renderer/settings_ui_bindings.cc chromium-132.0.6834.159/chromecast/renderer/settings_ui_bindings.cc --- chromium-132.0.6834.110/chromecast/renderer/settings_ui_bindings.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/settings_ui_bindings.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,173 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/renderer/settings_ui_bindings.h" - -#include -#include - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "content/public/renderer/render_frame.h" -#include "third_party/blink/public/platform/browser_interface_broker_proxy.h" -#include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h" -#include "third_party/blink/public/web/web_local_frame.h" - -namespace chromecast { -namespace shell { - -namespace { - -const int64_t kDelayBetweenReconnectionInMillis = 100; - -const char kSettingsUiName[] = "settings_ui"; -const char kSetSideSwipeHandler[] = "setSideSwipeHandler"; -const char kSetPlatformInfoHandler[] = "setPlatformInfoHandler"; -const char kRequestVisible[] = "requestVisible"; - -} // namespace - -SettingsUiBindings::SettingsUiBindings(content::RenderFrame* frame) - : CastBinding(frame), binding_(this), weak_factory_(this) { - ReconnectMojo(); -} - -SettingsUiBindings::~SettingsUiBindings() {} - -void SettingsUiBindings::HandleSideSwipe( - chromecast::mojom::SideSwipeEvent event, - chromecast::mojom::SideSwipeOrigin origin, - const gfx::Point& touch_location) { - if (side_swipe_handler_.IsEmpty()) { - return; - } - - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = web_frame->MainWorldScriptContext(); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - v8::Local handler = - v8::Local::New(isolate, std::move(side_swipe_handler_)); - - v8::Local touch_event = - v8::Integer::New(isolate, static_cast(event)); - v8::Local touch_origin = - v8::Integer::New(isolate, static_cast(origin)); - v8::Local touch_x = v8::Integer::New(isolate, touch_location.x()); - v8::Local touch_y = v8::Integer::New(isolate, touch_location.y()); - - auto args = v8::to_array>( - {touch_event, touch_origin, touch_x, touch_y}); - - v8::MaybeLocal maybe_result = - handler->Call(context, context->Global(), args.size(), args.data()); - - side_swipe_handler_ = v8::UniquePersistent(isolate, handler); - - v8::Local result; - std::ignore = maybe_result.ToLocal(&result); -} - -void SettingsUiBindings::SendPlatformInfo( - const std::string& platform_info_json) { - if (platform_info_handler_.IsEmpty()) { - pending_platform_info_json_ = platform_info_json; - return; - } - - blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame(); - v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = web_frame->MainWorldScriptContext(); - v8::MicrotasksScope microtasks_scope( - context, v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Context::Scope context_scope(context); - v8::Local handler = - v8::Local::New(isolate, std::move(platform_info_handler_)); - - v8::Local platform_info = - v8::String::NewFromUtf8(isolate, platform_info_json.data(), - v8::NewStringType::kInternalized) - .ToLocalChecked(); - - auto args = v8::to_array>({platform_info}); - - v8::MaybeLocal maybe_result = - handler->Call(context, context->Global(), args.size(), args.data()); - - platform_info_handler_ = v8::UniquePersistent(isolate, handler); - - v8::Local result; - std::ignore = maybe_result.ToLocal(&result); -} - -void SettingsUiBindings::Install(v8::Local cast_platform, - v8::Isolate* isolate) { - v8::Local settings_ui = - EnsureObjectExists(isolate, cast_platform, kSettingsUiName); - - InstallBinding(isolate, settings_ui, kSetSideSwipeHandler, - &SettingsUiBindings::SetSideSwipeHandler, - base::Unretained(this)); - InstallBinding(isolate, settings_ui, kSetPlatformInfoHandler, - &SettingsUiBindings::SetPlatformInfoHandler, - base::Unretained(this)); - InstallBinding(isolate, settings_ui, kRequestVisible, - &SettingsUiBindings::RequestVisible, base::Unretained(this)); -} - -void SettingsUiBindings::SetSideSwipeHandler( - v8::Local side_swipe_handler) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - side_swipe_handler_ = - v8::UniquePersistent(isolate, side_swipe_handler); -} - -void SettingsUiBindings::SetPlatformInfoHandler( - v8::Local platform_info_handler) { - v8::Isolate* isolate = - render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate(); - platform_info_handler_ = - v8::UniquePersistent(isolate, platform_info_handler); - if (!pending_platform_info_json_.empty()) { - SendPlatformInfo(pending_platform_info_json_); - pending_platform_info_json_.clear(); - } -} - -void SettingsUiBindings::RequestVisible(bool visible) { - if (settings_platform_ptr_) { - settings_platform_ptr_->RequestVisible(visible); - } -} - -void SettingsUiBindings::ReconnectMojo() { - if (binding_.is_bound()) - binding_.reset(); - if (settings_platform_ptr_.is_bound()) - settings_platform_ptr_.reset(); - - render_frame()->GetBrowserInterfaceBroker().GetInterface( - settings_platform_ptr_.BindNewPipeAndPassReceiver()); - settings_platform_ptr_.set_disconnect_handler(base::BindOnce( - &SettingsUiBindings::OnMojoConnectionError, weak_factory_.GetWeakPtr())); - settings_platform_ptr_->Connect(binding_.BindNewPipeAndPassRemote()); - mojo_reconnect_timer_.Stop(); -} - -void SettingsUiBindings::OnMojoConnectionError() { - LOG(WARNING) << "Disconnected from settings UI MOJO. Will reconnect every " - << kDelayBetweenReconnectionInMillis << " milliseconds."; - mojo_reconnect_timer_.Start( - FROM_HERE, base::Milliseconds(kDelayBetweenReconnectionInMillis), this, - &SettingsUiBindings::ReconnectMojo); -} - -} // namespace shell -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/renderer/settings_ui_bindings.h chromium-132.0.6834.159/chromecast/renderer/settings_ui_bindings.h --- chromium-132.0.6834.110/chromecast/renderer/settings_ui_bindings.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/renderer/settings_ui_bindings.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_RENDERER_SETTINGS_UI_BINDINGS_H_ -#define CHROMECAST_RENDERER_SETTINGS_UI_BINDINGS_H_ - -#include - -#include "base/memory/weak_ptr.h" -#include "base/timer/timer.h" -#include "chromecast/common/mojom/settings_ui.mojom.h" -#include "chromecast/renderer/native_bindings_helper.h" -#include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "v8/include/v8.h" - -namespace chromecast { -namespace shell { - -// Exposed to the platform settings UI app on display assistants. Handles -// certain swipe events to show/hide the settings menu. This also receives -// platform information periodically to update the device properties in the -// settings UI. -class SettingsUiBindings : public CastBinding, - public chromecast::mojom::SettingsClient { - public: - explicit SettingsUiBindings(content::RenderFrame* frame); - ~SettingsUiBindings() override; - SettingsUiBindings(const SettingsUiBindings&) = delete; - SettingsUiBindings& operator=(const SettingsUiBindings&) = delete; - - private: - friend class ::chromecast::CastBinding; - - // mojom::SettingsClient implementation: - void HandleSideSwipe(chromecast::mojom::SideSwipeEvent event, - chromecast::mojom::SideSwipeOrigin origin, - const gfx::Point& touch_location) override; - void SendPlatformInfo(const std::string& platform_info_json) override; - - // CastBinding implementation: - void Install(v8::Local cast_platform, - v8::Isolate* isolate) override; - - // Binding methods - void SetSideSwipeHandler(v8::Local side_swipe_handler); - void SetPlatformInfoHandler(v8::Local platform_info_handler); - void RequestVisible(bool visible); - - void ReconnectMojo(); - void OnMojoConnectionError(); - - std::string pending_platform_info_json_; - - v8::UniquePersistent side_swipe_handler_; - v8::UniquePersistent platform_info_handler_; - - mojo::Remote settings_platform_ptr_; - mojo::Receiver binding_; - base::RepeatingTimer mojo_reconnect_timer_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace shell -} // namespace chromecast - -#endif // CHROMECAST_RENDERER_SETTINGS_UI_BINDINGS_H_ diff -Nru chromium-132.0.6834.110/chromecast/resource_sizes/OWNERS chromium-132.0.6834.159/chromecast/resource_sizes/OWNERS --- chromium-132.0.6834.110/chromecast/resource_sizes/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/resource_sizes/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -juke@chromium.org -eliribble@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/resource_sizes/chromecast_resource_sizes.py chromium-132.0.6834.159/chromecast/resource_sizes/chromecast_resource_sizes.py --- chromium-132.0.6834.110/chromecast/resource_sizes/chromecast_resource_sizes.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/resource_sizes/chromecast_resource_sizes.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,330 +0,0 @@ -#!/usr/bin/env python -# Copyright 2021 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -"""Reports binary size metrics for Cast build artifacts. - -More information at //docs/speed/binary_size/metrics.md. -""" - -import argparse -import collections -import contextlib -import json -import logging -import os -import subprocess -import sys -import tempfile - - -@contextlib.contextmanager -def _SysPath(path): - """Library import context that temporarily appends |path| to |sys.path|.""" - if path and path not in sys.path: - sys.path.insert(0, path) - else: - path = None # Indicates that |sys.path| is not modified. - try: - yield - finally: - if path: - sys.path.pop(0) - - -DIR_SOURCE_ROOT = os.environ.get( - 'CHECKOUT_SOURCE_ROOT', - os.path.abspath( - os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))) - -BUILD_UTIL_PATH = os.path.join(DIR_SOURCE_ROOT, 'build', 'util') - -TRACING_PATH = os.path.join(DIR_SOURCE_ROOT, 'third_party', 'catapult', - 'tracing') - -EU_STRIP_PATH = os.path.join(DIR_SOURCE_ROOT, 'buildtools', 'third_party', - 'eu-strip', 'bin', 'eu-strip') - -with _SysPath(BUILD_UTIL_PATH): - from lib.common import perf_tests_results_helper - -with _SysPath(TRACING_PATH): - from tracing.value import convert_chart_json # pylint: disable=import-error - -_BASE_CHART = { - 'format_version': '0.1', - 'benchmark_name': 'resource_sizes', - 'benchmark_description': 'Cast resource size information.', - 'trace_rerun_options': [], - 'charts': {} -} - -_KEY_RAW = 'raw' -_KEY_GZIPPED = 'gzipped' -_KEY_STRIPPED = 'stripped' -_KEY_STRIPPED_GZIPPED = 'stripped_then_gzipped' - - -class _Group: - """A group of build artifacts whose file sizes are summed and tracked. - - Build artifacts for size tracking fall under these categories: - * File: A single file. - * Group: A collection of files. - * Dir: All files under a directory. - - Attributes: - paths: A list of files or directories to be tracked together. - title: The display name of the group. - track_stripped: Whether to also track summed stripped ELF sizes. - track_compressed: Whether to also track summed compressed sizes. - """ - - def __init__(self, paths, title, track_stripped=False, - track_compressed=False): - self.paths = paths - self.title = title - self.track_stripped = track_stripped - self.track_compressed = track_compressed - - -# List of disjoint build artifact groups for size tracking. -_TRACKED_GROUPS = [ - _Group(paths=['cast_shell'], - title='File: cast_shell', - track_stripped=True, - track_compressed=True), - _Group(paths=['assets/cast_shell.pak'], title='File: cast_shell.pak'), - _Group(paths=['chromecast_locales/'], title='Dir: chromecast_locales'), -] - - -def _visit_paths(base_dir, paths): - """Itemizes files specified by a list of paths. - - Args: - base_dir: Base directory for all elements in |paths|. - paths: A list of filenames or directory names to specify files whose sizes - to be counted. Directories are recursed. There's no de-duping effort. - Non-existing files or directories are ignored (with warning message). - """ - for path in paths: - full_path = os.path.join(base_dir, path) - if os.path.exists(full_path): - if os.path.isdir(full_path): - for dirpath, _, filenames in os.walk(full_path): - for filename in filenames: - yield os.path.join(dirpath, filename) - else: # Assume is file. - yield full_path - else: - logging.critical('Not found: %s', path) - - -def _is_probably_elf(filename): - """Heuristically decides whether |filename| is ELF via magic signature.""" - with open(filename, 'rb') as fh: - return fh.read(4) == '\x7FELF' - - -def _get_filesize(filename): - """Returns the size of a file, or 0 if file is not found.""" - try: - return os.path.getsize(filename) - except OSError: - logging.critical('Failed to get size: %s', filename) - return 0 - - -def _get_gzipped_filesize(filename): - """Returns the gzipped size of a file, or 0 if file is not found.""" - BUFFER_SIZE = 65536 - if not os.path.isfile(filename): - return 0 - try: - # Call gzip externally instead of using gzip package since it's > 2x faster. - cmd = ['gzip', '--best', '-c', filename] - p = subprocess.Popen(cmd, stdout=subprocess.PIPE) - # Manually counting bytes instead of using len(p.communicate()[0]) to avoid - # buffering the entire compressed data (can be ~100 MB). - ret = 0 - while True: - chunk = len(p.stdout.read(BUFFER_SIZE)) - if chunk == 0: - break - ret += chunk - return ret - except OSError: - logging.critical('Failed to get gzipped size: %s', filename) - return 0 - - -def _get_catagorized_filesizes(filename, track_compressed=False): - """Measures |filename| sizes under various transforms. - - Returns: A Counter (keyed by _Key_* constants) that stores measured sizes. - """ - sizes = collections.Counter() - sizes[_KEY_RAW] = _get_filesize(filename) - if track_compressed: - sizes[_KEY_GZIPPED] = _get_gzipped_filesize(filename) - - # Pre-assign values for non-ELF, or in case of failure for ELF. - sizes[_KEY_STRIPPED] = sizes[_KEY_RAW] - if track_compressed: - sizes[_KEY_STRIPPED_GZIPPED] = sizes[_KEY_GZIPPED] - - if _is_probably_elf(filename): - try: - temp_file = tempfile.NamedTemporaryFile() - cmd = [EU_STRIP_PATH, filename, '-o', temp_file.name] - subprocess.check_output(cmd) - sizes[_KEY_STRIPPED] = _get_filesize(temp_file.name) - if track_compressed: - sizes[_KEY_STRIPPED_GZIPPED] = _get_gzipped_filesize(temp_file.name) - if sizes[_KEY_STRIPPED] > sizes[_KEY_RAW]: - # This weird case has been observed for libwidevinecdm.so. - logging.critical('Stripping made things worse for %s' % filename) - except subprocess.CalledProcessError: - logging.critical('Failed to strip file: %s' % filename) - finally: - temp_file.close() - return sizes - - -def _dump_chart_json(output_dir, chartjson): - """Writes chart histogram to JSON files. - - Output files: - results-chart.json contains the chart JSON. - perf_results.json contains histogram JSON for Catapult. - - Args: - output_dir: Directory to place the JSON files. - chartjson: Source JSON data for output files. - """ - results_path = os.path.join(output_dir, 'results-chart.json') - logging.critical('Dumping chartjson to %s', results_path) - with open(results_path, 'w') as json_file: - json.dump(chartjson, json_file, indent=2) - - # We would ideally generate a histogram set directly instead of generating - # chartjson then converting. However, perf_tests_results_helper is in - # //build, which doesn't seem to have any precedent for depending on - # anything in Catapult. This can probably be fixed, but since this doesn't - # need to be super fast or anything, converting is a good enough solution - # for the time being. - histogram_result = convert_chart_json.ConvertChartJson(results_path) - if histogram_result.returncode != 0: - raise Exception('chartjson conversion failed with error: ' + - histogram_result.stdout) - - histogram_path = os.path.join(output_dir, 'perf_results.json') - logging.critical('Dumping histograms to %s', histogram_path) - with open(histogram_path, 'wb') as json_file: - json_file.write(histogram_result.stdout) - - -def _run_resource_sizes(args): - """Main flow to extract and output size data.""" - chartjson = _BASE_CHART.copy() - report_func = perf_tests_results_helper.ReportPerfResult - total_sizes = collections.Counter() - - def report_sizes(sizes, title, track_stripped, track_compressed): - report_func(chart_data=chartjson, - graph_title=title, - trace_title='size', - value=sizes[_KEY_RAW], - units='bytes') - - if track_stripped: - report_func(chart_data=chartjson, - graph_title=title + ' (Stripped)', - trace_title='size', - value=sizes[_KEY_STRIPPED], - units='bytes') - - if track_compressed: - report_func(chart_data=chartjson, - graph_title=title + ' (Gzipped)', - trace_title='size', - value=sizes[_KEY_GZIPPED], - units='bytes') - - if track_stripped and track_compressed: - report_func(chart_data=chartjson, - graph_title=title + ' (Stripped, Gzipped)', - trace_title='size', - value=sizes[_KEY_STRIPPED_GZIPPED], - units='bytes') - - for g in _TRACKED_GROUPS: - sizes = sum( - map(_get_catagorized_filesizes, _visit_paths(args.out_dir, g.paths), - [g.track_compressed] * len(g.paths)), collections.Counter()) - report_sizes(sizes, g.title, g.track_stripped, g.track_compressed) - - # Total compressed size is summed over individual compressed sizes, instead - # of concatanating first, then compress everything. This is done for - # simplicity. It also gives a conservative size estimate (assuming file - # metadata and overheads are negligible). - total_sizes += sizes - - report_sizes(total_sizes, 'Total', True, True) - - _dump_chart_json(args.output_dir, chartjson) - - -def main(): - """Parses arguments and runs high level flows.""" - argparser = argparse.ArgumentParser(description='Writes Cast size metrics.') - - argparser.add_argument('--chromium-output-directory', - dest='out_dir', - required=True, - type=os.path.realpath, - help='Location of the build artifacts.') - - output_group = argparser.add_mutually_exclusive_group() - - output_group.add_argument('--output-dir', - default='.', - help='Directory to save chartjson to.') - output_group.add_argument( - '--isolated-script-test-output', - type=os.path.realpath, - help='File to which results will be written in the simplified JSON ' - 'output format.') - - # Accepted to conform to the isolated script interface, but ignored. - argparser.add_argument('--isolated-script-test-filter', - help=argparse.SUPPRESS) - argparser.add_argument('--isolated-script-test-perf-output', - type=os.path.realpath, - help=argparse.SUPPRESS) - - args = argparser.parse_args() - - isolated_script_output = {'valid': False, 'failures': []} - if args.isolated_script_test_output: - test_name = 'chromecast_resource_sizes' - args.output_dir = os.path.join( - os.path.dirname(args.isolated_script_test_output), test_name) - if not os.path.exists(args.output_dir): - os.makedirs(args.output_dir) - - try: - _run_resource_sizes(args) - isolated_script_output = {'valid': True, 'failures': []} - finally: - if args.isolated_script_test_output: - results_path = os.path.join(args.output_dir, 'test_results.json') - with open(results_path, 'w') as output_file: - json.dump(isolated_script_output, output_file) - with open(args.isolated_script_test_output, 'w') as output_file: - json.dump(isolated_script_output, output_file) - - -if __name__ == '__main__': - main() diff -Nru chromium-132.0.6834.110/chromecast/service/cast_service.cc chromium-132.0.6834.159/chromecast/service/cast_service.cc --- chromium-132.0.6834.110/chromecast/service/cast_service.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/service/cast_service.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/service/cast_service.h" - -#include "base/check.h" -#include "base/notreached.h" -#include "base/run_loop.h" -#include "base/threading/thread_checker.h" - -namespace chromecast { - -CastService::CastService() - : stopped_(true), thread_checker_(new base::ThreadChecker()) {} - -CastService::~CastService() { - DCHECK(thread_checker_->CalledOnValidThread()); - DCHECK(stopped_); -} - -void CastService::Initialize() { - DCHECK(thread_checker_->CalledOnValidThread()); - InitializeInternal(); -} - -void CastService::Finalize() { - DCHECK(thread_checker_->CalledOnValidThread()); - FinalizeInternal(); -} - -void CastService::Start() { - DCHECK(thread_checker_->CalledOnValidThread()); - stopped_ = false; - StartInternal(); -} - -void CastService::Stop() { - DCHECK(thread_checker_->CalledOnValidThread()); - StopInternal(); - // Consume any pending tasks which should be done before destroying in-process - // renderer process, for example, destroying web_contents. - base::RunLoop().RunUntilIdle(); - stopped_ = true; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/service/cast_service.h chromium-132.0.6834.159/chromecast/service/cast_service.h --- chromium-132.0.6834.110/chromecast/service/cast_service.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/service/cast_service.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_SERVICE_CAST_SERVICE_H_ -#define CHROMECAST_SERVICE_CAST_SERVICE_H_ - -#include - -namespace base { -class ThreadChecker; -} - -namespace chromecast { - -class CastService { - public: - CastService(const CastService&) = delete; - CastService& operator=(const CastService&) = delete; - - virtual ~CastService(); - - // Initializes/finalizes the cast service. - void Initialize(); - void Finalize(); - - // Starts/stops the cast service. - void Start(); - void Stop(); - - protected: - CastService(); - - // Implementation-specific initialization. Initialization of cast service's - // sub-components, and anything that requires IO operations should go here. - // Anything that should happen before cast service is started but doesn't need - // the sub-components to finish initializing should also go here. - virtual void InitializeInternal() = 0; - - // Implementation-specific finalization. Any initializations done by - // InitializeInternal() should be finalized here. - virtual void FinalizeInternal() = 0; - - // Implementation-specific start behavior. It basically starts the - // sub-component services and does additional initialization that cannot be - // done in the InitializationInternal(). - virtual void StartInternal() = 0; - - // Implementation-specific stop behavior. Any initializations done by - // StartInternal() should be finalized here. - virtual void StopInternal() = 0; - - private: - bool stopped_; - const std::unique_ptr thread_checker_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_SERVICE_CAST_SERVICE_H_ diff -Nru chromium-132.0.6834.110/chromecast/shared/DEPS chromium-132.0.6834.159/chromecast/shared/DEPS --- chromium-132.0.6834.110/chromecast/shared/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/shared/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -include_rules = [ - "+chromecast/bindings/shared", - "+chromecast/public/media", - "+third_party/cast_core/public/src/proto/bindings", -] diff -Nru chromium-132.0.6834.110/chromecast/shared/platform_info_serializer.cc chromium-132.0.6834.159/chromecast/shared/platform_info_serializer.cc --- chromium-132.0.6834.110/chromecast/shared/platform_info_serializer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/shared/platform_info_serializer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,361 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/shared/platform_info_serializer.h" - -#include - -#include "base/check.h" -#include "base/functional/callback.h" -#include "base/logging.h" -#include "chromecast/bindings/shared/proto_serializer.h" - -namespace chromecast { -namespace { -bool IsOutOfRange(int value, int min, int max) { - return min > value || max < value; -} -} // namespace - -PlatformInfoSerializer::PlatformInfoSerializer() = default; - -PlatformInfoSerializer::PlatformInfoSerializer(PlatformInfoSerializer&& other) = - default; - -PlatformInfoSerializer::~PlatformInfoSerializer() = default; - -PlatformInfoSerializer& PlatformInfoSerializer::operator=( - PlatformInfoSerializer&& other) = default; - -// static -std::optional PlatformInfoSerializer::Deserialize( - std::string_view base64) { - std::optional proto = - chromecast::bindings::ProtoSerializer< - cast::bindings::MediaCapabilitiesMessage>::Deserialize(base64); - if (!proto) { - return std::nullopt; - } - - PlatformInfoSerializer parser; - parser.platform_info_ = std::move(*proto); - return parser; -} - -std::string PlatformInfoSerializer::Serialize() const { - return chromecast::bindings::ProtoSerializer< - cast::bindings::MediaCapabilitiesMessage>::Serialize(platform_info_); -} - -void PlatformInfoSerializer::SetMaxWidth(int max_width) { - platform_info_.set_max_width(max_width); -} - -void PlatformInfoSerializer::SetMaxHeight(int max_height) { - platform_info_.set_max_height(max_height); -} - -void PlatformInfoSerializer::SetMaxFrameRate(int max_frame_rate) { - platform_info_.set_max_frame_rate(max_frame_rate); -} - -void PlatformInfoSerializer::SetSupportedCryptoBlockFormat( - const std::string& format) { - platform_info_.set_supported_cryptoblock_format(format); -} - -void PlatformInfoSerializer::SetMaxChannels(int max_channels) { - platform_info_.set_max_channels(max_channels); -} - -void PlatformInfoSerializer::SetPcmSurroundSoundSupported(bool is_supported) { - platform_info_.set_is_pcm_surround_sound_supported(is_supported); -} - -void PlatformInfoSerializer::SetPlatformDolbyVisionEnabled(bool is_enabled) { - platform_info_.set_is_platform_dolby_vision_enabled(is_enabled); -} - -void PlatformInfoSerializer::SetDolbyVisionSupported(bool is_supported) { - platform_info_.set_is_dolby_vision_supported(is_supported); -} - -void PlatformInfoSerializer::SetDolbyVision4kP60Supported(bool is_supported) { - platform_info_.set_is_dolby_vision4k_p60_supported(is_supported); -} - -void PlatformInfoSerializer::SetDolbyVisionSupportedByCurrentHdmiMode( - bool is_supported) { - platform_info_.set_is_dolby_vision_supported_by_current_hdmi_mode( - is_supported); -} - -void PlatformInfoSerializer::SetHdmiVideoModeSwitchEnabled(bool is_enabled) { - platform_info_.set_is_hdmi_video_mode_switch_enabled(is_enabled); -} - -void PlatformInfoSerializer::SetPlatformHevcEnabled(bool is_enabled) { - platform_info_.set_is_platform_hevc_enabled(is_enabled); -} - -void PlatformInfoSerializer::SetHdmiModeHdrCheckEnforced(bool is_enforced) { - platform_info_.set_is_hdmi_mode_hdr_check_enforced(is_enforced); -} - -void PlatformInfoSerializer::SetHdrSupportedByCurrentHdmiMode( - bool is_supported) { - platform_info_.set_is_hdr_supported_by_current_hdmi_mode(is_supported); -} - -void PlatformInfoSerializer::SetSmpteSt2084Supported(bool is_supported) { - platform_info_.set_is_smpte_st2084_supported(is_supported); -} - -void PlatformInfoSerializer::SetHlgSupported(bool is_supported) { - platform_info_.set_is_hlg_supported(is_supported); -} - -void PlatformInfoSerializer::SetHdrFeatureEnabled(bool is_enabled) { - platform_info_.set_is_hdr_feature_enabled(is_enabled); -} - -void PlatformInfoSerializer::SetSupportedLegacyVp9Levels( - std::vector levels) { - platform_info_.clear_supported_legacy_vp9_levels(); - for (int level : levels) { - platform_info_.add_supported_legacy_vp9_levels(level); - } -} - -void PlatformInfoSerializer::SetHdcpVersion(int hdcp_version) { - platform_info_.set_hdcp_version(hdcp_version); -} - -void PlatformInfoSerializer::SetSpatialRenderingSupportMask(int mask) { - platform_info_.set_spatial_rendering_support_mask(mask); -} - -void PlatformInfoSerializer::SetMaxFillRate(int max_fill_rate) { - platform_info_.set_max_fill_rate(max_fill_rate); -} - -void PlatformInfoSerializer::SetSupportedAudioCodecs( - std::vector codec_infos) { - platform_info_.clear_supported_audio_codecs(); - for (const auto& element : codec_infos) { - cast::bindings::AudioCodecInfo info; - DCHECK(cast::bindings::AudioCodecInfo::AudioCodec_IsValid(element.codec)); - DCHECK(cast::bindings::AudioCodecInfo::SampleFormat_IsValid( - element.sample_format)); - info.set_codec( - cast::bindings::AudioCodecInfo::AudioCodec_IsValid(element.codec) - ? static_cast( - element.codec) - : cast::bindings::AudioCodecInfo::AUDIO_CODEC_UNKNOWN); - info.set_sample_format( - cast::bindings::AudioCodecInfo::SampleFormat_IsValid( - element.sample_format) - ? static_cast( - element.sample_format) - : cast::bindings::AudioCodecInfo::SAMPLE_FORMAT_UNKNOWN); - info.set_max_samples_per_second(element.max_samples_per_second); - info.set_max_audio_channels(element.max_audio_channels); - *platform_info_.add_supported_audio_codecs() = std::move(info); - } -} - -void PlatformInfoSerializer::SetSupportedVideoCodecs( - std::vector codec_infos) { - for (auto& element : codec_infos) { - cast::bindings::VideoCodecInfo info; - DCHECK(cast::bindings::VideoCodecInfo::VideoCodec_IsValid(element.codec)); - DCHECK( - cast::bindings::VideoCodecInfo::VideoProfile_IsValid(element.profile)); - info.set_codec( - cast::bindings::VideoCodecInfo::VideoCodec_IsValid(element.codec) - ? static_cast( - element.codec) - : cast::bindings::VideoCodecInfo::VIDEO_CODEC_UNKNOWN); - info.set_profile( - cast::bindings::VideoCodecInfo::VideoProfile_IsValid(element.profile) - ? static_cast( - element.profile) - : cast::bindings::VideoCodecInfo::VIDEO_PROFILE_UNKNOWN); - *platform_info_.add_supported_video_codecs() = std::move(info); - } -} - -std::optional PlatformInfoSerializer::MaxWidth() const { - return platform_info_.max_width(); -} - -std::optional PlatformInfoSerializer::MaxHeight() const { - return platform_info_.max_height(); -} - -std::optional PlatformInfoSerializer::MaxFrameRate() const { - return platform_info_.max_frame_rate(); -} - -std::optional PlatformInfoSerializer::SupportedCryptoBlockFormat() - const { - return platform_info_.supported_cryptoblock_format(); -} - -std::optional PlatformInfoSerializer::MaxChannels() const { - return platform_info_.max_channels(); -} - -std::optional PlatformInfoSerializer::PcmSurroundSoundSupported() const { - return platform_info_.is_pcm_surround_sound_supported(); -} - -std::optional PlatformInfoSerializer::IsPlatformDolbyVisionEnabled() - const { - return platform_info_.is_platform_dolby_vision_enabled(); -} - -std::optional PlatformInfoSerializer::IsDolbyVisionSupported() const { - return platform_info_.is_dolby_vision_supported(); -} - -std::optional PlatformInfoSerializer::IsDolbyVision4kP60Supported() - const { - return platform_info_.is_dolby_vision4k_p60_supported(); -} - -std::optional -PlatformInfoSerializer::IsDolbyVisionSupportedByCurrentHdmiMode() const { - return platform_info_.is_dolby_vision_supported_by_current_hdmi_mode(); -} - -std::optional PlatformInfoSerializer::IsHdmiVideoModeSwitchEnabled() - const { - return platform_info_.is_hdmi_video_mode_switch_enabled(); -} - -std::optional PlatformInfoSerializer::IsPlatformHevcEnabled() const { - return platform_info_.is_platform_hevc_enabled(); -} - -std::optional PlatformInfoSerializer::IsHdmiModeHdrCheckEnforced() const { - return platform_info_.is_hdmi_mode_hdr_check_enforced(); -} - -std::optional PlatformInfoSerializer::IsHdrSupportedByCurrentHdmiMode() - const { - return platform_info_.is_hdr_supported_by_current_hdmi_mode(); -} - -std::optional PlatformInfoSerializer::IsSmpteSt2084Supported() const { - return platform_info_.is_smpte_st2084_supported(); -} - -std::optional PlatformInfoSerializer::IsHlgSupported() const { - return platform_info_.is_hlg_supported(); -} - -std::optional PlatformInfoSerializer::IsHdrFeatureEnabled() const { - return platform_info_.is_hdr_feature_enabled(); -} - -std::optional> -PlatformInfoSerializer::SupportedLegacyVp9Levels() const { - std::vector levels; - levels.reserve(platform_info_.supported_legacy_vp9_levels_size()); - for (const auto& level : platform_info_.supported_legacy_vp9_levels()) { - levels.push_back(level); - } - - return levels; -} - -std::optional PlatformInfoSerializer::HdcpVersion() const { - return platform_info_.hdcp_version(); -} - -std::optional PlatformInfoSerializer::SpatialRenderingSupportMask() const { - return platform_info_.spatial_rendering_support_mask(); -} - -std::optional PlatformInfoSerializer::MaxFillRate() const { - return platform_info_.max_fill_rate(); -} - -std::optional> -PlatformInfoSerializer::SupportedAudioCodecs() const { - std::vector infos; - infos.reserve(platform_info_.supported_audio_codecs_size()); - for (const auto& info : platform_info_.supported_audio_codecs()) { - if (IsOutOfRange(info.codec(), media::AudioCodec::kAudioCodecMin, - media::AudioCodec::kAudioCodecMax)) { - LOG(WARNING) << "Unrecognized AudioCodec: " << info.codec(); - continue; - } - - if (IsOutOfRange(info.sample_format(), - media::SampleFormat::kSampleFormatMin, - media::SampleFormat::kSampleFormatMax)) { - LOG(WARNING) << "Unrecognized SampleFormat: " << info.sample_format(); - continue; - } - - AudioCodecInfo parsed; - parsed.codec = static_cast(info.codec()); - parsed.sample_format = - static_cast(info.sample_format()); - parsed.max_samples_per_second = info.max_samples_per_second(); - parsed.max_audio_channels = info.max_audio_channels(); - infos.push_back(std::move(parsed)); - } - - return infos.empty() - ? std::nullopt - : std::make_optional< - std::vector>(infos); -} - -std::optional> -PlatformInfoSerializer::SupportedVideoCodecs() const { - std::vector infos; - infos.reserve(platform_info_.supported_video_codecs_size()); - for (const auto& info : platform_info_.supported_video_codecs()) { - if (IsOutOfRange(info.codec(), media::VideoCodec::kVideoCodecMin, - media::VideoCodec::kVideoCodecMax)) { - LOG(WARNING) << "Unrecognized VideoCodec: " << info.codec(); - continue; - } - - if (IsOutOfRange(info.profile(), media::VideoProfile::kVideoProfileMin, - media::VideoProfile::kVideoProfileMax)) { - LOG(WARNING) << "Unrecognized VideoProfile: " << info.profile(); - continue; - } - - VideoCodecInfo parsed; - parsed.codec = static_cast(info.codec()); - parsed.profile = static_cast(info.profile()); - infos.push_back(std::move(parsed)); - } - - return infos.empty() - ? std::nullopt - : std::make_optional< - std::vector>(infos); -} - -bool operator==(const PlatformInfoSerializer::AudioCodecInfo& first, - const PlatformInfoSerializer::AudioCodecInfo& second) { - return first.codec == second.codec && - first.sample_format == second.sample_format && - first.max_samples_per_second == second.max_samples_per_second && - first.max_audio_channels == second.max_audio_channels; -} - -bool operator==(const PlatformInfoSerializer::VideoCodecInfo& first, - const PlatformInfoSerializer::VideoCodecInfo& second) { - return first.codec == second.codec && first.profile == second.profile; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/shared/platform_info_serializer.h chromium-132.0.6834.159/chromecast/shared/platform_info_serializer.h --- chromium-132.0.6834.110/chromecast/shared/platform_info_serializer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/shared/platform_info_serializer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_SHARED_PLATFORM_INFO_SERIALIZER_H_ -#define CHROMECAST_SHARED_PLATFORM_INFO_SERIALIZER_H_ - -#include -#include -#include -#include - -#include "chromecast/public/media/decoder_config.h" -#include "third_party/cast_core/public/src/proto/bindings/media_capabilities.pb.h" - -namespace chromecast { - -// This class is responsible for serialization and deserialization of JSON -// messages used for specifying the media capabilities of a Cast receiver. -class PlatformInfoSerializer { - public: - // Information about a supported audio codec. - struct AudioCodecInfo { - media::AudioCodec codec = media::AudioCodec::kAudioCodecUnknown; - media::SampleFormat sample_format = - media::SampleFormat::kUnknownSampleFormat; - int max_samples_per_second = 0; - int max_audio_channels = 0; - }; - - // Information about a supported video codec. - struct VideoCodecInfo { - media::VideoCodec codec = media::VideoCodec::kVideoCodecUnknown; - media::VideoProfile profile = media::VideoProfile::kVideoProfileUnknown; - }; - - PlatformInfoSerializer(); - PlatformInfoSerializer(PlatformInfoSerializer&& other); - ~PlatformInfoSerializer(); - PlatformInfoSerializer& operator=(PlatformInfoSerializer&& other); - - cast::bindings::MediaCapabilitiesMessage* platform_info(); - - std::string Serialize() const; - static std::optional Deserialize( - std::string_view base64); - - // Setters for known valid properties. - void SetMaxWidth(int max_width); - void SetMaxHeight(int max_height); - void SetMaxFrameRate(int max_frame_rate); - void SetSupportedCryptoBlockFormat(const std::string& format); - void SetMaxChannels(int max_channels); - void SetPcmSurroundSoundSupported(bool is_supported); - void SetPlatformDolbyVisionEnabled(bool is_enabled); - void SetDolbyVisionSupported(bool is_supported); - void SetDolbyVision4kP60Supported(bool is_supported); - void SetDolbyVisionSupportedByCurrentHdmiMode(bool is_supported); - void SetHdmiVideoModeSwitchEnabled(bool is_enabled); - void SetPlatformHevcEnabled(bool is_enabled); - void SetHdmiModeHdrCheckEnforced(bool is_enforced); - void SetHdrSupportedByCurrentHdmiMode(bool is_supported); - void SetSmpteSt2084Supported(bool is_supported); - void SetHlgSupported(bool is_supported); - void SetHdrFeatureEnabled(bool is_enabled); - void SetHdcpVersion(int hdcp_version); - void SetSpatialRenderingSupportMask(int mask); - void SetMaxFillRate(int max_fill_rate); - void SetSupportedAudioCodecs(std::vector codec_infos); - void SetSupportedVideoCodecs(std::vector codec_infos); - - // Getters for the same properties. Returns std::nullopt if no such value is - // set, and the set value in all other cases. - std::optional MaxWidth() const; - std::optional MaxHeight() const; - std::optional MaxFrameRate() const; - std::optional SupportedCryptoBlockFormat() const; - std::optional MaxChannels() const; - std::optional PcmSurroundSoundSupported() const; - std::optional IsPlatformDolbyVisionEnabled() const; - std::optional IsDolbyVisionSupported() const; - std::optional IsDolbyVision4kP60Supported() const; - std::optional IsDolbyVisionSupportedByCurrentHdmiMode() const; - std::optional IsHdmiVideoModeSwitchEnabled() const; - std::optional IsPlatformHevcEnabled() const; - std::optional IsHdmiModeHdrCheckEnforced() const; - std::optional IsHdrSupportedByCurrentHdmiMode() const; - std::optional IsSmpteSt2084Supported() const; - std::optional IsHlgSupported() const; - std::optional IsHdrFeatureEnabled() const; - std::optional HdcpVersion() const; - std::optional SpatialRenderingSupportMask() const; - std::optional MaxFillRate() const; - std::optional> SupportedAudioCodecs() const; - std::optional> SupportedVideoCodecs() const; - - // Deprecated fields. - void SetSupportedLegacyVp9Levels(std::vector levels); - std::optional> SupportedLegacyVp9Levels() const; - - private: - // All currently produced values. - cast::bindings::MediaCapabilitiesMessage platform_info_; -}; - -bool operator==(const PlatformInfoSerializer::AudioCodecInfo& first, - const PlatformInfoSerializer::AudioCodecInfo& second); - -bool operator==(const PlatformInfoSerializer::VideoCodecInfo& first, - const PlatformInfoSerializer::VideoCodecInfo& second); - -} // namespace chromecast - -#endif // CHROMECAST_SHARED_PLATFORM_INFO_SERIALIZER_H_ diff -Nru chromium-132.0.6834.110/chromecast/shared/platform_info_serializer_unittest.cc chromium-132.0.6834.159/chromecast/shared/platform_info_serializer_unittest.cc --- chromium-132.0.6834.110/chromecast/shared/platform_info_serializer_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/shared/platform_info_serializer_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,300 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/shared/platform_info_serializer.h" - -#include "chromecast/public/media/decoder_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -PlatformInfoSerializer ConvertAndValidate( - const PlatformInfoSerializer& parser) { - std::string base64 = parser.Serialize(); - std::optional deserialized_parser = - PlatformInfoSerializer::Deserialize(base64); - EXPECT_TRUE(deserialized_parser); - EXPECT_EQ(parser.Serialize(), deserialized_parser->Serialize()); - return std::move(deserialized_parser.value()); -} - -class PlatformInfoSerializerTest : public testing::Test { - public: - PlatformInfoSerializerTest() = default; - ~PlatformInfoSerializerTest() override = default; - - protected: - PlatformInfoSerializer serializer_; -}; - -TEST_F(PlatformInfoSerializerTest, MaxWidth) { - serializer_.SetMaxWidth(42); - EXPECT_EQ(42, ConvertAndValidate(serializer_).MaxWidth().value()); - - serializer_.SetMaxWidth(12); - EXPECT_EQ(12, ConvertAndValidate(serializer_).MaxWidth().value()); - - serializer_.SetMaxWidth(7); - EXPECT_EQ(7, ConvertAndValidate(serializer_).MaxWidth().value()); -} - -TEST_F(PlatformInfoSerializerTest, MaxHeight) { - serializer_.SetMaxHeight(42); - EXPECT_EQ(42, ConvertAndValidate(serializer_).MaxHeight().value()); - - serializer_.SetMaxHeight(12); - EXPECT_EQ(12, ConvertAndValidate(serializer_).MaxHeight().value()); - - serializer_.SetMaxHeight(7); - EXPECT_EQ(7, ConvertAndValidate(serializer_).MaxHeight().value()); -} - -TEST_F(PlatformInfoSerializerTest, MaxFrameRate) { - serializer_.SetMaxFrameRate(42); - EXPECT_EQ(42, ConvertAndValidate(serializer_).MaxFrameRate().value()); - - serializer_.SetMaxFrameRate(12); - EXPECT_EQ(12, ConvertAndValidate(serializer_).MaxFrameRate().value()); - - serializer_.SetMaxFrameRate(7); - EXPECT_EQ(7, ConvertAndValidate(serializer_).MaxFrameRate().value()); -} - -TEST_F(PlatformInfoSerializerTest, SupportedCryptoBlockFormat) { - serializer_.SetSupportedCryptoBlockFormat("foo"); - EXPECT_EQ( - "foo", - ConvertAndValidate(serializer_).SupportedCryptoBlockFormat().value()); - - serializer_.SetSupportedCryptoBlockFormat("bar"); - EXPECT_EQ( - "bar", - ConvertAndValidate(serializer_).SupportedCryptoBlockFormat().value()); - - serializer_.SetSupportedCryptoBlockFormat(""); - EXPECT_EQ( - "", ConvertAndValidate(serializer_).SupportedCryptoBlockFormat().value()); -} - -TEST_F(PlatformInfoSerializerTest, MaxChannels) { - serializer_.SetMaxChannels(42); - EXPECT_EQ(42, ConvertAndValidate(serializer_).MaxChannels().value()); - - serializer_.SetMaxChannels(12); - EXPECT_EQ(12, ConvertAndValidate(serializer_).MaxChannels().value()); - - serializer_.SetMaxChannels(7); - EXPECT_EQ(7, ConvertAndValidate(serializer_).MaxChannels().value()); -} - -TEST_F(PlatformInfoSerializerTest, PcmSurroundSoundSupported) { - serializer_.SetPcmSurroundSoundSupported(true); - EXPECT_TRUE( - ConvertAndValidate(serializer_).PcmSurroundSoundSupported().value()); - - serializer_.SetPcmSurroundSoundSupported(false); - EXPECT_FALSE( - ConvertAndValidate(serializer_).PcmSurroundSoundSupported().value()); -} - -TEST_F(PlatformInfoSerializerTest, PlatformDolbyVisionEnabled) { - serializer_.SetPlatformDolbyVisionEnabled(true); - EXPECT_TRUE( - ConvertAndValidate(serializer_).IsPlatformDolbyVisionEnabled().value()); - - serializer_.SetPlatformDolbyVisionEnabled(false); - EXPECT_FALSE( - ConvertAndValidate(serializer_).IsPlatformDolbyVisionEnabled().value()); -} - -TEST_F(PlatformInfoSerializerTest, DolbyVisionSupported) { - serializer_.SetDolbyVisionSupported(true); - EXPECT_TRUE(ConvertAndValidate(serializer_).IsDolbyVisionSupported().value()); - - serializer_.SetDolbyVisionSupported(false); - EXPECT_FALSE( - ConvertAndValidate(serializer_).IsDolbyVisionSupported().value()); -} - -TEST_F(PlatformInfoSerializerTest, DolbyVision4kP60Supported) { - serializer_.SetDolbyVision4kP60Supported(true); - EXPECT_TRUE( - ConvertAndValidate(serializer_).IsDolbyVision4kP60Supported().value()); - - serializer_.SetDolbyVision4kP60Supported(false); - EXPECT_FALSE( - ConvertAndValidate(serializer_).IsDolbyVision4kP60Supported().value()); -} - -TEST_F(PlatformInfoSerializerTest, DolbyVisionSupportedByCurrentHdmiMode) { - serializer_.SetDolbyVisionSupportedByCurrentHdmiMode(true); - EXPECT_TRUE(ConvertAndValidate(serializer_) - .IsDolbyVisionSupportedByCurrentHdmiMode() - .value()); - - serializer_.SetDolbyVisionSupportedByCurrentHdmiMode(false); - EXPECT_FALSE(ConvertAndValidate(serializer_) - .IsDolbyVisionSupportedByCurrentHdmiMode() - .value()); -} - -TEST_F(PlatformInfoSerializerTest, HdmiVideoModeSwitchEnabled) { - serializer_.SetHdmiVideoModeSwitchEnabled(true); - EXPECT_TRUE( - ConvertAndValidate(serializer_).IsHdmiVideoModeSwitchEnabled().value()); - - serializer_.SetHdmiVideoModeSwitchEnabled(false); - EXPECT_FALSE( - ConvertAndValidate(serializer_).IsHdmiVideoModeSwitchEnabled().value()); -} - -TEST_F(PlatformInfoSerializerTest, PlatformHevcEnabled) { - serializer_.SetPlatformHevcEnabled(true); - EXPECT_TRUE(ConvertAndValidate(serializer_).IsPlatformHevcEnabled().value()); - - serializer_.SetPlatformHevcEnabled(false); - EXPECT_FALSE(ConvertAndValidate(serializer_).IsPlatformHevcEnabled().value()); -} - -TEST_F(PlatformInfoSerializerTest, HdmiModeHdrCheckEnforced) { - serializer_.SetHdmiModeHdrCheckEnforced(true); - EXPECT_TRUE( - ConvertAndValidate(serializer_).IsHdmiModeHdrCheckEnforced().value()); - - serializer_.SetHdmiModeHdrCheckEnforced(false); - EXPECT_FALSE( - ConvertAndValidate(serializer_).IsHdmiModeHdrCheckEnforced().value()); -} - -TEST_F(PlatformInfoSerializerTest, HdrSupportedByCurrentHdmiMode) { - serializer_.SetHdrSupportedByCurrentHdmiMode(true); - EXPECT_TRUE(ConvertAndValidate(serializer_) - .IsHdrSupportedByCurrentHdmiMode() - .value()); - - serializer_.SetHdrSupportedByCurrentHdmiMode(false); - EXPECT_FALSE(ConvertAndValidate(serializer_) - .IsHdrSupportedByCurrentHdmiMode() - .value()); -} - -TEST_F(PlatformInfoSerializerTest, SmpteSt2084Supported) { - serializer_.SetSmpteSt2084Supported(true); - EXPECT_TRUE(ConvertAndValidate(serializer_).IsSmpteSt2084Supported().value()); - - serializer_.SetSmpteSt2084Supported(false); - EXPECT_FALSE( - ConvertAndValidate(serializer_).IsSmpteSt2084Supported().value()); -} - -TEST_F(PlatformInfoSerializerTest, Hlg) { - serializer_.SetHlgSupported(true); - EXPECT_TRUE(ConvertAndValidate(serializer_).IsHlgSupported().value()); - - serializer_.SetHlgSupported(false); - EXPECT_FALSE(ConvertAndValidate(serializer_).IsHlgSupported().value()); -} - -TEST_F(PlatformInfoSerializerTest, HdrFeatureEnabled) { - serializer_.SetHdrFeatureEnabled(true); - EXPECT_TRUE(ConvertAndValidate(serializer_).IsHdrFeatureEnabled().value()); - - serializer_.SetHdrFeatureEnabled(false); - EXPECT_FALSE(ConvertAndValidate(serializer_).IsHdrFeatureEnabled().value()); -} - -TEST_F(PlatformInfoSerializerTest, SupportedLegacyVp9Levels) { - std::vector source{42, 24, 7}; - serializer_.SetSupportedLegacyVp9Levels(source); - auto converted = - ConvertAndValidate(serializer_).SupportedLegacyVp9Levels().value(); - - ASSERT_EQ(source.size(), converted.size()); - for (int i = 0; i < static_cast(source.size()); i++) { - EXPECT_EQ(source[i], converted[i]); - } -} - -TEST_F(PlatformInfoSerializerTest, HdcpVersion) { - serializer_.SetHdcpVersion(42); - EXPECT_EQ(42, ConvertAndValidate(serializer_).HdcpVersion().value()); - - serializer_.SetHdcpVersion(12); - EXPECT_EQ(12, ConvertAndValidate(serializer_).HdcpVersion().value()); - - serializer_.SetHdcpVersion(7); - EXPECT_EQ(7, ConvertAndValidate(serializer_).HdcpVersion().value()); -} - -TEST_F(PlatformInfoSerializerTest, SpatialRenderingSupportMask) { - serializer_.SetSpatialRenderingSupportMask(42); - EXPECT_EQ( - 42, - ConvertAndValidate(serializer_).SpatialRenderingSupportMask().value()); - - serializer_.SetSpatialRenderingSupportMask(12); - EXPECT_EQ( - 12, - ConvertAndValidate(serializer_).SpatialRenderingSupportMask().value()); - - serializer_.SetSpatialRenderingSupportMask(7); - EXPECT_EQ( - 7, ConvertAndValidate(serializer_).SpatialRenderingSupportMask().value()); -} - -TEST_F(PlatformInfoSerializerTest, MaxFillRate) { - serializer_.SetMaxFillRate(42); - EXPECT_EQ(42, ConvertAndValidate(serializer_).MaxFillRate().value()); - - serializer_.SetMaxFillRate(12); - EXPECT_EQ(12, ConvertAndValidate(serializer_).MaxFillRate().value()); - - serializer_.SetMaxFillRate(7); - EXPECT_EQ(7, ConvertAndValidate(serializer_).MaxFillRate().value()); -} - -TEST_F(PlatformInfoSerializerTest, AudioCodecInfo) { - PlatformInfoSerializer::AudioCodecInfo first{ - media::AudioCodec::kCodecAAC, media::SampleFormat::kSampleFormatU8, 42, - 16}; - PlatformInfoSerializer::AudioCodecInfo second{ - media::AudioCodec::kCodecOpus, media::SampleFormat::kSampleFormatS32, 18, - 34}; - PlatformInfoSerializer::AudioCodecInfo third{ - media::AudioCodec::kCodecAC3, media::SampleFormat::kSampleFormatPlanarS16, - 9, 99}; - - std::vector codec_infos{first, second, - third}; - serializer_.SetSupportedAudioCodecs(codec_infos); - - auto converted = ConvertAndValidate(serializer_).SupportedAudioCodecs(); - ASSERT_TRUE(converted.has_value()); - ASSERT_EQ(codec_infos.size(), converted.value().size()); - for (int i = 0; i < static_cast(codec_infos.size()); i++) { - EXPECT_EQ(codec_infos[i], converted.value()[i]); - } -} - -TEST_F(PlatformInfoSerializerTest, VideoCodecInfo) { - PlatformInfoSerializer::VideoCodecInfo first{ - media::VideoCodec::kCodecVP8, media::VideoProfile::kVP8ProfileAny}; - PlatformInfoSerializer::VideoCodecInfo second{ - media::VideoCodec::kCodecVP9, media::VideoProfile::kVP9Profile2}; - PlatformInfoSerializer::VideoCodecInfo third{ - media::VideoCodec::kCodecH264, media::VideoProfile::kH264Extended}; - - std::vector codec_infos{first, second, - third}; - serializer_.SetSupportedVideoCodecs(codec_infos); - - auto converted = ConvertAndValidate(serializer_).SupportedVideoCodecs(); - ASSERT_TRUE(converted.has_value()); - ASSERT_EQ(codec_infos.size(), converted.value().size()); - for (int i = 0; i < static_cast(codec_infos.size()); i++) { - EXPECT_EQ(codec_infos[i], converted.value()[i]); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/DEPS chromium-132.0.6834.159/chromecast/starboard/DEPS --- chromium-132.0.6834.110/chromecast/starboard/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -include_rules = [ - "+chromecast/media", - "+google_apis", - "+media/base", - "+ui/base", - "+ui/events", - "+ui/platform_window", -] diff -Nru chromium-132.0.6834.110/chromecast/starboard/OWNERS chromium-132.0.6834.159/chromecast/starboard/OWNERS --- chromium-132.0.6834.110/chromecast/starboard/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -antoniori@google.com -shawnq@google.com diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/events/dummy_ui_event_source.cc chromium-132.0.6834.159/chromecast/starboard/chromecast/events/dummy_ui_event_source.cc --- chromium-132.0.6834.110/chromecast/starboard/chromecast/events/dummy_ui_event_source.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/events/dummy_ui_event_source.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// An implementation of UiEventSource::Create to be linked in for builds -// that do not use starboard. - -#include - -#include "chromecast/starboard/chromecast/events/ui_event_source.h" - -namespace chromecast { - -namespace { - -// A dummy impl that reports that all events should be dispatched. -class DummyUiEventSource : public UiEventSource { - public: - DummyUiEventSource() = default; - ~DummyUiEventSource() override = default; - - bool ShouldDispatchEvent(const ui::Event& /*event*/) override { return true; } -}; - -} // namespace - -// Declared in starboard_event_source.h. -std::unique_ptr UiEventSource::Create( - ui::PlatformWindowDelegate* delegate) { - return std::make_unique(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/events/starboard_event_source.cc chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source.cc --- chromium-132.0.6834.110/chromecast/starboard/chromecast/events/starboard_event_source.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,159 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/chromecast/events/starboard_event_source.h" - -#include "base/containers/fixed_flat_map.h" -#include "base/logging.h" -#include "ui/events/keycodes/dom/dom_code.h" -#include "ui/events/keycodes/dom/dom_key.h" -#include "ui/events/keycodes/keyboard_code_conversion.h" - -namespace chromecast { - -namespace { - -constexpr char kPropertyFromStarboard[] = "from_sb"; -constexpr size_t kPropertyFromStarboardSize = 1; - -// This map represents the key codes that can be recognized by Cast. The -// resulting DomCodes are the union of: -// - Keys which are used by the Cast SDK. -// - Keys which are used by the Cast SDK when the DPAD UI is enabled. -// - Keys which are not used by the Cast SDK, but are defined in the HDMI CEC -// specification and may be useful to apps. -constexpr auto kSbKeyToDomCodeMap = base::MakeFixedFlatMap({ - // Convenience keys for keyboard support. - {kSbKeySpace, ui::DomCode::MEDIA_PLAY_PAUSE}, - - // Keys which are used by the Cast SDK. - {kSbKeyReturn, ui::DomCode::ENTER}, - {kSbKeySelect, ui::DomCode::SELECT}, - {kSbKeyUp, ui::DomCode::ARROW_UP}, - {kSbKeyDown, ui::DomCode::ARROW_DOWN}, - {kSbKeyLeft, ui::DomCode::ARROW_LEFT}, - {kSbKeyRight, ui::DomCode::ARROW_RIGHT}, - {kSbKeyBack, ui::DomCode::BROWSER_BACK}, - - // Keys which are used by the Cast SDK when the DPAD UI is enabled. - {kSbKeyMediaPlayPause, ui::DomCode::MEDIA_PLAY_PAUSE}, - {kSbKeyMediaRewind, ui::DomCode::MEDIA_REWIND}, - {kSbKeyMediaFastForward, ui::DomCode::MEDIA_FAST_FORWARD}, - {kSbKeyMediaNextTrack, ui::DomCode::MEDIA_TRACK_NEXT}, - {kSbKeyMediaPrevTrack, ui::DomCode::MEDIA_TRACK_PREVIOUS}, - {kSbKeyPause, ui::DomCode::MEDIA_PAUSE}, - {kSbKeyPlay, ui::DomCode::MEDIA_PLAY}, - {kSbKeyMediaStop, ui::DomCode::MEDIA_STOP}, - - // Keys which are not used by the Cast SDK, but are defined in the HDMI CEC - // specification. - {kSbKeyMenu, ui::DomCode::HOME}, - {kSbKeyChannelUp, ui::DomCode::CHANNEL_UP}, - {kSbKeyChannelDown, ui::DomCode::CHANNEL_DOWN}, - {kSbKeyClosedCaption, ui::DomCode::CLOSED_CAPTION_TOGGLE}, -#if SB_API_VERSION >= 15 - {kSbKeyRecord, ui::DomCode::MEDIA_RECORD}, -#endif // SB_API_VERSION >=15 -}); - -// Returns the current SequencedTaskRunner. Crashes if not called from a -// sequenced task runner. -scoped_refptr GetCurrentSequencedTaskRunner() { - CHECK(base::SequencedTaskRunner::HasCurrentDefault()); - return base::SequencedTaskRunner::GetCurrentDefault(); -} - -} // namespace - -// static -void StarboardEventSource::SbEventHandle(void* context, const SbEvent* event) { - reinterpret_cast(context)->SbEventHandleInternal( - event); -} - -void StarboardEventSource::SbEventHandleInternal(const SbEvent* event) { - if (event->type != kSbEventTypeInput) { - return; - } - - if (event->data == nullptr) { - return; - } - auto* input_data = static_cast(event->data); - - SbTimeMonotonic raw_timestamp = event->timestamp; - SbInputEventType raw_type = input_data->type; - SbKey raw_key = input_data->key; - if (raw_type != kSbInputEventTypePress && - raw_type != kSbInputEventTypeUnpress) { - return; - } - - // Find out if the press is supported by Cast. - auto it = kSbKeyToDomCodeMap.find(raw_key); - if (it == kSbKeyToDomCodeMap.end()) { - return; - } - - std::unique_ptr ui_event; - ui::DomKey dom_key; - ui::KeyboardCode key_code; - ui::DomCode dom_code = it->second; - int flags = 0; - if (!DomCodeToUsLayoutDomKey(dom_code, flags, &dom_key, &key_code)) { - return; - } - - // Key press. - ui::EventType event_type = raw_type == kSbInputEventTypePress - ? ui::EventType::kKeyPressed - : ui::EventType::kKeyReleased; - ui_event = std::make_unique( - event_type, key_code, dom_code, flags, dom_key, - /*time_stamp=*/ - base::TimeTicks() + base::Microseconds(raw_timestamp)); - - ui::Event::Properties properties; - properties[chromecast::kPropertyFromStarboard] = - std::vector(chromecast::kPropertyFromStarboardSize); - ui_event->SetProperties(properties); - DispatchUiEvent(std::move(ui_event)); -} - -void StarboardEventSource::DispatchUiEvent(std::unique_ptr event) { - if (!task_runner_->RunsTasksInCurrentSequence()) { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&StarboardEventSource::DispatchUiEvent, - weak_factory_.GetWeakPtr(), std::move(event))); - return; - } - - delegate_->DispatchEvent(event.get()); -} - -StarboardEventSource::StarboardEventSource(ui::PlatformWindowDelegate* delegate) - : task_runner_(GetCurrentSequencedTaskRunner()), delegate_(delegate) { - DCHECK(delegate_); - CastStarboardApiAdapter::GetInstance()->Subscribe( - this, &StarboardEventSource::SbEventHandle); -} - -StarboardEventSource::~StarboardEventSource() { - CastStarboardApiAdapter::GetInstance()->Unsubscribe(this); -} - -bool StarboardEventSource::ShouldDispatchEvent(const ui::Event& event) { - const ui::Event::Properties* properties = event.properties(); - return properties && properties->find(chromecast::kPropertyFromStarboard) != - properties->end(); -} - -// Declared in starboard_event_source.h. -std::unique_ptr UiEventSource::Create( - ui::PlatformWindowDelegate* delegate) { - return std::make_unique(delegate); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/events/starboard_event_source.h chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source.h --- chromium-132.0.6834.110/chromecast/starboard/chromecast/events/starboard_event_source.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_CHROMECAST_EVENTS_STARBOARD_EVENT_SOURCE_H_ -#define CHROMECAST_STARBOARD_CHROMECAST_EVENTS_STARBOARD_EVENT_SOURCE_H_ - -#include "base/memory/scoped_refptr.h" -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/starboard/chromecast/events/ui_event_source.h" -#include "chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h" -#include "ui/events/event.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace chromecast { - -// Subscribes to |SbEvent| provided by -// |CastStarboardApiAdapter| and translates them to |ui::Event| before -// dispatching them to a |ui::PlatformWindowDelegate|. -// -// This class is used both to convert starboard events to ui::Event values, and -// to filter out events that did not originate from starboard. -class StarboardEventSource : public UiEventSource { - public: - // Creates an event source which will dispatch events to |delegate|. - StarboardEventSource(ui::PlatformWindowDelegate* delegate); - ~StarboardEventSource() override; - - // UiEventSource implementation: - bool ShouldDispatchEvent(const ui::Event& event) override; - - private: - // Receives |event| from Starboard and sends it to |context|, which represents - // an instance of this class. - static void SbEventHandle(void* context, const SbEvent* event); - - // Receives |event| from |SbEventHandle| and translates the event to a - // |ui::Event|. - void SbEventHandleInternal(const SbEvent* event); - - // Dispatches an |event| to the |delegate_| on the original |task_runner_| on - // which |this| was created. - void DispatchUiEvent(std::unique_ptr event); - - scoped_refptr task_runner_; - ui::PlatformWindowDelegate* delegate_; - - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_CHROMECAST_EVENTS_STARBOARD_EVENT_SOURCE_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/events/starboard_event_source_test.cc chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source_test.cc --- chromium-132.0.6834.110/chromecast/starboard/chromecast/events/starboard_event_source_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/events/starboard_event_source_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,170 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "starboard_event_source.h" - -#include "base/test/task_environment.h" -#include "chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/owned_window_anchor.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/dom/dom_code.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace chromecast { -namespace { - -// Copied from ui/ozone/test/mock_platform_window_delegate.h because of -// the visibility restriction. -class MockPlatformWindowDelegate : public ui::PlatformWindowDelegate { - public: - MockPlatformWindowDelegate() = default; - - MockPlatformWindowDelegate(const MockPlatformWindowDelegate&) = delete; - MockPlatformWindowDelegate& operator=(const MockPlatformWindowDelegate&) = - delete; - - ~MockPlatformWindowDelegate() override = default; - - MOCK_METHOD(gfx::Insets, - CalculateInsetsInDIP, - (ui::PlatformWindowState window_state), - (const, override)); - MOCK_METHOD(void, OnBoundsChanged, (const BoundsChange& change), (override)); - MOCK_METHOD(void, - OnDamageRect, - (const gfx::Rect& damaged_region), - (override)); - MOCK_METHOD(void, DispatchEvent, (ui::Event * event), (override)); - MOCK_METHOD(void, OnCloseRequest, (), (override)); - MOCK_METHOD(void, OnClosed, (), (override)); - MOCK_METHOD(void, - OnWindowStateChanged, - (ui::PlatformWindowState old_state, - ui::PlatformWindowState new_state), - (override)); -#if BUILDFLAG(IS_LINUX) - MOCK_METHOD(void, - OnWindowTiledStateChanged, - (ui::WindowTiledEdges new_tiled_edges), - (override)); -#endif -#if BUILDFLAG(IS_CHROMEOS_LACROS) - MOCK_METHOD(void, OnOverviewModeChanged, (bool overview), (override)); -#endif // BUILDFLAG(IS_CHROMEOS_LACROS) - MOCK_METHOD(void, OnLostCapture, (), (override)); - MOCK_METHOD(void, - OnAcceleratedWidgetAvailable, - (gfx::AcceleratedWidget widget), - (override)); - MOCK_METHOD(void, OnWillDestroyAcceleratedWidget, (), (override)); - MOCK_METHOD(void, OnAcceleratedWidgetDestroyed, (), (override)); - MOCK_METHOD(void, OnActivationChanged, (bool active), (override)); - MOCK_METHOD(std::optional, - GetMinimumSizeForWindow, - (), - (const, override)); - MOCK_METHOD(std::optional, - GetMaximumSizeForWindow, - (), - (const, override)); - MOCK_METHOD(std::optional, - GetOwnedWindowAnchorAndRectInDIP, - (), - (override)); - MOCK_METHOD(void, OnMouseEnter, (), (override)); - MOCK_METHOD(void, - OnOcclusionStateChanged, - (ui::PlatformWindowOcclusionState occlusion_state), - (override)); - MOCK_METHOD(int64_t, - OnStateUpdate, - (const State& old, const State& latest), - (override)); - MOCK_METHOD(bool, - OnRotateFocus, - (ui::PlatformWindowDelegate::RotateDirection, bool), - (override)); - MOCK_METHOD(bool, CanMaximize, (), (const, override)); - MOCK_METHOD(bool, CanFullscreen, (), (const, override)); -}; - -using ::testing::_; - -constexpr float kXPosClick = 1; -constexpr float kYPosClick = 2; - -void DispatchSbEvent(const SbEvent* event) { - // The |source_| should be subscribed to this and receive the event. - CastStarboardApiAdapterImpl::SbEventHandle(event); -} - -void EmulateKey(SbKey key, bool press) { - SbInputData input_data; - input_data.type = press ? kSbInputEventTypePress : kSbInputEventTypeUnpress; - input_data.key = key; - - // Normally invalid for keys other than mouse presses, but okay for test. - input_data.position.x = kXPosClick; - input_data.position.y = kYPosClick; - - SbEvent event; - event.type = kSbEventTypeInput; - event.data = &input_data; - - DispatchSbEvent(&event); -} - -// A test fixture is used to manage the global mock state and to handle the -// lifetime of the SingleThreadTaskEnvironment. -class StarboardEventSourceTest : public ::testing::Test { - protected: - StarboardEventSourceTest() : last_ui_event_(nullptr), source_(&delegate_) { - ON_CALL(delegate_, DispatchEvent(_)).WillByDefault([&](ui::Event* event) { - last_ui_event_ = event->Clone(); - }); - } - - ~StarboardEventSourceTest() override = default; - - // This should be destructed last. - base::test::SingleThreadTaskEnvironment task_environment_; - std::unique_ptr last_ui_event_; - MockPlatformWindowDelegate delegate_; - StarboardEventSource source_; -}; - -TEST_F(StarboardEventSourceTest, SupportedKeysArepropagated) { - EmulateKey(kSbKeyMediaPlayPause, /*press=*/true); - ASSERT_NE(last_ui_event_, nullptr); - EXPECT_TRUE(last_ui_event_->IsKeyEvent()); - EXPECT_EQ(last_ui_event_->AsKeyEvent()->code(), - ui::DomCode::MEDIA_PLAY_PAUSE); - EXPECT_EQ(last_ui_event_->type(), ui::EventType::kKeyPressed); - - EmulateKey(kSbKeyMediaPlayPause, /*press=*/false); - EXPECT_EQ(last_ui_event_->AsKeyEvent()->code(), - ui::DomCode::MEDIA_PLAY_PAUSE); - EXPECT_EQ(last_ui_event_->type(), ui::EventType::kKeyReleased); -} - -TEST_F(StarboardEventSourceTest, UnsupportedKeyIsNotPropagated) { - EmulateKey(kSbKeyCancel, /*press=*/true); - EXPECT_EQ(last_ui_event_, nullptr); - - EmulateKey(kSbKeyCancel, /*press=*/false); - EXPECT_EQ(last_ui_event_, nullptr); -} - -TEST_F(StarboardEventSourceTest, UnsupportedClickIsNotPropagated) { - EmulateKey(kSbKeyMouse2, /*press=*/true); - EXPECT_EQ(last_ui_event_, nullptr); - - EmulateKey(kSbKeyMouse2, /*press=*/false); - EXPECT_EQ(last_ui_event_, nullptr); -} - -} // namespace -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/events/ui_event_source.cc chromium-132.0.6834.159/chromecast/starboard/chromecast/events/ui_event_source.cc --- chromium-132.0.6834.110/chromecast/starboard/chromecast/events/ui_event_source.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/events/ui_event_source.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/chromecast/events/ui_event_source.h" - -namespace chromecast { - -UiEventSource::~UiEventSource() = default; - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/events/ui_event_source.h chromium-132.0.6834.159/chromecast/starboard/chromecast/events/ui_event_source.h --- chromium-132.0.6834.110/chromecast/starboard/chromecast/events/ui_event_source.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/events/ui_event_source.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_CHROMECAST_EVENTS_UI_EVENT_SOURCE_H_ -#define CHROMECAST_STARBOARD_CHROMECAST_EVENTS_UI_EVENT_SOURCE_H_ - -#include - -#include "ui/events/event.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace chromecast { - -// Represents events originating from some source. For example, if the user -// presses a directional button on the TV remote, that may trigger an event. -// -// A UiEventSource should be created via UiEventSource::Create. -// Platforms must define this function. -class UiEventSource { - public: - // Creates a UiEventSource that dispatches events to |delegate|. - static std::unique_ptr Create( - ui::PlatformWindowDelegate* delegate); - - virtual ~UiEventSource(); - - // Returns true if the event should be dispatched. - virtual bool ShouldDispatchEvent(const ui::Event& event) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_CHROMECAST_EVENTS_UI_EVENT_SOURCE_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h --- chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#ifndef CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_ADAPTER_PUBLIC_CAST_STARBOARD_API_ADAPTER_H_ -#define CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_ADAPTER_PUBLIC_CAST_STARBOARD_API_ADAPTER_H_ - -#include "chromecast/starboard/starboard_buildflags.h" - -#if BUILDFLAG(REMOVE_STARBOARD_HEADERS) - -using SbEvent = void; -using SbWindowOptions = void; -using SbEglNativeDisplayType = void*; -using SbWindow = void*; - -#else -#include -#include -#include -#include -#endif // BUILDFLAG(REMOVE_STARBOARD_HEADERS) - -namespace chromecast { - -// CastStarboardApiAdapter provides a C++ wrapper to the CastStarboardApi, -// which is a C-style interface implemented in an external library. The primary -// purpose of CastStarboardApiAdapter is to managage the lifecycle of the -// external library, which expects to always be initialized before use and only -// have a single instance. -class __attribute__((visibility("default"))) CastStarboardApiAdapter { - public: - static CastStarboardApiAdapter* GetInstance(); - - virtual ~CastStarboardApiAdapter() = default; - - // Ensures that the CastStarboardApi is initialized. Callers should invoke - // this before any other functions. - virtual bool EnsureInitialized() = 0; - - // When Starboard events occur, `callback` will be called with `context`, an - // integer corresponding to the SbEventType, and a void* containing the data - // for the event (which may be null, since some events do not contain data). - // The `callback` must be thread safe, i.e. it will not automatically be - // posted to the same thread on which Subscribe was called. - virtual void Subscribe(void* context, - void (*callback)(void* context, - const SbEvent* event)) = 0; - - // Removes a `context` which was previously provided to `Subscribe`. The - // `context` will no longer receive events. - virtual void Unsubscribe(void* context) = 0; - - // Gets the SbEglDisplay associated with the internally managed context. - virtual SbEglNativeDisplayType GetEglNativeDisplayType() = 0; - - // Gets the window shared between the graphics and media libraries. - virtual SbWindow GetWindow(const SbWindowOptions* options) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_ADAPTER_PUBLIC_CAST_STARBOARD_API_ADAPTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_dummy.cc chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_dummy.cc --- chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// A dummy implementation of egl_starboard.h. This can be used to compile -// without starboard headers. It should never be used in production. -// -// TODO(b/333131992): remove this - -#include - -#include "chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h" - -namespace chromecast { - -// static -CastStarboardApiAdapter* CastStarboardApiAdapter::GetInstance() { - std::cerr << "Returning a null CastStarboardApiAdapter" << std::endl; - return nullptr; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.cc chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.cc --- chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,120 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "cast_starboard_api_adapter_impl.h" - -// TODO(b/333961720): remove all the macros in this file and split the impl into -// two different classes: one for SB 15+, one for older versions of starboard. -// Only include the relevant one in the BUILD.gn file. -#if SB_API_VERSION >= 15 -#include -#else // SB_API_VERSION >=15 -#include -#endif // SB_API_VERSION >= 15 - -namespace chromecast { -namespace { -CastStarboardApiAdapterImpl* GetImpl() { - static CastStarboardApiAdapterImpl* starboard_adapter = - new CastStarboardApiAdapterImpl(); - return starboard_adapter; -} -} // namespace - -CastStarboardApiAdapter* CastStarboardApiAdapter::GetInstance() { - return GetImpl(); -} - -#if SB_API_VERSION >= 15 -CastStarboardApiAdapterImpl::CastStarboardApiAdapterImpl() - : init_f_(init_p_.get_future()), initialized_(false) {} -#else // SB_API_VERSION >=15 -CastStarboardApiAdapterImpl::CastStarboardApiAdapterImpl() - : initialized_(false) {} -#endif // SB_API_VERSION >= 15 - -CastStarboardApiAdapterImpl::~CastStarboardApiAdapterImpl() {} - -SbEglNativeDisplayType CastStarboardApiAdapterImpl::GetEglNativeDisplayType() { - return SB_EGL_DEFAULT_DISPLAY; -} - -// static -void CastStarboardApiAdapterImpl::SbEventHandle(const SbEvent* event) { - GetImpl()->SbEventHandleInternal(event); -} - -#if SB_API_VERSION >= 15 -void CastStarboardApiAdapterImpl::SbEventHandleInternal(const SbEvent* event) { - // If multiple instances of Starboard become supported, |event->window| may - // need to be checked here for some types before propagating. - switch (event->type) { - case kSbEventTypeStart: - init_p_.set_value(true); - break; - default: - for (const auto p : subscribers_) { - p.second(p.first, event); - } - break; - } -} -#else // SB_API_VERSION >=15 -void CastStarboardApiAdapterImpl::SbEventHandleInternal(const SbEvent* event) { - std::lock_guard lock(lock_); - for (const auto p : subscribers_) { - p.second(p.first, event); - } -} -#endif // SB_API_VERSION >= 15 - -#if SB_API_VERSION >= 15 -bool CastStarboardApiAdapterImpl::EnsureInitialized() { - std::lock_guard lock(lock_); - if (initialized_) { - return true; - } - - sb_main_ = std::make_unique( - &SbRunStarboardMain, /*argc=*/0, /*argv=*/nullptr, - &CastStarboardApiAdapterImpl::SbEventHandle); - sb_main_->detach(); - initialized_ = init_f_.get(); - return initialized_; -} -#else // SB_API_VERSION >=15 -bool CastStarboardApiAdapterImpl::EnsureInitialized() { - std::lock_guard lock(lock_); - if (initialized_) { - return true; - } - - CastStarboardApiInitialize(/*argc=*/0, /*argv=*/nullptr, - &CastStarboardApiAdapterImpl::SbEventHandle); - initialized_ = true; - return true; -} -#endif // SB_API_VERSION >= 15 - -void CastStarboardApiAdapterImpl::Subscribe(void* context, - CastStarboardApiAdapterImplCB cb) { - std::lock_guard lock(lock_); - subscribers_.insert({context, cb}); -} - -void CastStarboardApiAdapterImpl::Unsubscribe(void* context) { - std::lock_guard lock(lock_); - subscribers_.erase(context); -} - -SbWindow CastStarboardApiAdapterImpl::GetWindow( - const SbWindowOptions* options) { - if (!SbWindowIsValid(window_)) { - window_ = SbWindowCreate(options); - } - - return window_; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.h chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.h --- chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_adapter/src/cast_starboard_api_adapter_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_ADAPTER_SRC_CAST_STARBOARD_API_ADAPTER_IMPL_H_ -#define CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_ADAPTER_SRC_CAST_STARBOARD_API_ADAPTER_IMPL_H_ - -#include -#include - -#if SB_API_VERSION >= 15 -#include -#include -#endif // SB_API_VERSION >= 15 - -#include "chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h" - -namespace chromecast { - -using CastStarboardApiAdapterImplCB = void (*)(void* context, - const SbEvent* event); - -// Utility class for wrapping CastStarboardApi which allows delivery of events -// to multiple subscribers. -class CastStarboardApiAdapterImpl : public CastStarboardApiAdapter { - public: - // SbEventHandle is provided when calling CastStarboardApiInitialize and is - // expected to be used as the event callback for Starboard events. It routes - // events to the singleton instance via SbEventHandleInternal. - static void SbEventHandle(const SbEvent* event); - - CastStarboardApiAdapterImpl(); - ~CastStarboardApiAdapterImpl() override; - - private: - void SbEventHandleInternal(const SbEvent* event); - - // CastStarboardApiAdapter implementation: - bool EnsureInitialized() override; - void Subscribe(void* context, - CastStarboardApiAdapterImplCB callback) override; - void Unsubscribe(void* context) override; - SbEglNativeDisplayType GetEglNativeDisplayType() override; - SbWindow GetWindow(const SbWindowOptions*) override; - -#if SB_API_VERSION >= 15 - std::unique_ptr sb_main_; - std::promise init_p_; - std::future init_f_; -#endif // SB_API_VERSION >= 15 - SbWindow window_ = kSbWindowInvalid; - std::mutex lock_; - bool initialized_; - std::unordered_map subscribers_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_ADAPTER_SRC_CAST_STARBOARD_API_ADAPTER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api.h chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api.h --- chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_CAST_API_CAST_STARBOARD_API_H_ -#define CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_CAST_API_CAST_STARBOARD_API_H_ - -#include -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*SbEventHandleCB)(const SbEvent*); - -// Initializes the Starboard thread and event loop. After this function is -// called, the Starboard APIs included above are expected to be available. -// -// Optional command line arguments are passed through |argc| and |argv|. -// The |callback| is analogous to SbEventHandle and must receive SbEvents. -// -// Must be called prior to the other library functions. -__attribute__((visibility("default"))) int -CastStarboardApiInitialize(int argc, char** argv, SbEventHandleCB callback); - -// Finalizes the library in the provided |context|. -// -// Must not be called prior to the other library functions. -__attribute__((visibility("default"))) void CastStarboardApiFinalize(); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_CAST_API_CAST_STARBOARD_API_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h --- chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_CAST_API_CAST_STARBOARD_API_TYPES_H_ -#define CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_CAST_API_CAST_STARBOARD_API_TYPES_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// TODO(b/334907387): this enum can likely be removed in favor of a simpler -// approach to output formats. Either way, this file should be moved out of the -// starboard_cast_api dir, unless we make it part of a starboard API. -// -// Represents a sample format for PCM data to be resampled to. All formats are -// little endian and interleaved. -enum StarboardPcmSampleFormat { - kStarboardPcmSampleFormatS16, - kStarboardPcmSampleFormatS32, - kStarboardPcmSampleFormatF32, -}; - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // CHROMECAST_STARBOARD_CHROMECAST_STARBOARD_CAST_API_CAST_STARBOARD_API_TYPES_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_cast_dummy/cast_starboard_api_dummy.cc chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_dummy/cast_starboard_api_dummy.cc --- chromium-132.0.6834.110/chromecast/starboard/chromecast/starboard_cast_dummy/cast_starboard_api_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/chromecast/starboard_cast_dummy/cast_starboard_api_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,134 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include -#include -#include - -#if SB_API_VERSION < 15 -#include -#endif // SB_API_VERSION < 15 - -#if SB_API_VERSION >= 15 -int SbRunStarboardMain(int argc, char** argv, SbEventHandleCallback callback) { - SbEvent* fake_start = new SbEvent; - fake_start->type = kSbEventTypeStart; - callback(fake_start); - return 0; -} -#else // SB_API_VERSION >= 15 -int StarboardMain(int argc, char** argv) { - return 0; -} - -int CastStarboardApiInitialize(int argc, - char** argv, - SbEventHandleCB callback) { - SbEvent* fake_start = new SbEvent; - fake_start->type = kSbEventTypeStart; - callback(fake_start); - return 0; -} - -void CastStarboardApiFinalize() {} - -#endif // SB_API_VERSION >= 15 - -const SbGlesInterface* SbGetGlesInterface() { - return nullptr; -} -const SbEglInterface* SbGetEglInterface() { - return nullptr; -} - -SbWindow SbWindowCreate(const SbWindowOptions* options) { - return nullptr; -} - -void* SbWindowGetPlatformHandle(SbWindow window) { - return nullptr; -} - -SbPlayer SbPlayerCreate( - SbWindow window, - const SbPlayerCreationParam* creation_param, - SbPlayerDeallocateSampleFunc sample_deallocate_func, - SbPlayerDecoderStatusFunc decoder_status_func, - SbPlayerStatusFunc player_status_func, - SbPlayerErrorFunc player_error_func, - void* context, - SbDecodeTargetGraphicsContextProvider* context_provider) { - return nullptr; -} - -void SbPlayerSetBounds(SbPlayer player, - int z_index, - int x, - int y, - int width, - int height) {} -void SbPlayerWriteEndOfStream(SbPlayer player, SbMediaType stream_type) {} -#if SB_API_VERSION >= 15 -void SbPlayerSeek(SbPlayer player, SbTime seek_to_timestamp, int ticket) {} -void SbPlayerWriteSamples(SbPlayer player, - SbMediaType sample_type, - const SbPlayerSampleInfo* sample_infos, - int number_of_sample_infos) {} -void SbPlayerGetInfo(SbPlayer player, SbPlayerInfo* out_player_info2) {} -#else // SB_API_VERSION >= 15 -void SbPlayerSeek2(SbPlayer player, SbTime seek_to_timestamp, int ticket) {} -void SbPlayerWriteSample2(SbPlayer player, - SbMediaType sample_type, - const SbPlayerSampleInfo* sample_infos, - int number_of_sample_infos) {} -void SbPlayerGetInfo2(SbPlayer player, SbPlayerInfo2* out_player_info2) {} -#endif // SB_API_VERSION >= 15 -void SbPlayerSetVolume(SbPlayer player, double volume) {} -bool SbPlayerSetPlaybackRate(SbPlayer player, double playback_rate) { - return false; -} -void SbPlayerDestroy(SbPlayer player) {} - -SbDrmSystem SbDrmCreateSystem( - const char* key_system, - void* context, - SbDrmSessionUpdateRequestFunc update_request_callback, - SbDrmSessionUpdatedFunc session_updated_callback, - SbDrmSessionKeyStatusesChangedFunc key_statuses_changed_callback, - SbDrmServerCertificateUpdatedFunc server_certificate_updated_callback, - SbDrmSessionClosedFunc session_closed_callback) { - return kSbDrmSystemInvalid; -} -void SbDrmGenerateSessionUpdateRequest(SbDrmSystem drm_system, - int ticket, - const char* type, - const void* initialization_data, - int initialization_data_size) {} -void SbDrmUpdateSession(SbDrmSystem drm_system, - int ticket, - const void* key, - int key_size, - const void* session_id, - int session_id_size) {} -void SbDrmCloseSession(SbDrmSystem drm_system, - const void* session_id, - int session_id_size) {} -bool SbDrmIsServerCertificateUpdatable(SbDrmSystem drm_system) { - return false; -} -void SbDrmUpdateServerCertificate(SbDrmSystem drm_system, - int ticket, - const void* certificate, - int certificate_size) {} -const void* SbDrmGetMetrics(SbDrmSystem drm_system, int* size) { - return nullptr; -} -void SbDrmDestroySystem(SbDrmSystem drm_system) {} - -SbMediaSupportType SbMediaCanPlayMimeAndKeySystem(const char* mime, - const char* key_system) { - return kSbMediaSupportTypeMaybe; -} diff -Nru chromium-132.0.6834.110/chromecast/starboard/graphics/cast_egl_platform_starboard.cc chromium-132.0.6834.159/chromecast/starboard/graphics/cast_egl_platform_starboard.cc --- chromium-132.0.6834.110/chromecast/starboard/graphics/cast_egl_platform_starboard.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/graphics/cast_egl_platform_starboard.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,129 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include - -#include -#include - -#include "chromecast/public/cast_egl_platform.h" -#include "chromecast/public/cast_egl_platform_shlib.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/starboard/starboard_buildflags.h" - -#if !BUILDFLAG(REMOVE_STARBOARD_HEADERS) -#include - -#include "chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h" -#endif - -namespace chromecast { -namespace { - -// TODO(b/333131992): remove [[maybe_unused]] after removing the -// REMOVE_STARBOARD_HEADERS build flag. -[[maybe_unused]] constexpr char kGraphicsLibraryName[] = "libGL_starboard.so"; - -// Starboard CastEglPlatform implementation. -class CastEglPlatformStarboard : public CastEglPlatform { - public: - CastEglPlatformStarboard() -#if !BUILDFLAG(REMOVE_STARBOARD_HEADERS) - : sb_adapter_(CastStarboardApiAdapter::GetInstance()) -#endif - { - } - - const int* GetEGLSurfaceProperties(const int* desired) override { - return desired; - } - - ~CastEglPlatformStarboard() override {} - - bool InitializeHardware() override { -#if BUILDFLAG(REMOVE_STARBOARD_HEADERS) - return false; -#else - if (!sb_adapter_->EnsureInitialized()) { - return false; - } - graphics_lib_ = - dlopen(kGraphicsLibraryName, RTLD_NOW | RTLD_LOCAL | RTLD_DEEPBIND); - if (!graphics_lib_) { - std::cerr << "Failed to dlopen " << kGraphicsLibraryName << std::endl; - return false; - } - - get_proc_address_ = reinterpret_cast( - dlsym(graphics_lib_, "Sb_eglGetProcAddress")); - - if (!get_proc_address_) { - std::cerr << "Failed to dlsym Sb_eglGetProcAddress from " - << kGraphicsLibraryName << std::endl; - return false; - } - return true; -#endif - } - - void* GetEglLibrary() override { return nullptr; } - - void* GetGles2Library() override { return nullptr; } - - GLGetProcAddressProc GetGLProcAddressProc() override { - return get_proc_address_; - } - - NativeDisplayType CreateDisplayType(const Size& size) override { -#if BUILDFLAG(REMOVE_STARBOARD_HEADERS) - return nullptr; -#else - // TODO(b/334138792): The need to create a window before getting the display - // is an implementation detail. Luckily for us, created windows are not - // visible and GlOzoneEglCast always couples the call to CreateDisplayType - // and CreateWindow, so there is no downside to creating |window_| early. - if (!SbWindowIsValid(window_)) { - SbWindowOptions options{}; - options.name = "cast"; - options.size.width = size.width; - options.size.height = size.height; - window_ = sb_adapter_->GetWindow(&options); - } - - NativeDisplayType ndt = reinterpret_cast( - sb_adapter_->GetEglNativeDisplayType()); - return ndt; -#endif - } - - NativeWindowType CreateWindow(NativeDisplayType display_type, - const Size& size) override { -#if BUILDFLAG(REMOVE_STARBOARD_HEADERS) - return nullptr; -#else - assert(SbWindowIsValid(window_)); - auto* result = - static_cast(SbWindowGetPlatformHandle(window_)); - - return result; -#endif - } - - private: - GLGetProcAddressProc get_proc_address_ = nullptr; -#if !BUILDFLAG(REMOVE_STARBOARD_HEADERS) - void* graphics_lib_ = nullptr; - SbWindow window_ = nullptr; - CastStarboardApiAdapter* sb_adapter_; -#endif -}; -} // namespace - -CastEglPlatform* CastEglPlatformShlib::Create( - const std::vector& argv) { - return new CastEglPlatformStarboard(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/graphics/egl_starboard.cc chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard.cc --- chromium-132.0.6834.110/chromecast/starboard/graphics/egl_starboard.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,232 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/graphics/egl_starboard.h" - -#include -#include -#include -#include - -#include -#include - -extern "C" { - -constexpr char kSupportedExtensions[] = "EGL_EXT_client_extensions"; - -EGLBoolean Sb_eglChooseConfig(EGLDisplay dpy, - const EGLint* attrib_list, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config) { - return SbGetEglInterface()->eglChooseConfig(dpy, attrib_list, configs, - config_size, num_config); -} - -EGLBoolean Sb_eglCopyBuffers(EGLDisplay dpy, - EGLSurface surface, - EGLNativePixmapType target) { - return SbGetEglInterface()->eglCopyBuffers(dpy, surface, target); -} - -EGLContext Sb_eglCreateContext(EGLDisplay dpy, - EGLConfig config, - EGLContext share_context, - const EGLint* attrib_list) { - return SbGetEglInterface()->eglCreateContext(dpy, config, share_context, - attrib_list); -} - -EGLSurface Sb_eglCreatePbufferSurface(EGLDisplay dpy, - EGLConfig config, - const EGLint* attrib_list) { - return SbGetEglInterface()->eglCreatePbufferSurface(dpy, config, attrib_list); -} - -EGLSurface Sb_eglCreatePixmapSurface(EGLDisplay dpy, - EGLConfig config, - EGLNativePixmapType pixmap, - const EGLint* attrib_list) { - return SbGetEglInterface()->eglCreatePixmapSurface(dpy, config, pixmap, - attrib_list); -} - -EGLSurface Sb_eglCreateWindowSurface(EGLDisplay dpy, - EGLConfig config, - EGLNativeWindowType win, - const EGLint* attrib_list) { - return SbGetEglInterface()->eglCreateWindowSurface(dpy, config, win, - attrib_list); -} - -EGLBoolean Sb_eglDestroyContext(EGLDisplay dpy, EGLContext ctx) { - return SbGetEglInterface()->eglDestroyContext(dpy, ctx); -} - -EGLBoolean Sb_eglDestroySurface(EGLDisplay dpy, EGLSurface surface) { - return SbGetEglInterface()->eglDestroySurface(dpy, surface); -} - -EGLBoolean Sb_eglGetConfigAttrib(EGLDisplay dpy, - EGLConfig config, - EGLint attribute, - EGLint* value) { - return SbGetEglInterface()->eglGetConfigAttrib(dpy, config, attribute, value); -} - -EGLBoolean Sb_eglGetConfigs(EGLDisplay dpy, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config) { - return SbGetEglInterface()->eglGetConfigs(dpy, configs, config_size, - num_config); -} - -EGLDisplay Sb_eglGetCurrentDisplay(void) { - return SbGetEglInterface()->eglGetCurrentDisplay(); -} - -EGLSurface Sb_eglGetCurrentSurface(EGLint readdraw) { - return SbGetEglInterface()->eglGetCurrentSurface(readdraw); -} - -EGLDisplay Sb_eglGetDisplay(EGLNativeDisplayType display_id) { - return SbGetEglInterface()->eglGetDisplay( - reinterpret_cast(display_id)); -} - -EGLint Sb_eglGetError(void) { - return SbGetEglInterface()->eglGetError(); -} - -__eglMustCastToProperFunctionPointerType Sb_eglGetProcAddress( - const char* procname) { - // First, look up an "Sb_" prefixed function that has been loaded. If that - // fails, perform an un-prefixed lookup via starboard. - const std::string prefixed_name = std::string("Sb_") + procname; - auto* addr = reinterpret_cast<__eglMustCastToProperFunctionPointerType>( - dlsym(RTLD_DEFAULT, prefixed_name.c_str())); - if (!addr) { - addr = SbGetEglInterface()->eglGetProcAddress(procname); - } - - return addr; -} - -EGLBoolean Sb_eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor) { - return SbGetEglInterface()->eglInitialize(dpy, major, minor); -} - -EGLBoolean Sb_eglMakeCurrent(EGLDisplay dpy, - EGLSurface draw, - EGLSurface read, - EGLContext ctx) { - return SbGetEglInterface()->eglMakeCurrent(dpy, draw, read, ctx); -} - -EGLBoolean Sb_eglQueryContext(EGLDisplay dpy, - EGLContext ctx, - EGLint attribute, - EGLint* value) { - return SbGetEglInterface()->eglQueryContext(dpy, ctx, attribute, value); -} - -const char* Sb_eglQueryString(EGLDisplay dpy, EGLint name) { - if (dpy == EGL_NO_DISPLAY && name == EGL_EXTENSIONS) { - // Report that we do not support any additional client extensions. See - // https://registry.khronos.org/EGL/sdk/docs/man/html/eglQueryString.xhtml - // for more details about the eglQueryString API. - // - // If any ANGLE platforms were returned here, chromium would attempt to use - // an ANGLE ozone implementation rather than the EGL implementation - // supported by cast. - return kSupportedExtensions; - } - return SbGetEglInterface()->eglQueryString(dpy, name); -} - -EGLBoolean Sb_eglQuerySurface(EGLDisplay dpy, - EGLSurface surface, - EGLint attribute, - EGLint* value) { - return SbGetEglInterface()->eglQuerySurface(dpy, surface, attribute, value); -} - -EGLBoolean Sb_eglSwapBuffers(EGLDisplay dpy, EGLSurface surface) { - static const char* const cast_quirk_disable_ui = - std::getenv("CAST_QUIRK_DISABLE_UI"); - if (cast_quirk_disable_ui && cast_quirk_disable_ui[0] != '0') { - auto* gles = SbGetGlesInterface(); - gles->glClearColor(0, 0, 0, 0); - gles->glClear(SB_GL_COLOR_BUFFER_BIT); - } - return SbGetEglInterface()->eglSwapBuffers(dpy, surface); -} - -EGLBoolean Sb_eglTerminate(EGLDisplay dpy) { - return SbGetEglInterface()->eglTerminate(dpy); -} - -EGLBoolean Sb_eglWaitGL(void) { - return SbGetEglInterface()->eglWaitGL(); -} - -EGLBoolean Sb_eglWaitNative(EGLint engine) { - return SbGetEglInterface()->eglWaitNative(engine); -} - -EGLBoolean Sb_eglBindTexImage(EGLDisplay dpy, - EGLSurface surface, - EGLint buffer) { - return SbGetEglInterface()->eglBindTexImage(dpy, surface, buffer); -} - -EGLBoolean Sb_eglReleaseTexImage(EGLDisplay dpy, - EGLSurface surface, - EGLint buffer) { - return SbGetEglInterface()->eglReleaseTexImage(dpy, surface, buffer); -} - -EGLBoolean Sb_eglSurfaceAttrib(EGLDisplay dpy, - EGLSurface surface, - EGLint attribute, - EGLint value) { - return SbGetEglInterface()->eglSurfaceAttrib(dpy, surface, attribute, value); -} - -EGLBoolean Sb_eglSwapInterval(EGLDisplay dpy, EGLint interval) { - return SbGetEglInterface()->eglSwapInterval(dpy, interval); -} - -EGLBoolean Sb_eglBindAPI(EGLenum api) { - return SbGetEglInterface()->eglBindAPI(api); -} - -EGLenum Sb_eglQueryAPI(void) { - return SbGetEglInterface()->eglQueryAPI(); -} - -EGLSurface Sb_eglCreatePbufferFromClientBuffer(EGLDisplay dpy, - EGLenum buftype, - EGLClientBuffer buffer, - EGLConfig config, - const EGLint* attrib_list) { - return SbGetEglInterface()->eglCreatePbufferFromClientBuffer( - dpy, buftype, buffer, config, attrib_list); -} - -EGLBoolean Sb_eglWaitClient(void) { - return SbGetEglInterface()->eglWaitClient(); -} - -EGLBoolean Sb_eglReleaseThread(void) { - return SbGetEglInterface()->eglReleaseThread(); -} - -EGLContext Sb_eglGetCurrentContext(void) { - return SbGetEglInterface()->eglGetCurrentContext(); -} - -} // extern "C" diff -Nru chromium-132.0.6834.110/chromecast/starboard/graphics/egl_starboard.h chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard.h --- chromium-132.0.6834.110/chromecast/starboard/graphics/egl_starboard.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,160 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_GRAPHICS_EGL_STARBOARD_H_ -#define CHROMECAST_STARBOARD_GRAPHICS_EGL_STARBOARD_H_ - -#include - -extern "C" { - -// egl 1.0 - -__attribute__((visibility("default"))) EGLBoolean Sb_eglChooseConfig( - EGLDisplay dpy, - const EGLint* attrib_list, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglCopyBuffers( - EGLDisplay dpy, - EGLSurface surface, - EGLNativePixmapType target); - -__attribute__((visibility("default"))) EGLContext Sb_eglCreateContext( - EGLDisplay dpy, - EGLConfig config, - EGLContext share_context, - const EGLint* attrib_list); - -__attribute__((visibility("default"))) EGLSurface Sb_eglCreatePbufferSurface( - EGLDisplay dpy, - EGLConfig config, - const EGLint* attrib_list); - -__attribute__((visibility("default"))) EGLSurface Sb_eglCreatePixmapSurface( - EGLDisplay dpy, - EGLConfig config, - EGLNativePixmapType pixmap, - const EGLint* attrib_list); - -__attribute__((visibility("default"))) EGLSurface Sb_eglCreateWindowSurface( - EGLDisplay dpy, - EGLConfig config, - EGLNativeWindowType win, - const EGLint* attrib_list); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglDestroyContext( - EGLDisplay dpy, - EGLContext ctx); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglDestroySurface( - EGLDisplay dpy, - EGLSurface surface); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglGetConfigAttrib( - EGLDisplay dpy, - EGLConfig config, - EGLint attribute, - EGLint* value); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglGetConfigs( - EGLDisplay dpy, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config); - -__attribute__((visibility("default"))) EGLDisplay Sb_eglGetCurrentDisplay(void); - -__attribute__((visibility("default"))) EGLSurface Sb_eglGetCurrentSurface( - EGLint readdraw); - -__attribute__((visibility("default"))) EGLDisplay Sb_eglGetDisplay( - EGLNativeDisplayType display_id); - -__attribute__((visibility("default"))) __eglMustCastToProperFunctionPointerType -Sb_eglGetProcAddress(const char* procname); - -__attribute__((visibility("default"))) EGLBoolean -Sb_eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglMakeCurrent( - EGLDisplay dpy, - EGLSurface draw, - EGLSurface read, - EGLContext ctx); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglQueryContext( - EGLDisplay dpy, - EGLContext ctx, - EGLint attribute, - EGLint* value); - -__attribute__((visibility("default"))) const char* Sb_eglQueryString( - EGLDisplay dpy, - EGLint name); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglQuerySurface( - EGLDisplay dpy, - EGLSurface surface, - EGLint attribute, - EGLint* value); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglSwapBuffers( - EGLDisplay dpy, - EGLSurface surface); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglTerminate( - EGLDisplay dpy); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglWaitGL(void); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglWaitNative( - EGLint engine); - -// egl 1.1 - -__attribute__((visibility("default"))) EGLBoolean -Sb_eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer); - -__attribute__((visibility("default"))) EGLBoolean -Sb_eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglSurfaceAttrib( - EGLDisplay dpy, - EGLSurface surface, - EGLint attribute, - EGLint value); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglSwapInterval( - EGLDisplay dpy, - EGLint interval); - -// egl 1.2 -__attribute__((visibility("default"))) EGLBoolean Sb_eglBindAPI(EGLenum api); - -__attribute__((visibility("default"))) EGLenum Sb_eglQueryAPI(void); - -__attribute__((visibility("default"))) EGLSurface -Sb_eglCreatePbufferFromClientBuffer(EGLDisplay dpy, - EGLenum buftype, - EGLClientBuffer buffer, - EGLConfig config, - const EGLint* attrib_list); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglReleaseThread(void); - -__attribute__((visibility("default"))) EGLBoolean Sb_eglWaitClient(void); - -// egl 1.3 -// does not define new function prototypes. - -// egl 1.4 - -__attribute__((visibility("default"))) EGLContext Sb_eglGetCurrentContext(void); - -} // extern "C" - -#endif // CHROMECAST_STARBOARD_GRAPHICS_EGL_STARBOARD_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/graphics/egl_starboard_dummy.cc chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard_dummy.cc --- chromium-132.0.6834.110/chromecast/starboard/graphics/egl_starboard_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/graphics/egl_starboard_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,194 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// A dummy implementation of egl_starboard.h. This can be used to compile -// without starboard headers. It should never be used in production. -// -// TODO(b/333131992): remove this - -#include "chromecast/starboard/graphics/egl_starboard.h" - -extern "C" { - -EGLBoolean Sb_eglChooseConfig(EGLDisplay dpy, - const EGLint* attrib_list, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config) { - return 0; -} - -EGLBoolean Sb_eglCopyBuffers(EGLDisplay dpy, - EGLSurface surface, - EGLNativePixmapType target) { - return 0; -} - -EGLContext Sb_eglCreateContext(EGLDisplay dpy, - EGLConfig config, - EGLContext share_context, - const EGLint* attrib_list) { - return nullptr; -} - -EGLSurface Sb_eglCreatePbufferSurface(EGLDisplay dpy, - EGLConfig config, - const EGLint* attrib_list) { - return nullptr; -} - -EGLSurface Sb_eglCreatePixmapSurface(EGLDisplay dpy, - EGLConfig config, - EGLNativePixmapType pixmap, - const EGLint* attrib_list) { - return nullptr; -} - -EGLSurface Sb_eglCreateWindowSurface(EGLDisplay dpy, - EGLConfig config, - EGLNativeWindowType win, - const EGLint* attrib_list) { - return nullptr; -} - -EGLBoolean Sb_eglDestroyContext(EGLDisplay dpy, EGLContext ctx) { - return 0; -} - -EGLBoolean Sb_eglDestroySurface(EGLDisplay dpy, EGLSurface surface) { - return 0; -} - -EGLBoolean Sb_eglGetConfigAttrib(EGLDisplay dpy, - EGLConfig config, - EGLint attribute, - EGLint* value) { - return 0; -} - -EGLBoolean Sb_eglGetConfigs(EGLDisplay dpy, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config) { - return 0; -} - -EGLDisplay Sb_eglGetCurrentDisplay(void) { - return nullptr; -} - -EGLSurface Sb_eglGetCurrentSurface(EGLint readdraw) { - return nullptr; -} - -EGLDisplay Sb_eglGetDisplay(EGLNativeDisplayType display_id) { - return nullptr; -} - -EGLint Sb_eglGetError(void) { - return 0; -} - -__eglMustCastToProperFunctionPointerType Sb_eglGetProcAddress( - const char* procname) { - return nullptr; -} - -EGLBoolean Sb_eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor) { - return 0; -} - -EGLBoolean Sb_eglMakeCurrent(EGLDisplay dpy, - EGLSurface draw, - EGLSurface read, - EGLContext ctx) { - return 0; -} - -EGLBoolean Sb_eglQueryContext(EGLDisplay dpy, - EGLContext ctx, - EGLint attribute, - EGLint* value) { - return 0; -} - -const char* Sb_eglQueryString(EGLDisplay dpy, EGLint name) { - return ""; -} - -EGLBoolean Sb_eglQuerySurface(EGLDisplay dpy, - EGLSurface surface, - EGLint attribute, - EGLint* value) { - return 0; -} - -EGLBoolean Sb_eglSwapBuffers(EGLDisplay dpy, EGLSurface surface) { - return 0; -} - -EGLBoolean Sb_eglTerminate(EGLDisplay dpy) { - return 0; -} - -EGLBoolean Sb_eglWaitGL(void) { - return 0; -} - -EGLBoolean Sb_eglWaitNative(EGLint engine) { - return 0; -} - -EGLBoolean Sb_eglBindTexImage(EGLDisplay dpy, - EGLSurface surface, - EGLint buffer) { - return 0; -} - -EGLBoolean Sb_eglReleaseTexImage(EGLDisplay dpy, - EGLSurface surface, - EGLint buffer) { - return 0; -} - -EGLBoolean Sb_eglSurfaceAttrib(EGLDisplay dpy, - EGLSurface surface, - EGLint attribute, - EGLint value) { - return 0; -} - -EGLBoolean Sb_eglSwapInterval(EGLDisplay dpy, EGLint interval) { - return 0; -} - -EGLBoolean Sb_eglBindAPI(EGLenum api) { - return 0; -} - -EGLenum Sb_eglQueryAPI(void) { - return 0; -} - -EGLSurface Sb_eglCreatePbufferFromClientBuffer(EGLDisplay dpy, - EGLenum buftype, - EGLClientBuffer buffer, - EGLConfig config, - const EGLint* attrib_list) { - return nullptr; -} - -EGLBoolean Sb_eglWaitClient(void) { - return 0; -} - -EGLBoolean Sb_eglReleaseThread(void) { - return 0; -} - -EGLContext Sb_eglGetCurrentContext(void) { - return nullptr; -} - -} // extern "C" diff -Nru chromium-132.0.6834.110/chromecast/starboard/graphics/gles2_starboard.cc chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard.cc --- chromium-132.0.6834.110/chromecast/starboard/graphics/gles2_starboard.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,856 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/graphics/gles2_starboard.h" - -#include - -extern "C" { - -// gl2.h - -GL_APICALL void GL_APIENTRY Sb_glActiveTexture(GLenum texture) { - return SbGetGlesInterface()->glActiveTexture(texture); -} - -GL_APICALL void GL_APIENTRY Sb_glAttachShader(GLuint program, GLuint shader) { - return SbGetGlesInterface()->glAttachShader(program, shader); -} - -GL_APICALL void GL_APIENTRY Sb_glBindAttribLocation(GLuint program, - GLuint index, - const GLchar* name) { - return SbGetGlesInterface()->glBindAttribLocation(program, index, name); -} - -GL_APICALL void GL_APIENTRY Sb_glBindBuffer(GLenum target, GLuint buffer) { - return SbGetGlesInterface()->glBindBuffer(target, buffer); -} - -GL_APICALL void GL_APIENTRY Sb_glBindFramebuffer(GLenum target, - GLuint framebuffer) { - return SbGetGlesInterface()->glBindFramebuffer(target, framebuffer); -} - -GL_APICALL void GL_APIENTRY Sb_glBindRenderbuffer(GLenum target, - GLuint renderbuffer) { - return SbGetGlesInterface()->glBindRenderbuffer(target, renderbuffer); -} - -GL_APICALL void GL_APIENTRY Sb_glBindTexture(GLenum target, GLuint texture) { - return SbGetGlesInterface()->glBindTexture(target, texture); -} - -GL_APICALL void GL_APIENTRY Sb_glBlendColor(GLfloat red, - GLfloat green, - GLfloat blue, - GLfloat alpha) { - return SbGetGlesInterface()->glBlendColor(red, green, blue, alpha); -} - -GL_APICALL void GL_APIENTRY Sb_glBlendEquation(GLenum mode) { - return SbGetGlesInterface()->glBlendEquation(mode); -} - -GL_APICALL void GL_APIENTRY Sb_glBlendEquationSeparate(GLenum modeRGB, - GLenum modeAlpha) { - return SbGetGlesInterface()->glBlendEquationSeparate(modeRGB, modeAlpha); -} - -GL_APICALL void GL_APIENTRY Sb_glBlendFunc(GLenum sfactor, GLenum dfactor) { - return SbGetGlesInterface()->glBlendFunc(sfactor, dfactor); -} - -GL_APICALL void GL_APIENTRY Sb_glBlendFuncSeparate(GLenum sfactorRGB, - GLenum dfactorRGB, - GLenum sfactorAlpha, - GLenum dfactorAlpha) { - return SbGetGlesInterface()->glBlendFuncSeparate(sfactorRGB, dfactorRGB, - sfactorAlpha, dfactorAlpha); -} - -GL_APICALL void GL_APIENTRY Sb_glBufferData(GLenum target, - GLsizeiptr size, - const void* data, - GLenum usage) { - return SbGetGlesInterface()->glBufferData(target, size, data, usage); -} - -GL_APICALL void GL_APIENTRY Sb_glBufferSubData(GLenum target, - GLintptr offset, - GLsizeiptr size, - const void* data) { - return SbGetGlesInterface()->glBufferSubData(target, offset, size, data); -} - -GL_APICALL GLenum GL_APIENTRY Sb_glCheckFramebufferStatus(GLenum target) { - return SbGetGlesInterface()->glCheckFramebufferStatus(target); -} - -GL_APICALL void GL_APIENTRY Sb_glClear(GLbitfield mask) { - return SbGetGlesInterface()->glClear(mask); -} - -GL_APICALL void GL_APIENTRY Sb_glClearColor(GLfloat red, - GLfloat green, - GLfloat blue, - GLfloat alpha) { - // TODO(rknichols): - // When casting, the UI overlay is rendered on top of the video frame. - // We must use punch through to display the video frame underneath, thus - // the alpha when displaying videos must be 0.f. - // However, sourcing the location in chromium's code that sets us to (0,0,0,1) - // is proving difficult. the last breadcrumb has been: - // `cc/layers/recording_source.cc:DetermineIfSolidColor` - // if `solid_color_` is set at the end of the function, to 0 then we observe - // the expected output. Where the originating `black` layer comes from is - // unclear. - // - // Remove the force set of alpha to 0.f when the above comment has been - // resolved. - return SbGetGlesInterface()->glClearColor(red, green, blue, 0.f); -} - -GL_APICALL void GL_APIENTRY Sb_glClearDepthf(GLfloat d) { - return SbGetGlesInterface()->glClearDepthf(d); -} - -GL_APICALL void GL_APIENTRY Sb_glClearStencil(GLint s) { - return SbGetGlesInterface()->glClearStencil(s); -} - -GL_APICALL void GL_APIENTRY Sb_glColorMask(GLboolean red, - GLboolean green, - GLboolean blue, - GLboolean alpha) { - return SbGetGlesInterface()->glColorMask(red, green, blue, alpha); -} - -GL_APICALL void GL_APIENTRY Sb_glCompileShader(GLuint shader) { - return SbGetGlesInterface()->glCompileShader(shader); -} - -GL_APICALL void GL_APIENTRY Sb_glCompressedTexImage2D(GLenum target, - GLint level, - GLenum internalformat, - GLsizei width, - GLsizei height, - GLint border, - GLsizei imageSize, - const void* data) { - return SbGetGlesInterface()->glCompressedTexImage2D( - target, level, internalformat, width, height, border, imageSize, data); -} - -GL_APICALL void GL_APIENTRY Sb_glCompressedTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLsizei imageSize, - const void* data) { - return SbGetGlesInterface()->glCompressedTexSubImage2D( - target, level, xoffset, yoffset, width, height, format, imageSize, data); -} - -GL_APICALL void GL_APIENTRY Sb_glCopyTexImage2D(GLenum target, - GLint level, - GLenum internalformat, - GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLint border) { - return SbGetGlesInterface()->glCopyTexImage2D(target, level, internalformat, - x, y, width, height, border); -} - -GL_APICALL void GL_APIENTRY Sb_glCopyTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLint x, - GLint y, - GLsizei width, - GLsizei height) { - return SbGetGlesInterface()->glCopyTexSubImage2D( - target, level, xoffset, yoffset, x, y, width, height); -} - -GL_APICALL GLuint GL_APIENTRY Sb_glCreateProgram(void) { - return SbGetGlesInterface()->glCreateProgram(); -} - -GL_APICALL GLuint GL_APIENTRY Sb_glCreateShader(GLenum type) { - return SbGetGlesInterface()->glCreateShader(type); -} - -GL_APICALL void GL_APIENTRY Sb_glCullFace(GLenum mode) { - return SbGetGlesInterface()->glCullFace(mode); -} - -GL_APICALL void GL_APIENTRY Sb_glDeleteBuffers(GLsizei n, - const GLuint* buffers) { - return SbGetGlesInterface()->glDeleteBuffers(n, buffers); -} - -GL_APICALL void GL_APIENTRY -Sb_glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers) { - return SbGetGlesInterface()->glDeleteFramebuffers(n, framebuffers); -} - -GL_APICALL void GL_APIENTRY Sb_glDeleteProgram(GLuint program) { - return SbGetGlesInterface()->glDeleteProgram(program); -} - -GL_APICALL void GL_APIENTRY -Sb_glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers) { - return SbGetGlesInterface()->glDeleteRenderbuffers(n, renderbuffers); -} - -GL_APICALL void GL_APIENTRY Sb_glDeleteShader(GLuint shader) { - return SbGetGlesInterface()->glDeleteShader(shader); -} - -GL_APICALL void GL_APIENTRY Sb_glDeleteTextures(GLsizei n, - const GLuint* textures) { - return SbGetGlesInterface()->glDeleteTextures(n, textures); -} - -GL_APICALL void GL_APIENTRY Sb_glDepthFunc(GLenum func) { - return SbGetGlesInterface()->glDepthFunc(func); -} - -GL_APICALL void GL_APIENTRY Sb_glDepthMask(GLboolean flag) { - return SbGetGlesInterface()->glDepthMask(flag); -} - -GL_APICALL void GL_APIENTRY Sb_glDepthRangef(GLfloat n, GLfloat f) { - return SbGetGlesInterface()->glDepthRangef(n, f); -} - -GL_APICALL void GL_APIENTRY Sb_glDetachShader(GLuint program, GLuint shader) { - return SbGetGlesInterface()->glDetachShader(program, shader); -} - -GL_APICALL void GL_APIENTRY Sb_glDisable(GLenum cap) { - return SbGetGlesInterface()->glDisable(cap); -} - -GL_APICALL void GL_APIENTRY Sb_glDisableVertexAttribArray(GLuint index) { - return SbGetGlesInterface()->glDisableVertexAttribArray(index); -} - -GL_APICALL void GL_APIENTRY Sb_glDrawArrays(GLenum mode, - GLint first, - GLsizei count) { - return SbGetGlesInterface()->glDrawArrays(mode, first, count); -} - -GL_APICALL void GL_APIENTRY Sb_glDrawElements(GLenum mode, - GLsizei count, - GLenum type, - const void* indices) { - return SbGetGlesInterface()->glDrawElements(mode, count, type, indices); -} - -GL_APICALL void GL_APIENTRY Sb_glEnable(GLenum cap) { - return SbGetGlesInterface()->glEnable(cap); -} - -GL_APICALL void GL_APIENTRY Sb_glEnableVertexAttribArray(GLuint index) { - return SbGetGlesInterface()->glEnableVertexAttribArray(index); -} - -GL_APICALL void GL_APIENTRY Sb_glFinish(void) { - return SbGetGlesInterface()->glFinish(); -} - -GL_APICALL void GL_APIENTRY Sb_glFlush(void) { - return SbGetGlesInterface()->glFlush(); -} - -GL_APICALL void GL_APIENTRY -Sb_glFramebufferRenderbuffer(GLenum target, - GLenum attachment, - GLenum renderbuffertarget, - GLuint renderbuffer) { - return SbGetGlesInterface()->glFramebufferRenderbuffer( - target, attachment, renderbuffertarget, renderbuffer); -} - -GL_APICALL void GL_APIENTRY Sb_glFramebufferTexture2D(GLenum target, - GLenum attachment, - GLenum textarget, - GLuint texture, - GLint level) { - return SbGetGlesInterface()->glFramebufferTexture2D( - target, attachment, textarget, texture, level); -} - -GL_APICALL void GL_APIENTRY Sb_glFrontFace(GLenum mode) { - return SbGetGlesInterface()->glFrontFace(mode); -} - -GL_APICALL void GL_APIENTRY Sb_glGenBuffers(GLsizei n, GLuint* buffers) { - return SbGetGlesInterface()->glGenBuffers(n, buffers); -} - -GL_APICALL void GL_APIENTRY Sb_glGenerateMipmap(GLenum target) { - return SbGetGlesInterface()->glGenerateMipmap(target); -} - -GL_APICALL void GL_APIENTRY Sb_glGenFramebuffers(GLsizei n, - GLuint* framebuffers) { - return SbGetGlesInterface()->glGenFramebuffers(n, framebuffers); -} - -GL_APICALL void GL_APIENTRY Sb_glGenRenderbuffers(GLsizei n, - GLuint* renderbuffers) { - return SbGetGlesInterface()->glGenRenderbuffers(n, renderbuffers); -} - -GL_APICALL void GL_APIENTRY Sb_glGenTextures(GLsizei n, GLuint* textures) { - return SbGetGlesInterface()->glGenTextures(n, textures); -} - -GL_APICALL void GL_APIENTRY Sb_glGetActiveAttrib(GLuint program, - GLuint index, - GLsizei bufSize, - GLsizei* length, - GLint* size, - GLenum* type, - GLchar* name) { - return SbGetGlesInterface()->glGetActiveAttrib(program, index, bufSize, - length, size, type, name); -} - -GL_APICALL void GL_APIENTRY Sb_glGetActiveUniform(GLuint program, - GLuint index, - GLsizei bufSize, - GLsizei* length, - GLint* size, - GLenum* type, - GLchar* name) { - return SbGetGlesInterface()->glGetActiveUniform(program, index, bufSize, - length, size, type, name); -} - -GL_APICALL void GL_APIENTRY Sb_glGetAttachedShaders(GLuint program, - GLsizei maxCount, - GLsizei* count, - GLuint* shaders) { - return SbGetGlesInterface()->glGetAttachedShaders(program, maxCount, count, - shaders); -} - -GL_APICALL GLint GL_APIENTRY Sb_glGetAttribLocation(GLuint program, - const GLchar* name) { - return SbGetGlesInterface()->glGetAttribLocation(program, name); -} - -GL_APICALL void GL_APIENTRY Sb_glGetBooleanv(GLenum pname, GLboolean* data) { - return SbGetGlesInterface()->glGetBooleanv(pname, data); -} - -GL_APICALL void GL_APIENTRY Sb_glGetBufferParameteriv(GLenum target, - GLenum pname, - GLint* params) { - return SbGetGlesInterface()->glGetBufferParameteriv(target, pname, params); -} - -GL_APICALL GLenum GL_APIENTRY Sb_glGetError(void) { - return SbGetGlesInterface()->glGetError(); -} - -GL_APICALL void GL_APIENTRY Sb_glGetFloatv(GLenum pname, GLfloat* data) { - return SbGetGlesInterface()->glGetFloatv(pname, data); -} - -GL_APICALL void GL_APIENTRY -Sb_glGetFramebufferAttachmentParameteriv(GLenum target, - GLenum attachment, - GLenum pname, - GLint* params) { - return SbGetGlesInterface()->glGetFramebufferAttachmentParameteriv( - target, attachment, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetIntegerv(GLenum pname, GLint* data) { - return SbGetGlesInterface()->glGetIntegerv(pname, data); -} - -GL_APICALL void GL_APIENTRY Sb_glGetProgramiv(GLuint program, - GLenum pname, - GLint* params) { - return SbGetGlesInterface()->glGetProgramiv(program, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetProgramInfoLog(GLuint program, - GLsizei bufSize, - GLsizei* length, - GLchar* infoLog) { - return SbGetGlesInterface()->glGetProgramInfoLog(program, bufSize, length, - infoLog); -} - -GL_APICALL void GL_APIENTRY Sb_glGetRenderbufferParameteriv(GLenum target, - GLenum pname, - GLint* params) { - return SbGetGlesInterface()->glGetRenderbufferParameteriv(target, pname, - params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetShaderiv(GLuint shader, - GLenum pname, - GLint* params) { - return SbGetGlesInterface()->glGetShaderiv(shader, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetShaderInfoLog(GLuint shader, - GLsizei bufSize, - GLsizei* length, - GLchar* infoLog) { - return SbGetGlesInterface()->glGetShaderInfoLog(shader, bufSize, length, - infoLog); -} - -GL_APICALL void GL_APIENTRY Sb_glGetShaderPrecisionFormat(GLenum shadertype, - GLenum precisiontype, - GLint* range, - GLint* precision) { - return SbGetGlesInterface()->glGetShaderPrecisionFormat( - shadertype, precisiontype, range, precision); -} - -GL_APICALL void GL_APIENTRY Sb_glGetShaderSource(GLuint shader, - GLsizei bufSize, - GLsizei* length, - GLchar* source) { - return SbGetGlesInterface()->glGetShaderSource(shader, bufSize, length, - source); -} - -GL_APICALL const GLubyte* GL_APIENTRY Sb_glGetString(GLenum name) { - static const unsigned char opengl_es_2_str[] = "OpenGL ES 2.0"; - - const GLubyte* result = SbGetGlesInterface()->glGetString(name); - return (result && name == SB_GL_VERSION) ? opengl_es_2_str : result; -} - -GL_APICALL void GL_APIENTRY Sb_glGetTexParameterfv(GLenum target, - GLenum pname, - GLfloat* params) { - return SbGetGlesInterface()->glGetTexParameterfv(target, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetTexParameteriv(GLenum target, - GLenum pname, - GLint* params) { - return SbGetGlesInterface()->glGetTexParameteriv(target, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetUniformfv(GLuint program, - GLint location, - GLfloat* params) { - return SbGetGlesInterface()->glGetUniformfv(program, location, params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetUniformiv(GLuint program, - GLint location, - GLint* params) { - return SbGetGlesInterface()->glGetUniformiv(program, location, params); -} - -GL_APICALL GLint GL_APIENTRY Sb_glGetUniformLocation(GLuint program, - const GLchar* name) { - return SbGetGlesInterface()->glGetUniformLocation(program, name); -} - -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribfv(GLuint index, - GLenum pname, - GLfloat* params) { - return SbGetGlesInterface()->glGetVertexAttribfv(index, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribiv(GLuint index, - GLenum pname, - GLint* params) { - return SbGetGlesInterface()->glGetVertexAttribiv(index, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribPointerv(GLuint index, - GLenum pname, - void** pointer) { - return SbGetGlesInterface()->glGetVertexAttribPointerv(index, pname, pointer); -} - -GL_APICALL void GL_APIENTRY Sb_glHint(GLenum target, GLenum mode) { - return SbGetGlesInterface()->glHint(target, mode); -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsBuffer(GLuint buffer) { - return SbGetGlesInterface()->glIsBuffer(buffer); -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsEnabled(GLenum cap) { - return SbGetGlesInterface()->glIsEnabled(cap); -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsFramebuffer(GLuint framebuffer) { - return SbGetGlesInterface()->glIsFramebuffer(framebuffer); -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsProgram(GLuint program) { - return SbGetGlesInterface()->glIsProgram(program); -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsRenderbuffer(GLuint renderbuffer) { - return SbGetGlesInterface()->glIsRenderbuffer(renderbuffer); -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsShader(GLuint shader) { - return SbGetGlesInterface()->glIsShader(shader); -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsTexture(GLuint texture) { - return SbGetGlesInterface()->glIsTexture(texture); -} - -GL_APICALL void GL_APIENTRY Sb_glLineWidth(GLfloat width) { - return SbGetGlesInterface()->glLineWidth(width); -} - -GL_APICALL void GL_APIENTRY Sb_glLinkProgram(GLuint program) { - return SbGetGlesInterface()->glLinkProgram(program); -} - -GL_APICALL void GL_APIENTRY Sb_glPixelStorei(GLenum pname, GLint param) { - return SbGetGlesInterface()->glPixelStorei(pname, param); -} - -GL_APICALL void GL_APIENTRY Sb_glPolygonOffset(GLfloat factor, GLfloat units) { - return SbGetGlesInterface()->glPolygonOffset(factor, units); -} - -GL_APICALL void GL_APIENTRY Sb_glReadPixels(GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - void* pixels) { - return SbGetGlesInterface()->glReadPixels(x, y, width, height, format, type, - pixels); -} - -GL_APICALL void GL_APIENTRY Sb_glReleaseShaderCompiler(void) { - return SbGetGlesInterface()->glReleaseShaderCompiler(); -} - -GL_APICALL void GL_APIENTRY Sb_glRenderbufferStorage(GLenum target, - GLenum internalformat, - GLsizei width, - GLsizei height) { - return SbGetGlesInterface()->glRenderbufferStorage(target, internalformat, - width, height); -} - -GL_APICALL void GL_APIENTRY Sb_glSampleCoverage(GLfloat value, - GLboolean invert) { - return SbGetGlesInterface()->glSampleCoverage(value, invert); -} - -GL_APICALL void GL_APIENTRY Sb_glScissor(GLint x, - GLint y, - GLsizei width, - GLsizei height) { - return SbGetGlesInterface()->glScissor(x, y, width, height); -} - -GL_APICALL void GL_APIENTRY Sb_glShaderBinary(GLsizei count, - const GLuint* shaders, - GLenum binaryformat, - const void* binary, - GLsizei length) { - return SbGetGlesInterface()->glShaderBinary(count, shaders, binaryformat, - binary, length); -} - -GL_APICALL void GL_APIENTRY Sb_glShaderSource(GLuint shader, - GLsizei count, - const GLchar* const* string, - const GLint* length) { - return SbGetGlesInterface()->glShaderSource(shader, count, string, length); -} - -GL_APICALL void GL_APIENTRY Sb_glStencilFunc(GLenum func, - GLint ref, - GLuint mask) { - return SbGetGlesInterface()->glStencilFunc(func, ref, mask); -} - -GL_APICALL void GL_APIENTRY Sb_glStencilFuncSeparate(GLenum face, - GLenum func, - GLint ref, - GLuint mask) { - return SbGetGlesInterface()->glStencilFuncSeparate(face, func, ref, mask); -} - -GL_APICALL void GL_APIENTRY Sb_glStencilMask(GLuint mask) { - return SbGetGlesInterface()->glStencilMask(mask); -} - -GL_APICALL void GL_APIENTRY Sb_glStencilMaskSeparate(GLenum face, GLuint mask) { - return SbGetGlesInterface()->glStencilMaskSeparate(face, mask); -} - -GL_APICALL void GL_APIENTRY Sb_glStencilOp(GLenum fail, - GLenum zfail, - GLenum zpass) { - return SbGetGlesInterface()->glStencilOp(fail, zfail, zpass); -} - -GL_APICALL void GL_APIENTRY Sb_glStencilOpSeparate(GLenum face, - GLenum sfail, - GLenum dpfail, - GLenum dppass) { - return SbGetGlesInterface()->glStencilOpSeparate(face, sfail, dpfail, dppass); -} - -GL_APICALL void GL_APIENTRY Sb_glTexImage2D(GLenum target, - GLint level, - GLint internalformat, - GLsizei width, - GLsizei height, - GLint border, - GLenum format, - GLenum type, - const void* pixels) { - return SbGetGlesInterface()->glTexImage2D(target, level, internalformat, - width, height, border, format, type, - pixels); -} - -GL_APICALL void GL_APIENTRY Sb_glTexParameterf(GLenum target, - GLenum pname, - GLfloat param) { - return SbGetGlesInterface()->glTexParameterf(target, pname, param); -} - -GL_APICALL void GL_APIENTRY Sb_glTexParameterfv(GLenum target, - GLenum pname, - const GLfloat* params) { - return SbGetGlesInterface()->glTexParameterfv(target, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glTexParameteri(GLenum target, - GLenum pname, - GLint param) { - return SbGetGlesInterface()->glTexParameteri(target, pname, param); -} - -GL_APICALL void GL_APIENTRY Sb_glTexParameteriv(GLenum target, - GLenum pname, - const GLint* params) { - return SbGetGlesInterface()->glTexParameteriv(target, pname, params); -} - -GL_APICALL void GL_APIENTRY Sb_glTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - const void* pixels) { - return SbGetGlesInterface()->glTexSubImage2D( - target, level, xoffset, yoffset, width, height, format, type, pixels); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform1f(GLint location, GLfloat v0) { - return SbGetGlesInterface()->glUniform1f(location, v0); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform1fv(GLint location, - GLsizei count, - const GLfloat* value) { - return SbGetGlesInterface()->glUniform1fv(location, count, value); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform1i(GLint location, GLint v0) { - return SbGetGlesInterface()->glUniform1i(location, v0); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform1iv(GLint location, - GLsizei count, - const GLint* value) { - return SbGetGlesInterface()->glUniform1iv(location, count, value); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform2f(GLint location, - GLfloat v0, - GLfloat v1) { - return SbGetGlesInterface()->glUniform2f(location, v0, v1); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform2fv(GLint location, - GLsizei count, - const GLfloat* value) { - return SbGetGlesInterface()->glUniform2fv(location, count, value); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform2i(GLint location, GLint v0, GLint v1) { - return SbGetGlesInterface()->glUniform2i(location, v0, v1); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform2iv(GLint location, - GLsizei count, - const GLint* value) { - return SbGetGlesInterface()->glUniform2iv(location, count, value); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform3f(GLint location, - GLfloat v0, - GLfloat v1, - GLfloat v2) { - return SbGetGlesInterface()->glUniform3f(location, v0, v1, v2); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform3fv(GLint location, - GLsizei count, - const GLfloat* value) { - return SbGetGlesInterface()->glUniform3fv(location, count, value); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform3i(GLint location, - GLint v0, - GLint v1, - GLint v2) { - return SbGetGlesInterface()->glUniform3i(location, v0, v1, v2); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform3iv(GLint location, - GLsizei count, - const GLint* value) { - return SbGetGlesInterface()->glUniform3iv(location, count, value); -} - -GL_APICALL void GL_APIENTRY -Sb_glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { - return SbGetGlesInterface()->glUniform4f(location, v0, v1, v2, v3); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform4fv(GLint location, - GLsizei count, - const GLfloat* value) { - return SbGetGlesInterface()->glUniform4fv(location, count, value); -} - -GL_APICALL void GL_APIENTRY -Sb_glUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) { - return SbGetGlesInterface()->glUniform4i(location, v0, v1, v2, v3); -} - -GL_APICALL void GL_APIENTRY Sb_glUniform4iv(GLint location, - GLsizei count, - const GLint* value) { - return SbGetGlesInterface()->glUniform4iv(location, count, value); -} - -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix2fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value) { - return SbGetGlesInterface()->glUniformMatrix2fv(location, count, transpose, - value); -} - -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix3fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value) { - return SbGetGlesInterface()->glUniformMatrix3fv(location, count, transpose, - value); -} - -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix4fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value) { - return SbGetGlesInterface()->glUniformMatrix4fv(location, count, transpose, - value); -} - -GL_APICALL void GL_APIENTRY Sb_glUseProgram(GLuint program) { - return SbGetGlesInterface()->glUseProgram(program); -} - -GL_APICALL void GL_APIENTRY Sb_glValidateProgram(GLuint program) { - return SbGetGlesInterface()->glValidateProgram(program); -} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib1f(GLuint index, GLfloat x) { - return SbGetGlesInterface()->glVertexAttrib1f(index, x); -} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib1fv(GLuint index, - const GLfloat* v) { - return SbGetGlesInterface()->glVertexAttrib1fv(index, v); -} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib2f(GLuint index, - GLfloat x, - GLfloat y) { - return SbGetGlesInterface()->glVertexAttrib2f(index, x, y); -} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib2fv(GLuint index, - const GLfloat* v) { - return SbGetGlesInterface()->glVertexAttrib2fv(index, v); -} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib3f(GLuint index, - GLfloat x, - GLfloat y, - GLfloat z) { - return SbGetGlesInterface()->glVertexAttrib3f(index, x, y, z); -} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib3fv(GLuint index, - const GLfloat* v) { - return SbGetGlesInterface()->glVertexAttrib3fv(index, v); -} - -GL_APICALL void GL_APIENTRY -Sb_glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { - return SbGetGlesInterface()->glVertexAttrib4f(index, x, y, z, w); -} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib4fv(GLuint index, - const GLfloat* v) { - return SbGetGlesInterface()->glVertexAttrib4fv(index, v); -} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttribPointer(GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const void* pointer) { - return SbGetGlesInterface()->glVertexAttribPointer( - index, size, type, normalized, stride, pointer); -} - -GL_APICALL void GL_APIENTRY Sb_glViewport(GLint x, - GLint y, - GLsizei width, - GLsizei height) { - return SbGetGlesInterface()->glViewport(x, y, width, height); -} - -} // extern "C" diff -Nru chromium-132.0.6834.110/chromecast/starboard/graphics/gles2_starboard.h chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard.h --- chromium-132.0.6834.110/chromecast/starboard/graphics/gles2_starboard.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,392 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_GRAPHICS_GLES2_STARBOARD_H_ -#define CHROMECAST_STARBOARD_GRAPHICS_GLES2_STARBOARD_H_ - -#include - -extern "C" { - -// gl2.h - -GL_APICALL void GL_APIENTRY Sb_glActiveTexture(GLenum texture); -GL_APICALL void GL_APIENTRY Sb_glAttachShader(GLuint program, GLuint shader); -GL_APICALL void GL_APIENTRY Sb_glBindAttribLocation(GLuint program, - GLuint index, - const GLchar* name); -GL_APICALL void GL_APIENTRY Sb_glBindBuffer(GLenum target, GLuint buffer); -GL_APICALL void GL_APIENTRY Sb_glBindFramebuffer(GLenum target, - GLuint framebuffer); -GL_APICALL void GL_APIENTRY Sb_glBindRenderbuffer(GLenum target, - GLuint renderbuffer); -GL_APICALL void GL_APIENTRY Sb_glBindTexture(GLenum target, GLuint texture); -GL_APICALL void GL_APIENTRY Sb_glBlendColor(GLfloat red, - GLfloat green, - GLfloat blue, - GLfloat alpha); -GL_APICALL void GL_APIENTRY Sb_glBlendEquation(GLenum mode); -GL_APICALL void GL_APIENTRY Sb_glBlendEquationSeparate(GLenum modeRGB, - GLenum modeAlpha); -GL_APICALL void GL_APIENTRY Sb_glBlendFunc(GLenum sfactor, GLenum dfactor); -GL_APICALL void GL_APIENTRY Sb_glBlendFuncSeparate(GLenum sfactorRGB, - GLenum dfactorRGB, - GLenum sfactorAlpha, - GLenum dfactorAlpha); -GL_APICALL void GL_APIENTRY Sb_glBufferData(GLenum target, - GLsizeiptr size, - const void* data, - GLenum usage); -GL_APICALL void GL_APIENTRY Sb_glBufferSubData(GLenum target, - GLintptr offset, - GLsizeiptr size, - const void* data); -GL_APICALL GLenum GL_APIENTRY Sb_glCheckFramebufferStatus(GLenum target); -GL_APICALL void GL_APIENTRY Sb_glClear(GLbitfield mask); -GL_APICALL void GL_APIENTRY Sb_glClearColor(GLfloat red, - GLfloat green, - GLfloat blue, - GLfloat alpha); -GL_APICALL void GL_APIENTRY Sb_glClearDepthf(GLfloat d); -GL_APICALL void GL_APIENTRY Sb_glClearStencil(GLint s); -GL_APICALL void GL_APIENTRY Sb_glColorMask(GLboolean red, - GLboolean green, - GLboolean blue, - GLboolean alpha); -GL_APICALL void GL_APIENTRY Sb_glCompileShader(GLuint shader); -GL_APICALL void GL_APIENTRY Sb_glCompressedTexImage2D(GLenum target, - GLint level, - GLenum internalformat, - GLsizei width, - GLsizei height, - GLint border, - GLsizei imageSize, - const void* data); -GL_APICALL void GL_APIENTRY Sb_glCompressedTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLsizei imageSize, - const void* data); -GL_APICALL void GL_APIENTRY Sb_glCopyTexImage2D(GLenum target, - GLint level, - GLenum internalformat, - GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLint border); -GL_APICALL void GL_APIENTRY Sb_glCopyTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLint x, - GLint y, - GLsizei width, - GLsizei height); -GL_APICALL GLuint GL_APIENTRY Sb_glCreateProgram(void); -GL_APICALL GLuint GL_APIENTRY Sb_glCreateShader(GLenum type); -GL_APICALL void GL_APIENTRY Sb_glCullFace(GLenum mode); -GL_APICALL void GL_APIENTRY Sb_glDeleteBuffers(GLsizei n, - const GLuint* buffers); -GL_APICALL void GL_APIENTRY Sb_glDeleteFramebuffers(GLsizei n, - const GLuint* framebuffers); -GL_APICALL void GL_APIENTRY Sb_glDeleteProgram(GLuint program); -GL_APICALL void GL_APIENTRY -Sb_glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers); -GL_APICALL void GL_APIENTRY Sb_glDeleteShader(GLuint shader); -GL_APICALL void GL_APIENTRY Sb_glDeleteTextures(GLsizei n, - const GLuint* textures); -GL_APICALL void GL_APIENTRY Sb_glDepthFunc(GLenum func); -GL_APICALL void GL_APIENTRY Sb_glDepthMask(GLboolean flag); -GL_APICALL void GL_APIENTRY Sb_glDepthRangef(GLfloat n, GLfloat f); -GL_APICALL void GL_APIENTRY Sb_glDetachShader(GLuint program, GLuint shader); -GL_APICALL void GL_APIENTRY Sb_glDisable(GLenum cap); -GL_APICALL void GL_APIENTRY Sb_glDisableVertexAttribArray(GLuint index); -GL_APICALL void GL_APIENTRY Sb_glDrawArrays(GLenum mode, - GLint first, - GLsizei count); -GL_APICALL void GL_APIENTRY Sb_glDrawElements(GLenum mode, - GLsizei count, - GLenum type, - const void* indices); -GL_APICALL void GL_APIENTRY Sb_glEnable(GLenum cap); -GL_APICALL void GL_APIENTRY Sb_glEnableVertexAttribArray(GLuint index); -GL_APICALL void GL_APIENTRY Sb_glFinish(void); -GL_APICALL void GL_APIENTRY Sb_glFlush(void); -GL_APICALL void GL_APIENTRY -Sb_glFramebufferRenderbuffer(GLenum target, - GLenum attachment, - GLenum renderbuffertarget, - GLuint renderbuffer); -GL_APICALL void GL_APIENTRY Sb_glFramebufferTexture2D(GLenum target, - GLenum attachment, - GLenum textarget, - GLuint texture, - GLint level); -GL_APICALL void GL_APIENTRY Sb_glFrontFace(GLenum mode); -GL_APICALL void GL_APIENTRY Sb_glGenBuffers(GLsizei n, GLuint* buffers); -GL_APICALL void GL_APIENTRY Sb_glGenerateMipmap(GLenum target); -GL_APICALL void GL_APIENTRY Sb_glGenFramebuffers(GLsizei n, - GLuint* framebuffers); -GL_APICALL void GL_APIENTRY Sb_glGenRenderbuffers(GLsizei n, - GLuint* renderbuffers); -GL_APICALL void GL_APIENTRY Sb_glGenTextures(GLsizei n, GLuint* textures); -GL_APICALL void GL_APIENTRY Sb_glGetActiveAttrib(GLuint program, - GLuint index, - GLsizei bufSize, - GLsizei* length, - GLint* size, - GLenum* type, - GLchar* name); -GL_APICALL void GL_APIENTRY Sb_glGetActiveUniform(GLuint program, - GLuint index, - GLsizei bufSize, - GLsizei* length, - GLint* size, - GLenum* type, - GLchar* name); -GL_APICALL void GL_APIENTRY Sb_glGetAttachedShaders(GLuint program, - GLsizei maxCount, - GLsizei* count, - GLuint* shaders); -GL_APICALL GLint GL_APIENTRY Sb_glGetAttribLocation(GLuint program, - const GLchar* name); -GL_APICALL void GL_APIENTRY Sb_glGetBooleanv(GLenum pname, GLboolean* data); -GL_APICALL void GL_APIENTRY Sb_glGetBufferParameteriv(GLenum target, - GLenum pname, - GLint* params); -GL_APICALL GLenum GL_APIENTRY Sb_glGetError(void); -GL_APICALL void GL_APIENTRY Sb_glGetFloatv(GLenum pname, GLfloat* data); -GL_APICALL void GL_APIENTRY -Sb_glGetFramebufferAttachmentParameteriv(GLenum target, - GLenum attachment, - GLenum pname, - GLint* params); -GL_APICALL void GL_APIENTRY Sb_glGetIntegerv(GLenum pname, GLint* data); -GL_APICALL void GL_APIENTRY Sb_glGetProgramiv(GLuint program, - GLenum pname, - GLint* params); -GL_APICALL void GL_APIENTRY Sb_glGetProgramInfoLog(GLuint program, - GLsizei bufSize, - GLsizei* length, - GLchar* infoLog); -GL_APICALL void GL_APIENTRY Sb_glGetRenderbufferParameteriv(GLenum target, - GLenum pname, - GLint* params); -GL_APICALL void GL_APIENTRY Sb_glGetShaderiv(GLuint shader, - GLenum pname, - GLint* params); -GL_APICALL void GL_APIENTRY Sb_glGetShaderInfoLog(GLuint shader, - GLsizei bufSize, - GLsizei* length, - GLchar* infoLog); -GL_APICALL void GL_APIENTRY Sb_glGetShaderPrecisionFormat(GLenum shadertype, - GLenum precisiontype, - GLint* range, - GLint* precision); -GL_APICALL void GL_APIENTRY Sb_glGetShaderSource(GLuint shader, - GLsizei bufSize, - GLsizei* length, - GLchar* source); -GL_APICALL const GLubyte* GL_APIENTRY Sb_glGetString(GLenum name); -GL_APICALL void GL_APIENTRY Sb_glGetTexParameterfv(GLenum target, - GLenum pname, - GLfloat* params); -GL_APICALL void GL_APIENTRY Sb_glGetTexParameteriv(GLenum target, - GLenum pname, - GLint* params); -GL_APICALL void GL_APIENTRY Sb_glGetUniformfv(GLuint program, - GLint location, - GLfloat* params); -GL_APICALL void GL_APIENTRY Sb_glGetUniformiv(GLuint program, - GLint location, - GLint* params); -GL_APICALL GLint GL_APIENTRY Sb_glGetUniformLocation(GLuint program, - const GLchar* name); -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribfv(GLuint index, - GLenum pname, - GLfloat* params); -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribiv(GLuint index, - GLenum pname, - GLint* params); -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribPointerv(GLuint index, - GLenum pname, - void** pointer); -GL_APICALL void GL_APIENTRY Sb_glHint(GLenum target, GLenum mode); -GL_APICALL GLboolean GL_APIENTRY Sb_glIsBuffer(GLuint buffer); -GL_APICALL GLboolean GL_APIENTRY Sb_glIsEnabled(GLenum cap); -GL_APICALL GLboolean GL_APIENTRY Sb_glIsFramebuffer(GLuint framebuffer); -GL_APICALL GLboolean GL_APIENTRY Sb_glIsProgram(GLuint program); -GL_APICALL GLboolean GL_APIENTRY Sb_glIsRenderbuffer(GLuint renderbuffer); -GL_APICALL GLboolean GL_APIENTRY Sb_glIsShader(GLuint shader); -GL_APICALL GLboolean GL_APIENTRY Sb_glIsTexture(GLuint texture); -GL_APICALL void GL_APIENTRY Sb_glLineWidth(GLfloat width); -GL_APICALL void GL_APIENTRY Sb_glLinkProgram(GLuint program); -GL_APICALL void GL_APIENTRY Sb_glPixelStorei(GLenum pname, GLint param); -GL_APICALL void GL_APIENTRY Sb_glPolygonOffset(GLfloat factor, GLfloat units); -GL_APICALL void GL_APIENTRY Sb_glReadPixels(GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - void* pixels); -GL_APICALL void GL_APIENTRY Sb_glReleaseShaderCompiler(void); -GL_APICALL void GL_APIENTRY Sb_glRenderbufferStorage(GLenum target, - GLenum internalformat, - GLsizei width, - GLsizei height); -GL_APICALL void GL_APIENTRY Sb_glSampleCoverage(GLfloat value, - GLboolean invert); -GL_APICALL void GL_APIENTRY Sb_glScissor(GLint x, - GLint y, - GLsizei width, - GLsizei height); -GL_APICALL void GL_APIENTRY Sb_glShaderBinary(GLsizei count, - const GLuint* shaders, - GLenum binaryformat, - const void* binary, - GLsizei length); -GL_APICALL void GL_APIENTRY Sb_glShaderSource(GLuint shader, - GLsizei count, - const GLchar* const* string, - const GLint* length); -GL_APICALL void GL_APIENTRY Sb_glStencilFunc(GLenum func, - GLint ref, - GLuint mask); -GL_APICALL void GL_APIENTRY Sb_glStencilFuncSeparate(GLenum face, - GLenum func, - GLint ref, - GLuint mask); -GL_APICALL void GL_APIENTRY Sb_glStencilMask(GLuint mask); -GL_APICALL void GL_APIENTRY Sb_glStencilMaskSeparate(GLenum face, GLuint mask); -GL_APICALL void GL_APIENTRY Sb_glStencilOp(GLenum fail, - GLenum zfail, - GLenum zpass); -GL_APICALL void GL_APIENTRY Sb_glStencilOpSeparate(GLenum face, - GLenum sfail, - GLenum dpfail, - GLenum dppass); -GL_APICALL void GL_APIENTRY Sb_glTexImage2D(GLenum target, - GLint level, - GLint internalformat, - GLsizei width, - GLsizei height, - GLint border, - GLenum format, - GLenum type, - const void* pixels); -GL_APICALL void GL_APIENTRY Sb_glTexParameterf(GLenum target, - GLenum pname, - GLfloat param); -GL_APICALL void GL_APIENTRY Sb_glTexParameterfv(GLenum target, - GLenum pname, - const GLfloat* params); -GL_APICALL void GL_APIENTRY Sb_glTexParameteri(GLenum target, - GLenum pname, - GLint param); -GL_APICALL void GL_APIENTRY Sb_glTexParameteriv(GLenum target, - GLenum pname, - const GLint* params); -GL_APICALL void GL_APIENTRY Sb_glTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - const void* pixels); -GL_APICALL void GL_APIENTRY Sb_glUniform1f(GLint location, GLfloat v0); -GL_APICALL void GL_APIENTRY Sb_glUniform1fv(GLint location, - GLsizei count, - const GLfloat* value); -GL_APICALL void GL_APIENTRY Sb_glUniform1i(GLint location, GLint v0); -GL_APICALL void GL_APIENTRY Sb_glUniform1iv(GLint location, - GLsizei count, - const GLint* value); -GL_APICALL void GL_APIENTRY Sb_glUniform2f(GLint location, - GLfloat v0, - GLfloat v1); -GL_APICALL void GL_APIENTRY Sb_glUniform2fv(GLint location, - GLsizei count, - const GLfloat* value); -GL_APICALL void GL_APIENTRY Sb_glUniform2i(GLint location, GLint v0, GLint v1); -GL_APICALL void GL_APIENTRY Sb_glUniform2iv(GLint location, - GLsizei count, - const GLint* value); -GL_APICALL void GL_APIENTRY Sb_glUniform3f(GLint location, - GLfloat v0, - GLfloat v1, - GLfloat v2); -GL_APICALL void GL_APIENTRY Sb_glUniform3fv(GLint location, - GLsizei count, - const GLfloat* value); -GL_APICALL void GL_APIENTRY Sb_glUniform3i(GLint location, - GLint v0, - GLint v1, - GLint v2); -GL_APICALL void GL_APIENTRY Sb_glUniform3iv(GLint location, - GLsizei count, - const GLint* value); -GL_APICALL void GL_APIENTRY -Sb_glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GL_APICALL void GL_APIENTRY Sb_glUniform4fv(GLint location, - GLsizei count, - const GLfloat* value); -GL_APICALL void GL_APIENTRY -Sb_glUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GL_APICALL void GL_APIENTRY Sb_glUniform4iv(GLint location, - GLsizei count, - const GLint* value); -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix2fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value); -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix3fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value); -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix4fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value); -GL_APICALL void GL_APIENTRY Sb_glUseProgram(GLuint program); -GL_APICALL void GL_APIENTRY Sb_glValidateProgram(GLuint program); -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib1f(GLuint index, GLfloat x); -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib1fv(GLuint index, - const GLfloat* v); -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib2f(GLuint index, - GLfloat x, - GLfloat y); -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib2fv(GLuint index, - const GLfloat* v); -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib3f(GLuint index, - GLfloat x, - GLfloat y, - GLfloat z); -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib3fv(GLuint index, - const GLfloat* v); -GL_APICALL void GL_APIENTRY -Sb_glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib4fv(GLuint index, - const GLfloat* v); -GL_APICALL void GL_APIENTRY Sb_glVertexAttribPointer(GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const void* pointer); -GL_APICALL void GL_APIENTRY Sb_glViewport(GLint x, - GLint y, - GLsizei width, - GLsizei height); - -} // extern "C" - -#endif // CHROMECAST_STARBOARD_GRAPHICS_GLES2_STARBOARD_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/graphics/gles2_starboard_dummy.cc chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard_dummy.cc --- chromium-132.0.6834.110/chromecast/starboard/graphics/gles2_starboard_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/graphics/gles2_starboard_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,561 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// A dummy implementation of gles2_starboard.h. This can be used to compile -// without starboard headers. It should never be used in production. -// -// TODO(b/333131992): remove this - -#include "chromecast/starboard/graphics/gles2_starboard.h" - -extern "C" { - -GL_APICALL void GL_APIENTRY Sb_glActiveTexture(GLenum texture) {} - -GL_APICALL void GL_APIENTRY Sb_glAttachShader(GLuint program, GLuint shader) {} - -GL_APICALL void GL_APIENTRY Sb_glBindAttribLocation(GLuint program, - GLuint index, - const GLchar* name) {} - -GL_APICALL void GL_APIENTRY Sb_glBindBuffer(GLenum target, GLuint buffer) {} - -GL_APICALL void GL_APIENTRY Sb_glBindFramebuffer(GLenum target, - GLuint framebuffer) {} - -GL_APICALL void GL_APIENTRY Sb_glBindRenderbuffer(GLenum target, - GLuint renderbuffer) {} - -GL_APICALL void GL_APIENTRY Sb_glBindTexture(GLenum target, GLuint texture) {} - -GL_APICALL void GL_APIENTRY Sb_glBlendColor(GLfloat red, - GLfloat green, - GLfloat blue, - GLfloat alpha) {} - -GL_APICALL void GL_APIENTRY Sb_glBlendEquation(GLenum mode) {} - -GL_APICALL void GL_APIENTRY Sb_glBlendEquationSeparate(GLenum modeRGB, - GLenum modeAlpha) {} - -GL_APICALL void GL_APIENTRY Sb_glBlendFunc(GLenum sfactor, GLenum dfactor) {} - -GL_APICALL void GL_APIENTRY Sb_glBlendFuncSeparate(GLenum sfactorRGB, - GLenum dfactorRGB, - GLenum sfactorAlpha, - GLenum dfactorAlpha) {} - -GL_APICALL void GL_APIENTRY Sb_glBufferData(GLenum target, - GLsizeiptr size, - const void* data, - GLenum usage) {} - -GL_APICALL void GL_APIENTRY Sb_glBufferSubData(GLenum target, - GLintptr offset, - GLsizeiptr size, - const void* data) {} - -GL_APICALL GLenum GL_APIENTRY Sb_glCheckFramebufferStatus(GLenum target) { - return 0; -} - -GL_APICALL void GL_APIENTRY Sb_glClear(GLbitfield mask) {} - -GL_APICALL void GL_APIENTRY Sb_glClearColor(GLfloat red, - GLfloat green, - GLfloat blue, - GLfloat alpha) {} - -GL_APICALL void GL_APIENTRY Sb_glClearDepthf(GLfloat d) {} - -GL_APICALL void GL_APIENTRY Sb_glClearStencil(GLint s) {} - -GL_APICALL void GL_APIENTRY Sb_glColorMask(GLboolean red, - GLboolean green, - GLboolean blue, - GLboolean alpha) {} - -GL_APICALL void GL_APIENTRY Sb_glCompileShader(GLuint shader) {} - -GL_APICALL void GL_APIENTRY Sb_glCompressedTexImage2D(GLenum target, - GLint level, - GLenum internalformat, - GLsizei width, - GLsizei height, - GLint border, - GLsizei imageSize, - const void* data) {} - -GL_APICALL void GL_APIENTRY Sb_glCompressedTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLsizei imageSize, - const void* data) {} - -GL_APICALL void GL_APIENTRY Sb_glCopyTexImage2D(GLenum target, - GLint level, - GLenum internalformat, - GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLint border) {} - -GL_APICALL void GL_APIENTRY Sb_glCopyTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLint x, - GLint y, - GLsizei width, - GLsizei height) {} - -GL_APICALL GLuint GL_APIENTRY Sb_glCreateProgram(void) { - return 0; -} - -GL_APICALL GLuint GL_APIENTRY Sb_glCreateShader(GLenum type) { - return 0; -} - -GL_APICALL void GL_APIENTRY Sb_glCullFace(GLenum mode) {} - -GL_APICALL void GL_APIENTRY Sb_glDeleteBuffers(GLsizei n, - const GLuint* buffers) {} - -GL_APICALL void GL_APIENTRY -Sb_glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers) {} - -GL_APICALL void GL_APIENTRY Sb_glDeleteProgram(GLuint program) {} - -GL_APICALL void GL_APIENTRY -Sb_glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers) {} - -GL_APICALL void GL_APIENTRY Sb_glDeleteShader(GLuint shader) {} - -GL_APICALL void GL_APIENTRY Sb_glDeleteTextures(GLsizei n, - const GLuint* textures) {} - -GL_APICALL void GL_APIENTRY Sb_glDepthFunc(GLenum func) {} - -GL_APICALL void GL_APIENTRY Sb_glDepthMask(GLboolean flag) {} - -GL_APICALL void GL_APIENTRY Sb_glDepthRangef(GLfloat n, GLfloat f) {} - -GL_APICALL void GL_APIENTRY Sb_glDetachShader(GLuint program, GLuint shader) {} - -GL_APICALL void GL_APIENTRY Sb_glDisable(GLenum cap) {} - -GL_APICALL void GL_APIENTRY Sb_glDisableVertexAttribArray(GLuint index) {} - -GL_APICALL void GL_APIENTRY Sb_glDrawArrays(GLenum mode, - GLint first, - GLsizei count) {} - -GL_APICALL void GL_APIENTRY Sb_glDrawElements(GLenum mode, - GLsizei count, - GLenum type, - const void* indices) {} - -GL_APICALL void GL_APIENTRY Sb_glEnable(GLenum cap) {} - -GL_APICALL void GL_APIENTRY Sb_glEnableVertexAttribArray(GLuint index) {} - -GL_APICALL void GL_APIENTRY Sb_glFinish(void) {} - -GL_APICALL void GL_APIENTRY Sb_glFlush(void) {} - -GL_APICALL void GL_APIENTRY -Sb_glFramebufferRenderbuffer(GLenum target, - GLenum attachment, - GLenum renderbuffertarget, - GLuint renderbuffer) {} - -GL_APICALL void GL_APIENTRY Sb_glFramebufferTexture2D(GLenum target, - GLenum attachment, - GLenum textarget, - GLuint texture, - GLint level) {} - -GL_APICALL void GL_APIENTRY Sb_glFrontFace(GLenum mode) {} - -GL_APICALL void GL_APIENTRY Sb_glGenBuffers(GLsizei n, GLuint* buffers) {} - -GL_APICALL void GL_APIENTRY Sb_glGenerateMipmap(GLenum target) {} - -GL_APICALL void GL_APIENTRY Sb_glGenFramebuffers(GLsizei n, - GLuint* framebuffers) {} - -GL_APICALL void GL_APIENTRY Sb_glGenRenderbuffers(GLsizei n, - GLuint* renderbuffers) {} - -GL_APICALL void GL_APIENTRY Sb_glGenTextures(GLsizei n, GLuint* textures) {} - -GL_APICALL void GL_APIENTRY Sb_glGetActiveAttrib(GLuint program, - GLuint index, - GLsizei bufSize, - GLsizei* length, - GLint* size, - GLenum* type, - GLchar* name) {} - -GL_APICALL void GL_APIENTRY Sb_glGetActiveUniform(GLuint program, - GLuint index, - GLsizei bufSize, - GLsizei* length, - GLint* size, - GLenum* type, - GLchar* name) {} - -GL_APICALL void GL_APIENTRY Sb_glGetAttachedShaders(GLuint program, - GLsizei maxCount, - GLsizei* count, - GLuint* shaders) {} - -GL_APICALL GLint GL_APIENTRY Sb_glGetAttribLocation(GLuint program, - const GLchar* name) { - return 0; -} - -GL_APICALL void GL_APIENTRY Sb_glGetBooleanv(GLenum pname, GLboolean* data) {} - -GL_APICALL void GL_APIENTRY Sb_glGetBufferParameteriv(GLenum target, - GLenum pname, - GLint* params) {} - -GL_APICALL GLenum GL_APIENTRY Sb_glGetError(void) { - return 0; -} - -GL_APICALL void GL_APIENTRY Sb_glGetFloatv(GLenum pname, GLfloat* data) {} - -GL_APICALL void GL_APIENTRY -Sb_glGetFramebufferAttachmentParameteriv(GLenum target, - GLenum attachment, - GLenum pname, - GLint* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetIntegerv(GLenum pname, GLint* data) {} - -GL_APICALL void GL_APIENTRY Sb_glGetProgramiv(GLuint program, - GLenum pname, - GLint* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetProgramInfoLog(GLuint program, - GLsizei bufSize, - GLsizei* length, - GLchar* infoLog) {} - -GL_APICALL void GL_APIENTRY Sb_glGetRenderbufferParameteriv(GLenum target, - GLenum pname, - GLint* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetShaderiv(GLuint shader, - GLenum pname, - GLint* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetShaderInfoLog(GLuint shader, - GLsizei bufSize, - GLsizei* length, - GLchar* infoLog) {} - -GL_APICALL void GL_APIENTRY Sb_glGetShaderPrecisionFormat(GLenum shadertype, - GLenum precisiontype, - GLint* range, - GLint* precision) {} - -GL_APICALL void GL_APIENTRY Sb_glGetShaderSource(GLuint shader, - GLsizei bufSize, - GLsizei* length, - GLchar* source) {} - -GL_APICALL const GLubyte* GL_APIENTRY Sb_glGetString(GLenum name) { - return nullptr; -} - -GL_APICALL void GL_APIENTRY Sb_glGetTexParameterfv(GLenum target, - GLenum pname, - GLfloat* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetTexParameteriv(GLenum target, - GLenum pname, - GLint* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetUniformfv(GLuint program, - GLint location, - GLfloat* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetUniformiv(GLuint program, - GLint location, - GLint* params) {} - -GL_APICALL GLint GL_APIENTRY Sb_glGetUniformLocation(GLuint program, - const GLchar* name) { - return 0; -} - -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribfv(GLuint index, - GLenum pname, - GLfloat* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribiv(GLuint index, - GLenum pname, - GLint* params) {} - -GL_APICALL void GL_APIENTRY Sb_glGetVertexAttribPointerv(GLuint index, - GLenum pname, - void** pointer) {} - -GL_APICALL void GL_APIENTRY Sb_glHint(GLenum target, GLenum mode) {} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsBuffer(GLuint buffer) { - return 0; -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsEnabled(GLenum cap) { - return 0; -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsFramebuffer(GLuint framebuffer) { - return 0; -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsProgram(GLuint program) { - return 0; -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsRenderbuffer(GLuint renderbuffer) { - return 0; -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsShader(GLuint shader) { - return 0; -} - -GL_APICALL GLboolean GL_APIENTRY Sb_glIsTexture(GLuint texture) { - return 0; -} - -GL_APICALL void GL_APIENTRY Sb_glLineWidth(GLfloat width) {} - -GL_APICALL void GL_APIENTRY Sb_glLinkProgram(GLuint program) {} - -GL_APICALL void GL_APIENTRY Sb_glPixelStorei(GLenum pname, GLint param) {} - -GL_APICALL void GL_APIENTRY Sb_glPolygonOffset(GLfloat factor, GLfloat units) {} - -GL_APICALL void GL_APIENTRY Sb_glReadPixels(GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - void* pixels) {} - -GL_APICALL void GL_APIENTRY Sb_glReleaseShaderCompiler(void) {} - -GL_APICALL void GL_APIENTRY Sb_glRenderbufferStorage(GLenum target, - GLenum internalformat, - GLsizei width, - GLsizei height) {} - -GL_APICALL void GL_APIENTRY Sb_glSampleCoverage(GLfloat value, - GLboolean invert) {} - -GL_APICALL void GL_APIENTRY Sb_glScissor(GLint x, - GLint y, - GLsizei width, - GLsizei height) {} - -GL_APICALL void GL_APIENTRY Sb_glShaderBinary(GLsizei count, - const GLuint* shaders, - GLenum binaryformat, - const void* binary, - GLsizei length) {} - -GL_APICALL void GL_APIENTRY Sb_glShaderSource(GLuint shader, - GLsizei count, - const GLchar* const* string, - const GLint* length) {} - -GL_APICALL void GL_APIENTRY Sb_glStencilFunc(GLenum func, - GLint ref, - GLuint mask) {} - -GL_APICALL void GL_APIENTRY Sb_glStencilFuncSeparate(GLenum face, - GLenum func, - GLint ref, - GLuint mask) {} - -GL_APICALL void GL_APIENTRY Sb_glStencilMask(GLuint mask) {} - -GL_APICALL void GL_APIENTRY Sb_glStencilMaskSeparate(GLenum face, GLuint mask) { -} - -GL_APICALL void GL_APIENTRY Sb_glStencilOp(GLenum fail, - GLenum zfail, - GLenum zpass) {} - -GL_APICALL void GL_APIENTRY Sb_glStencilOpSeparate(GLenum face, - GLenum sfail, - GLenum dpfail, - GLenum dppass) {} - -GL_APICALL void GL_APIENTRY Sb_glTexImage2D(GLenum target, - GLint level, - GLint internalformat, - GLsizei width, - GLsizei height, - GLint border, - GLenum format, - GLenum type, - const void* pixels) {} - -GL_APICALL void GL_APIENTRY Sb_glTexParameterf(GLenum target, - GLenum pname, - GLfloat param) {} - -GL_APICALL void GL_APIENTRY Sb_glTexParameterfv(GLenum target, - GLenum pname, - const GLfloat* params) {} - -GL_APICALL void GL_APIENTRY Sb_glTexParameteri(GLenum target, - GLenum pname, - GLint param) {} - -GL_APICALL void GL_APIENTRY Sb_glTexParameteriv(GLenum target, - GLenum pname, - const GLint* params) {} - -GL_APICALL void GL_APIENTRY Sb_glTexSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - const void* pixels) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform1f(GLint location, GLfloat v0) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform1fv(GLint location, - GLsizei count, - const GLfloat* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform1i(GLint location, GLint v0) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform1iv(GLint location, - GLsizei count, - const GLint* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform2f(GLint location, - GLfloat v0, - GLfloat v1) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform2fv(GLint location, - GLsizei count, - const GLfloat* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform2i(GLint location, GLint v0, GLint v1) { -} - -GL_APICALL void GL_APIENTRY Sb_glUniform2iv(GLint location, - GLsizei count, - const GLint* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform3f(GLint location, - GLfloat v0, - GLfloat v1, - GLfloat v2) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform3fv(GLint location, - GLsizei count, - const GLfloat* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform3i(GLint location, - GLint v0, - GLint v1, - GLint v2) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform3iv(GLint location, - GLsizei count, - const GLint* value) {} - -GL_APICALL void GL_APIENTRY -Sb_glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { -} - -GL_APICALL void GL_APIENTRY Sb_glUniform4fv(GLint location, - GLsizei count, - const GLfloat* value) {} - -GL_APICALL void GL_APIENTRY -Sb_glUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) {} - -GL_APICALL void GL_APIENTRY Sb_glUniform4iv(GLint location, - GLsizei count, - const GLint* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix2fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix3fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUniformMatrix4fv(GLint location, - GLsizei count, - GLboolean transpose, - const GLfloat* value) {} - -GL_APICALL void GL_APIENTRY Sb_glUseProgram(GLuint program) {} - -GL_APICALL void GL_APIENTRY Sb_glValidateProgram(GLuint program) {} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib1f(GLuint index, GLfloat x) {} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib1fv(GLuint index, - const GLfloat* v) {} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib2f(GLuint index, - GLfloat x, - GLfloat y) {} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib2fv(GLuint index, - const GLfloat* v) {} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib3f(GLuint index, - GLfloat x, - GLfloat y, - GLfloat z) {} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib3fv(GLuint index, - const GLfloat* v) {} - -GL_APICALL void GL_APIENTRY -Sb_glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) {} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttrib4fv(GLuint index, - const GLfloat* v) {} - -GL_APICALL void GL_APIENTRY Sb_glVertexAttribPointer(GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const void* pointer) {} - -GL_APICALL void GL_APIENTRY Sb_glViewport(GLint x, - GLint y, - GLsizei width, - GLsizei height) {} -} diff -Nru chromium-132.0.6834.110/chromecast/starboard/graphics/graphics_properties_default.cc chromium-132.0.6834.159/chromecast/starboard/graphics/graphics_properties_default.cc --- chromium-132.0.6834.110/chromecast/starboard/graphics/graphics_properties_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/graphics/graphics_properties_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/public/graphics_properties_shlib.h" - -namespace chromecast { - -bool GraphicsPropertiesShlib::IsSupported( - Resolution resolution, - const std::vector& argv) { - switch (resolution) { - case Resolution::k1080p: - return true; - case Resolution::kUHDTV: - return false; - default: - return false; - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_decryptor_cast.cc chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast.cc --- chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_decryptor_cast.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,864 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/cdm/starboard_decryptor_cast.h" - -#include - -#include -#include -#include - -#include "base/check_op.h" -#include "base/functional/bind.h" -#include "base/hash/hash.h" -#include "base/notreached.h" -#include "base/strings/strcat.h" -#include "base/strings/string_number_conversions.h" -#include "base/time/time.h" -#include "chromecast/media/base/decrypt_context_impl.h" -#include "chromecast/starboard/media/cdm/starboard_drm_key_tracker.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "google_apis/google_api_keys.h" -#include "media/base/cdm_callback_promise.h" -#include "media/base/eme_constants.h" - -namespace chromecast { -namespace media { - -namespace { - -// The API key must be added. -constexpr char kProvisionServerUrlMinusKey[] = - "https://www.googleapis.com/certificateprovisioning/v1/devicecertificates/" - "create?key="; - -// A decrypt context that fakes decryption, so that the real decryption can be -// done in Starboard. -class DummyDecryptContext : public DecryptContextImpl { - public: - DummyDecryptContext() - : DecryptContextImpl(CastKeySystem::KEY_SYSTEM_WIDEVINE) {} - - ~DummyDecryptContext() override = default; - - // DecryptContextImpl implementation: - void DecryptAsync(CastDecoderBuffer* buffer, - uint8_t* output_or_handle, - size_t data_offset, - bool clear_output, - DecryptCB decrypt_cb) override { - LOG(FATAL) << "Decryption in cast is not allowed for the starboard " - "pipeline (decryption must be done in starboard itself, via " - "SbPlayer and SbDrmSystem)."; - } - - DecryptContextImpl::OutputType GetOutputType() const override { - // This should force decryption to be done in the MediaPipelineBackend (see - // CdmDecryptor::Decrypt for the relevant logic that reads this value). - return OutputType::kSecure; - } -}; - -std::string DrmKeyStatusToString(StarboardDrmKeyStatus status) { - switch (status) { - case kStarboardDrmKeyStatusUsable: - return "kStarboardDrmKeyStatusUsable"; - case kStarboardDrmKeyStatusExpired: - return "kStarboardDrmKeyStatusExpired"; - case kStarboardDrmKeyStatusReleased: - return "kStarboardDrmKeyStatusReleased"; - case kStarboardDrmKeyStatusRestricted: - return "kStarboardDrmKeyStatusRestricted"; - case kStarboardDrmKeyStatusDownscaled: - return "kStarboardDrmKeyStatusDownscaled"; - case kStarboardDrmKeyStatusPending: - return "kStarboardDrmKeyStatusPending"; - case kStarboardDrmKeyStatusError: - return "kStarboardDrmKeyStatusError"; - } -} - -// Converts a starboard DRM status to a CdmPromise exception. This must not be -// called for a success status. Defaults to NotSupportedError. -::media::CdmPromise::Exception StarboardDrmErrorStatusToCdmException( - StarboardDrmStatus status) { - switch (status) { - case kStarboardDrmStatusSuccess: - LOG(FATAL) << "Success status cannot be converted to a CDM Exception"; - case kStarboardDrmStatusTypeError: - return ::media::CdmPromise::Exception::TYPE_ERROR; - case kStarboardDrmStatusNotSupportedError: - return ::media::CdmPromise::Exception::NOT_SUPPORTED_ERROR; - case kStarboardDrmStatusInvalidStateError: - return ::media::CdmPromise::Exception::INVALID_STATE_ERROR; - case kStarboardDrmStatusQuotaExceededError: - return ::media::CdmPromise::Exception::QUOTA_EXCEEDED_ERROR; - case kStarboardDrmStatusUnknownError: - default: - return ::media::CdmPromise::Exception::NOT_SUPPORTED_ERROR; - } -} - -::media::CdmKeyInformation::KeyStatus ToMediaKeyStatus( - StarboardDrmKeyStatus status) { - switch (status) { - case kStarboardDrmKeyStatusUsable: - return ::media::CdmKeyInformation::KeyStatus::USABLE; - case kStarboardDrmKeyStatusExpired: - return ::media::CdmKeyInformation::KeyStatus::EXPIRED; - case kStarboardDrmKeyStatusReleased: - return ::media::CdmKeyInformation::KeyStatus::RELEASED; - case kStarboardDrmKeyStatusRestricted: - return ::media::CdmKeyInformation::KeyStatus::OUTPUT_RESTRICTED; - case kStarboardDrmKeyStatusDownscaled: - return ::media::CdmKeyInformation::KeyStatus::OUTPUT_DOWNSCALED; - case kStarboardDrmKeyStatusPending: - return ::media::CdmKeyInformation::KeyStatus::KEY_STATUS_PENDING; - case kStarboardDrmKeyStatusError: - return ::media::CdmKeyInformation::KeyStatus::INTERNAL_ERROR; - } -} - -::media::CdmMessageType ToCdmMessageType(StarboardDrmSessionRequestType type) { - switch (type) { - case kStarboardDrmSessionRequestTypeLicenseRequest: - return ::media::CdmMessageType::LICENSE_REQUEST; - case kStarboardDrmSessionRequestTypeLicenseRenewal: - return ::media::CdmMessageType::LICENSE_RENEWAL; - case kStarboardDrmSessionRequestTypeLicenseRelease: - return ::media::CdmMessageType::LICENSE_RELEASE; - case kStarboardDrmSessionRequestTypeIndividualizationRequest: - return ::media::CdmMessageType::INDIVIDUALIZATION_REQUEST; - } -} - -} // namespace - -StarboardDecryptorCast::StarboardDecryptorCast( - ::media::CreateFetcherCB create_provision_fetcher_cb, - MediaResourceTracker* media_resource_tracker) - : CastCdm(media_resource_tracker), - create_provision_fetcher_cb_(std::move(create_provision_fetcher_cb)), - callback_handler_{ - this, - &CallOnSessionUpdateRequest, - &CallOnSessionUpdated, - &CallOnKeyStatusesChanged, - &CallOnCertificateUpdated, - &CallOnSessionClosed, - }, - starboard_(GetStarboardApiWrapper()) { - CHECK(base::SequencedTaskRunner::HasCurrentDefault()); - task_runner_ = base::SequencedTaskRunner::GetCurrentDefault(); -} - -void StarboardDecryptorCast::CreateSessionAndGenerateRequest( - ::media::CdmSessionType session_type, - ::media::EmeInitDataType init_data_type, - const std::vector& init_data, - std::unique_ptr<::media::NewSessionCdmPromise> promise) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - LOG(INFO) << "StarboardDecryptorCast::CreateSessionAndGenerateRequest"; - - // Persistent session types are not supported, since SbDrmSystem does not - // support load/remove. - if (session_type == ::media::CdmSessionType::kPersistentLicense) { - promise->reject(::media::CdmPromise::Exception::NOT_SUPPORTED_ERROR, 0, - "Persistent licenses are not supported by starboard."); - return; - } - - CHECK_EQ(session_type, ::media::CdmSessionType::kTemporary) - << "Unsupported session type: " << static_cast(session_type); - - queued_session_requests_.push( - {base::BindOnce( - &StarboardDecryptorCast::HandleCreateSessionAndGenerateRequest, - weak_factory_.GetWeakPtr(), session_type, init_data_type, init_data), - std::move(promise)}); - - ProcessQueuedSessionRequests(); -} - -void StarboardDecryptorCast::HandleCreateSessionAndGenerateRequest( - ::media::CdmSessionType session_type, - ::media::EmeInitDataType init_data_type, - const std::vector& init_data, - std::unique_ptr<::media::NewSessionCdmPromise> promise) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(!pending_session_setup_); - DCHECK(drm_system_); - - pending_session_setup_ = true; - std::string init_type; - switch (init_data_type) { - case ::media::EmeInitDataType::WEBM: - init_type = "webm"; - break; - case ::media::EmeInitDataType::CENC: - init_type = "cenc"; - break; - case ::media::EmeInitDataType::KEYIDS: - init_type = "keyids"; - break; - default: - // Covers the case of the UNKOWN type, or any unrecognized types. - promise->reject( - ::media::CdmPromise::Exception::NOT_SUPPORTED_ERROR, 0, - "Unsupported init_data_type: " + - base::NumberToString(static_cast(init_data_type))); - return; - } - - const int ticket = current_ticket_++; - ticket_to_new_session_promise_[ticket] = std::move(promise); - starboard_->DrmGenerateSessionUpdateRequest( - drm_system_, ticket, init_type.c_str(), init_data.data(), - init_data.size()); -} - -void StarboardDecryptorCast::LoadSession( - ::media::CdmSessionType session_type, - const std::string& session_id, - std::unique_ptr<::media::NewSessionCdmPromise> promise) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - LOG(ERROR) << "StarboardDecryptorCast::LoadSession (not supported)"; - promise->reject(::media::CdmPromise::Exception::NOT_SUPPORTED_ERROR, 0, - "LoadSession is not supported by starboard."); -} - -void StarboardDecryptorCast::UpdateSession( - const std::string& web_session_id, - const std::vector& response, - std::unique_ptr<::media::SimpleCdmPromise> promise) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(drm_system_); - - LOG(INFO) << "StarboardDecryptorCast::UpdateSession, web session id = " - << web_session_id; - - const int ticket = current_ticket_++; - ticket_to_simple_cdm_promise_[ticket] = std::move(promise); - // This will eventually call OnSessionUpdated. - starboard_->DrmUpdateSession(drm_system_, ticket, response.data(), - response.size(), web_session_id.c_str(), - web_session_id.size()); -} - -void StarboardDecryptorCast::CloseSession( - const std::string& web_session_id, - std::unique_ptr<::media::SimpleCdmPromise> promise) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(drm_system_); - - LOG(INFO) << "StarboardDecryptorCast::CloseSession, web session id = " - << web_session_id; - - std::vector>& promises = - session_id_to_simple_cdm_promises_[web_session_id]; - promises.push_back(std::move(promise)); - - if (promises.size() == 1) { - // This is the first request to close the session; mark the session as - // removed and call starboard to perform the close logic - StarboardDrmKeyTracker::GetInstance().RemoveKeysForSession(web_session_id); - starboard_->DrmCloseSession(drm_system_, web_session_id.c_str(), - web_session_id.size()); - } else { - LOG(INFO) << "Session is already closing."; - } -} - -void StarboardDecryptorCast::RemoveSession( - const std::string& session_id, - std::unique_ptr<::media::SimpleCdmPromise> promise) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(drm_system_); - - LOG(INFO) - << "StarboardDecryptorCast::RemoveSession (implemented as CloseSession), " - "session id = " - << session_id; - CloseSession(session_id, std::move(promise)); -} - -void StarboardDecryptorCast::SetServerCertificate( - const std::vector& certificate_data, - std::unique_ptr<::media::SimpleCdmPromise> promise) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(drm_system_); - - LOG(INFO) << "StarboardDecryptorCast::SetServerCertificate"; - - if (!server_certificate_updatable_) { - LOG(ERROR) << "Tried to update a server certificate for a DRM system that " - "does not support it."; - promise->reject(::media::CdmPromise::Exception::NOT_SUPPORTED_ERROR, 0, - "DRM system does not support certificate update"); - return; - } - - const int ticket = current_ticket_++; - ticket_to_simple_cdm_promise_[ticket] = std::move(promise); - starboard_->DrmUpdateServerCertificate( - drm_system_, ticket, certificate_data.data(), certificate_data.size()); -} - -std::unique_ptr StarboardDecryptorCast::GetDecryptContext( - const std::string& key_id, - EncryptionScheme encryption_scheme) const { - return std::make_unique(); -} - -void StarboardDecryptorCast::SetKeyStatus(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) { - NOTIMPLEMENTED(); -} - -void StarboardDecryptorCast::SetVideoResolution(int width, int height) { - // This would normally be used to support per resolution keys, but is not - // supported via any starboard API. - LOG(ERROR) << "Called StarboardDecryptorCast::SetVideoResolution(" << width - << ", " << height << "). This is not supported by starboard."; -} - -StarboardDecryptorCast::~StarboardDecryptorCast() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - if (drm_system_) { - LOG(INFO) << "Destroying DRM system with address " << drm_system_; - // Once this call returns, all DRM-related callbacks from Starboard are - // guaranteed to be finished. - starboard_->DrmDestroySystem(drm_system_); - - for (const std::string& session_id : session_ids_) { - StarboardDrmKeyTracker::GetInstance().RemoveKeysForSession(session_id); - } - } - - RejectPendingPromises(); -} - -void StarboardDecryptorCast::InitializeInternal() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - // This just calls EnsureStarboardInitialized in production, but in tests the - // behavior can be overridden to prevent relying on a real Starboard - // implementation. - starboard_->EnsureInitialized(); - - drm_system_ = starboard_->CreateDrmSystem( - /*key_system=*/"com.widevine.alpha", - /*callback_handler=*/&callback_handler_); - CHECK(drm_system_) << "Failed to create an SbDrmSystem"; - LOG(INFO) << "Created DRM system with address " << drm_system_; - - server_certificate_updatable_ = - starboard_->DrmIsServerCertificateUpdatable(drm_system_); -} - -void StarboardDecryptorCast::RejectPendingPromises() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - while (!queued_session_requests_.empty()) { - SessionRequest session_request = - std::move(queued_session_requests_.front()); - queued_session_requests_.pop(); - if (session_request.second) { - session_request.second->reject( - ::media::CdmPromise::Exception::INVALID_STATE_ERROR, 0, - "GenerateKeyRequest not completed by teardown"); - } - } -} - -void StarboardDecryptorCast::SendProvisionRequest( - int ticket, - const std::string& session_id, - const std::vector& content) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - if (!provision_fetcher_) { - provision_fetcher_ = create_provision_fetcher_cb_.Run(); - } - LOG(INFO) << "Sending provision request"; - - const std::string api_key = google_apis::GetAPIKey(); - if (api_key.empty()) { - LOG(ERROR) - << "Could not retrieve Google API key. Unable to provision the device."; - return; - } - provision_fetcher_->Retrieve( - GURL(base::StrCat({kProvisionServerUrlMinusKey, api_key})), - std::string(reinterpret_cast(content.data()), - content.size()), - base::BindOnce(&StarboardDecryptorCast::OnProvisionResponse, - weak_factory_.GetWeakPtr(), ticket, session_id)); -} - -void StarboardDecryptorCast::ProcessQueuedSessionRequests() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - if (queued_session_requests_.empty()) { - return; - } - - if (pending_session_setup_) { - LOG(INFO) << "Queueing session request because another one is in flight"; - return; - } - - SessionRequest session_request = std::move(queued_session_requests_.front()); - queued_session_requests_.pop(); - // This runs HandleCreateSessionAndGenerateRequest(). - std::move(session_request.first).Run(std::move(session_request.second)); -} - -void StarboardDecryptorCast::OnSessionUpdateRequest( - void* drm_system, - int ticket, - StarboardDrmStatus status, - StarboardDrmSessionRequestType type, - std::optional error_message, - std::optional session_id, - std::vector content) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - pending_session_setup_ = false; - - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&StarboardDecryptorCast::ProcessQueuedSessionRequests, - weak_factory_.GetWeakPtr())); - - if (status == kStarboardDrmStatusSuccess && session_id && - type == kStarboardDrmSessionRequestTypeIndividualizationRequest) { - // Provision requests need to be sent regardless of whether the ticket is - // valid, so we send this before checking the ticket map. - SendProvisionRequest(ticket, *session_id, content); - return; - } - - auto it = ticket_to_new_session_promise_.find(ticket); - - if (it == ticket_to_new_session_promise_.end()) { - LOG(WARNING) << "Bad ticket for DRM session create request: " << ticket; - if (session_id) { - CHECK_NE(type, kStarboardDrmSessionRequestTypeIndividualizationRequest); - OnSessionMessage(*session_id, content, ToCdmMessageType(type)); - } - return; - } - - // Regardless of success/failure, the promise at it->second must be - // resolved/rejected and then deleted. - if (status != kStarboardDrmStatusSuccess) { - LOG(ERROR) << "Call to StarboardDrmGenerateSessionUpdateRequest for ticket " - << it->first << " failed with error: " - << (error_message ? *error_message : "(null)"); - it->second->reject(StarboardDrmErrorStatusToCdmException(status), 0, - error_message ? *error_message : ""); - } else if (!session_id) { - LOG(ERROR) << "Starboard returned a null session_id on success for ticket " - << it->first; - it->second->reject(::media::CdmPromise::Exception::INVALID_STATE_ERROR, 0, - ""); - } else { - // Success case. - LOG(INFO) << "Created session id " << *session_id << " for ticket " - << it->first; - it->second->resolve(*session_id); - } - ticket_to_new_session_promise_.erase(it); - if (status == kStarboardDrmStatusSuccess && session_id) { - // This function -- defined by the parent class -- should ultimately send - // the message to the JS app. That will eventually trigger a license - // request, followed by an update session message being sent to this class. - // Note that, per the documentation of - // ContentDecryptionModule::CreateSessionAndGenerateRequest, this must be - // called AFTER the promise has been resolved. - OnSessionMessage(*session_id, content, ToCdmMessageType(type)); - } -} - -void StarboardDecryptorCast::OnProvisionResponse(int ticket, - const std::string& session_id, - bool success, - const std::string& response) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - if (!success) { - LOG(ERROR) << "Provisioning failed."; - auto it = ticket_to_new_session_promise_.find(ticket); - if (it == ticket_to_new_session_promise_.end()) { - return; - } - it->second->reject(::media::CdmPromise::Exception::INVALID_STATE_ERROR, - /*system_code=*/0, "Widevine provisioning failed"); - return; - } - - LOG(INFO) << "Provisioning succeeded. Updating session in starboard."; - std::vector response_vec(response.size()); - memcpy(response_vec.data(), response.c_str(), response.size()); - - // This will be called if we successfully update the session. - auto success_cb = - [](base::flat_map>* - promise_map, - int ticket, std::string session_id) { - CHECK(promise_map); - LOG(INFO) << "UpdateSession for provision response succeeded"; - auto it = promise_map->find(ticket); - if (it == promise_map->end()) { - return; - } - it->second->resolve(session_id); - promise_map->erase(it); - }; - - // This will be called if the session cannot be updated. The first two args - // are bound here. - auto failure_cb = - [](base::flat_map>* - promise_map, - int ticket, ::media::CdmPromise::Exception exception_code, - uint32_t system_code, const std::string& error_message) { - CHECK(promise_map); - LOG(ERROR) << "UpdateSession for provision response failed with " - "exception " - << static_cast(exception_code) << ", system code " - << system_code << ", and error message " << error_message; - auto it = promise_map->find(ticket); - if (it == promise_map->end()) { - return; - } - it->second->reject(exception_code, system_code, error_message); - promise_map->erase(it); - }; - - UpdateSession( - session_id, response_vec, - std::make_unique<::media::CdmCallbackPromise<>>( - /*resolve_cb=*/base::BindOnce( - success_cb, &ticket_to_new_session_promise_, ticket, session_id), - /*reject_cb=*/base::BindOnce( - failure_cb, &ticket_to_new_session_promise_, ticket))); -} - -// Called by starboard (via CallOnSessionUpdated) once a session has been -// updated. -void StarboardDecryptorCast::OnSessionUpdated( - void* drm_system, - int ticket, - StarboardDrmStatus status, - std::optional error_message, - std::optional session_id) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - LOG(INFO) << "StarboardDecryptorCast::OnSessionUpdated, ticket: " << ticket - << ", status: " << status - << ", session id: " << (session_id ? *session_id : "nullopt") - << ", error: " << (error_message ? *error_message : "none"); - auto it = ticket_to_simple_cdm_promise_.find(ticket); - - if (it == ticket_to_simple_cdm_promise_.end()) { - LOG(WARNING) << "Bad ticket for DRM session update request: " << ticket; - return; - } - - // Regardless of success/failure, the promise at it->second must be - // resolved/rejected and then deleted. - if (status != kStarboardDrmStatusSuccess) { - LOG(ERROR) << "Call to StarboardDrmUpdateSession for ticket " << it->first - << " failed with error: " - << (error_message ? *error_message : "(null)"); - it->second->reject(StarboardDrmErrorStatusToCdmException(status), 0, - error_message ? *error_message : ""); - } else if (!session_id) { - LOG(ERROR) << "Starboard returned a null session_id on success for ticket " - << it->first; - it->second->reject(::media::CdmPromise::Exception::INVALID_STATE_ERROR, 0, - ""); - } else { - // Success case. - LOG(INFO) << "Updated session id " << *session_id << " for ticket " - << it->first; - it->second->resolve(); - } - ticket_to_simple_cdm_promise_.erase(it); -} - -// Called by starboard (via CallOnKeyStatusesChanged) when the status of keys -// change. -void StarboardDecryptorCast::OnKeyStatusesChanged( - void* drm_system, - std::string session_id, - std::vector> - key_ids_and_statuses) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - LOG(INFO) << "StarboardDecryptorCast::OnKeyStatusChanged for " - << key_ids_and_statuses.size() << " keys"; - ::media::CdmKeysInfo keys_info; - bool usable_keys_exist = false; - for (const auto& key_id_and_status : key_ids_and_statuses) { - const StarboardDrmKeyId& key_id = key_id_and_status.first; - const StarboardDrmKeyStatus status = key_id_and_status.second; - - const std::string key_name( - reinterpret_cast(&key_id.identifier), - key_id.identifier_size); - CHECK_GE(key_id.identifier_size, 0); - const size_t key_hash = base::FastHash(base::make_span( - key_id.identifier, static_cast(key_id.identifier_size))); - LOG(INFO) << "DRM key (hash) " << key_hash << " changed status to " - << DrmKeyStatusToString(status) << " for DRM system with address " - << drm_system << ", for session " << session_id; - - auto key_info = std::make_unique<::media::CdmKeyInformation>(); - key_info->key_id.assign(key_id.identifier, - key_id.identifier + key_id.identifier_size); - key_info->status = ToMediaKeyStatus(status); - keys_info.push_back(std::move(key_info)); - - usable_keys_exist = - usable_keys_exist || (status == kStarboardDrmKeyStatusUsable); - - switch (status) { - case kStarboardDrmKeyStatusUsable: - case kStarboardDrmKeyStatusRestricted: - case kStarboardDrmKeyStatusDownscaled: - // As long as the key is available to the DRM system in some way, we - // should treat the key as available so that the MediaPipelineBackend - // can push buffers for the given key. - StarboardDrmKeyTracker::GetInstance().AddKey(key_name, session_id); - break; - case kStarboardDrmKeyStatusPending: - // The key status will be updated later; do nothing for now. - break; - case kStarboardDrmKeyStatusExpired: - case kStarboardDrmKeyStatusReleased: - case kStarboardDrmKeyStatusError: - // The key is no longer usable. - StarboardDrmKeyTracker::GetInstance().RemoveKey(key_name, session_id); - break; - } - } - - if (usable_keys_exist) { - // At least one key is available for the session, so we need to track the - // session to clean it up on destruction. - session_ids_.insert(session_id); - } - - OnSessionKeysChange(session_id, usable_keys_exist, std::move(keys_info)); -} - -// Called by starboard (via CallOnCertificateUpdated) when a certificate has -// been updated. -void StarboardDecryptorCast::OnCertificateUpdated( - void* drm_system, - int ticket, - StarboardDrmStatus status, - std::optional error_message) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - auto it = ticket_to_simple_cdm_promise_.find(ticket); - - if (it == ticket_to_simple_cdm_promise_.end()) { - LOG(WARNING) << "Bad ticket for DRM certificate update request: " << ticket; - return; - } - - // Regardless of success/failure, the promise at it->second must be - // resolved/rejected and then deleted. - if (status != kStarboardDrmStatusSuccess) { - LOG(ERROR) << "Call to StarboardDrmUpdateServerCertificate for ticket " - << it->first << " failed with error: " - << (error_message ? *error_message : "(null)"); - it->second->reject(StarboardDrmErrorStatusToCdmException(status), 0, - error_message ? *error_message : ""); - } else { - // Success case. - LOG(INFO) << "Updated DRM certificate for ticket " << it->first; - it->second->resolve(); - } - ticket_to_simple_cdm_promise_.erase(it); -} - -// Called by starboard (via CallOnSessionClosed) when a session has closed. -void StarboardDecryptorCast::OnSessionClosed(void* drm_system, - std::string session_id) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - LOG(INFO) << "StarboardDecryptorCast::OnSessionClosed, session_id: " - << session_id; - auto it = session_id_to_simple_cdm_promises_.find(session_id); - if (it == session_id_to_simple_cdm_promises_.end()) { - LOG(ERROR) - << "Bad session ID passed to StarboardDrmCloseSession's callback: " - << session_id; - return; - } - - for (std::unique_ptr<::media::SimpleCdmPromise>& promise : it->second) { - promise->resolve(); - } - session_id_to_simple_cdm_promises_.erase(it); - - CastCdm::OnSessionClosed(session_id, ::media::CdmSessionClosedReason::kClose); -} - -void StarboardDecryptorCast::CallOnSessionUpdateRequest( - void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - StarboardDrmSessionRequestType type, - const char* error_message, - const void* session_id, - int session_id_size, - const void* content, - int content_size, - const char* url) { - if (url && strcmp(url, "") != 0) { - LOG(ERROR) - << "Non-empty URL was specified in SessionUpdateRequest callback: " - << url; - } - std::optional error_message_copy; - if (error_message) { - error_message_copy.emplace(error_message); - } - - std::optional session_id_copy; - std::vector content_copy; - if (session_id) { - session_id_copy.emplace(reinterpret_cast(session_id), - session_id_size); - content_copy.resize(content_size); - memcpy(content_copy.data(), content, content_size); - } - auto* decryptor = reinterpret_cast(context); - decryptor->task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&StarboardDecryptorCast::OnSessionUpdateRequest, - decryptor->weak_factory_.GetWeakPtr(), drm_system, ticket, - status, type, std::move(error_message_copy), - std::move(session_id_copy), std::move(content_copy))); -} - -void StarboardDecryptorCast::CallOnSessionUpdated(void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - const char* error_message, - const void* session_id, - int session_id_size) { - std::optional error_message_copy; - if (error_message) { - error_message_copy.emplace(error_message); - } - - std::optional session_id_copy; - if (session_id) { - session_id_copy.emplace(reinterpret_cast(session_id), - session_id_size); - } - auto* decryptor = reinterpret_cast(context); - decryptor->task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&StarboardDecryptorCast::OnSessionUpdated, - decryptor->weak_factory_.GetWeakPtr(), drm_system, ticket, - status, std::move(error_message_copy), - std::move(session_id_copy))); -} - -void StarboardDecryptorCast::CallOnKeyStatusesChanged( - void* drm_system, - void* context, - const void* session_id, - int session_id_size, - int number_of_keys, - const StarboardDrmKeyId* key_ids, - const StarboardDrmKeyStatus* key_statuses) { - if (!session_id) { - LOG(ERROR) << "StarboardDecryptorCast::CallOnKeyStatusesChanged was called " - "by starboard with a null session_id. Ignoring the call."; - return; - } - std::string session_id_copy(reinterpret_cast(session_id), - session_id_size); - if (number_of_keys <= 0) { - LOG(ERROR) << "Invalid number of keys (" << number_of_keys - << ") for session " << session_id_copy; - return; - } - std::vector> - key_ids_and_statuses; - for (int i = 0; i < number_of_keys; ++i) { - key_ids_and_statuses.push_back({key_ids[i], key_statuses[i]}); - } - - auto* decryptor = reinterpret_cast(context); - decryptor->task_runner_->PostTask( - FROM_HERE, base::BindOnce(&StarboardDecryptorCast::OnKeyStatusesChanged, - decryptor->weak_factory_.GetWeakPtr(), - drm_system, std::move(session_id_copy), - std::move(key_ids_and_statuses))); -} - -void StarboardDecryptorCast::CallOnCertificateUpdated( - void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - const char* error_message) { - std::optional error_message_copy; - if (error_message) { - error_message_copy.emplace(error_message); - } - - auto* decryptor = reinterpret_cast(context); - decryptor->task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&StarboardDecryptorCast::OnCertificateUpdated, - decryptor->weak_factory_.GetWeakPtr(), drm_system, ticket, - status, std::move(error_message_copy))); -} - -void StarboardDecryptorCast::CallOnSessionClosed(void* drm_system, - void* context, - const void* session_id, - int session_id_size) { - if (!session_id) { - LOG(ERROR) - << "Null session_id was passed to StarboardDrmCloseSession's callback"; - return; - } - - std::string session_id_copy(reinterpret_cast(session_id), - session_id_size); - - auto* decryptor = reinterpret_cast(context); - decryptor->task_runner_->PostTask( - FROM_HERE, base::BindOnce(&StarboardDecryptorCast::OnSessionClosed, - decryptor->weak_factory_.GetWeakPtr(), - drm_system, std::move(session_id_copy))); -} - -void StarboardDecryptorCast::SetStarboardApiWrapperForTest( - std::unique_ptr starboard) { - LOG(INFO) << "Replacing the StarboardApiWrapper used by " - "StarboardDecryptorCast. This should only happen in tests."; - starboard_ = std::move(starboard); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_decryptor_cast.h chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast.h --- chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_decryptor_cast.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,246 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_CDM_STARBOARD_DECRYPTOR_CAST_H_ -#define CHROMECAST_STARBOARD_MEDIA_CDM_STARBOARD_DECRYPTOR_CAST_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include "base/containers/flat_map.h" -#include "base/containers/flat_set.h" -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "base/threading/thread.h" -#include "base/threading/thread_checker.h" -#include "chromecast/media/cdm/cast_cdm.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "media/base/cdm_promise.h" -#include "media/base/provision_fetcher.h" - -namespace chromecast { -namespace media { - -// An implementation of CastCdm that forwards calls to an underlying Starboard -// SbDrmSystem. Currently only supports widevine (the key system passed to -// starboard is hardcoded, as is the provisioning server URL). -// -// The constructor, destructor, and all functions (except the Call* callbacks -// stored in callback_handler_) must be called on the same sequence. -class StarboardDecryptorCast : public CastCdm { - public: - explicit StarboardDecryptorCast( - ::media::CreateFetcherCB create_provision_fetcher_cb, - MediaResourceTracker* media_resource_tracker); - - // Disallow copy and assign. - StarboardDecryptorCast(const StarboardDecryptorCast&) = delete; - StarboardDecryptorCast& operator=(const StarboardDecryptorCast&) = delete; - - // For testing purposes, `starboard` will be used to call starboard functions. - void SetStarboardApiWrapperForTest( - std::unique_ptr starboard); - - // ::media::ContentDecryptionModule implementation: - void CreateSessionAndGenerateRequest( - ::media::CdmSessionType session_type, - ::media::EmeInitDataType init_data_type, - const std::vector& init_data, - std::unique_ptr<::media::NewSessionCdmPromise> promise) override; - void LoadSession( - ::media::CdmSessionType session_type, - const std::string& session_id, - std::unique_ptr<::media::NewSessionCdmPromise> promise) override; - void UpdateSession( - const std::string& web_session_id, - const std::vector& response, - std::unique_ptr<::media::SimpleCdmPromise> promise) override; - void CloseSession( - const std::string& web_session_id, - std::unique_ptr<::media::SimpleCdmPromise> promise) override; - void RemoveSession( - const std::string& session_id, - std::unique_ptr<::media::SimpleCdmPromise> promise) override; - void SetServerCertificate( - const std::vector& certificate_data, - std::unique_ptr<::media::SimpleCdmPromise> promise) override; - - // CastCdm implementation: - std::unique_ptr GetDecryptContext( - const std::string& key_id, - EncryptionScheme encryption_scheme) const override; - void SetKeyStatus(const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code) override; - void SetVideoResolution(int width, int height) override; - - private: - using SessionRequest = std::pair< - base::OnceCallback)>, - std::unique_ptr<::media::NewSessionCdmPromise>>; - - ~StarboardDecryptorCast() override; - - // CastCdm implementation: - void InitializeInternal() override; - - // Sends the actual request to create the session. - void HandleCreateSessionAndGenerateRequest( - ::media::CdmSessionType session_type, - ::media::EmeInitDataType init_data_type, - const std::vector& init_data, - std::unique_ptr<::media::NewSessionCdmPromise> promise); - - // Rejects all promises in queued_session_requests_. - void RejectPendingPromises(); - - // Processes any pending requests to create sessions. - void ProcessQueuedSessionRequests(); - - // Sends a provision request to the Widevine licensing server. This is used to - // create cert.bin in starboard. Note that -- for the gLinux implementation of - // starboard, at least -- cert.bin is not an actual file. It's a - // logical/conceptual file, and its stored in the cache at - // ~/.cache/cobalt/wvcdm.dat. - void SendProvisionRequest(int ticket, - const std::string& session_id, - const std::vector& content); - - // Called by starboard (via CallOnSessionUpdateRequest) once a new session has - // been created. - void OnSessionUpdateRequest(void* drm_system, - int ticket, - StarboardDrmStatus status, - StarboardDrmSessionRequestType type, - std::optional error_message, - std::optional session_id, - std::vector content); - - // Called by starboard (via CallOnSessionUpdated) once a session has been - // updated. - void OnSessionUpdated(void* drm_system, - int ticket, - StarboardDrmStatus status, - std::optional error_message, - std::optional session_id); - - // Called by starboard (via CallOnKeyStatusesChanged) when the status of keys - // change. - void OnKeyStatusesChanged( - void* drm_system, - std::string session_id, - std::vector> - key_ids_and_statuses); - - // Called by starboard (via CallOnCertificateUpdated) when a certificate has - // been updated. - void OnCertificateUpdated(void* drm_system, - int ticket, - StarboardDrmStatus status, - std::optional error_message); - - // Called by starboard (via CallOnSessionClosed) when a session has closed. - void OnSessionClosed(void* drm_system, std::string session_id); - - // Calls OnSessionUpdateRequest for `context`, which is an instance of - // StarboardDecryptorCast. - static void CallOnSessionUpdateRequest(void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - StarboardDrmSessionRequestType type, - const char* error_message, - const void* session_id, - int session_id_size, - const void* content, - int content_size, - const char* url); - - // Calls OnSessionUpdated for `context`, which is an instance of - // StarboardDecryptorCast. - static void CallOnSessionUpdated(void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - const char* error_message, - const void* session_id, - int session_id_size); - - // Calls OnKeyStatusesChanged for `context`, which is an instance of - // StarboardDecryptorCast. - static void CallOnKeyStatusesChanged( - void* drm_system, - void* context, - const void* session_id, - int session_id_size, - int number_of_keys, - const StarboardDrmKeyId* key_ids, - const StarboardDrmKeyStatus* key_statuses); - - // Calls OnCertificateUpdated for `context`, which is an instance of - // StarboardDecryptorCast. - static void CallOnCertificateUpdated(void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - const char* error_message); - - // Calls OnSessionClosed for `context`, which is an instance of - // StarboardDecryptorCast. - static void CallOnSessionClosed(void* drm_system, - void* context, - const void* session_id, - int session_id_size); - - // Called when provisioning the device, in response to an individualization - // request. - void OnProvisionResponse(int ticket, - const std::string& session_id, - bool success, - const std::string& response); - - THREAD_CHECKER(thread_checker_); - ::media::CreateFetcherCB create_provision_fetcher_cb_; - StarboardDrmSystemCallbackHandler callback_handler_; - std::unique_ptr starboard_; - bool server_certificate_updatable_ = false; - std::queue queued_session_requests_; - - // Ticket used to track session update requests. - int current_ticket_ = 0; - base::flat_map> - ticket_to_new_session_promise_; - base::flat_map> - ticket_to_simple_cdm_promise_; - base::flat_map>> - session_id_to_simple_cdm_promises_; - - // There's a session create/load in processing. If true, all the new session - // create/load operations should be queued. - bool pending_session_setup_ = false; - - // An opaque handle to an SbDrmSystem instance. - void* drm_system_ = nullptr; - scoped_refptr task_runner_; - std::unique_ptr<::media::ProvisionFetcher> provision_fetcher_; - - // Tracks all sessions that have had at least one key created. Used to clean - // up keys in StarboardDrmKeyTracker on destruction. - base::flat_set session_ids_; - - // This must be destructed first, to invalidate any remaining weak ptrs. - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_CDM_STARBOARD_DECRYPTOR_CAST_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_decryptor_cast_test.cc chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast_test.cc --- chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_decryptor_cast_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_decryptor_cast_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,714 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/cdm/starboard_decryptor_cast.h" - -#include -#include -#include - -#include "base/functional/callback.h" -#include "base/test/bind.h" -#include "base/test/task_environment.h" -#include "chromecast/starboard/media/cdm/starboard_drm_key_tracker.h" -#include "chromecast/starboard/media/media/mock_starboard_api_wrapper.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "media/base/cdm_callback_promise.h" -#include "media/base/provision_fetcher.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace chromecast { -namespace media { -namespace { - -using ::media::CdmKeyInformation; -using ::media::CdmKeysInfo; -using ::media::CdmMessageType; -using ::media::ProvisionFetcher; -using ::testing::_; -using ::testing::DoAll; -using ::testing::ElementsAreArray; -using ::testing::Eq; -using ::testing::Field; -using ::testing::Mock; -using ::testing::MockFunction; -using ::testing::NotNull; -using ::testing::Pointee; -using ::testing::Return; -using ::testing::SaveArg; -using ::testing::StartsWith; -using ::testing::StrEq; -using ::testing::WithArg; - -constexpr char kProvisionServerUrl[] = - "https://www.googleapis.com/" - "certificateprovisioning/v1/devicecertificates/create" - "?key="; - -// Checks that a const void* arg matches a string. -// -// str is an std::string, arg is a const void*. Only the first str.length() -// characters will be checked. -MATCHER_P(StrEqWhenCast, str, "") { - const char* c_str_arg = static_cast(arg); - if (!c_str_arg) { - *result_listener << "the argument is null"; - return false; - } - - if (strlen(c_str_arg) < str.length()) { - *result_listener << "the argument is too short"; - return false; - } - - return ExplainMatchResult(StrEq(str), std::string(c_str_arg, str.length()), - result_listener); -} - -// Checks that a GURL arg's string starts with the given string. -// -// str is a string (or c string), arg is a GURL. -MATCHER_P(GurlStartsWith, str, "") { - return ExplainMatchResult(StartsWith(str), arg.spec(), result_listener); -} - -// Returns the number of elements in a C array. -template -constexpr size_t NumElements(const T (&)[n]) { - return n; -} - -class MockProvisionFetcher : public ProvisionFetcher { - public: - MockProvisionFetcher() = default; - ~MockProvisionFetcher() override = default; - - MOCK_METHOD(void, - Retrieve, - (const GURL& default_url, - const std::string& request_data, - ResponseCB response_cb), - (override)); -}; - -// A test fixture is used to manage the global mock state and to handle the -// lifetime of the SingleThreadTaskEnvironment. -class StarboardDecryptorCastTest : public ::testing::Test { - public: - std::unique_ptr CreateProvisionFetcher() { - CHECK(provision_fetcher_) << "provision_fetcher_ must be set by a test " - "before CreateProvisionFetcher is called"; - return std::move(provision_fetcher_); - } - - protected: - StarboardDecryptorCastTest() - : starboard_(std::make_unique()) { - ON_CALL(*starboard_, EnsureInitialized).WillByDefault(Return(true)); - ON_CALL(*starboard_, DrmIsServerCertificateUpdatable) - .WillByDefault(Return(true)); - } - - ~StarboardDecryptorCastTest() override = default; - - // This should be destructed last. - base::test::SingleThreadTaskEnvironment task_environment_; - // This will be passed to the StarboardDecryptorCast, and all calls to - // Starboard will go through it. Thus, we can mock out those calls. - std::unique_ptr starboard_; - // This will be returned when CreateProvisionFetcher is called. It can be set - // by tests to mock the provision fetcher. - std::unique_ptr provision_fetcher_; - // Since SbDrmSystem is just an opaque blob to the StarboardDecryptorCast, we - // will simply use an int to represent it. - int fake_drm_system_ = 1; - - // Mock functions passed to CastCdm::Initialize. - MockFunction& message)> - session_message_cb_; - MockFunction - session_closed_cb_; - MockFunction - session_keys_change_cb_; - MockFunction - session_expiration_update_cb_; -}; - -TEST_F(StarboardDecryptorCastTest, - SendsProvisionRequestToWidevineProvisioningServer) { - scoped_refptr decryptor = new StarboardDecryptorCast( - /*create_provision_fetcher_cb=*/base::BindRepeating( - &StarboardDecryptorCastTest::CreateProvisionFetcher, - base::Unretained(this)), - /*media_resource_tracker=*/nullptr); - - const std::string provision_request_data = "request data"; - const std::string provision_response_data = "response data"; - const std::string session_id = "some_session"; - - // This will get populated by decryptor. - const StarboardDrmSystemCallbackHandler* decryptor_provided_callbacks = - nullptr; - - EXPECT_CALL(*starboard_, CreateDrmSystem("com.widevine.alpha", _)) - .WillOnce(DoAll(SaveArg<1>(&decryptor_provided_callbacks), - Return(&fake_drm_system_))); - EXPECT_CALL(*starboard_, - DrmUpdateSession(&fake_drm_system_, _, - StrEqWhenCast(provision_response_data), - provision_response_data.size(), - StrEqWhenCast(session_id), session_id.size())) - .Times(1); - - decryptor->SetStarboardApiWrapperForTest(std::move(starboard_)); - decryptor->Initialize( - base::BindLambdaForTesting(session_message_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_closed_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_keys_change_cb_.AsStdFunction()), - base::BindLambdaForTesting( - session_expiration_update_cb_.AsStdFunction())); - - ASSERT_THAT(decryptor_provided_callbacks, NotNull()); - - // This provision fetcher will be returned when - // create_provision_fetcher_cb is called. - provision_fetcher_ = std::make_unique(); - EXPECT_CALL(*provision_fetcher_, Retrieve(GurlStartsWith(kProvisionServerUrl), - StrEq(provision_request_data), _)) - .WillOnce( - WithArg<2>([provision_response_data]( - base::OnceCallback - response_callback) { - std::move(response_callback).Run(true, provision_response_data); - })); - - // Trigger the provision request. - - // This ticket does not need to match an existing ticket from decryptor, since - // Starboard initializes provisioning. - const int ticket = 123; - const std::string error_message = ""; - ASSERT_THAT(decryptor_provided_callbacks->update_request_fn, NotNull()); - decryptor_provided_callbacks->update_request_fn( - &fake_drm_system_, decryptor_provided_callbacks->context, ticket, - kStarboardDrmStatusSuccess, - kStarboardDrmSessionRequestTypeIndividualizationRequest, - error_message.c_str(), session_id.c_str(), session_id.size(), - provision_request_data.c_str(), provision_request_data.size(), nullptr); - - // The functions in decryptor_provided_callbacks post tasks to - // task_environment_. - task_environment_.RunUntilIdle(); -} - -TEST_F(StarboardDecryptorCastTest, SendsSessionUpdateToStarboard) { - const std::string session_id = "session_id"; - const std::string key = "some_key"; - std::vector key_vec(key.size()); - memcpy(key_vec.data(), key.c_str(), key_vec.size()); - - scoped_refptr decryptor = new StarboardDecryptorCast( - /*create_provision_fetcher_cb=*/base::BindRepeating( - &StarboardDecryptorCastTest::CreateProvisionFetcher, - base::Unretained(this)), - /*media_resource_tracker=*/nullptr); - - // This will get populated by decryptor. - const StarboardDrmSystemCallbackHandler* decryptor_provided_callbacks = - nullptr; - - EXPECT_CALL(*starboard_, CreateDrmSystem("com.widevine.alpha", _)) - .WillOnce(DoAll(SaveArg<1>(&decryptor_provided_callbacks), - Return(&fake_drm_system_))); - - // This will be set when drm_update_session_fn is called. - int ticket = -1; - EXPECT_CALL( - *starboard_, - DrmUpdateSession(&fake_drm_system_, _, StrEqWhenCast(key), key.size(), - StrEqWhenCast(session_id), session_id.size())) - .WillOnce(SaveArg<1>(&ticket)); - - decryptor->SetStarboardApiWrapperForTest(std::move(starboard_)); - decryptor->Initialize( - base::BindLambdaForTesting(session_message_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_closed_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_keys_change_cb_.AsStdFunction()), - base::BindLambdaForTesting( - session_expiration_update_cb_.AsStdFunction())); - - ASSERT_THAT(decryptor_provided_callbacks, NotNull()); - - // This will be set to true if the promise passed to UpdateSession is resolved - // successfully. - bool resolved_promise = false; - - // Trigger the session update. - decryptor->UpdateSession( - session_id, key_vec, - std::make_unique<::media::CdmCallbackPromise<>>( - /*resolve_cb=*/base::BindOnce( - +[](bool* b) { - CHECK(b != nullptr); - *b = true; - }, - &resolved_promise), - /*reject_cb=*/base::BindOnce( - +[](::media::CdmPromise::Exception exception_code, - uint32_t system_code, const std::string& error_message) { - LOG(ERROR) << "Rejected promise with system code " - << system_code << " and error message " - << error_message; - }))); - - // Simulate a successful session update. - ASSERT_THAT(decryptor_provided_callbacks->session_updated_fn, NotNull()); - decryptor_provided_callbacks->session_updated_fn( - &fake_drm_system_, decryptor_provided_callbacks->context, ticket, - kStarboardDrmStatusSuccess, nullptr, session_id.c_str(), - session_id.size()); - - // The functions in decryptor_provided_callbacks post tasks to - // task_environment_. - task_environment_.RunUntilIdle(); - EXPECT_TRUE(resolved_promise); -} - -TEST_F(StarboardDecryptorCastTest, CallsKeyChangeCallbackOnKeyUpdate) { - StarboardDrmKeyTracker::GetInstance().ClearStateForTesting(); - - const std::string session_id = "some_session"; - const std::vector key_id = {1, 2, 3, 4, 5, 6}; - const auto key_status = CdmKeyInformation::KeyStatus::USABLE; - const uint32_t system_code = 0; - // The starboard representation of key_id. - StarboardDrmKeyId starboard_key_id; - CHECK_LE(key_id.size(), NumElements(starboard_key_id.identifier)); - memcpy(starboard_key_id.identifier, key_id.data(), key_id.size()); - starboard_key_id.identifier_size = key_id.size(); - // The starboard representation of key_status. - const StarboardDrmKeyStatus starboard_key_status = - kStarboardDrmKeyStatusUsable; - - scoped_refptr decryptor = new StarboardDecryptorCast( - /*create_provision_fetcher_cb=*/base::BindRepeating( - &StarboardDecryptorCastTest::CreateProvisionFetcher, - base::Unretained(this)), - /*media_resource_tracker=*/nullptr); - - // This will get populated by decryptor. - const StarboardDrmSystemCallbackHandler* decryptor_provided_callbacks = - nullptr; - - EXPECT_CALL(*starboard_, CreateDrmSystem("com.widevine.alpha", _)) - .WillOnce(DoAll(SaveArg<1>(&decryptor_provided_callbacks), - Return(&fake_drm_system_))); - - EXPECT_CALL( - session_keys_change_cb_, - Call(StrEq(session_id), true, - ElementsAre(Pointee(AllOf( - Field(&CdmKeyInformation::key_id, ElementsAreArray(key_id)), - Field(&CdmKeyInformation::status, Eq(key_status)), - Field(&CdmKeyInformation::system_code, Eq(system_code))))))) - .Times(1); - - decryptor->SetStarboardApiWrapperForTest(std::move(starboard_)); - decryptor->Initialize( - base::BindLambdaForTesting(session_message_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_closed_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_keys_change_cb_.AsStdFunction()), - base::BindLambdaForTesting( - session_expiration_update_cb_.AsStdFunction())); - - ASSERT_THAT(decryptor_provided_callbacks, NotNull()); - ASSERT_THAT(decryptor_provided_callbacks->key_statuses_changed_fn, NotNull()); - // Notify the decryptor that the key status changed. This should trigger the - // expected call to session_keys_change_cb_ above. - decryptor_provided_callbacks->key_statuses_changed_fn( - &fake_drm_system_, decryptor_provided_callbacks->context, - session_id.c_str(), session_id.size(), /*number_of_keys=*/1, - &starboard_key_id, &starboard_key_status); - - // The functions in decryptor_provided_callbacks post tasks to - // task_environment_. - task_environment_.RunUntilIdle(); - - // Verify that StarboardDrmKeyTracker was updated. - const std::string key_str(reinterpret_cast(key_id.data()), - key_id.size()); - EXPECT_TRUE(StarboardDrmKeyTracker::GetInstance().HasKey(key_str)); - - // Verify that the key is removed when the decryptor is destroyed. - decryptor = nullptr; - EXPECT_FALSE(StarboardDrmKeyTracker::GetInstance().HasKey(key_str)); -} - -TEST_F(StarboardDecryptorCastTest, - RemovesKeyFromStarboardDrmKeyTrackerWhenKeyIsReleased) { - StarboardDrmKeyTracker::GetInstance().ClearStateForTesting(); - - const std::string session_id = "some_session"; - const std::vector key_id = {1, 2, 3, 4, 5, 6}; - const auto key_status = CdmKeyInformation::KeyStatus::USABLE; - const auto key_released_status = CdmKeyInformation::KeyStatus::RELEASED; - const uint32_t system_code = 0; - // The starboard representation of key_id. - StarboardDrmKeyId starboard_key_id; - CHECK_LE(key_id.size(), NumElements(starboard_key_id.identifier)); - memcpy(starboard_key_id.identifier, key_id.data(), key_id.size()); - starboard_key_id.identifier_size = key_id.size(); - // The starboard representation of key_status. - const StarboardDrmKeyStatus starboard_key_status = - kStarboardDrmKeyStatusUsable; - const StarboardDrmKeyStatus starboard_key_released_status = - kStarboardDrmKeyStatusReleased; - - scoped_refptr decryptor = new StarboardDecryptorCast( - /*create_provision_fetcher_cb=*/base::BindRepeating( - &StarboardDecryptorCastTest::CreateProvisionFetcher, - base::Unretained(this)), - /*media_resource_tracker=*/nullptr); - - // This will get populated by decryptor. - const StarboardDrmSystemCallbackHandler* decryptor_provided_callbacks = - nullptr; - - EXPECT_CALL(*starboard_, CreateDrmSystem("com.widevine.alpha", _)) - .WillOnce(DoAll(SaveArg<1>(&decryptor_provided_callbacks), - Return(&fake_drm_system_))); - - EXPECT_CALL( - session_keys_change_cb_, - Call(StrEq(session_id), true, - ElementsAre(Pointee(AllOf( - Field(&CdmKeyInformation::key_id, ElementsAreArray(key_id)), - Field(&CdmKeyInformation::status, Eq(key_status)), - Field(&CdmKeyInformation::system_code, Eq(system_code))))))) - .Times(1); - EXPECT_CALL( - session_keys_change_cb_, - Call(StrEq(session_id), false, - ElementsAre(Pointee(AllOf( - Field(&CdmKeyInformation::key_id, ElementsAreArray(key_id)), - Field(&CdmKeyInformation::status, Eq(key_released_status)), - Field(&CdmKeyInformation::system_code, Eq(system_code))))))) - .Times(1); - - decryptor->SetStarboardApiWrapperForTest(std::move(starboard_)); - decryptor->Initialize( - base::BindLambdaForTesting(session_message_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_closed_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_keys_change_cb_.AsStdFunction()), - base::BindLambdaForTesting( - session_expiration_update_cb_.AsStdFunction())); - - ASSERT_THAT(decryptor_provided_callbacks, NotNull()); - ASSERT_THAT(decryptor_provided_callbacks->key_statuses_changed_fn, NotNull()); - // Notify the decryptor that the key status changed. This should trigger the - // expected call to session_keys_change_cb_ above. - decryptor_provided_callbacks->key_statuses_changed_fn( - &fake_drm_system_, decryptor_provided_callbacks->context, - session_id.c_str(), session_id.size(), /*number_of_keys=*/1, - &starboard_key_id, &starboard_key_status); - - // The functions in decryptor_provided_callbacks post tasks to - // task_environment_. - task_environment_.RunUntilIdle(); - - // Verify that StarboardDrmKeyTracker was updated. - const std::string key_str(reinterpret_cast(key_id.data()), - key_id.size()); - EXPECT_TRUE(StarboardDrmKeyTracker::GetInstance().HasKey(key_str)); - - // Verify that the key is removed when the status changes to removed. - decryptor_provided_callbacks->key_statuses_changed_fn( - &fake_drm_system_, decryptor_provided_callbacks->context, - session_id.c_str(), session_id.size(), /*number_of_keys=*/1, - &starboard_key_id, &starboard_key_released_status); - - // The functions in decryptor_provided_callbacks post tasks to - // task_environment_. - task_environment_.RunUntilIdle(); - - EXPECT_FALSE(StarboardDrmKeyTracker::GetInstance().HasKey(key_str)); -} - -TEST_F(StarboardDecryptorCastTest, CreatesSessionAndGeneratesLicenseRequest) { - constexpr char kLicenseUrl[] = "www.example.com"; - const std::string session_id = "session_id"; - const std::string content = "license_request_content"; - const ::media::EmeInitDataType init_type = ::media::EmeInitDataType::CENC; - const std::string init_data_str = "init_data"; - const std::vector init_data( - reinterpret_cast(init_data_str.c_str()), - reinterpret_cast(init_data_str.c_str()) + - init_data_str.size()); - - scoped_refptr decryptor = new StarboardDecryptorCast( - /*create_provision_fetcher_cb=*/base::BindRepeating( - &StarboardDecryptorCastTest::CreateProvisionFetcher, - base::Unretained(this)), - /*media_resource_tracker=*/nullptr); - - // This will get populated by decryptor. - const StarboardDrmSystemCallbackHandler* decryptor_provided_callbacks = - nullptr; - - EXPECT_CALL(*starboard_, CreateDrmSystem("com.widevine.alpha", _)) - .WillOnce(DoAll(SaveArg<1>(&decryptor_provided_callbacks), - Return(&fake_drm_system_))); - // This will be set when drm_generate_session_update_request_fn is called. - int ticket = -1; - EXPECT_CALL(*starboard_, - DrmGenerateSessionUpdateRequest( - &fake_drm_system_, _, StrEq("cenc"), - StrEqWhenCast(init_data_str), init_data_str.size())) - .WillOnce(SaveArg<1>(&ticket)); - - EXPECT_CALL( - session_message_cb_, - Call(StrEq(session_id), CdmMessageType::LICENSE_REQUEST, - ElementsAreArray(reinterpret_cast(content.c_str()), - content.size()))) - .Times(1); - - decryptor->SetStarboardApiWrapperForTest(std::move(starboard_)); - decryptor->Initialize( - base::BindLambdaForTesting(session_message_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_closed_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_keys_change_cb_.AsStdFunction()), - base::BindLambdaForTesting( - session_expiration_update_cb_.AsStdFunction())); - - ASSERT_THAT(decryptor_provided_callbacks, NotNull()); - - // These will be set to if the promise passed to - // CreateSessionAndGenerateRequest is resolved successfully. - bool resolved_promise = false; - std::string actual_session_id; - - // Trigger the session creation. - decryptor->CreateSessionAndGenerateRequest( - ::media::CdmSessionType::kTemporary, init_type, init_data, - std::make_unique<::media::CdmCallbackPromise>( - /*resolve_cb=*/base::BindOnce( - +[](bool* b, std::string* out_session_id, - const std::string& session_id) { - CHECK(b != nullptr); - CHECK(out_session_id != nullptr); - *b = true; - *out_session_id = session_id; - }, - &resolved_promise, &actual_session_id), - /*reject_cb=*/base::BindOnce( - +[](::media::CdmPromise::Exception exception_code, - uint32_t system_code, const std::string& error_message) { - LOG(ERROR) << "Rejected promise with system code " - << system_code << " and error message " - << error_message; - }))); - - // Simulate starboard's response to drm_generate_session_update_request_fn. - ASSERT_THAT(decryptor_provided_callbacks->update_request_fn, NotNull()); - decryptor_provided_callbacks->update_request_fn( - &fake_drm_system_, decryptor_provided_callbacks->context, ticket, - kStarboardDrmStatusSuccess, kStarboardDrmSessionRequestTypeLicenseRequest, - /*error_message=*/nullptr, session_id.c_str(), session_id.size(), - content.c_str(), content.size(), kLicenseUrl); - - // The functions in decryptor_provided_callbacks post tasks to - // task_environment_. - task_environment_.RunUntilIdle(); - EXPECT_TRUE(resolved_promise); - EXPECT_THAT(actual_session_id, StrEq(session_id)); -} - -TEST_F(StarboardDecryptorCastTest, CreatesSessionAndGeneratesLicenseRenewal) { - constexpr char kLicenseUrl[] = "www.example.com"; - const std::string session_id = "session_id"; - const std::string content = "license_request_content"; - const ::media::EmeInitDataType init_type = ::media::EmeInitDataType::CENC; - const std::string init_data_str = "init_data"; - const std::vector init_data( - reinterpret_cast(init_data_str.c_str()), - reinterpret_cast(init_data_str.c_str()) + - init_data_str.size()); - - scoped_refptr decryptor = new StarboardDecryptorCast( - /*create_provision_fetcher_cb=*/base::BindRepeating( - &StarboardDecryptorCastTest::CreateProvisionFetcher, - base::Unretained(this)), - /*media_resource_tracker=*/nullptr); - - // This will get populated by decryptor. - const StarboardDrmSystemCallbackHandler* decryptor_provided_callbacks = - nullptr; - - EXPECT_CALL(*starboard_, CreateDrmSystem("com.widevine.alpha", _)) - .WillOnce(DoAll(SaveArg<1>(&decryptor_provided_callbacks), - Return(&fake_drm_system_))); - - // This will be set when drm_generate_session_update_request_fn is called. - int ticket = -1; - EXPECT_CALL(*starboard_, - DrmGenerateSessionUpdateRequest( - &fake_drm_system_, _, StrEq("cenc"), - StrEqWhenCast(init_data_str), init_data_str.size())) - .WillOnce(SaveArg<1>(&ticket)); - - EXPECT_CALL( - session_message_cb_, - Call(StrEq(session_id), CdmMessageType::LICENSE_RENEWAL, - ElementsAreArray(reinterpret_cast(content.c_str()), - content.size()))) - .Times(1); - - decryptor->SetStarboardApiWrapperForTest(std::move(starboard_)); - decryptor->Initialize( - base::BindLambdaForTesting(session_message_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_closed_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_keys_change_cb_.AsStdFunction()), - base::BindLambdaForTesting( - session_expiration_update_cb_.AsStdFunction())); - - ASSERT_THAT(decryptor_provided_callbacks, NotNull()); - - // These will be set to if the promise passed to - // CreateSessionAndGenerateRequest is resolved successfully. - bool resolved_promise = false; - std::string actual_session_id; - - // Trigger the session creation. - decryptor->CreateSessionAndGenerateRequest( - ::media::CdmSessionType::kTemporary, init_type, init_data, - std::make_unique<::media::CdmCallbackPromise>( - /*resolve_cb=*/base::BindOnce( - +[](bool* b, std::string* out_session_id, - const std::string& session_id) { - CHECK(b != nullptr); - CHECK(out_session_id != nullptr); - *b = true; - *out_session_id = session_id; - }, - &resolved_promise, &actual_session_id), - /*reject_cb=*/base::BindOnce( - +[](::media::CdmPromise::Exception exception_code, - uint32_t system_code, const std::string& error_message) { - LOG(ERROR) << "Rejected promise with system code " - << system_code << " and error message " - << error_message; - }))); - - // Simulate starboard's response to drm_generate_session_update_request_fn. - ASSERT_THAT(decryptor_provided_callbacks->update_request_fn, NotNull()); - decryptor_provided_callbacks->update_request_fn( - &fake_drm_system_, decryptor_provided_callbacks->context, ticket, - kStarboardDrmStatusSuccess, kStarboardDrmSessionRequestTypeLicenseRenewal, - /*error_message=*/nullptr, session_id.c_str(), session_id.size(), - content.c_str(), content.size(), kLicenseUrl); - - // The functions in decryptor_provided_callbacks post tasks to - // task_environment_. - task_environment_.RunUntilIdle(); - EXPECT_TRUE(resolved_promise); - EXPECT_THAT(actual_session_id, StrEq(session_id)); -} - -TEST_F(StarboardDecryptorCastTest, ForwardsCloseSessionToStarboard) { - const std::string session_id = "session_id"; - - scoped_refptr decryptor = new StarboardDecryptorCast( - /*create_provision_fetcher_cb=*/base::BindRepeating( - &StarboardDecryptorCastTest::CreateProvisionFetcher, - base::Unretained(this)), - /*media_resource_tracker=*/nullptr); - - // This will get populated by decryptor. - const StarboardDrmSystemCallbackHandler* decryptor_provided_callbacks = - nullptr; - - EXPECT_CALL(*starboard_, CreateDrmSystem("com.widevine.alpha", _)) - .WillOnce(DoAll(SaveArg<1>(&decryptor_provided_callbacks), - Return(&fake_drm_system_))); - - // This will be called when drm_generate_session_update_request_fn is called. - EXPECT_CALL( - *starboard_, - DrmCloseSession(&fake_drm_system_, session_id.c_str(), session_id.size())) - .Times(1); - - decryptor->SetStarboardApiWrapperForTest(std::move(starboard_)); - decryptor->Initialize( - base::BindLambdaForTesting(session_message_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_closed_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_keys_change_cb_.AsStdFunction()), - base::BindLambdaForTesting( - session_expiration_update_cb_.AsStdFunction())); - - ASSERT_THAT(decryptor_provided_callbacks, NotNull()); - - // This will be set to true if the promise passed to CloseSession is resolved - // successfully. - bool resolved_promise = false; - - // Trigger the session creation. - decryptor->CloseSession( - session_id, - std::make_unique<::media::CdmCallbackPromise<>>( - /*resolve_cb=*/base::BindOnce( - +[](bool* b) { - CHECK(b != nullptr); - *b = true; - }, - &resolved_promise), - /*reject_cb=*/base::BindOnce( - +[](::media::CdmPromise::Exception exception_code, - uint32_t system_code, const std::string& error_message) { - LOG(ERROR) << "Rejected promise with system code " - << system_code << " and error message " - << error_message; - }))); - - // Simulate starboard's response to drm_close_session_fn. - ASSERT_THAT(decryptor_provided_callbacks->session_closed_fn, NotNull()); - decryptor_provided_callbacks->session_closed_fn( - &fake_drm_system_, decryptor_provided_callbacks->context, - session_id.c_str(), session_id.size()); - - // The functions in decryptor_provided_callbacks post tasks to - // task_environment_. - task_environment_.RunUntilIdle(); - EXPECT_TRUE(resolved_promise); -} - -TEST_F(StarboardDecryptorCastTest, DestroysSbDrmSystemOnDestruction) { - EXPECT_CALL(*starboard_, CreateDrmSystem("com.widevine.alpha", _)) - .WillOnce(Return(&fake_drm_system_)); - EXPECT_CALL(*starboard_, DrmDestroySystem(&fake_drm_system_)).Times(1); - - scoped_refptr decryptor = new StarboardDecryptorCast( - /*create_provision_fetcher_cb=*/base::BindRepeating( - &StarboardDecryptorCastTest::CreateProvisionFetcher, - base::Unretained(this)), - /*media_resource_tracker=*/nullptr); - decryptor->SetStarboardApiWrapperForTest(std::move(starboard_)); - decryptor->Initialize( - base::BindLambdaForTesting(session_message_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_closed_cb_.AsStdFunction()), - base::BindLambdaForTesting(session_keys_change_cb_.AsStdFunction()), - base::BindLambdaForTesting( - session_expiration_update_cb_.AsStdFunction())); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_drm_key_tracker.cc chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker.cc --- chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_drm_key_tracker.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,131 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/cdm/starboard_drm_key_tracker.h" - -#include - -#include "starboard_drm_key_tracker.h" - -namespace chromecast { -namespace media { - -StarboardDrmKeyTracker::StarboardDrmKeyTracker() = default; -StarboardDrmKeyTracker::~StarboardDrmKeyTracker() = default; - -StarboardDrmKeyTracker& StarboardDrmKeyTracker::GetInstance() { - static base::NoDestructor instance; - return *instance; -} - -void StarboardDrmKeyTracker::AddKey(const std::string& key, - const std::string& session_id) { - std::vector tokens_and_callbacks; - { - base::AutoLock lock(state_lock_); - session_id_to_keys_[session_id].insert(key); - auto it = key_to_cb_.find(key); - if (it == key_to_cb_.end()) { - // No callbacks to run. - return; - } - tokens_and_callbacks = std::move(it->second); - key_to_cb_.erase(it); - } // state_lock_ is released. - - // Run any callbacks that were waiting for key to be available. - for (auto& token_and_cb : tokens_and_callbacks) { - const int64_t token = token_and_cb.token; - std::move(token_and_cb.callback).Run(token); - } -} - -void StarboardDrmKeyTracker::RemoveKey(const std::string& key, - const std::string& session_id) { - base::AutoLock lock(state_lock_); - auto it = session_id_to_keys_.find(session_id); - if (it == session_id_to_keys_.end()) { - return; - } - it->second.erase(key); -} - -bool StarboardDrmKeyTracker::HasKey(const std::string& key) { - base::AutoLock lock(state_lock_); - return HasKeyLockHeld(key); -} - -void StarboardDrmKeyTracker::RemoveKeysForSession( - const std::string& session_id) { - base::AutoLock lock(state_lock_); - session_id_to_keys_.erase(session_id); -} - -int64_t StarboardDrmKeyTracker::WaitForKey(const std::string& key, - KeyAvailableCb cb) { - // Avoid holding the lock when running `cb` in the case where key is already - // available. - int64_t token = 0; - { - base::AutoLock lock(state_lock_); - token = next_token_++; - if (!HasKeyLockHeld(key)) { - key_to_cb_[key].push_back(TokenAndCallback(token, std::move(cb))); - return token; - } - } // state_lock_ is released. - - // We already have `key`, so run the callback immediately. - std::move(cb).Run(token); - return token; -} - -void StarboardDrmKeyTracker::UnregisterCallback(int64_t callback_token) { - base::AutoLock lock(state_lock_); - for (auto& key_and_vec : key_to_cb_) { - std::vector& tokens_and_cbs = key_and_vec.second; - for (size_t i = 0; i < tokens_and_cbs.size(); ++i) { - if (tokens_and_cbs[i].token == callback_token) { - // Remove the callback and token. For a vector this can be done in O(1) - // by swapping with the last element, since we do not care about the - // order of the elements in the vector. - std::swap(tokens_and_cbs[i], tokens_and_cbs.back()); - tokens_and_cbs.pop_back(); - return; - } - } - } -} - -void StarboardDrmKeyTracker::ClearStateForTesting() { - base::AutoLock lock(state_lock_); - session_id_to_keys_.clear(); - key_to_cb_.clear(); - next_token_ = 0; -} - -bool StarboardDrmKeyTracker::HasKeyLockHeld(const std::string& key) { - state_lock_.AssertAcquired(); - return std::any_of(session_id_to_keys_.cbegin(), session_id_to_keys_.cend(), - [&](const auto& session_id_and_keys) { - return session_id_and_keys.second.contains(key); - }); -} - -StarboardDrmKeyTracker::TokenAndCallback::TokenAndCallback( - int64_t token, - KeyAvailableCb callback) { - this->token = token; - this->callback = std::move(callback); -} - -StarboardDrmKeyTracker::TokenAndCallback::~TokenAndCallback() = default; -StarboardDrmKeyTracker::TokenAndCallback::TokenAndCallback(TokenAndCallback&&) = - default; -StarboardDrmKeyTracker::TokenAndCallback& -StarboardDrmKeyTracker::TokenAndCallback::operator=(TokenAndCallback&&) = - default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_drm_key_tracker.h chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker.h --- chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_drm_key_tracker.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,130 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_CDM_STARBOARD_DRM_KEY_TRACKER_H_ -#define CHROMECAST_STARBOARD_MEDIA_CDM_STARBOARD_DRM_KEY_TRACKER_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/containers/flat_set.h" -#include "base/functional/callback.h" -#include "base/functional/callback_forward.h" -#include "base/no_destructor.h" -#include "base/synchronization/lock.h" - -namespace chromecast { -namespace media { - -// Tracks available DRM keys. -// -// This class should be accessed via the singleton returned from GetInstance. -// All its functions are threadsafe, so it can be accessed from any sequence. -// -// The CDM is expected to add and remove keys as those keys become -// available/unavailable. Decoders are expected to check whether keys are -// available (via HasKey) before pushing buffers to starboard. If necessary, the -// decoders can register callbacks to run when a given key is available (via -// WaitForKey). -class StarboardDrmKeyTracker { - public: - // A callback that takes an int64 ticket as an identifier. This will match the - // ticket returned from WaitForKey. - using KeyAvailableCb = base::OnceCallback; - - // Returns the singleton instance of this class. - static StarboardDrmKeyTracker& GetInstance(); - - // Disallow copy and assign. This class should only be accessed via - // GetInstance(). - StarboardDrmKeyTracker(const StarboardDrmKeyTracker&) = delete; - StarboardDrmKeyTracker& operator=(const StarboardDrmKeyTracker&) = delete; - - // Adds a DRM key for the given session. - void AddKey(const std::string& key, const std::string& session_id); - - // Removes a DRM key from the given session. - void RemoveKey(const std::string& key, const std::string& session_id); - - // Removes all keys for the given session. - void RemoveKeysForSession(const std::string& session_id); - - // Returns true if the DRM key exists in any session. - bool HasKey(const std::string& key); - - // TODO(antoniori): we should probably require that the callback be run via a - // posted task by taking a TaskRunner argument and posting the task in this - // class. This works fine for now, but the TaskRunner approach would be - // slightly safer. - // - // Registers `cb` to be run once `key` is available in a session. If it is - // already available, `cb` will be run immediately. The argument to `cb` is - // the token returned from WaitForKey. - // - // If the callback must run on a particular sequence, consider using - // base::BindPostTask to create the callback. This class makes no guarantees - // about which sequence will run `cb`. - // - // Returns an opaque token that can be used to unregister the callback at a - // later time via UnregisterCallback, if necessary (e.g. when a session is - // ending). - int64_t WaitForKey(const std::string& key, KeyAvailableCb cb); - - // Unregisters a callback. `callback_token` should be the value previously - // returned by WaitForKey. - // - // If the callback was already run or if the token is invalid, this is - // functionally a no-op. - void UnregisterCallback(int64_t callback_token); - - // Clears any state. Test code need to clear the instance's state so that - // TESTs do not influence each other. - void ClearStateForTesting(); - - private: - friend class base::NoDestructor; - - // Holds a token and a callback, so that callbacks can be identified. - struct TokenAndCallback { - TokenAndCallback(int64_t token, KeyAvailableCb callback); - - // Movable, but not copyable. - TokenAndCallback(TokenAndCallback&&); - TokenAndCallback& operator=(TokenAndCallback&&); - TokenAndCallback(TokenAndCallback&) = delete; - TokenAndCallback& operator=(TokenAndCallback&) = delete; - - ~TokenAndCallback(); - - int64_t token; - KeyAvailableCb callback; - }; - - StarboardDrmKeyTracker(); - ~StarboardDrmKeyTracker(); - - // Returns whether `key` exists. state_lock_ must be held when calling this - // function. - bool HasKeyLockHeld(const std::string& key); - - base::flat_map> session_id_to_keys_; - - // A lock for this class's state. - base::Lock state_lock_; - - // Callbacks to be run once a given key is available. - base::flat_map> key_to_cb_; - - // The next token to be returned via WaitForKey. - int64_t next_token_ = 0; - - // Note: any additional state added to this class should be cleared in - // ClearStateForTesting. -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_CDM_STARBOARD_DRM_KEY_TRACKER_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_drm_key_tracker_test.cc chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker_test.cc --- chromium-132.0.6834.110/chromecast/starboard/media/cdm/starboard_drm_key_tracker_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/cdm/starboard_drm_key_tracker_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,151 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/cdm/starboard_drm_key_tracker.h" - -#include "base/test/bind.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::MockFunction; - -constexpr char kSessionId1[] = "session1"; -constexpr char kSessionId2[] = "session2"; - -// A test fixture is used to ensure that the StarboardDrmKeyTracker's state is -// cleared before each test. -class StarboardDrmKeyTrackerTest : public ::testing::Test { - protected: - StarboardDrmKeyTrackerTest() { - StarboardDrmKeyTracker::GetInstance().ClearStateForTesting(); - } - - ~StarboardDrmKeyTrackerTest() override = default; -}; - -TEST_F(StarboardDrmKeyTrackerTest, HasKeyFindsAddedKey) { - constexpr char kKey[] = "key"; - - StarboardDrmKeyTracker& cdm_manager = StarboardDrmKeyTracker::GetInstance(); - - cdm_manager.AddKey(kKey, kSessionId1); - EXPECT_TRUE(cdm_manager.HasKey(kKey)); -} - -TEST_F(StarboardDrmKeyTrackerTest, HasKeyDoesNotFindKeyThatWasNotAdded) { - constexpr char kKey[] = "key"; - - StarboardDrmKeyTracker& cdm_manager = StarboardDrmKeyTracker::GetInstance(); - - EXPECT_FALSE(cdm_manager.HasKey(kKey)); -} - -TEST_F(StarboardDrmKeyTrackerTest, HasKeyDoesNotFindKeyThatWasRemoved) { - constexpr char kKey[] = "key"; - - StarboardDrmKeyTracker& cdm_manager = StarboardDrmKeyTracker::GetInstance(); - - cdm_manager.AddKey(kKey, kSessionId1); - EXPECT_TRUE(cdm_manager.HasKey(kKey)); - cdm_manager.RemoveKey(kKey, kSessionId1); - EXPECT_FALSE(cdm_manager.HasKey(kKey)); -} - -TEST_F(StarboardDrmKeyTrackerTest, OnlyRemovesKeyForRelevantSession) { - constexpr char kKey[] = "key"; - - StarboardDrmKeyTracker& cdm_manager = StarboardDrmKeyTracker::GetInstance(); - - cdm_manager.AddKey(kKey, kSessionId1); - cdm_manager.AddKey(kKey, kSessionId2); - - EXPECT_TRUE(cdm_manager.HasKey(kKey)); - cdm_manager.RemoveKey(kKey, kSessionId1); - // The key should still be present in kSessionId2. - EXPECT_TRUE(cdm_manager.HasKey(kKey)); -} - -TEST_F(StarboardDrmKeyTrackerTest, RemoveKeysForSessionRemovesAllRelevantKeys) { - constexpr char kKey1[] = "key1"; - constexpr char kKey2[] = "key2"; - - StarboardDrmKeyTracker& cdm_manager = StarboardDrmKeyTracker::GetInstance(); - - cdm_manager.AddKey(kKey1, kSessionId1); - cdm_manager.AddKey(kKey2, kSessionId1); - - cdm_manager.AddKey(kKey1, kSessionId2); - - EXPECT_TRUE(cdm_manager.HasKey(kKey1)); - EXPECT_TRUE(cdm_manager.HasKey(kKey2)); - - cdm_manager.RemoveKeysForSession(kSessionId1); - // The key should still be present in kSessionId2. - EXPECT_TRUE(cdm_manager.HasKey(kKey1)); - EXPECT_FALSE(cdm_manager.HasKey(kKey2)); -} - -TEST_F(StarboardDrmKeyTrackerTest, RunsCallbacksWhenKeyIsAvailable) { - constexpr char kKey[] = "key"; - - StarboardDrmKeyTracker& cdm_manager = StarboardDrmKeyTracker::GetInstance(); - - MockFunction cb1; - MockFunction cb2; - - EXPECT_CALL(cb1, Call).Times(1); - EXPECT_CALL(cb2, Call).Times(1); - - const int64_t ticket1 = cdm_manager.WaitForKey( - kKey, base::BindLambdaForTesting(cb1.AsStdFunction())); - const int64_t ticket2 = cdm_manager.WaitForKey( - kKey, base::BindLambdaForTesting(cb2.AsStdFunction())); - - EXPECT_NE(ticket1, ticket2); - - cdm_manager.AddKey(kKey, kSessionId1); -} - -TEST_F(StarboardDrmKeyTrackerTest, - RunsCallbackImmediatelyIfKeyIsAlreadyAvailable) { - constexpr char kKey[] = "key"; - - StarboardDrmKeyTracker& cdm_manager = StarboardDrmKeyTracker::GetInstance(); - cdm_manager.AddKey(kKey, kSessionId1); - - MockFunction cb; - EXPECT_CALL(cb, Call).Times(1); - - cdm_manager.WaitForKey(kKey, base::BindLambdaForTesting(cb.AsStdFunction())); -} - -TEST_F(StarboardDrmKeyTrackerTest, DoesNotRunUnregisteredCallback) { - constexpr char kKey[] = "key"; - - StarboardDrmKeyTracker& cdm_manager = StarboardDrmKeyTracker::GetInstance(); - - MockFunction cb1; - MockFunction cb2; - - // cb1 will be unregistered, so it should not be run. - EXPECT_CALL(cb1, Call).Times(0); - EXPECT_CALL(cb2, Call).Times(1); - - const int64_t ticket1 = cdm_manager.WaitForKey( - kKey, base::BindLambdaForTesting(cb1.AsStdFunction())); - const int64_t ticket2 = cdm_manager.WaitForKey( - kKey, base::BindLambdaForTesting(cb2.AsStdFunction())); - - EXPECT_NE(ticket1, ticket2); - cdm_manager.UnregisterCallback(ticket1); - cdm_manager.AddKey(kKey, kSessionId1); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/cast_media_starboard.cc chromium-132.0.6834.159/chromecast/starboard/media/media/cast_media_starboard.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/cast_media_starboard.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/cast_media_starboard.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/logging.h" -#include "chromecast/public/cast_media_shlib.h" -#include "chromecast/public/media/media_capabilities_shlib.h" -#include "chromecast/public/video_plane.h" -#include "chromecast/starboard/media/media/media_pipeline_backend_starboard.h" -#include "chromecast/starboard/media/media/mime_utils.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "chromecast/starboard/media/media/starboard_video_plane.h" - -namespace chromecast { -namespace media { -namespace { - -StarboardVideoPlane* g_video_plane = nullptr; - -// Returns true if starboard supports Dolby Vision playback for HEVC content -// with the given profile and level. -bool IsHEVCDolbyVisionSupported(VideoProfile profile, int level) { - // A leak is intentional here, since starboard_api has static storage - // duration. - static StarboardApiWrapper* const starboard_api = - GetStarboardApiWrapper().release(); - - const std::string mime = GetMimeType(kCodecDolbyVisionHEVC, profile, level); - if (mime.empty()) { - return false; - } - - const bool supported = - starboard_api->CanPlayMimeAndKeySystem(mime.c_str(), /*key_system=*/"") == - kStarboardMediaSupportTypeProbably; - LOG(INFO) << "HEVC profile=" << profile << ", level=" << level << " is " - << (supported ? "supported" : "not supported"); - return supported; -} - -} // namespace - -void CastMediaShlib::Initialize(const std::vector& argv) { - CHECK(g_video_plane == nullptr); - g_video_plane = new StarboardVideoPlane(); -} - -void CastMediaShlib::Finalize() { - delete g_video_plane; - g_video_plane = nullptr; -} - -VideoPlane* CastMediaShlib::GetVideoPlane() { - return g_video_plane; -} - -MediaPipelineBackend* CastMediaShlib::CreateMediaPipelineBackend( - const MediaPipelineDeviceParams& params) { - CHECK(g_video_plane); - return new MediaPipelineBackendStarboard(params, g_video_plane); -} - -double CastMediaShlib::GetMediaClockRate() { - return 0.0; -} - -double CastMediaShlib::MediaClockRatePrecision() { - return 0.0; -} - -void CastMediaShlib::MediaClockRateRange(double* minimum_rate, - double* maximum_rate) { - *minimum_rate = 0.0; - *maximum_rate = 1.0; -} - -bool CastMediaShlib::SetMediaClockRate(double new_rate) { - return false; -} - -bool CastMediaShlib::SupportsMediaClockRateChange() { - return false; -} - -VideoPlane::Coordinates VideoPlane::GetCoordinates() { - // SbPlayerSetBounds takes coordinates in terms of the graphics resolution. - return VideoPlane::Coordinates::kGraphics; -} - -bool MediaCapabilitiesShlib::IsSupportedVideoConfig(VideoCodec codec, - VideoProfile profile, - int level) { - // TODO(b/275430044): expand this to cover all video codecs/profiles/levels. - if (codec == kCodecDolbyVisionHEVC) { - return IsHEVCDolbyVisionSupported(profile, level); - } - - return codec == kCodecH264 || codec == kCodecVP8 || codec == kCodecVP9 || - codec == kCodecHEVC; -} - -bool MediaCapabilitiesShlib::IsSupportedAudioConfig(const AudioConfig& config) { - // TODO(b/275430044): potentially call Starboard here, to determine codec - // support. This is probably only necessary for optional codecs (AC3/E-AC3). - return config.codec == kCodecAAC || config.codec == kCodecMP3 || - config.codec == kCodecPCM || config.codec == kCodecVorbis || - config.codec == kCodecOpus || config.codec == kCodecAC3 || - config.codec == kCodecEAC3 || config.codec == kCodecFLAC; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/drm_util.cc chromium-132.0.6834.159/chromecast/starboard/media/media/drm_util.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/drm_util.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/drm_util.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,138 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/drm_util.h" - -#include - -#include "base/check.h" -#include "base/logging.h" - -namespace chromecast { -namespace media { - -// Returns the length of an array. -template -static constexpr size_t ArrayLength(const T (&)[n]) { - return n; -} - -// Rather than hard-coding values here, we simply read the length of the -// relevant arrays in StarboardDrmSampleInfo. -constexpr int kMaxIvLength = ArrayLength( - static_cast(nullptr)->initialization_vector); -constexpr int kMaxIdLength = - ArrayLength(static_cast(nullptr)->identifier); - -DrmInfoWrapper::DrmInfoWrapper() = default; - -DrmInfoWrapper::DrmInfoWrapper( - StarboardDrmSampleInfo drm_sample_info, - std::vector mappings) { - drm_sample_info_ = std::move(drm_sample_info); - subsample_mappings_ = std::move(mappings); - - UpdateSubsampleInfo(); -} - -DrmInfoWrapper::DrmInfoWrapper(DrmInfoWrapper&& other) { - drm_sample_info_ = std::move(other.drm_sample_info_); - subsample_mappings_ = std::move(other.subsample_mappings_); - - UpdateSubsampleInfo(); - other.drm_sample_info_ = std::nullopt; -} - -DrmInfoWrapper& DrmInfoWrapper::operator=(DrmInfoWrapper&& other) { - drm_sample_info_ = std::move(other.drm_sample_info_); - subsample_mappings_ = std::move(other.subsample_mappings_); - - UpdateSubsampleInfo(); - other.drm_sample_info_ = std::nullopt; - return *this; -} - -DrmInfoWrapper::~DrmInfoWrapper() = default; - -StarboardDrmSampleInfo* DrmInfoWrapper::GetDrmSampleInfo() { - return drm_sample_info_ ? &*drm_sample_info_ : nullptr; -} - -void DrmInfoWrapper::UpdateSubsampleInfo() { - if (!drm_sample_info_) { - return; - } - - drm_sample_info_->subsample_count = subsample_mappings_.size(); - drm_sample_info_->subsample_mapping = - subsample_mappings_.empty() ? nullptr : subsample_mappings_.data(); -} - -DrmInfoWrapper GetDrmInfo(const CastDecoderBuffer& buffer) { - const CastDecryptConfig* decrypt_config = buffer.decrypt_config(); - if (!decrypt_config) { - return DrmInfoWrapper(); - } - - // Populate drm_sample_info. - StarboardDrmSampleInfo drm_info; - - switch (decrypt_config->encryption_scheme()) { - case EncryptionScheme::kUnencrypted: - return DrmInfoWrapper(); - case EncryptionScheme::kAesCtr: - drm_info.encryption_scheme = kStarboardDrmEncryptionSchemeAesCtr; - break; - case EncryptionScheme::kAesCbc: - drm_info.encryption_scheme = kStarboardDrmEncryptionSchemeAesCbc; - break; - } - - drm_info.encryption_pattern.crypt_byte_block = - decrypt_config->pattern().encrypt_blocks; - drm_info.encryption_pattern.skip_byte_block = - decrypt_config->pattern().skip_blocks; - - int iv_size = decrypt_config->iv().size(); - if (iv_size > kMaxIvLength) { - LOG(ERROR) - << "Encrypted buffer contained too many initialization vector values " - "(max supported by Starboard is " - << kMaxIvLength << "): " << iv_size; - iv_size = kMaxIvLength; - } - for (int i = 0; i < iv_size; ++i) { - drm_info.initialization_vector[i] = - static_cast(decrypt_config->iv().at(i)); - } - drm_info.initialization_vector_size = iv_size; - - int id_size = decrypt_config->key_id().size(); - if (id_size > kMaxIdLength) { - LOG(ERROR) << "Encrypted buffer contained too many key ID vector values " - "(max supported by Starboard is " - << kMaxIdLength << "): " << id_size; - id_size = kMaxIdLength; - } - for (int i = 0; i < id_size; ++i) { - drm_info.identifier[i] = - static_cast(decrypt_config->key_id().at(i)); - } - drm_info.identifier_size = id_size; - - // Populate subsample_mappings. - std::vector subsample_mappings; - subsample_mappings.reserve(decrypt_config->subsamples().size()); - for (const SubsampleEntry& subsample : decrypt_config->subsamples()) { - StarboardDrmSubSampleMapping mapping; - mapping.clear_byte_count = subsample.clear_bytes; - mapping.encrypted_byte_count = subsample.cypher_bytes; - subsample_mappings.push_back(std::move(mapping)); - } - - return DrmInfoWrapper(std::move(drm_info), std::move(subsample_mappings)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/drm_util.h chromium-132.0.6834.159/chromecast/starboard/media/media/drm_util.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/drm_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/drm_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Contains a helper function to get DRM info from buffers. This logic can be -// used by both the StarboardAudioDecoder and the StarboardVideoDecoder. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_DRM_UTIL_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_DRM_UTIL_H_ - -#include -#include - -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/public/media/cast_decrypt_config.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -// A wrapper for fields related to DRM. If GetDrmSampleInfo() returns a -// non-null value and subsample mappings are present, the lifetime of those -// subsamples is tied to the lifetime of the wrapper. -// -// After moving or destroying a DrmInfoWrapper, any pointers previously returned -// by GetDrmSampleInfo should not be dereferenced, as they are no longer valid. -class DrmInfoWrapper { - public: - // Constructs a DrmInfoWrapper for unencrypted content. GetDrmSampleInfo() - // will return null. - DrmInfoWrapper(); - - // Constructs a DrmInfoWrapper representing encrypted content. - // GetDrmSampleInfo() will return a populated StarboardDrmSampleInfo. - DrmInfoWrapper(StarboardDrmSampleInfo drm_sample_info, - std::vector mappings); - - // DrmInfoWrapper is movable but not copyable. - DrmInfoWrapper(DrmInfoWrapper&& other); - DrmInfoWrapper& operator=(DrmInfoWrapper&& other); - DrmInfoWrapper(const DrmInfoWrapper&) = delete; - DrmInfoWrapper& operator=(const DrmInfoWrapper&) = delete; - - ~DrmInfoWrapper(); - - // Returns a pointer to the DrmSampleInfo owned by this wrapper, or null if - // there is no sample info. The returned pointer must not be dereferenced - // after moving or destroying this object. - StarboardDrmSampleInfo* GetDrmSampleInfo(); - - private: - // Updates drm_sample_info->subsample_count and - // drm_sample_info->subsample_mapping to refer to `subsample_mappings`. These - // fields need to be updated when moving a DrmInfoWrapper. - void UpdateSubsampleInfo(); - - std::optional drm_sample_info_; - std::vector subsample_mappings_; -}; - -// Extracts and returns DRM info from `buffer`. If the buffer is not encrypted, -// the StarboardDrmSampleInfo returned by GetDrmSampleInfo will be null. -DrmInfoWrapper GetDrmInfo(const CastDecoderBuffer& buffer); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_DRM_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/media_pipeline_backend_starboard.cc chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/media_pipeline_backend_starboard.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,418 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media_pipeline_backend_starboard.h" - -#include - -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -MediaPipelineBackendStarboard::MediaPipelineBackendStarboard( - const MediaPipelineDeviceParams& params, - StarboardVideoPlane* video_plane) - : starboard_(GetStarboardApiWrapper()), - video_plane_(video_plane), - is_streaming_( - params.sync_type == - MediaPipelineDeviceParams::MediaSyncType::kModeIgnorePts || - params.sync_type == MediaPipelineDeviceParams::MediaSyncType:: - kModeIgnorePtsAndVSync) { - DCHECK(video_plane_); - CHECK(base::SequencedTaskRunner::HasCurrentDefault()); - media_task_runner_ = base::SequencedTaskRunner::GetCurrentDefault(); - video_plane_callback_token_ = - video_plane_->RegisterCallback(base::BindPostTask( - media_task_runner_, - base::BindRepeating(&MediaPipelineBackendStarboard::OnGeometryChanged, - weak_factory_.GetWeakPtr()))); - - LOG(INFO) << "Constructed a MediaPipelineBackendStarboard" - << (is_streaming_ ? " for streaming" : ""); -} - -MediaPipelineBackendStarboard::~MediaPipelineBackendStarboard() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - video_plane_->UnregisterCallback(video_plane_callback_token_); - if (player_) { - starboard_->DestroyPlayer(player_); - } -} - -MediaPipelineBackend::AudioDecoder* -MediaPipelineBackendStarboard::CreateAudioDecoder() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - if (audio_decoder_) { - return nullptr; - } - audio_decoder_.emplace(starboard_.get()); - return &*audio_decoder_; -} - -MediaPipelineBackend::VideoDecoder* -MediaPipelineBackendStarboard::CreateVideoDecoder() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - if (video_decoder_) { - return nullptr; - } - video_decoder_.emplace(starboard_.get()); - return &*video_decoder_; -} - -bool MediaPipelineBackendStarboard::Initialize() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - CHECK(starboard_->EnsureInitialized()); - state_ = State::kInitialized; - CreatePlayer(); - return true; -} - -bool MediaPipelineBackendStarboard::Start(int64_t start_pts) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK_EQ(state_, State::kInitialized); - state_ = State::kPlaying; - last_seek_pts_ = start_pts; - - if (!player_) { - LOG(WARNING) << "Start was called before starboard initialization " - "finished. Deferring start."; - return true; - } - - DoSeek(); - DoPlay(); - return true; -} - -void MediaPipelineBackendStarboard::DoSeek() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK(player_); - DCHECK_GE(last_seek_pts_, 0); - - if (audio_decoder_ && audio_decoder_->IsInitialized()) { - audio_decoder_->Stop(); - } - if (video_decoder_ && video_decoder_->IsInitialized()) { - video_decoder_->Stop(); - } - - ++seek_ticket_; - starboard_->SeekTo(player_, last_seek_pts_, seek_ticket_); -} - -void MediaPipelineBackendStarboard::DoPlay() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK(player_); - - starboard_->SetPlaybackRate(player_, playback_rate_); -} - -void MediaPipelineBackendStarboard::Stop() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK(state_ == State::kPlaying || state_ == State::kPaused) - << "Cannot call MediaPipelineBackend::Stop when in state " - << static_cast(state_); - - if (state_ == State::kPlaying) { - DoPause(); - } - playback_rate_ = 1.0; - state_ = State::kInitialized; -} - -bool MediaPipelineBackendStarboard::Pause() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK_EQ(state_, State::kPlaying); - state_ = State::kPaused; - - if (!player_) { - LOG(WARNING) << "Pause was called before starboard initialization " - "finished. Deferring pause."; - return true; - } - - DoPause(); - return true; -} - -void MediaPipelineBackendStarboard::DoPause() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK(player_); - - StarboardPlayerInfo info = {}; - starboard_->GetPlayerInfo(player_, &info); - playback_rate_ = info.playback_rate; - - // Setting playback rate to 0 signifies that playback is paused. - starboard_->SetPlaybackRate(player_, 0); -} - -bool MediaPipelineBackendStarboard::Resume() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK_EQ(state_, State::kPaused); - state_ = State::kPlaying; - - if (player_) { - DoPlay(); - } - return true; -} - -int64_t MediaPipelineBackendStarboard::GetCurrentPts() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - if (player_) { - StarboardPlayerInfo info = {}; - starboard_->GetPlayerInfo(player_, &info); - return info.current_media_timestamp_micros; - } else { - return std::numeric_limits::min(); - } -} - -bool MediaPipelineBackendStarboard::SetPlaybackRate(float rate) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - DCHECK(state_ == State::kPlaying || state_ == State::kPaused) - << "Cannot call MediaPipelineBackend::SetPlaybackRate when in state " - << static_cast(state_); - DCHECK(player_); - - if (rate <= 0.0) { - LOG(ERROR) << "Invalid playback rate: " << rate; - return false; - } - - if (starboard_->SetPlaybackRate(player_, rate)) { - // Success case. - playback_rate_ = rate; - return true; - } - - LOG(ERROR) << "Failed to set the playback rate in Starboard to " << rate; - return false; -} - -void MediaPipelineBackendStarboard::OnGeometryChanged( - const RectF& display_rect, - StarboardVideoPlane::Transform transform) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - if (!player_) { - LOG(INFO) << "Player was not created before OnGeometryChanged was called. " - "Queueing geometry change."; - pending_geometry_change_ = display_rect; - return; - } - - LOG(INFO) << "Setting SbPlayer's bounds to z=0, x=" << display_rect.x - << ", y=" << display_rect.y << ", width=" << display_rect.width - << ", height=" << display_rect.height; - starboard_->SetPlayerBounds( - player_, /*z_index=*/0, static_cast(display_rect.x), - static_cast(display_rect.y), static_cast(display_rect.width), - static_cast(display_rect.height)); -} - -void MediaPipelineBackendStarboard::CreatePlayer() { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - - StarboardPlayerCreationParam params = {}; - if (audio_decoder_) { - const std::optional& audio_info = - audio_decoder_->GetAudioSampleInfo(); - CHECK(audio_info); - params.audio_sample_info = *audio_info; - } - if (video_decoder_) { - const std::optional& video_info = - video_decoder_->GetVideoSampleInfo(); - CHECK(video_info); - params.video_sample_info = *video_info; - if (is_streaming_) { - // Note: this is not part of the official starboard API. We are using this - // arbitrary string value to inform the starboard impl that they should - // prioritize minimizing latency (render the frames as soon as possible). - params.video_sample_info.max_video_capabilities = "streaming=1"; - } - } - params.output_mode = kStarboardPlayerOutputModePunchOut; - player_ = - starboard_->CreatePlayer(¶ms, - /*callback_handler=*/&player_callback_handler_); - CHECK(player_); - - if (pending_geometry_change_) { - OnGeometryChanged(*pending_geometry_change_, - StarboardVideoPlane::Transform::TRANSFORM_NONE); - pending_geometry_change_ = std::nullopt; - } -} - -void MediaPipelineBackendStarboard::OnSampleDecoded( - void* player, - StarboardMediaType type, - StarboardDecoderState decoder_state, - int ticket) { - if (!media_task_runner_->RunsTasksInCurrentSequence()) { - media_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MediaPipelineBackendStarboard::OnSampleDecoded, - weak_factory_.GetWeakPtr(), player, type, decoder_state, - ticket)); - return; - } - - DCHECK_EQ(player, player_); - - if (ticket != seek_ticket_) { - // TODO(antoniori): we may still need to trigger a - // Delegate::OnPushBufferComplete callback here for both decoders, even if - // there was a seek. Need to verify the expected behavior. - - LOG(INFO) << "Seek ticket mismatch"; - return; - } - - // If a decoder is not initialized, it means this is the first OnSampleDecoded - // call after a seek. So no buffer was pushed, but we still need to initialize - // the decoder. - if (type == kStarboardMediaTypeAudio) { - DCHECK(audio_decoder_); - if (audio_decoder_->IsInitialized()) { - audio_decoder_->OnBufferWritten(); - } else { - LOG(INFO) << "Initializing audio decoder"; - audio_decoder_->Initialize(player_); - } - } else { - DCHECK(video_decoder_); - if (video_decoder_->IsInitialized()) { - video_decoder_->OnBufferWritten(); - } else { - LOG(INFO) << "Initializing video decoder"; - video_decoder_->Initialize(player_); - } - } -} - -void MediaPipelineBackendStarboard::DeallocateSample( - void* player, - const void* sample_buffer) { - if (!media_task_runner_->RunsTasksInCurrentSequence()) { - media_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MediaPipelineBackendStarboard::DeallocateSample, - weak_factory_.GetWeakPtr(), player, sample_buffer)); - return; - } - - // Unfortunately, the starboard SbPlayer API does not report the type of the - // buffer, so we let both decoders attempt to deallocate it. Each decoder - // knows which buffers it owns, so they will not attempt to deallocate buffers - // that they do not own. - if (audio_decoder_) { - audio_decoder_->Deallocate(static_cast(sample_buffer)); - } - if (video_decoder_) { - video_decoder_->Deallocate(static_cast(sample_buffer)); - } -} - -void MediaPipelineBackendStarboard::CallOnSampleDecoded( - void* player, - void* context, - StarboardMediaType type, - StarboardDecoderState decoder_state, - int ticket) { - static_cast(context)->OnSampleDecoded( - player, type, decoder_state, ticket); -} - -void MediaPipelineBackendStarboard::CallDeallocateSample( - void* player, - void* context, - const void* sample_buffer) { - static_cast(context)->DeallocateSample( - player, sample_buffer); -} - -void MediaPipelineBackendStarboard::CallOnPlayerStatus( - void* player, - void* context, - StarboardPlayerState state, - int ticket) { - static_cast(context)->OnPlayerStatus( - player, state, ticket); -} - -void MediaPipelineBackendStarboard::CallOnPlayerError( - void* player, - void* context, - StarboardPlayerError error, - const char* message) { - static_cast(context)->OnPlayerError( - player, error, message); -} - -void MediaPipelineBackendStarboard::OnPlayerStatus(void* player, - StarboardPlayerState state, - int ticket) { - if (!media_task_runner_->RunsTasksInCurrentSequence()) { - media_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MediaPipelineBackendStarboard::OnPlayerStatus, - weak_factory_.GetWeakPtr(), player, state, ticket)); - return; - } - DCHECK_EQ(player, player_); - - LOG(INFO) << "Received starboard player status: " << state; - if (state == kStarboardPlayerStateEndOfStream) { - // Since playback has stopped, the decoders' delegates must be notified. - if (audio_decoder_) { - audio_decoder_->OnSbPlayerEndOfStream(); - } - if (video_decoder_) { - video_decoder_->OnSbPlayerEndOfStream(); - } - } -} - -void MediaPipelineBackendStarboard::OnPlayerError(void* player, - StarboardPlayerError error, - const std::string& message) { - if (!media_task_runner_->RunsTasksInCurrentSequence()) { - media_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&MediaPipelineBackendStarboard::OnPlayerError, - weak_factory_.GetWeakPtr(), player, error, message)); - return; - } - - LOG(ERROR) << "Received starboard player error: " << error - << ", with message " << message; - if (error == kStarboardPlayerErrorDecode) { - if (audio_decoder_) { - audio_decoder_->OnStarboardDecodeError(); - } - if (video_decoder_) { - video_decoder_->OnStarboardDecodeError(); - } - } -} - -void MediaPipelineBackendStarboard::TestOnlySetStarboardApiWrapper( - std::unique_ptr starboard) { - DCHECK(media_task_runner_->RunsTasksInCurrentSequence()); - LOG(INFO) << "Replacing the StarboardApiWrapper used by " - "MediaPipelineBackendStarboard and decoders. This should only " - "happen in tests"; - starboard_ = std::move(starboard); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/media_pipeline_backend_starboard.h chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/media_pipeline_backend_starboard.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,176 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_MEDIA_PIPELINE_BACKEND_STARBOARD_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_MEDIA_PIPELINE_BACKEND_STARBOARD_H_ - -#include - -#include "base/memory/weak_ptr.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "chromecast/starboard/media/media/starboard_audio_decoder.h" -#include "chromecast/starboard/media/media/starboard_video_decoder.h" -#include "chromecast/starboard/media/media/starboard_video_plane.h" - -namespace chromecast { -namespace media { - -// A backend that uses starboard for decoding/rendering. -// -// Public functions and the destructor must be called on the sequence that -// consntructed the MediaPipelineBackendStarboard. -class MediaPipelineBackendStarboard : public MediaPipelineBackend { - public: - MediaPipelineBackendStarboard(const MediaPipelineDeviceParams& params, - StarboardVideoPlane* video_plane); - ~MediaPipelineBackendStarboard() override; - - // For testing purposes, `starboard` will be used to call starboard functions. - void TestOnlySetStarboardApiWrapper( - std::unique_ptr starboard); - - // MediaPipelineBackend implementation: - AudioDecoder* CreateAudioDecoder() override; - VideoDecoder* CreateVideoDecoder() override; - bool Initialize() override; - bool Start(int64_t start_pts) override; - void Stop() override; - bool Pause() override; - bool Resume() override; - int64_t GetCurrentPts() override; - bool SetPlaybackRate(float rate) override; - - // StarboardVideoPlane::Delegate implementation: - - private: - // Represents the state of the backend. See the documentation of - // media_pipeline_backend.h for more information about valid transitions - // between states. - enum class State { - kUninitialized, - kInitialized, - kPlaying, - kPaused, - }; - - // Called when the video plane's geometry changes. This means that we need to - // update the SbPlayer's bounds. - // - // Expects that `display_rect` is in display coordinates, NOT (physical) - // screen coordinates. - // - // This function must be called on media_task_runner_. - void OnGeometryChanged(const RectF& display_rect, - StarboardVideoPlane::Transform transform); - - // Creates the starboard player object. - void CreatePlayer(); - - // Called when a starboard audio or video decoder needs more samples. This - // occurs after either: - // 1. A sample has been decoded, or - // 2. A seek has finished - // - // For case 1, we notify the relevant decoder that the sample has been - // decoded. For case 2, we re-initialize the decoder, meaning it will start - // pushing buffers to starboard again. - void OnSampleDecoded(void* player, - StarboardMediaType type, - StarboardDecoderState decoder_state, - int ticket); - - // Called when a sample can be deallocated. The decoders handle the actual - // deallocation. - void DeallocateSample(void* player, const void* sample_buffer); - - // Called when the SbPlayer's state has changed. - void OnPlayerStatus(void* player, StarboardPlayerState state, int ticket); - - // Called when the SbPlayer has encountered an error. - void OnPlayerError(void* player, - StarboardPlayerError error, - const std::string& message); - - // Called when starboard has started. This must be called on the media task - // runner. - void OnStarboardStarted(); - - // Performs the actual play logic by setting the playback rate to a non-zero - // value. player_ must not be null when this is called. - void DoPlay(); - - // Performs the actual pause logic by setting the playback rate to 0. player_ - // must not be null when this is called. - void DoPause(); - - // Seeks to last_seek_pts_ and increments seek_ticket_. - void DoSeek(); - - // A pure function that calls OnSampleDecoded. `context` is a pointer to a - // MediaPipelineBackendStarboard object. The rest of the arguments are - // forwarded to OnSampleDecoded. - static void CallOnSampleDecoded(void* player, - void* context, - StarboardMediaType type, - StarboardDecoderState decoder_state, - int ticket); - - // Called by starboard when a sample can be deallocated. Note that this may be - // called after CallOnSampleDecoded is called for a given sample, meaning that - // the sample needs to outlive the call to CallOnSampleDecoded. - static void CallDeallocateSample(void* player, - void* context, - const void* sample_buffer); - - // Called by starboard when the player's status changes. Notably, this will be - // called with state kStarboardPlayerStateEndOfStream when the end of stream - // buffer has been rendered. - static void CallOnPlayerStatus(void* player, - void* context, - StarboardPlayerState state, - int ticket); - - // Called by starboard when there is a player error. - static void CallOnPlayerError(void* player, - void* context, - StarboardPlayerError error, - const char* message); - - StarboardPlayerCallbackHandler player_callback_handler_ = { - /*context=*/this, &CallOnSampleDecoded, - &CallDeallocateSample, &CallOnPlayerStatus, - &CallOnPlayerError, - }; - // Calls to Starboard are made through this struct, to allow tests to mock - // their behavior (and not rely on Starboard). - std::unique_ptr starboard_; - State state_ = State::kUninitialized; - float playback_rate_ = 1.0; - int64_t last_seek_pts_ = -1; - // Ticket representing the last seek. This is necessary to recognize callbacks - // from old seeks, which are no longer relevant. - int seek_ticket_ = 0; - scoped_refptr media_task_runner_; - // An opaque handle to the SbPlayer. - void* player_ = nullptr; - std::optional audio_decoder_; - std::optional video_decoder_; - std::optional pending_geometry_change_; - StarboardVideoPlane* video_plane_ = nullptr; - int64_t video_plane_callback_token_ = 0; - // If true, we should render frames immediately to minimize latency. This - // should be true when mirroring. - bool is_streaming_ = false; - - // This must be destructed first. - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_MEDIA_PIPELINE_BACKEND_STARBOARD_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/media_pipeline_backend_starboard_test.cc chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard_test.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/media_pipeline_backend_starboard_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/media_pipeline_backend_starboard_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,459 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media_pipeline_backend_starboard.h" - -#include "base/test/task_environment.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/media/media_pipeline_device_params.h" -#include "chromecast/public/volume_control.h" -#include "chromecast/starboard/media/media/mock_starboard_api_wrapper.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::_; -using ::testing::AllOf; -using ::testing::AnyNumber; -using ::testing::DoAll; -using ::testing::DoubleEq; -using ::testing::Mock; -using ::testing::MockFunction; -using ::testing::Not; -using ::testing::NotNull; -using ::testing::Return; -using ::testing::SaveArg; -using ::testing::WithArg; - -// Takes a StarboardPlayerCreationParam* argument and ensures that its max video -// capabilities specify streaming=1. -MATCHER(CreationParamHasStreamingEnabled, "") { - if (!arg) { - *result_listener << "the StarboardPlayerCreationParam* is null"; - return false; - } - return strcmp(arg->video_sample_info.max_video_capabilities, "streaming=1") == - 0; -} - -// A mock delegate that can be passed to decoders. -class MockDelegate : public MediaPipelineBackend::Decoder::Delegate { - public: - MockDelegate() = default; - ~MockDelegate() override = default; - - MOCK_METHOD(void, OnPushBufferComplete, (BufferStatus status), (override)); - MOCK_METHOD(void, OnEndOfStream, (), (override)); - MOCK_METHOD(void, OnDecoderError, (), (override)); - MOCK_METHOD(void, - OnKeyStatusChanged, - (const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code), - (override)); - MOCK_METHOD(void, OnVideoResolutionChanged, (const Size& size), (override)); -}; - -// Returns a simple AudioConfig. -AudioConfig GetBasicAudioConfig() { - AudioConfig config; - - config.codec = AudioCodec::kCodecMP3; - config.channel_layout = ChannelLayout::STEREO; - config.sample_format = SampleFormat::kSampleFormatF32; - config.bytes_per_channel = 4; - config.channel_number = 2; - config.samples_per_second = 44100; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - - return config; -} - -// Returns a simple VideoConfig. -VideoConfig GetBasicVideoConfig() { - VideoConfig config; - - config.codec = VideoCodec::kCodecH264; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - config.width = 123; - config.height = 456; - - return config; -} - -// A test fixture is used to manage the global mock state and to handle the -// lifetime of the SingleThreadTaskEnvironment. -class MediaPipelineBackendStarboardTest : public ::testing::Test { - protected: - MediaPipelineBackendStarboardTest() - : starboard_(std::make_unique()), - device_params_( - /*task_runner_in=*/nullptr, - AudioContentType::kMedia, - /*device_id_in=*/"id") { - // Sets up default behavior for the mock functions that return values, so - // that tests that do not care about this functionality can ignore them. - ON_CALL(*starboard_, CreatePlayer).WillByDefault(Return(&fake_player_)); - ON_CALL(*starboard_, EnsureInitialized).WillByDefault(Return(true)); - ON_CALL(*starboard_, SetPlaybackRate).WillByDefault(Return(true)); - } - - ~MediaPipelineBackendStarboardTest() override = default; - - // This should be destructed last. - base::test::SingleThreadTaskEnvironment task_environment_; - // This will be passed to the MediaPipelineBackendStarboard, and all calls to - // Starboard will go through it. Thus, we can mock out those calls. - std::unique_ptr starboard_; - // Since SbPlayer is just an opaque blob to the MPB, we will simply use an int - // to represent it. - int fake_player_ = 1; - StarboardVideoPlane video_plane_; - MediaPipelineDeviceParams device_params_; -}; - -TEST_F(MediaPipelineBackendStarboardTest, InitializesSuccessfully) { - EXPECT_CALL(*starboard_, EnsureInitialized).WillOnce(Return(true)); - EXPECT_CALL(*starboard_, CreatePlayer).WillOnce(Return(&fake_player_)); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - - EXPECT_TRUE(backend.Initialize()); -} - -TEST_F(MediaPipelineBackendStarboardTest, - SetsMaxVideoCapabilitiesToStreamingForIgnorePtsSyncType) { - EXPECT_CALL(*starboard_, EnsureInitialized).WillOnce(Return(true)); - EXPECT_CALL(*starboard_, CreatePlayer(CreationParamHasStreamingEnabled(), _)) - .WillOnce(Return(&fake_player_)); - - MediaPipelineDeviceParams device_params = device_params_; - device_params.sync_type = - MediaPipelineDeviceParams::MediaSyncType::kModeIgnorePts; - MediaPipelineBackendStarboard backend(device_params, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - - // We need to create a video decoder in order for video params to be set when - // creating the SbPlayer. - MediaPipelineBackend::VideoDecoder* video_decoder = - backend.CreateVideoDecoder(); - ASSERT_THAT(video_decoder, NotNull()); - video_decoder->SetConfig(VideoConfig()); - - EXPECT_TRUE(backend.Initialize()); -} - -TEST_F(MediaPipelineBackendStarboardTest, - DoesNotSetMaxVideoCapabilitiesToStreamingForSyncPtsSyncType) { - EXPECT_CALL(*starboard_, EnsureInitialized).WillOnce(Return(true)); - EXPECT_CALL(*starboard_, - CreatePlayer( - AllOf(NotNull(), Not(CreationParamHasStreamingEnabled())), _)) - .WillOnce(Return(&fake_player_)); - - MediaPipelineDeviceParams device_params = device_params_; - device_params.sync_type = - MediaPipelineDeviceParams::MediaSyncType::kModeSyncPts; - MediaPipelineBackendStarboard backend(device_params, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - - // We need to create a video decoder in order for video params to be set when - // creating the SbPlayer. - MediaPipelineBackend::VideoDecoder* video_decoder = - backend.CreateVideoDecoder(); - ASSERT_THAT(video_decoder, NotNull()); - video_decoder->SetConfig(VideoConfig()); - - EXPECT_TRUE(backend.Initialize()); -} - -TEST_F(MediaPipelineBackendStarboardTest, - HandlesGeometryChangeAfterPlayerCreation) { - EXPECT_CALL(*starboard_, CreatePlayer).WillOnce(Return(&fake_player_)); - EXPECT_CALL(*starboard_, SetPlayerBounds(&fake_player_, 0, 1, 2, 1920, 1080)); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - - MediaPipelineBackend::VideoDecoder* video_decoder = - backend.CreateVideoDecoder(); - - // The video's width and height match the display's aspect ratio (set above). - // Thus, the player's bound should be set to the full screen, 1920x1080. - VideoConfig config = GetBasicVideoConfig(); - config.width = 1280; - config.height = 720; - video_decoder->SetConfig(config); - - EXPECT_TRUE(backend.Initialize()); - - video_plane_.SetGeometry(RectF(1, 2, 1920, 1080), - StarboardVideoPlane::Transform::TRANSFORM_NONE); - task_environment_.RunUntilIdle(); -} - -TEST_F(MediaPipelineBackendStarboardTest, - HandlesGeometryChangeBeforePlayerCreation) { - EXPECT_CALL(*starboard_, CreatePlayer).WillOnce(Return(&fake_player_)); - EXPECT_CALL(*starboard_, SetPlayerBounds(&fake_player_, 0, 3, 4, 1920, 1080)); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - - MediaPipelineBackend::VideoDecoder* video_decoder = - backend.CreateVideoDecoder(); - - // The video's width and height match the display's aspect ratio (set above). - // Thus, the player's bound should be set to the full screen, 1920x1080. - VideoConfig config = GetBasicVideoConfig(); - config.width = 1280; - config.height = 720; - video_decoder->SetConfig(config); - - video_plane_.SetGeometry(RectF(3, 4, 1920, 1080), - StarboardVideoPlane::Transform::TRANSFORM_NONE); - task_environment_.RunUntilIdle(); - - // Calling Initialize should trigger the call to set the player's bounds. - EXPECT_TRUE(backend.Initialize()); -} - -TEST_F(MediaPipelineBackendStarboardTest, DestroysPlayerOnDestruction) { - EXPECT_CALL(*starboard_, DestroyPlayer(&fake_player_)).Times(1); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - EXPECT_TRUE(backend.Initialize()); -} - -TEST_F(MediaPipelineBackendStarboardTest, - DoesNotCallDestroyPlayerIfNotInitialized) { - EXPECT_CALL(*starboard_, DestroyPlayer).Times(0); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); -} - -TEST_F(MediaPipelineBackendStarboardTest, SeeksToBeginningOnStart) { - constexpr int64_t start_time = 0; - - EXPECT_CALL(*starboard_, SeekTo(&fake_player_, start_time, _)).Times(1); - EXPECT_CALL(*starboard_, SetPlaybackRate(&fake_player_, DoubleEq(1.0))) - .Times(1); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - CHECK(backend.Initialize()); - EXPECT_TRUE(backend.Start(start_time)); -} - -TEST_F(MediaPipelineBackendStarboardTest, SeeksToMidPointOnStart) { - constexpr int64_t start_time = 10; - - EXPECT_CALL(*starboard_, SeekTo(&fake_player_, start_time, _)).Times(1); - EXPECT_CALL(*starboard_, SetPlaybackRate(&fake_player_, DoubleEq(1.0))) - .Times(1); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - CHECK(backend.Initialize()); - EXPECT_TRUE(backend.Start(start_time)); -} - -TEST_F(MediaPipelineBackendStarboardTest, SetsPlaybackRateToZeroOnPause) { - EXPECT_CALL(*starboard_, SetPlaybackRate(&fake_player_, DoubleEq(1.0))) - .Times(AnyNumber()); - // Pausing playback means setting the playback rate to 0 in starboard. - EXPECT_CALL(*starboard_, SetPlaybackRate(&fake_player_, DoubleEq(0.0))) - .Times(1); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - CHECK(backend.Initialize()); - CHECK(backend.Start(0)); - - EXPECT_TRUE(backend.Pause()); -} - -TEST_F(MediaPipelineBackendStarboardTest, - SetsPlaybackRateToPreviousValueOnResume) { - constexpr double playback_rate = 2.0; - - // This should be called when playback is paused. - EXPECT_CALL(*starboard_, GetPlayerInfo) - .WillRepeatedly(WithArg<1>([](StarboardPlayerInfo* player_info) { - CHECK(player_info); - player_info->playback_rate = playback_rate; - })); - - EXPECT_CALL(*starboard_, SetPlaybackRate(&fake_player_, DoubleEq(1.0))) - .Times(AnyNumber()); - // This should be called twice: once when we set the playback rate, and once - // when we resume playback. - EXPECT_CALL(*starboard_, - SetPlaybackRate(&fake_player_, DoubleEq(playback_rate))) - .Times(2); - // This should be called when we pause playback. - EXPECT_CALL(*starboard_, SetPlaybackRate(&fake_player_, DoubleEq(0.0))) - .Times(1); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - CHECK(backend.Initialize()); - CHECK(backend.Start(0)); - - EXPECT_TRUE(backend.SetPlaybackRate(playback_rate)); - EXPECT_TRUE(backend.Pause()); - EXPECT_TRUE(backend.Resume()); -} - -TEST_F(MediaPipelineBackendStarboardTest, GetsCurrentPts) { - constexpr int64_t current_pts = 123; - - EXPECT_CALL(*starboard_, GetPlayerInfo) - .WillRepeatedly(WithArg<1>([](StarboardPlayerInfo* player_info) { - CHECK(player_info); - player_info->current_media_timestamp_micros = current_pts; - player_info->playback_rate = 1.0; - })); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - CHECK(backend.Initialize()); - CHECK(backend.Start(0)); - - EXPECT_EQ(backend.GetCurrentPts(), current_pts); -} - -TEST_F(MediaPipelineBackendStarboardTest, - CallsDelegateEndOfStreamWhenStarboardReportsEoS) { - const StarboardPlayerCallbackHandler* callback_handler = nullptr; - EXPECT_CALL(*starboard_, CreatePlayer) - .WillOnce(DoAll(SaveArg<1>(&callback_handler), Return(&fake_player_))); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - - MediaPipelineBackend::AudioDecoder* audio_decoder = - backend.CreateAudioDecoder(); - MediaPipelineBackend::VideoDecoder* video_decoder = - backend.CreateVideoDecoder(); - - ASSERT_THAT(audio_decoder, NotNull()); - ASSERT_THAT(video_decoder, NotNull()); - audio_decoder->SetConfig(GetBasicAudioConfig()); - video_decoder->SetConfig(GetBasicVideoConfig()); - - MockDelegate audio_delegate; - MockDelegate video_delegate; - EXPECT_CALL(audio_delegate, OnEndOfStream).Times(1); - EXPECT_CALL(video_delegate, OnEndOfStream).Times(1); - - audio_decoder->SetDelegate(&audio_delegate); - video_decoder->SetDelegate(&video_delegate); - - CHECK(backend.Initialize()); - CHECK(backend.Start(0)); - - ASSERT_THAT(callback_handler, NotNull()); - - // This should trigger the calls to audio_delegate.OnEndOfStream() and - // video_delegate.OnEndOfStream(). - callback_handler->player_status_fn(&fake_player_, callback_handler->context, - kStarboardPlayerStateEndOfStream, - /*ticket=*/1); - Mock::VerifyAndClearExpectations(&audio_delegate); - Mock::VerifyAndClearExpectations(&video_delegate); -} - -TEST_F(MediaPipelineBackendStarboardTest, - DelegatesAreNotifiedOnStarboardDecoderError) { - const StarboardPlayerCallbackHandler* callback_handler = nullptr; - EXPECT_CALL(*starboard_, CreatePlayer) - .WillOnce(DoAll(SaveArg<1>(&callback_handler), Return(&fake_player_))); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - - MediaPipelineBackend::AudioDecoder* audio_decoder = - backend.CreateAudioDecoder(); - MediaPipelineBackend::VideoDecoder* video_decoder = - backend.CreateVideoDecoder(); - - ASSERT_THAT(audio_decoder, NotNull()); - ASSERT_THAT(video_decoder, NotNull()); - audio_decoder->SetConfig(GetBasicAudioConfig()); - video_decoder->SetConfig(GetBasicVideoConfig()); - - MockDelegate audio_delegate; - MockDelegate video_delegate; - EXPECT_CALL(audio_delegate, OnDecoderError).Times(1); - EXPECT_CALL(video_delegate, OnDecoderError).Times(1); - - audio_decoder->SetDelegate(&audio_delegate); - video_decoder->SetDelegate(&video_delegate); - - CHECK(backend.Initialize()); - CHECK(backend.Start(0)); - - ASSERT_THAT(callback_handler, NotNull()); - - // This should trigger the calls to audio_delegate.OnDecoderError() and - // video_delegate.OnDecoderError(). - callback_handler->player_error_fn(&fake_player_, callback_handler->context, - kStarboardPlayerErrorDecode, - "A decoder error occurred"); - Mock::VerifyAndClearExpectations(&audio_delegate); - Mock::VerifyAndClearExpectations(&video_delegate); -} - -TEST_F(MediaPipelineBackendStarboardTest, - DelegatesAreNotNotifiedOnUnrelatedError) { - const StarboardPlayerCallbackHandler* callback_handler = nullptr; - EXPECT_CALL(*starboard_, CreatePlayer) - .WillOnce(DoAll(SaveArg<1>(&callback_handler), Return(&fake_player_))); - - MediaPipelineBackendStarboard backend(device_params_, &video_plane_); - backend.TestOnlySetStarboardApiWrapper(std::move(starboard_)); - - MediaPipelineBackend::AudioDecoder* audio_decoder = - backend.CreateAudioDecoder(); - MediaPipelineBackend::VideoDecoder* video_decoder = - backend.CreateVideoDecoder(); - - ASSERT_THAT(audio_decoder, NotNull()); - ASSERT_THAT(video_decoder, NotNull()); - audio_decoder->SetConfig(GetBasicAudioConfig()); - video_decoder->SetConfig(GetBasicVideoConfig()); - - MockDelegate audio_delegate; - MockDelegate video_delegate; - EXPECT_CALL(audio_delegate, OnDecoderError).Times(0); - EXPECT_CALL(video_delegate, OnDecoderError).Times(0); - - audio_decoder->SetDelegate(&audio_delegate); - video_decoder->SetDelegate(&video_delegate); - - CHECK(backend.Initialize()); - CHECK(backend.Start(0)); - - ASSERT_THAT(callback_handler, NotNull()); - - // This should NOT trigger the calls to audio_delegate.OnDecoderError() and - // video_delegate.OnDecoderError(), since it's not a decoder error. - callback_handler->player_error_fn(&fake_player_, callback_handler->context, - kStarboardPlayerErrorCapabilityChanged, - "Starboard capabilities changed"); - Mock::VerifyAndClearExpectations(&audio_delegate); - Mock::VerifyAndClearExpectations(&video_delegate); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/mime_utils.cc chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/mime_utils.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/mime_utils.h" - -#include "base/logging.h" -#include "base/strings/stringprintf.h" - -namespace chromecast { -namespace media { - -namespace { - -// Returns a MIME string for HEVC dolby vision. -// -// Returns an empty string if the MIME type is not supported by cast, or if it -// cannot be determined. -std::string GetHEVCDolbyVisionMimeType(VideoProfile profile, uint32_t level) { - if (level >= 10 || level == 0) { - // Note: there ARE valid dolby vision levels > 10, but they are not - // officially supported by cast. See - // https://developers.google.com/cast/docs/media and - // https://professionalsupport.dolby.com/s/article/What-is-Dolby-Vision-Profile?language=en_US - LOG(INFO) << "Unsupported dolby vision level: " << level; - return ""; - } - - int profile_int = 0; - - // According to - // https://professional.dolby.com/siteassets/content-creation/dolby-vision-for-content-creators/dolbyvisioninmpegdashspecification_v2_0_public_20190107.pdf, - // only profiles 5 and 8 are supported for online streaming. - switch (profile) { - case kDolbyVisionProfile5: - profile_int = 5; - break; - case kDolbyVisionProfile8: - profile_int = 8; - break; - default: - LOG(INFO) << "Unsupported dolby vision profile: " << profile; - return ""; - } - - // 'level' is exactly one digit, due to the above check. - return base::StringPrintf(R"-(video/mp4; codecs="dvhe.0%d.0%d")-", - profile_int, level); -} - -} // namespace - -std::string GetMimeType(VideoCodec codec, - VideoProfile profile, - uint32_t level) { - if (codec == kCodecDolbyVisionHEVC) { - return GetHEVCDolbyVisionMimeType(profile, level); - } - return ""; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/mime_utils.h chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/mime_utils.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_MIME_UTILS_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_MIME_UTILS_H_ - -#include -#include - -#include "chromecast/public/media/decoder_config.h" - -namespace chromecast { -namespace media { - -// TODO(b/275430044): Add support for all codecs here. For now, we only need -// this for Dolby Vision. -// -// Returns the MIME string for the given codec/profile/level. Container is -// guessed in a way that should be compatible with Starboard's checks (e.g. for -// HEVC we guess MP4). Ideally Starboard should not care about the container, -// since they do not handle demuxing. -// -// If a MIME type cannot be determined, an empty string is returned. -std::string GetMimeType(VideoCodec codec, VideoProfile profile, uint32_t level); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_MIME_UTILS_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/mime_utils_test.cc chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils_test.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/mime_utils_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/mime_utils_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/mime_utils.h" - -#include -#include - -#include "chromecast/public/media/decoder_config.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::StrEq; - -// Holds codec info and the corresponding mime type. -struct CodecInfoAndMime { - CodecProfileLevel codec_profile_level; - std::string mime; -}; - -// Returns a list of supported codecs and the corresponding MIME strings. See -// https://developers.google.com/cast/docs/media for supported codecs. -// -// TODO(b/275430044): expand this to cover all supported codecs. -std::vector GetCodecMimeValues() { - std::vector out; - // Profile 5. - out.push_back({.codec_profile_level = {.codec = kCodecDolbyVisionHEVC, - .profile = kDolbyVisionProfile5, - .level = 6}, - .mime = R"-(video/mp4; codecs="dvhe.05.06")-"}); - out.push_back({.codec_profile_level = {.codec = kCodecDolbyVisionHEVC, - .profile = kDolbyVisionProfile5, - .level = 7}, - .mime = R"-(video/mp4; codecs="dvhe.05.07")-"}); - out.push_back({.codec_profile_level = {.codec = kCodecDolbyVisionHEVC, - .profile = kDolbyVisionProfile5, - .level = 9}, - .mime = R"-(video/mp4; codecs="dvhe.05.09")-"}); - - // Profile 8. - out.push_back({.codec_profile_level = {.codec = kCodecDolbyVisionHEVC, - .profile = kDolbyVisionProfile8, - .level = 6}, - .mime = R"-(video/mp4; codecs="dvhe.08.06")-"}); - out.push_back({.codec_profile_level = {.codec = kCodecDolbyVisionHEVC, - .profile = kDolbyVisionProfile8, - .level = 7}, - .mime = R"-(video/mp4; codecs="dvhe.08.07")-"}); - out.push_back({.codec_profile_level = {.codec = kCodecDolbyVisionHEVC, - .profile = kDolbyVisionProfile8, - .level = 9}, - .mime = R"-(video/mp4; codecs="dvhe.08.09")-"}); - - // Unsupported cases should return an empty string for the MIME type. - out.push_back({.codec_profile_level = {.codec = kCodecDolbyVisionHEVC, - .profile = kDolbyVisionProfile5, - .level = 11}, - .mime = ""}); - out.push_back({.codec_profile_level = {.codec = kCodecDolbyVisionHEVC, - .profile = kDolbyVisionProfile8, - .level = 11}, - .mime = ""}); - return out; -} - -// The parameter is a codec/profile/level and the corresponding MIME type. -using MimeUtilsTest = ::testing::TestWithParam; - -TEST_P(MimeUtilsTest, ConvertsToMimeType) { - const CodecProfileLevel codec_profile_level = GetParam().codec_profile_level; - const std::string expected_mime = GetParam().mime; - - EXPECT_THAT( - GetMimeType(codec_profile_level.codec, codec_profile_level.profile, - codec_profile_level.level), - StrEq(expected_mime)); -} - -INSTANTIATE_TEST_SUITE_P(MimeTypes, - MimeUtilsTest, - ::testing::ValuesIn(GetCodecMimeValues())); - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/mock_starboard_api_wrapper.cc chromium-132.0.6834.159/chromecast/starboard/media/media/mock_starboard_api_wrapper.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/mock_starboard_api_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/mock_starboard_api_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/mock_starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -MockStarboardApiWrapper::MockStarboardApiWrapper() = default; -MockStarboardApiWrapper::~MockStarboardApiWrapper() = default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/mock_starboard_api_wrapper.h chromium-132.0.6834.159/chromecast/starboard/media/media/mock_starboard_api_wrapper.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/mock_starboard_api_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/mock_starboard_api_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_MOCK_STARBOARD_API_WRAPPER_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_MOCK_STARBOARD_API_WRAPPER_H_ - -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace chromecast { -namespace media { - -class MockStarboardApiWrapper : public StarboardApiWrapper { - public: - MockStarboardApiWrapper(); - ~MockStarboardApiWrapper() override; - - MOCK_METHOD(bool, EnsureInitialized, (), (override)); - - MOCK_METHOD(void*, - CreatePlayer, - (const StarboardPlayerCreationParam* creation_param, - const StarboardPlayerCallbackHandler* callback_handler), - (override)); - MOCK_METHOD(void, - SetPlayerBounds, - (void* player, int z_index, int x, int y, int width, int height), - (override)); - MOCK_METHOD(void, - SeekTo, - (void* player, int64_t time, int seek_ticket), - (override)); - MOCK_METHOD(void, - WriteSample, - (void* player, - StarboardMediaType type, - StarboardSampleInfo* sample_infos, - int sample_infos_count), - (override)); - MOCK_METHOD(void, - WriteEndOfStream, - (void* player, StarboardMediaType type), - (override)); - MOCK_METHOD(void, - GetPlayerInfo, - (void* player, StarboardPlayerInfo* player_info), - (override)); - MOCK_METHOD(void, SetVolume, (void* player, double volume), (override)); - MOCK_METHOD(bool, - SetPlaybackRate, - (void* player, double playback_rate), - (override)); - MOCK_METHOD(void, DestroyPlayer, (void* player), (override)); - - MOCK_METHOD(void*, - CreateDrmSystem, - (const char* key_system, - const StarboardDrmSystemCallbackHandler* callback_handler), - (override)); - MOCK_METHOD(void, - DrmGenerateSessionUpdateRequest, - (void* drm_system, - int ticket, - const char* type, - const void* initialization_data, - int initialization_data_size), - (override)); - MOCK_METHOD(void, - DrmUpdateSession, - (void* drm_system, - int ticket, - const void* key, - int key_size, - const void* session_id, - int session_id_size), - (override)); - MOCK_METHOD(void, - DrmCloseSession, - (void* drm_system, const void* session_id, int session_id_size), - (override)); - MOCK_METHOD(void, - DrmUpdateServerCertificate, - (void* drm_system, - int ticket, - const void* certificate, - int certificate_size), - (override)); - MOCK_METHOD(bool, - DrmIsServerCertificateUpdatable, - (void* drm_system), - (override)); - MOCK_METHOD(void, DrmDestroySystem, (void* drm_system), (override)); - MOCK_METHOD(StarboardMediaSupportType, - CanPlayMimeAndKeySystem, - (const char* mime, const char* key_system), - (override)); -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_MOCK_STARBOARD_API_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -StarboardApiWrapper::~StarboardApiWrapper() = default; - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper.h chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,517 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// The structs/enums in this file represent corresponding structs/enums in -// starboard. By using these types instead of Starboard's, we can abstract away -// minor changes (e.g. function renames) in Starboard without having to change -// the rest of the MediaPipelineBackend. Additionally, these types can be -// converted to different version-specific Starboard types. -// -// Users of this header should interact with Starboard via a StarboardApiWrapper -// created via GetStarboardApiWrapper(). For testing purposes, a mock -// StarboardApiWrapper can be used instead. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_API_WRAPPER_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_API_WRAPPER_H_ - -#include -#include -#include - -namespace chromecast { -namespace media { - -// Copy of SbMediaSupportType from starboard. -enum StarboardMediaSupportType { - kStarboardMediaSupportTypeNotSupported, - kStarboardMediaSupportTypeMaybe, - kStarboardMediaSupportTypeProbably, -}; - -// Copy of SbMediaType from starboard. -enum StarboardMediaType { - kStarboardMediaTypeAudio, - kStarboardMediaTypeVideo, -}; - -// Copy of SbMediaAudioCodec from starboard. -enum StarboardAudioCodec { - kStarboardAudioCodecNone, - kStarboardAudioCodecAac, - kStarboardAudioCodecAc3, - kStarboardAudioCodecEac3, - kStarboardAudioCodecOpus, - kStarboardAudioCodecVorbis, - kStarboardAudioCodecMp3, - kStarboardAudioCodecFlac, - kStarboardAudioCodecPcm, -}; - -// Copy of SbMediaVideoCodec from starboard. -enum StarboardVideoCodec { - kStarboardVideoCodecNone, - kStarboardVideoCodecH264, - kStarboardVideoCodecH265, - kStarboardVideoCodecMpeg2, - kStarboardVideoCodecTheora, - kStarboardVideoCodecVc1, - kStarboardVideoCodecAv1, - kStarboardVideoCodecVp8, - kStarboardVideoCodecVp9, -}; - -// Copy of SbPlayerSampleSideDataType from starboard. -enum StarboardSampleSideDataType { - kStarboardSampleSideDataTypeMatroskaBlockAdditional, -}; - -// Copy of SbPlayerDecoderState from starboard. -enum StarboardDecoderState { - kStarboardDecoderStateNeedsData, -}; - -// Copy of SbPlayerOutputMode from starboard. -enum StarboardPlayerOutputMode { - kStarboardPlayerOutputModeDecodeToTexture, - kStarboardPlayerOutputModePunchOut, - kStarboardPlayerOutputModeInvalid, -}; - -// Copy of SbPlayerState from starboard. -enum StarboardPlayerState { - kStarboardPlayerStateInitialized, - kStarboardPlayerStatePrerolling, - kStarboardPlayerStatePresenting, - kStarboardPlayerStateEndOfStream, - kStarboardPlayerStateDestroyed, -}; - -// Copy of SbPlayerError from starboard. -enum StarboardPlayerError { - kStarboardPlayerErrorDecode, - kStarboardPlayerErrorCapabilityChanged, - kStarboardPlayerErrorMax, -}; - -// Copy of SbDrmEncryptionScheme from starboard. -enum StarboardDrmEncryptionScheme { - kStarboardDrmEncryptionSchemeAesCtr, - kStarboardDrmEncryptionSchemeAesCbc, -}; - -// Copy of SbDrmStatus from starboard. -enum StarboardDrmStatus { - kStarboardDrmStatusSuccess, - kStarboardDrmStatusTypeError, - kStarboardDrmStatusNotSupportedError, - kStarboardDrmStatusInvalidStateError, - kStarboardDrmStatusQuotaExceededError, - kStarboardDrmStatusUnknownError, -}; - -// Copy of SbDrmSessionRequestType from starboard. -enum StarboardDrmSessionRequestType { - kStarboardDrmSessionRequestTypeLicenseRequest, - kStarboardDrmSessionRequestTypeLicenseRenewal, - kStarboardDrmSessionRequestTypeLicenseRelease, - kStarboardDrmSessionRequestTypeIndividualizationRequest, -}; - -// Copy of SbDrmKeyStatus from starboard. -enum StarboardDrmKeyStatus { - kStarboardDrmKeyStatusUsable, - kStarboardDrmKeyStatusExpired, - kStarboardDrmKeyStatusReleased, - kStarboardDrmKeyStatusRestricted, - kStarboardDrmKeyStatusDownscaled, - kStarboardDrmKeyStatusPending, - kStarboardDrmKeyStatusError, -}; - -// Copy of SbMediaMasteringMetadata from starboard. -struct StarboardMediaMasteringMetadata { - float primary_r_chromaticity_x; - float primary_r_chromaticity_y; - float primary_g_chromaticity_x; - float primary_g_chromaticity_y; - float primary_b_chromaticity_x; - float primary_b_chromaticity_y; - float white_point_chromaticity_x; - float white_point_chromaticity_y; - float luminance_max; - float luminance_min; -}; - -// Copy of SbMediaMasteringMetadata from starboard. -struct StarboardColorMetadata { - unsigned int bits_per_channel; - unsigned int chroma_subsampling_horizontal; - unsigned int chroma_subsampling_vertical; - unsigned int cb_subsampling_horizontal; - unsigned int cb_subsampling_vertical; - unsigned int chroma_siting_horizontal; - unsigned int chroma_siting_vertical; - StarboardMediaMasteringMetadata mastering_metadata; - unsigned int max_cll; - unsigned int max_fall; - // See SbMediaPrimaryId from starboard. - int primaries; - // See SbMediaTransferId from starboard. - int transfer; - // See SbMediaMatrixId from starboard. - int matrix; - // See SbMediaRangeId from starboard. - int range; - float custom_primary_matrix[12]; -}; - -// Copy of SbMediaAudioSampleInfo from starboard. -struct StarboardAudioSampleInfo { - StarboardAudioCodec codec; - const char* mime; - uint16_t format_tag; - uint16_t number_of_channels; - uint32_t samples_per_second; - uint32_t average_bytes_per_second; - uint16_t block_alignment; - uint16_t bits_per_sample; - uint16_t audio_specific_config_size; - const void* audio_specific_config; -}; - -// Copy of SbMediaVideoSampleInfo from starboard. -struct StarboardVideoSampleInfo { - StarboardVideoCodec codec; - const char* mime; - const char* max_video_capabilities; - bool is_key_frame; - int frame_width; - int frame_height; - StarboardColorMetadata color_metadata; -}; - -// Copy of SbPlayerSampleSideData from starboard. -struct StarboardSampleSideData { - StarboardSampleSideDataType type; - const uint8_t* data; - size_t size; -}; - -// Copy of SbDrmEncryptionPattern from starboard. -struct StarboardDrmEncryptionPattern { - uint32_t crypt_byte_block; - uint32_t skip_byte_block; -}; - -// Copy of SbDrmSubSampleMapping from starboard. -struct StarboardDrmSubSampleMapping { - // How many bytes of the corresponding subsample are not encrypted - int32_t clear_byte_count; - - // How many bytes of the corresponding subsample are encrypted. - int32_t encrypted_byte_count; -}; - -// Copy of SbDrmSampleInfo from starboard. -struct StarboardDrmSampleInfo { - StarboardDrmEncryptionScheme encryption_scheme; - - // The encryption pattern of this sample. - StarboardDrmEncryptionPattern encryption_pattern; - - // The Initialization Vector needed to decrypt this sample. - uint8_t initialization_vector[16]; - int initialization_vector_size; - - // The ID of the license (or key) required to decrypt this sample. For - // PlayReady, this is the license GUID in packed little-endian binary form. - uint8_t identifier[16]; - int identifier_size; - - // The number of subsamples in this sample, must be at least 1. - int32_t subsample_count; - - // The clear/encrypted mapping of each subsample in this sample. This must be - // an array of |subsample_count| mappings. - const StarboardDrmSubSampleMapping* subsample_mapping; -}; - -// Copy of SbPlayerSampleInfo from starboard. -struct StarboardSampleInfo { - // See SbMediaType. - int type; - // Points to the buffer containing the sample data. - const void* buffer; - // Size of the data pointed to by |buffer|. - int buffer_size; - // The timestamp of the sample. - int64_t timestamp; - // Points to an array of side data for the input, when available. - StarboardSampleSideData* side_data; - // The number of side data pointed by |side_data|. It should be set to 0 if - // there is no side data for the input. - int side_data_count; - union { - // Information about an audio sample. This value can only be used when - // |type| is kSbMediaTypeAudio. - StarboardAudioSampleInfo audio_sample_info; - // Information about a video sample. This value can only be used when |type| - // is kSbMediaTypeVideo. - StarboardVideoSampleInfo video_sample_info; - }; - // The DRM system related info for the media sample. This value is required - // for encrypted samples. Otherwise, it must be |NULL|. - const StarboardDrmSampleInfo* drm_info; -}; - -// Copy of SbPlayerCreationParam from starboard. -struct StarboardPlayerCreationParam { - // Note: a DRM system is not included in this struct. Due to the architecture - // of cast, the MediaPipelineBackend does not have direct access to the CDM. - // So instead we pass a global to Starboard (in starboard_media_api.cc). - - // Contains a populated SbMediaAudioSampleInfo if |audio_sample_info.codec| - // isn't |kSbMediaAudioCodecNone|. When |audio_sample_info.codec| is - // |kSbMediaAudioCodecNone|, the video doesn't have an audio track. - StarboardAudioSampleInfo audio_sample_info; - - // Contains a populated SbMediaVideoSampleInfo if |video_sample_info.codec| - // isn't |kSbMediaVideoCodecNone|. When |video_sample_info.codec| is - // |kSbMediaVideoCodecNone|, the video is audio only. - StarboardVideoSampleInfo video_sample_info; - - // Selects how the decoded video frames will be output. For example, - // |kSbPlayerOutputModePunchOut| indicates that the decoded video frames will - // be output to a background video layer by the platform, and - // |kSbPlayerOutputDecodeToTexture| indicates that the decoded video frames - // should be made available for the application to pull via calls to - // SbPlayerGetCurrentFrame(). - StarboardPlayerOutputMode output_mode; -}; - -// Copy of SbPlayerInfo2 from starboard. -struct StarboardPlayerInfo { - // The position of the playback head, as precisely as possible, in - // microseconds. - int64_t current_media_timestamp_micros; - // The known duration of the currently playing media stream, in microseconds. - int64_t duration_micros; - // The result of getStartDate for the currently playing media stream, in - // microseconds since the epoch of January 1, 1601 UTC. - int64_t start_date; - // The width of the currently displayed frame, in pixels, or 0 if not provided - // by this player. - int frame_width; - // The height of the currently displayed frame, in pixels, or 0 if not - // provided by this player. - int frame_height; - // Whether playback is currently paused. - bool is_paused; - // The current player volume in [0, 1]. - double volume; - // The number of video frames sent to the player since the creation of the - // player. - int total_video_frames; - // The number of video frames decoded but not displayed since the creation of - // the player. - int dropped_video_frames; - // The number of video frames that failed to be decoded since the creation of - // the player. - int corrupted_video_frames; - // The rate of playback. The video is played back in a speed that is - // proportional to this. By default it is 1.0 which indicates that the - // playback is at normal speed. When it is greater than one, the video is - // played in a faster than normal speed. When it is less than one, the video - // is played in a slower than normal speed. Negative speeds are not supported. - double playback_rate; -}; - -// Copy of SbDrmKeyId from starboard. -struct StarboardDrmKeyId { - uint8_t identifier[16]; - int identifier_size; -}; - -// Copy of SbPlayerDecoderStatusFunc from starboard. -using StarboardPlayerDecoderStatusFunc = - void (*)(void* player, - void* context, - StarboardMediaType type, - StarboardDecoderState decoder_state, - int ticket); - -// Copy of SbPlayerDeallocateSampleFunc from starboard. -using StarboardPlayerDeallocateSampleFunc = void (*)(void* player, - void* context, - const void* sample_buffer); - -// Copy of SbPlayerStatusFunc from starboard. -using StarboardPlayerStatusFunc = void (*)(void* player, - void* context, - StarboardPlayerState state, - int ticket); - -// Copy of SbPlayerErrorFunc from starboard. -using StarboardPlayerErrorFunc = void (*)(void* player, - void* context, - StarboardPlayerError error, - const char* message); - -// Copy of SbDrmSessionUpdateRequestFunc from starboard. -using StarboardDrmSessionUpdateRequestFunc = - void (*)(void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - StarboardDrmSessionRequestType type, - const char* error_message, - const void* session_id, - int session_id_size, - const void* content, - int content_size, - const char* url); - -// Copy of SbDrmSessionUpdatedFunc from starboard. -using StarboardDrmSessionUpdatedFunc = void (*)(void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - const char* error_message, - const void* session_id, - int session_id_size); - -// Copy of SbDrmSessionKeyStatusesChangedFunc from starboard. -using StarboardDrmSessionKeyStatusesChangedFunc = - void (*)(void* drm_system, - void* context, - const void* session_id, - int session_id_size, - int number_of_keys, - const StarboardDrmKeyId* key_ids, - const StarboardDrmKeyStatus* key_statuses); - -// Copy of SbDrmServerCertificateUpdatedFunc from starboard. -using StarboardDrmServerCertificateUpdatedFunc = - void (*)(void* drm_system, - void* context, - int ticket, - StarboardDrmStatus status, - const char* error_message); - -// Copy of SbDrmSessionClosedFunc from starboard. -using StarboardDrmSessionClosedFunc = void (*)(void* drm_system, - void* context, - const void* session_id, - int session_id_size); - -// A wrapper for the player-related callbacks that starboard calls. -struct StarboardPlayerCallbackHandler { - // The context that will be passed to all functions. - void* context; - StarboardPlayerDecoderStatusFunc decoder_status_fn; - StarboardPlayerDeallocateSampleFunc deallocate_sample_fn; - StarboardPlayerStatusFunc player_status_fn; - StarboardPlayerErrorFunc player_error_fn; -}; - -// A wrapper for the DRM-related callbacks that starboard calls. -struct StarboardDrmSystemCallbackHandler { - // The context that will be passed to all functions. - void* context; - StarboardDrmSessionUpdateRequestFunc update_request_fn; - StarboardDrmSessionUpdatedFunc session_updated_fn; - StarboardDrmSessionKeyStatusesChangedFunc key_statuses_changed_fn; - StarboardDrmServerCertificateUpdatedFunc server_certificate_updated_fn; - StarboardDrmSessionClosedFunc session_closed_fn; -}; - -// A wrapper around the Starboard API, allowing a mock to be used for testing. -// It also abstracts away details specific to certain versions of Starboard, by -// utilizing the structs defined above. Internally, those structs will be -// converted to the relevant starboard structs for the given starboard version. -class StarboardApiWrapper { - public: - virtual ~StarboardApiWrapper(); - - // This function matches the EnsureInitialized function in - // cast_starboard_api_adapter.h. It blocks until Starboard has started and - // returns true, or returns false if initialization fails. - // - // This function is included in this wrapper so we can avoid calling the - // production implementation in unit tests, thus removing a dependency on - // Starboard. - virtual bool EnsureInitialized() = 0; - - // Version-agnostic functions for SbPlayer. See starboard/player.h for more - // info about the corresponding functions. - // - // StarboardPlayerCallbackHandler is used to wrap multiple callbacks that are - // passed to starboard. - virtual void* CreatePlayer( - const StarboardPlayerCreationParam* creation_param, - const StarboardPlayerCallbackHandler* callback_handler) = 0; - virtual void SetPlayerBounds(void* player, - int z_index, - int x, - int y, - int width, - int height) = 0; - virtual void SeekTo(void* player, int64_t time, int seek_ticket) = 0; - virtual void WriteSample(void* player, - StarboardMediaType type, - StarboardSampleInfo* sample_infos, - int sample_infos_count) = 0; - virtual void WriteEndOfStream(void* player, StarboardMediaType type) = 0; - virtual void GetPlayerInfo(void* player, - StarboardPlayerInfo* player_info) = 0; - virtual void SetVolume(void* player, double volume) = 0; - virtual bool SetPlaybackRate(void* player, double playback_rate) = 0; - virtual void DestroyPlayer(void* player) = 0; - - // Version-agnostic functions for SbDrmSystem. See starboard/drm.h for more - // info about the corresponding functions. - // - // StarboardDrmSystemCallbackHandler is used to wrap multiple callbacks that - // are passed to starboard. - virtual void* CreateDrmSystem( - const char* key_system, - const StarboardDrmSystemCallbackHandler* callback_handler) = 0; - virtual void DrmGenerateSessionUpdateRequest( - void* drm_system, - int ticket, - const char* type, - const void* initialization_data, - int initialization_data_size) = 0; - virtual void DrmUpdateSession(void* drm_system, - int ticket, - const void* key, - int key_size, - const void* session_id, - int session_id_size) = 0; - virtual void DrmCloseSession(void* drm_system, - const void* session_id, - int session_id_size) = 0; - virtual void DrmUpdateServerCertificate(void* drm_system, - int ticket, - const void* certificate, - int certificate_size) = 0; - virtual bool DrmIsServerCertificateUpdatable(void* drm_system) = 0; - virtual void DrmDestroySystem(void* drm_system) = 0; - - // Version-agnostic functions for starboard/media.h. - virtual StarboardMediaSupportType CanPlayMimeAndKeySystem( - const char* mime, - const char* key_system) = 0; -}; - -// Returns a StarboardApiWrapper that calls into libcast_starboard_api.so. This -// function is defined for each starboard version supported by cast. For -// example, there is a starboard 15 version that calls the starboard 15 APIs, a -// starboard 14 version that calls the starboard 14 APIs, etc. -std::unique_ptr GetStarboardApiWrapper(); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_API_WRAPPER_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_14.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_14.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_14.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_14.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,166 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Defines APIs that are specific to Starboard 14. GetStarboardApiWrapper() is -// the public API; everything else is an implementation detail. -#include -#include -#include - -#include -#include - -#include "base/logging.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper_base.h" - -namespace chromecast { -namespace media { - -namespace { - -// A concrete implementation of StarboardApiWrapper for Starboard version 14. -class StarboardApiWrapper14 : public StarboardApiWrapperBase { - public: - StarboardApiWrapper14() = default; - ~StarboardApiWrapper14() override = default; - - // StarboardApiWrapper impl: - void SeekTo(void* player, int64_t time, int seek_ticket) override { - SbPlayerSeek2(static_cast(player), time, seek_ticket); - } - - void GetPlayerInfo(void* player, StarboardPlayerInfo* player_info) override { - SbPlayerInfo2 sb_player_info = {}; - SbPlayerGetInfo2(static_cast(player), &sb_player_info); - - player_info->current_media_timestamp_micros = - sb_player_info.current_media_timestamp; - player_info->duration_micros = sb_player_info.duration; - player_info->start_date = sb_player_info.start_date; - player_info->frame_width = sb_player_info.frame_width; - player_info->frame_height = sb_player_info.frame_height; - player_info->is_paused = sb_player_info.is_paused; - player_info->volume = sb_player_info.volume; - player_info->total_video_frames = sb_player_info.total_video_frames; - player_info->dropped_video_frames = sb_player_info.dropped_video_frames; - player_info->corrupted_video_frames = sb_player_info.corrupted_video_frames; - player_info->playback_rate = sb_player_info.playback_rate; - } - - private: - // StarboardApiWrapperBase impl: - SbPlayerCreationParam ToSbPlayerCreationParam( - const StarboardPlayerCreationParam& in_param, - void* drm_system) override { - SbPlayerCreationParam out_param = {}; - - out_param.audio_sample_info = - ToSbMediaAudioSampleInfo(in_param.audio_sample_info); - out_param.video_sample_info = - ToSbMediaVideoSampleInfo(in_param.video_sample_info); - out_param.output_mode = - static_cast(in_param.output_mode); - - if (drm_system) { - LOG(INFO) << "Using an SbDrmSystem for decryption."; - out_param.drm_system = static_cast(drm_system); - } else { - LOG(INFO) - << "No SbDrmSystem was created before SbPlayer; no decryption is " - "possible in starboard."; - out_param.drm_system = kSbDrmSystemInvalid; - } - - return out_param; - } - - SbMediaVideoSampleInfo ToSbMediaVideoSampleInfo( - const StarboardVideoSampleInfo& in_video_info) override { - SbMediaVideoSampleInfo out_video_info = {}; - - out_video_info.codec = static_cast(in_video_info.codec); - out_video_info.mime = in_video_info.mime; - out_video_info.max_video_capabilities = - in_video_info.max_video_capabilities; - out_video_info.is_key_frame = in_video_info.is_key_frame; - out_video_info.frame_width = in_video_info.frame_width; - out_video_info.frame_height = in_video_info.frame_height; - - const StarboardColorMetadata& in_color_metadata = - in_video_info.color_metadata; - SbMediaColorMetadata& out_color_metadata = out_video_info.color_metadata; - - out_color_metadata.bits_per_channel = in_color_metadata.bits_per_channel; - out_color_metadata.chroma_subsampling_horizontal = - in_color_metadata.chroma_subsampling_horizontal; - out_color_metadata.chroma_subsampling_vertical = - in_color_metadata.chroma_subsampling_vertical; - out_color_metadata.cb_subsampling_horizontal = - in_color_metadata.cb_subsampling_horizontal; - out_color_metadata.cb_subsampling_vertical = - in_color_metadata.cb_subsampling_vertical; - out_color_metadata.chroma_siting_horizontal = - in_color_metadata.chroma_siting_horizontal; - out_color_metadata.chroma_siting_vertical = - in_color_metadata.chroma_siting_vertical; - // note: we skip SbMediaMasteringMetadata - out_color_metadata.max_cll = in_color_metadata.max_cll; - out_color_metadata.max_fall = in_color_metadata.max_fall; - out_color_metadata.primaries = - static_cast(in_color_metadata.primaries); - out_color_metadata.transfer = - static_cast(in_color_metadata.transfer); - out_color_metadata.matrix = - static_cast(in_color_metadata.matrix); - out_color_metadata.range = - static_cast(in_color_metadata.range); - - static_assert(sizeof(out_color_metadata.custom_primary_matrix) == - sizeof(in_color_metadata.custom_primary_matrix), - "Struct field size mismatch (custom_primary_matrix)"); - memcpy(out_color_metadata.custom_primary_matrix, - in_color_metadata.custom_primary_matrix, - sizeof(out_color_metadata.custom_primary_matrix)); - - return out_video_info; - } - - SbMediaAudioSampleInfo ToSbMediaAudioSampleInfo( - const StarboardAudioSampleInfo& in_audio_info) override { - SbMediaAudioSampleInfo out_audio_info = {}; - - out_audio_info.codec = static_cast(in_audio_info.codec); - out_audio_info.mime = in_audio_info.mime; - out_audio_info.format_tag = in_audio_info.format_tag; - out_audio_info.number_of_channels = in_audio_info.number_of_channels; - out_audio_info.samples_per_second = in_audio_info.samples_per_second; - out_audio_info.average_bytes_per_second = - in_audio_info.average_bytes_per_second; - out_audio_info.block_alignment = in_audio_info.block_alignment; - out_audio_info.bits_per_sample = in_audio_info.bits_per_sample; - out_audio_info.audio_specific_config_size = - in_audio_info.audio_specific_config_size; - out_audio_info.audio_specific_config = in_audio_info.audio_specific_config; - - return out_audio_info; - } - - void CallWriteSamples(SbPlayer player, - SbMediaType sample_type, - const SbPlayerSampleInfo* sample_infos, - int number_of_sample_infos) override { - SbPlayerWriteSample2(player, sample_type, sample_infos, - number_of_sample_infos); - } -}; - -} // namespace - -// Note: declared in starboard_api_wrapper.h. -std::unique_ptr GetStarboardApiWrapper() { - return std::make_unique(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_15.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_15.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_15.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_15.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,178 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Defines APIs that are specific to Starboard 15. GetStarboardApiWrapper() is -// the public API; everything else is an implementation detail. -#include -#include -#include - -#include "base/logging.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper_base.h" - -namespace chromecast { -namespace media { - -namespace { - -// Populates a VideoStreamInfo struct from a StarboardVideoSampleInfo. -SbMediaVideoStreamInfo ToSbMediaVideoStreamInfo( - const StarboardVideoSampleInfo& in_video_info) { - SbMediaVideoStreamInfo out_video_info = {}; - - out_video_info.codec = static_cast(in_video_info.codec); - out_video_info.mime = in_video_info.mime; - out_video_info.max_video_capabilities = in_video_info.max_video_capabilities; - out_video_info.frame_width = in_video_info.frame_width; - out_video_info.frame_height = in_video_info.frame_height; - - const StarboardColorMetadata& in_color_metadata = - in_video_info.color_metadata; - SbMediaColorMetadata& out_color_metadata = out_video_info.color_metadata; - - out_color_metadata.bits_per_channel = in_color_metadata.bits_per_channel; - out_color_metadata.chroma_subsampling_horizontal = - in_color_metadata.chroma_subsampling_horizontal; - out_color_metadata.chroma_subsampling_vertical = - in_color_metadata.chroma_subsampling_vertical; - out_color_metadata.cb_subsampling_horizontal = - in_color_metadata.cb_subsampling_horizontal; - out_color_metadata.cb_subsampling_vertical = - in_color_metadata.cb_subsampling_vertical; - out_color_metadata.chroma_siting_horizontal = - in_color_metadata.chroma_siting_horizontal; - out_color_metadata.chroma_siting_vertical = - in_color_metadata.chroma_siting_vertical; - // note: we skip SbMediaMasteringMetadata - out_color_metadata.max_cll = in_color_metadata.max_cll; - out_color_metadata.max_fall = in_color_metadata.max_fall; - out_color_metadata.primaries = - static_cast(in_color_metadata.primaries); - out_color_metadata.transfer = - static_cast(in_color_metadata.transfer); - out_color_metadata.matrix = - static_cast(in_color_metadata.matrix); - out_color_metadata.range = - static_cast(in_color_metadata.range); - - static_assert(sizeof(out_color_metadata.custom_primary_matrix) == - sizeof(in_color_metadata.custom_primary_matrix), - "Struct field size mismatch (custom_primary_matrix)"); - memcpy(out_color_metadata.custom_primary_matrix, - in_color_metadata.custom_primary_matrix, - sizeof(out_color_metadata.custom_primary_matrix)); - - return out_video_info; -} - -// Populates an AudioStreamInfo struct from a StarboardAudioSampleInfo. -SbMediaAudioStreamInfo ToSbMediaAudioStreamInfo( - const StarboardAudioSampleInfo& in_audio_info) { - SbMediaAudioStreamInfo out_audio_info = {}; - - out_audio_info.codec = static_cast(in_audio_info.codec); - out_audio_info.mime = in_audio_info.mime; - out_audio_info.number_of_channels = in_audio_info.number_of_channels; - out_audio_info.samples_per_second = in_audio_info.samples_per_second; - out_audio_info.bits_per_sample = in_audio_info.bits_per_sample; - out_audio_info.audio_specific_config_size = - in_audio_info.audio_specific_config_size; - out_audio_info.audio_specific_config = in_audio_info.audio_specific_config; - - return out_audio_info; -} - -// A concrete implementation of StarboardApiWrapper for Starboard version 15. -class StarboardApiWrapper15 : public StarboardApiWrapperBase { - public: - StarboardApiWrapper15() = default; - ~StarboardApiWrapper15() override = default; - - // StarboardApiWrapper impl: - void SeekTo(void* player, int64_t time, int seek_ticket) override { - SbPlayerSeek(static_cast(player), time, seek_ticket); - } - - void GetPlayerInfo(void* player, StarboardPlayerInfo* player_info) override { - SbPlayerInfo sb_player_info = {}; - SbPlayerGetInfo(static_cast(player), &sb_player_info); - - player_info->current_media_timestamp_micros = - sb_player_info.current_media_timestamp; - player_info->duration_micros = sb_player_info.duration; - player_info->start_date = sb_player_info.start_date; - player_info->frame_width = sb_player_info.frame_width; - player_info->frame_height = sb_player_info.frame_height; - player_info->is_paused = sb_player_info.is_paused; - player_info->volume = sb_player_info.volume; - player_info->total_video_frames = sb_player_info.total_video_frames; - player_info->dropped_video_frames = sb_player_info.dropped_video_frames; - player_info->corrupted_video_frames = sb_player_info.corrupted_video_frames; - player_info->playback_rate = sb_player_info.playback_rate; - } - - private: - // StarboardApiWrapperBase impl: - SbPlayerCreationParam ToSbPlayerCreationParam( - const StarboardPlayerCreationParam& in_param, - void* drm_system) override { - SbPlayerCreationParam out_param = {}; - - out_param.audio_stream_info = - ToSbMediaAudioStreamInfo(in_param.audio_sample_info); - out_param.video_stream_info = - ToSbMediaVideoStreamInfo(in_param.video_sample_info); - out_param.output_mode = - static_cast(in_param.output_mode); - - if (drm_system) { - LOG(INFO) << "Using an SbDrmSystem for decryption."; - out_param.drm_system = static_cast(drm_system); - } else { - LOG(INFO) - << "No SbDrmSystem was created before SbPlayer; no decryption is " - "possible in starboard."; - out_param.drm_system = kSbDrmSystemInvalid; - } - - return out_param; - } - - SbMediaVideoSampleInfo ToSbMediaVideoSampleInfo( - const StarboardVideoSampleInfo& in_video_info) override { - SbMediaVideoSampleInfo out_video_info; - out_video_info.stream_info = ToSbMediaVideoStreamInfo(in_video_info); - out_video_info.is_key_frame = in_video_info.is_key_frame; - - return out_video_info; - } - - SbMediaAudioSampleInfo ToSbMediaAudioSampleInfo( - const StarboardAudioSampleInfo& in_audio_info) override { - SbMediaAudioSampleInfo out_audio_info = {}; - out_audio_info.stream_info = ToSbMediaAudioStreamInfo(in_audio_info); - out_audio_info.discarded_duration_from_front = 0; - out_audio_info.discarded_duration_from_back = 0; - - return out_audio_info; - } - - void CallWriteSamples(SbPlayer player, - SbMediaType sample_type, - const SbPlayerSampleInfo* sample_infos, - int number_of_sample_infos) override { - SbPlayerWriteSamples(player, sample_type, sample_infos, - number_of_sample_infos); - } -}; - -} // namespace - -// Note: declared in starboard_api_wrapper.h. -std::unique_ptr GetStarboardApiWrapper() { - return std::make_unique(); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_base.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_base.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_base.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_base.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,404 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/starboard_api_wrapper_base.h" - -#include -#include -#include - -#include -#include - -#include "base/check_op.h" -#include "base/logging.h" -#include "chromecast/starboard/chromecast/starboard_adapter/public/cast_starboard_api_adapter.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -namespace { - -// Set via StarboardCreateDrmSystem, and passed to the SbPlayer when the player -// is created. -SbDrmSystem g_drm_system = nullptr; - -void DeallocateSample(SbPlayer player, - void* context, - const void* sample_buffer) { - const auto* handler = - static_cast(context); - handler->deallocate_sample_fn(player, handler->context, sample_buffer); -} - -// Called by starboard to notify cast of a decoder state change. -void OnDecoderStatus(SbPlayer player, - void* context, - SbMediaType type, - SbPlayerDecoderState state, - int ticket) { - const auto* handler = - static_cast(context); - handler->decoder_status_fn(player, handler->context, - static_cast(type), - static_cast(state), ticket); -} - -// Called by starboard to notify cast of a player state change. -void OnPlayerStatus(SbPlayer player, - void* context, - SbPlayerState state, - int ticket) { - const auto* handler = - static_cast(context); - handler->player_status_fn(player, handler->context, - static_cast(state), ticket); -} - -// Called by starboard to notify cast of a player error. -void OnPlayerError(SbPlayer player, - void* context, - SbPlayerError error, - const char* message) { - const auto* handler = - static_cast(context); - handler->player_error_fn(player, handler->context, - static_cast(error), message); -} - -// Converts starboard's representation of a key ID to cast's version-agnostic -// representation. -StarboardDrmKeyId ToStarboardDrmKeyId(const SbDrmKeyId& in_key_id) { - StarboardDrmKeyId out_key_id = {}; - - static_assert(sizeof(in_key_id.identifier) == sizeof(out_key_id.identifier), - "StarboardDrmKeyId.identifier and SbDrmKeyId.identifier must " - "be arrays of the same size"); - - memcpy(out_key_id.identifier, in_key_id.identifier, - sizeof(out_key_id.identifier)); - out_key_id.identifier_size = in_key_id.identifier_size; - - return out_key_id; -} - -// Called by starboard when a generated session update request is ready to be -// sent to cast. -void OnUpdateRequest(SbDrmSystem drm_system, - void* context, - int ticket, - SbDrmStatus status, - SbDrmSessionRequestType type, - const char* error_message, - const void* session_id, - int session_id_size, - const void* content, - int content_size, - const char* url) { - const auto* handler = - static_cast(context); - handler->update_request_fn(drm_system, handler->context, ticket, - static_cast(status), - static_cast(type), - error_message, session_id, session_id_size, - content, content_size, url); -} - -// Called by starboard to notify cast that a session has been updated. -void OnSessionUpdated(SbDrmSystem drm_system, - void* context, - int ticket, - SbDrmStatus status, - const char* error_message, - const void* session_id, - int session_id_size) { - const auto* handler = - static_cast(context); - handler->session_updated_fn(drm_system, handler->context, ticket, - static_cast(status), - error_message, session_id, session_id_size); -} - -// Called by starboard to notify cast that key statuses have changed. -void OnKeyStatusesChanged(SbDrmSystem drm_system, - void* context, - const void* session_id, - int session_id_size, - int number_of_keys, - const SbDrmKeyId* key_ids, - const SbDrmKeyStatus* key_statuses) { - std::vector internal_key_ids; - std::vector internal_key_statuses; - - internal_key_ids.reserve(number_of_keys); - internal_key_statuses.reserve(number_of_keys); - - for (int i = 0; i < number_of_keys; ++i) { - internal_key_ids.push_back(ToStarboardDrmKeyId(key_ids[i])); - internal_key_statuses.push_back( - static_cast(key_statuses[i])); - } - - const auto* handler = - static_cast(context); - handler->key_statuses_changed_fn( - drm_system, handler->context, session_id, session_id_size, number_of_keys, - internal_key_ids.data(), internal_key_statuses.data()); -} - -// Called by starboard when a server certificate has been updated. -void OnServerCertificateUpdated(SbDrmSystem drm_system, - void* context, - int ticket, - SbDrmStatus status, - const char* error_message) { - const auto* handler = - static_cast(context); - handler->server_certificate_updated_fn( - drm_system, handler->context, ticket, - static_cast(status), error_message); -} - -// Called by starboard when a DRM session has closed. -void OnSessionClosed(SbDrmSystem drm_system, - void* context, - const void* session_id, - int session_id_size) { - const auto* handler = - static_cast(context); - handler->session_closed_fn(drm_system, handler->context, session_id, - session_id_size); -} - -} // namespace - -StarboardApiWrapperBase::StarboardApiWrapperBase() = default; -StarboardApiWrapperBase::~StarboardApiWrapperBase() = default; - -bool StarboardApiWrapperBase::EnsureInitialized() { - return chromecast::CastStarboardApiAdapter::GetInstance() - ->EnsureInitialized(); -} - -void* StarboardApiWrapperBase::CreatePlayer( - const StarboardPlayerCreationParam* creation_param, - const StarboardPlayerCallbackHandler* callback_handler) { - SbWindow window = - chromecast::CastStarboardApiAdapter::GetInstance()->GetWindow(nullptr); - - SbPlayerCreationParam sb_creation_param = - ToSbPlayerCreationParam(*creation_param, g_drm_system); - - return SbPlayerCreate( - window, &sb_creation_param, &DeallocateSample, &OnDecoderStatus, - &OnPlayerStatus, &OnPlayerError, - /*context=*/ - static_cast( - const_cast(callback_handler)), - nullptr); -} - -void StarboardApiWrapperBase::SetPlayerBounds(void* player, - int z_index, - int x, - int y, - int width, - int height) { - SbPlayerSetBounds(static_cast(player), z_index, x, y, width, - height); -} - -void StarboardApiWrapperBase::WriteEndOfStream(void* player, - StarboardMediaType type) { - SbPlayerWriteEndOfStream(static_cast(player), - static_cast(type)); -} - -void StarboardApiWrapperBase::SetVolume(void* player, double volume) { - SbPlayerSetVolume(static_cast(player), volume); -} - -bool StarboardApiWrapperBase::SetPlaybackRate(void* player, - double playback_rate) { - return SbPlayerSetPlaybackRate(static_cast(player), playback_rate); -} - -void StarboardApiWrapperBase::DestroyPlayer(void* player) { - SbPlayerDestroy(static_cast(player)); -} - -void* StarboardApiWrapperBase::CreateDrmSystem( - const char* key_system, - const StarboardDrmSystemCallbackHandler* callback_handler) { - if (g_drm_system) { - LOG(INFO) << "An SbDrmSystem already exists; creating a new one."; - } - - LOG(INFO) << "Creating SbDrmSystem"; - g_drm_system = SbDrmCreateSystem( - key_system, - /*context=*/ - static_cast( - const_cast(callback_handler)), - &OnUpdateRequest, &OnSessionUpdated, &OnKeyStatusesChanged, - &OnServerCertificateUpdated, &OnSessionClosed); - return g_drm_system; -} - -void StarboardApiWrapperBase::DrmGenerateSessionUpdateRequest( - void* drm_system, - int ticket, - const char* type, - const void* initialization_data, - int initialization_data_size) { - SbDrmGenerateSessionUpdateRequest(static_cast(drm_system), - ticket, type, initialization_data, - initialization_data_size); -} - -void StarboardApiWrapperBase::DrmUpdateSession(void* drm_system, - int ticket, - const void* key, - int key_size, - const void* session_id, - int session_id_size) { - SbDrmUpdateSession(static_cast(drm_system), ticket, key, - key_size, session_id, session_id_size); -} - -void StarboardApiWrapperBase::DrmCloseSession(void* drm_system, - const void* session_id, - int session_id_size) { - SbDrmCloseSession(static_cast(drm_system), session_id, - session_id_size); -} - -void StarboardApiWrapperBase::DrmUpdateServerCertificate( - void* drm_system, - int ticket, - const void* certificate, - int certificate_size) { - SbDrmUpdateServerCertificate(static_cast(drm_system), ticket, - certificate, certificate_size); -} - -bool StarboardApiWrapperBase::DrmIsServerCertificateUpdatable( - void* drm_system) { - return SbDrmIsServerCertificateUpdatable( - static_cast(drm_system)); -} - -void StarboardApiWrapperBase::DrmDestroySystem(void* drm_system) { - LOG(INFO) << "Destroying SbDrmSystem"; - if (reinterpret_cast(g_drm_system) == drm_system) { - g_drm_system = nullptr; - } - SbDrmDestroySystem(static_cast(drm_system)); -} - -SbPlayerSampleInfo StarboardApiWrapperBase::ToSbPlayerSampleInfo( - const StarboardSampleInfo& in_info, - std::vector& side_data, - SbDrmSampleInfo& drm_info, - std::vector& subsample_mappings) { - SbPlayerSampleInfo out_info = {}; - out_info.type = static_cast(in_info.type); - out_info.buffer = in_info.buffer; - out_info.buffer_size = in_info.buffer_size; - out_info.timestamp = in_info.timestamp; - - side_data.reserve(in_info.side_data_count); - for (int i = 0; i < in_info.side_data_count; ++i) { - const StarboardSampleSideData& in_side_data = in_info.side_data[i]; - SbPlayerSampleSideData out_side_data; - - out_side_data.type = - static_cast(in_side_data.type); - out_side_data.data = in_side_data.data; - out_side_data.size = in_side_data.size; - - side_data.push_back(std::move(out_side_data)); - } - out_info.side_data = side_data.empty() ? nullptr : side_data.data(); - out_info.side_data_count = side_data.size(); - - // Set the audio/video specific fields. - switch (in_info.type) { - case kStarboardMediaTypeAudio: - out_info.audio_sample_info = - ToSbMediaAudioSampleInfo(in_info.audio_sample_info); - break; - case kStarboardMediaTypeVideo: - out_info.video_sample_info = - ToSbMediaVideoSampleInfo(in_info.video_sample_info); - break; - } - - if (in_info.drm_info) { - const StarboardDrmSampleInfo& in_drm_info = *in_info.drm_info; - - drm_info.encryption_scheme = - static_cast(in_drm_info.encryption_scheme); - drm_info.encryption_pattern.crypt_byte_block = - in_drm_info.encryption_pattern.crypt_byte_block; - drm_info.encryption_pattern.skip_byte_block = - in_drm_info.encryption_pattern.skip_byte_block; - - memcpy(drm_info.initialization_vector, in_drm_info.initialization_vector, - in_drm_info.initialization_vector_size); - drm_info.initialization_vector_size = - in_drm_info.initialization_vector_size; - - memcpy(drm_info.identifier, in_drm_info.identifier, - in_drm_info.identifier_size); - drm_info.identifier_size = in_drm_info.identifier_size; - - subsample_mappings.reserve(in_drm_info.subsample_count); - for (int i = 0; i < in_drm_info.subsample_count; ++i) { - SbDrmSubSampleMapping mapping; - mapping.clear_byte_count = - in_drm_info.subsample_mapping[i].clear_byte_count; - mapping.encrypted_byte_count = - in_drm_info.subsample_mapping[i].encrypted_byte_count; - subsample_mappings.push_back(std::move(mapping)); - } - drm_info.subsample_count = subsample_mappings.size(); - drm_info.subsample_mapping = - subsample_mappings.empty() ? nullptr : subsample_mappings.data(); - - out_info.drm_info = &drm_info; - } else { - out_info.drm_info = nullptr; - } - return out_info; -} - -void StarboardApiWrapperBase::WriteSample(void* player, - StarboardMediaType type, - StarboardSampleInfo* sample_infos, - int sample_infos_count) { - std::vector samples; - std::vector> side_data; - SbDrmSampleInfo drm_info; - std::vector subsample_mappings; - for (int i = 0; i < sample_infos_count; ++i) { - side_data.push_back({}); - samples.push_back(ToSbPlayerSampleInfo(sample_infos[i], side_data.back(), - drm_info, subsample_mappings)); - } - CallWriteSamples(static_cast(player), - static_cast(type), samples.data(), - sample_infos_count); -} - -StarboardMediaSupportType StarboardApiWrapperBase::CanPlayMimeAndKeySystem( - const char* mime, - const char* key_system) { - return static_cast( - SbMediaCanPlayMimeAndKeySystem(mime, key_system)); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_base.h chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_base.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_base.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_base.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_API_WRAPPER_BASE_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_API_WRAPPER_BASE_H_ - -#include -#include - -#include - -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -// Implements the functions of StarboardApiWrapper that are common across -// different starboard versions. This is still an abstract class, as it does not -// implement all of StarboardApiWrapper's functions. -class StarboardApiWrapperBase : public StarboardApiWrapper { - public: - StarboardApiWrapperBase(); - ~StarboardApiWrapperBase() override; - - // StarboardApiWrapper impl: - bool EnsureInitialized() override; - void* CreatePlayer( - const StarboardPlayerCreationParam* creation_param, - const StarboardPlayerCallbackHandler* callback_handler) override; - void SetPlayerBounds(void* player, - int z_index, - int x, - int y, - int width, - int height) override; - void WriteSample(void* player, - StarboardMediaType type, - StarboardSampleInfo* sample_infos, - int sample_infos_count) override; - void WriteEndOfStream(void* player, StarboardMediaType type) override; - void SetVolume(void* player, double volume) override; - bool SetPlaybackRate(void* player, double playback_rate) override; - void DestroyPlayer(void* player) override; - void* CreateDrmSystem( - const char* key_system, - const StarboardDrmSystemCallbackHandler* callback_handler) override; - void DrmGenerateSessionUpdateRequest(void* drm_system, - int ticket, - const char* type, - const void* initialization_data, - int initialization_data_size) override; - void DrmUpdateSession(void* drm_system, - int ticket, - const void* key, - int key_size, - const void* session_id, - int session_id_size) override; - void DrmCloseSession(void* drm_system, - const void* session_id, - int session_id_size) override; - void DrmUpdateServerCertificate(void* drm_system, - int ticket, - const void* certificate, - int certificate_size) override; - bool DrmIsServerCertificateUpdatable(void* drm_system) override; - void DrmDestroySystem(void* drm_system) override; - - StarboardMediaSupportType CanPlayMimeAndKeySystem( - const char* mime, - const char* key_system) override; - - private: - // Converts StarboardSampleInfo to SbPlayerSampleInfo. `side_data` is used to - // store side data for this sample, since that data must outlive this function - // call. Same for `drm_info` and `subsample_mappings`. - // - // `side_data` and `subsample_mappings` should be empty vectors. They will be - // populated as necessary, so that they can outlive the later call to - // SbPlayerWriteSample. - SbPlayerSampleInfo ToSbPlayerSampleInfo( - const StarboardSampleInfo& in_info, - std::vector& side_data, - SbDrmSampleInfo& drm_info, - std::vector& subsample_mappings); - - // Converts the version-agnostic StarboardPlayerCreationParam to starboard's - // SbPlayerCreationParam. - virtual SbPlayerCreationParam ToSbPlayerCreationParam( - const StarboardPlayerCreationParam& in_param, - void* drm_system) = 0; - - // Converts from cast's version-agnostic struct to starboard's version. - virtual SbMediaVideoSampleInfo ToSbMediaVideoSampleInfo( - const StarboardVideoSampleInfo& in_video_info) = 0; - - // Converts from cast's version-agnostic struct to starboard's version. - virtual SbMediaAudioSampleInfo ToSbMediaAudioSampleInfo( - const StarboardAudioSampleInfo& in_audio_info) = 0; - - // Calls the relevant starboard version's function to write samples (e.g. - // SbPlayerWriteSamples or SbPlayerWriteSample2). - virtual void CallWriteSamples(SbPlayer player, - SbMediaType sample_type, - const SbPlayerSampleInfo* sample_infos, - int number_of_sample_infos) = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_API_WRAPPER_BASE_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_dummy.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_dummy.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_api_wrapper_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_api_wrapper_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -std::unique_ptr GetStarboardApiWrapper() { - return nullptr; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_audio_decoder.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_audio_decoder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,217 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "starboard_audio_decoder.h" - -#include -#include -#include -#include - -#include "base/check.h" -#include "base/logging.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h" -#include "chromecast/starboard/media/media/drm_util.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -using BufferStatus = ::chromecast::media::MediaPipelineBackend::BufferStatus; -using RenderingDelay = - ::chromecast::media::MediaPipelineBackend::AudioDecoder::RenderingDelay; - -static StarboardAudioCodec AudioCodecToStarboardCodec(AudioCodec codec) { - switch (codec) { - case kCodecAAC: - return kStarboardAudioCodecAac; - case kCodecMP3: - return kStarboardAudioCodecMp3; - case kCodecPCM_S16BE: - case kCodecPCM: - return kStarboardAudioCodecPcm; - case kCodecVorbis: - return kStarboardAudioCodecVorbis; - case kCodecOpus: - return kStarboardAudioCodecOpus; - case kCodecEAC3: - return kStarboardAudioCodecEac3; - case kCodecAC3: - return kStarboardAudioCodecAc3; - case kCodecFLAC: - return kStarboardAudioCodecFlac; - case kCodecMpegHAudio: - case kCodecDTS: - case kAudioCodecUnknown: - default: - LOG(ERROR) << "Unsupported audio codec: " << codec; - return kStarboardAudioCodecNone; - } -} - -static StarboardAudioSampleInfo ToAudioSampleInfo(const AudioConfig& config) { - StarboardAudioSampleInfo sample_info = {}; - - sample_info.codec = AudioCodecToStarboardCodec(config.codec); - sample_info.mime = ""; - sample_info.format_tag = 0; - sample_info.number_of_channels = config.channel_number; - sample_info.samples_per_second = config.samples_per_second; - // Based on starboard_utils.cc (MediaAudioConfigToSbMediaAudioSampleInfo) in - // the cobalt codebase, this value does not take into account the number of - // channels. - // TODO(b/334907387): Add logic to change audio_sample_info_.bits_per_sample - // depending on our desired output. For now it's just 16 because we only - // need signed 16 as our desired out. - if (sample_info.codec == kStarboardAudioCodecPcm) { - sample_info.bits_per_sample = 16; - } else { - sample_info.bits_per_sample = config.bytes_per_channel * 8; - } - sample_info.block_alignment = 4; - sample_info.average_bytes_per_second = sample_info.number_of_channels * - sample_info.samples_per_second * - sample_info.bits_per_sample / 8; - // Since extra_data is a vector of uint8_t, size() gives us the size in bytes. - sample_info.audio_specific_config_size = config.extra_data.size(); - sample_info.audio_specific_config = - sample_info.audio_specific_config_size > 0 - ? static_cast(config.extra_data.data()) - : nullptr; - - return sample_info; -} - -StarboardAudioDecoder::StarboardAudioDecoder(StarboardApiWrapper* starboard) - : StarboardDecoder(starboard, kStarboardMediaTypeAudio), - format_to_decode_to_( - StarboardPcmSampleFormat::kStarboardPcmSampleFormatS16) {} - -StarboardAudioDecoder::~StarboardAudioDecoder() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -void StarboardAudioDecoder::InitializeInternal() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (volume_) { - LOG(INFO) << "Setting starboard's volume to " << *volume_; - GetStarboardApi().SetVolume(GetPlayer(), *volume_); - volume_ = std::nullopt; - } -} - -const std::optional& -StarboardAudioDecoder::GetAudioSampleInfo() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return audio_sample_info_; -} - -bool StarboardAudioDecoder::SetConfig(const AudioConfig& config) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if ((config.codec == kCodecPCM || config.codec == kCodecPCM_S16BE) && - config.channel_number > 8) { - LOG(ERROR) << "Config channels exceeds 8, which is not supported."; - return false; - } - - config_ = config; - audio_sample_info_.emplace(ToAudioSampleInfo(config_)); - return IsValidConfig(config_); -} - -bool StarboardAudioDecoder::SetVolume(float multiplier) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (multiplier < 0.0 || multiplier > 1.0) { - LOG(ERROR) << "Invalid volume multiplier: " << multiplier; - return false; - } - - void* const player = GetPlayer(); - if (player) { - LOG(INFO) << "Setting starboard's volume to " << multiplier; - GetStarboardApi().SetVolume(player, multiplier); - } else { - LOG(INFO) << "Delaying setting volume until SbPlayer is created."; - volume_ = multiplier; - } - - return true; -} - -RenderingDelay StarboardAudioDecoder::GetRenderingDelay() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - RenderingDelay delay = {}; - // Signifies that the latency is not available. - delay.timestamp_microseconds = std::numeric_limits::min(); - delay.delay_microseconds = 0; - return delay; -} - -BufferStatus StarboardAudioDecoder::PushBuffer(CastDecoderBuffer* buffer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(buffer); - - if (buffer->end_of_stream()) { - return PushEndOfStream(); - } - - DCHECK(audio_sample_info_); - size_t size_of_buffer = buffer->data_size(); - std::unique_ptr data_copy; - - if (audio_sample_info_->codec == kStarboardAudioCodecPcm) { - // This call will also set the value for `size_of_buffer`. - data_copy = ResamplePCMAudioDataForStarboard( - format_to_decode_to_, config_.sample_format, config_.codec, - audio_sample_info_->number_of_channels, *buffer, size_of_buffer); - } else { - // Need to do this when not resampling to ensure that the input data is not - // freed until Starboard is done using it. - data_copy = std::make_unique(size_of_buffer); - memcpy(data_copy.get(), buffer->data(), size_of_buffer); - } - - StarboardSampleInfo sample = {}; - sample.type = kStarboardMediaTypeAudio; - sample.timestamp = buffer->timestamp(); - sample.side_data = nullptr; - sample.side_data_count = 0; - sample.audio_sample_info = *audio_sample_info_; - - decoded_bytes_ += size_of_buffer; - - return PushBufferInternal(std::move(sample), GetDrmInfo(*buffer), - std::move(data_copy), size_of_buffer); -} - -void StarboardAudioDecoder::GetStatistics(Statistics* statistics) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!statistics) { - return; - } - - statistics->decoded_bytes = decoded_bytes_; -} - -void StarboardAudioDecoder::SetDelegate(Delegate* delegate) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - SetDecoderDelegate(delegate); -} - -StarboardAudioDecoder::AudioTrackTimestamp -StarboardAudioDecoder::GetAudioTrackTimestamp() { - return AudioTrackTimestamp(); -} - -int StarboardAudioDecoder::GetStartThresholdInFrames() { - return 0; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_audio_decoder.h chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_audio_decoder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_AUDIO_DECODER_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_AUDIO_DECODER_H_ - -#include - -#include "base/sequence_checker.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "chromecast/starboard/media/media/starboard_decoder.h" -#include "chromecast/starboard/media/media/starboard_resampler.h" - -namespace chromecast { -namespace media { - -// An AudioDecoder that sends buffers to a Starboard SbPlayer. -// -// All functions and the constructor/destructor must be called on the same -// sequence (the media thread). -class StarboardAudioDecoder : public StarboardDecoder, - public MediaPipelineBackend::AudioDecoder { - public: - explicit StarboardAudioDecoder(StarboardApiWrapper* starboard); - ~StarboardAudioDecoder() override; - - // Returns the audio config or nullopt if the config has not been set yet. - const std::optional& GetAudioSampleInfo(); - - // MediaPipelineBackend::AudioDecoder implementation: - bool SetConfig(const AudioConfig& config) override; - bool SetVolume(float multiplier) override; - RenderingDelay GetRenderingDelay() override; - void GetStatistics(Statistics* statistics) override; - MediaPipelineBackend::BufferStatus PushBuffer( - CastDecoderBuffer* buffer) override; - void SetDelegate(Delegate* delegate) override; - AudioTrackTimestamp GetAudioTrackTimestamp() override; - int GetStartThresholdInFrames() override; - - private: - // StarboardDecoder impl: - void InitializeInternal() override; - - SEQUENCE_CHECKER(sequence_checker_); - // If SetVolume is called before player_ is created, we need to store the - // value and update starboard once the player is ready. If this value is not - // nullopt, it means that there is a pending volume change, and that the - // volume must be set on the next call to Initialize(). - std::optional volume_; - std::optional audio_sample_info_; - AudioConfig config_; - // The number of bytes sent to the SbPlayer. Used for statistics. - uint64_t decoded_bytes_ = 0; - // This format is what we will be changing all PCM data to during decoding. - StarboardPcmSampleFormat format_to_decode_to_; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_AUDIO_DECODER_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_audio_decoder_test.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder_test.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_audio_decoder_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_audio_decoder_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,690 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/starboard_audio_decoder.h" - -#include -#include -#include -#include - -#include "base/logging.h" -#include "base/test/task_environment.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/starboard/media/cdm/starboard_drm_key_tracker.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "media/base/decoder_buffer.h" -#include "media/base/decrypt_config.h" -#include "media/base/encryption_scheme.h" -#include "media/base/subsample_entry.h" -#include "mock_starboard_api_wrapper.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::AllOf; -using ::testing::DoubleEq; -using ::testing::ElementsAre; -using ::testing::ElementsAreArray; -using ::testing::Eq; -using ::testing::ExplainMatchResult; -using ::testing::Field; -using ::testing::FloatEq; -using ::testing::MockFunction; -using ::testing::Optional; -using ::testing::Pointee; -using ::testing::Pointwise; -using ::testing::StrEq; -using ::testing::WithArg; - -// Converts between AudioCodec and StarboardAudioCodec. -StarboardAudioCodec ToStarboardAudioCodec(AudioCodec codec) { - switch (codec) { - case kCodecAAC: - return kStarboardAudioCodecAac; - case kCodecMP3: - return kStarboardAudioCodecMp3; - case kCodecPCM: - return kStarboardAudioCodecPcm; - case kCodecVorbis: - return kStarboardAudioCodecVorbis; - case kCodecOpus: - return kStarboardAudioCodecOpus; - case kCodecEAC3: - return kStarboardAudioCodecEac3; - case kCodecAC3: - return kStarboardAudioCodecAc3; - case kCodecFLAC: - return kStarboardAudioCodecFlac; - // The rest of these codecs are currently unsupported by starboard. - case kCodecDTS: - case kCodecPCM_S16BE: - case kCodecMpegHAudio: - default: - return kStarboardAudioCodecNone; - } -} - -// Returns the number of bits per sample per channel for the given sample -// format. -uint16_t GetBitsPerSample(SampleFormat sample_format) { - switch (sample_format) { - case kSampleFormatU8: - return 8; - case kSampleFormatS16: - case kSampleFormatPlanarS16: - return 16; - case kSampleFormatS24: - return 24; - case kSampleFormatS32: - case kSampleFormatF32: - case kSampleFormatPlanarF32: - case kSampleFormatPlanarS32: - return 32; - default: - return 0; - } -} - -// Compares a StarboardSampleInfo (arg) to an AudioConfig (config) and a -// scoped_refptr (buffer). -MATCHER_P2(MatchesAudioConfigAndBuffer, config, buffer, "") { - CHECK(buffer) << "Passed a null buffer to the matcher."; - - if (arg.type != kStarboardMediaTypeAudio) { - *result_listener << "the StarboardSampleInfo's type is not audio"; - return false; - } - - // Check that the buffer's data matches. - if (!ExplainMatchResult( - ElementsAreArray(buffer->data(), buffer->data_size()), - std::tuple( - static_cast(arg.buffer), arg.buffer_size), - result_listener)) { - *result_listener << " the expected audio data"; - return false; - } - - // Check the rest of the fields. - return ExplainMatchResult(Eq(buffer->timestamp()), arg.timestamp, - result_listener) && - ExplainMatchResult( - AllOf(Field(&StarboardAudioSampleInfo::codec, - ToStarboardAudioCodec(config.codec)), - Field(&StarboardAudioSampleInfo::number_of_channels, - config.channel_number), - Field(&StarboardAudioSampleInfo::samples_per_second, - config.samples_per_second), - Field(&StarboardAudioSampleInfo::bits_per_sample, - GetBitsPerSample(config.sample_format))), - arg.audio_sample_info, result_listener); - return true; -} - -// Compares a StarboardSampleInfo (arg) to a -// scoped_refptr (buffer). -MATCHER_P(MatchesAudioBufferPCM, buffer, "") { - CHECK(buffer) << "Passed a null buffer to the matcher."; - if (arg.type != kStarboardMediaTypeAudio) { - *result_listener << "the StarboardSampleInfo's type is not audio"; - return false; - } - - CHECK_EQ(static_cast(buffer->data_size()) % 4, 0); - CHECK_EQ(arg.buffer_size % 4, 0); - - const std::vector expected_buffer( - reinterpret_cast(buffer->data()), - reinterpret_cast(buffer->data()) + buffer->data_size() / 4); - - if (!ExplainMatchResult( - Pointwise(FloatEq(), expected_buffer), - std::tuple( - reinterpret_cast(arg.buffer), arg.buffer_size / 4), - result_listener)) { - *result_listener << "buffer data mismatch"; - return false; - } - return true; -} - -// A mock delegate that can be passed to the decoder. -class MockDelegate : public MediaPipelineBackend::Decoder::Delegate { - public: - MockDelegate() = default; - ~MockDelegate() override = default; - - MOCK_METHOD(void, OnPushBufferComplete, (BufferStatus status), (override)); - MOCK_METHOD(void, OnEndOfStream, (), (override)); - MOCK_METHOD(void, OnDecoderError, (), (override)); - MOCK_METHOD(void, - OnKeyStatusChanged, - (const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code), - (override)); - MOCK_METHOD(void, OnVideoResolutionChanged, (const Size& size), (override)); -}; - -// A test fixture is used to manage the global mock state and to handle the -// lifetime of the SingleThreadTaskEnvironment. -class StarboardAudioDecoderTest : public ::testing::Test { - protected: - StarboardAudioDecoderTest() - : starboard_(std::make_unique()) { - // Ensure that tests begin with a clean slate regarding DRM keys. - StarboardDrmKeyTracker::GetInstance().ClearStateForTesting(); - } - - ~StarboardAudioDecoderTest() override = default; - - // This should be destructed last. - base::test::SingleThreadTaskEnvironment task_environment_; - // This will be passed to the MediaPipelineBackendStarboard, and all calls to - // Starboard will go through it. Thus, we can mock out those calls. - std::unique_ptr starboard_; - // Since SbPlayer is just an opaque blob to the MPB, we will simply use an int - // to represent it. - int fake_player_ = 1; -}; - -// Returns a simple AudioConfig. -AudioConfig GetBasicConfig() { - AudioConfig config; - - config.codec = AudioCodec::kCodecMP3; - config.channel_layout = ChannelLayout::STEREO; - config.sample_format = SampleFormat::kSampleFormatF32; - config.bytes_per_channel = 4; - config.channel_number = 2; - config.samples_per_second = 44100; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - - return config; -} - -TEST_F(StarboardAudioDecoderTest, PushesBufferToStarboard) { - const AudioConfig config = GetBasicConfig(); - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr buffer( - new CastDecoderBufferImpl(buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), buffer_data.size()); - - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeAudio, - Pointee(MatchesAudioConfigAndBuffer(config, buffer)), 1)) - .Times(1); - - StarboardAudioDecoder decoder(starboard_.get()); - MockDelegate delegate; - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); -} - -TEST_F(StarboardAudioDecoderTest, WritesEndOfStreamToStarboard) { - EXPECT_CALL(*starboard_, - WriteEndOfStream(&fake_player_, kStarboardMediaTypeAudio)) - .Times(1); - - StarboardAudioDecoder decoder(starboard_.get()); - MockDelegate delegate; - - const AudioConfig config = GetBasicConfig(); - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(CastDecoderBufferImpl::CreateEOSBuffer().get()), - MediaPipelineBackend::BufferStatus::kBufferSuccess); -} - -TEST_F(StarboardAudioDecoderTest, ForwardsSetVolumeCallToStarboard) { - constexpr float kVolume = 0.77; - - EXPECT_CALL(*starboard_, SetVolume(&fake_player_, DoubleEq(kVolume))) - .Times(1); - - StarboardAudioDecoder decoder(starboard_.get()); - MockDelegate delegate; - - const AudioConfig config = GetBasicConfig(); - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_TRUE(decoder.SetVolume(kVolume)); -} - -TEST_F(StarboardAudioDecoderTest, PopulatesDrmInfoInSamples) { - // The length should be at most 16 bytes. - constexpr char kKeyId[] = "key_id"; - // This must be 16 bytes. - constexpr char kIv[] = "abcdefghijklmnop"; - // This must contain at least one subsample. - const std::vector<::media::SubsampleEntry> subsamples = { - ::media::SubsampleEntry(/*clear_bytes=*/1, /*cypher_bytes=*/2), - ::media::SubsampleEntry(/*clear_bytes=*/3, /*cypher_bytes=*/4), - }; - - // If we do not add this key, buffers will not be pushed to starboard. - StarboardDrmKeyTracker::GetInstance().AddKey(kKeyId, "session_id"); - - AudioConfig config = GetBasicConfig(); - // Match the behavior of AudioPipelineImpl::Initialize by setting this to - // unencrypted even for encrypted content. - config.encryption_scheme = EncryptionScheme::kUnencrypted; - - const ::media::EncryptionPattern encryption_pattern(5, 6); - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCbcsConfig(kKeyId, kIv, subsamples, - encryption_pattern); - CHECK(decrypt_config); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr<::media::DecoderBuffer> decoder_buffer = - ::media::DecoderBuffer::CopyFrom(buffer_data); - CHECK(decoder_buffer); - decoder_buffer->set_decrypt_config(std::move(decrypt_config)); - - scoped_refptr buffer = - new DecoderBufferAdapter(decoder_buffer); - - StarboardDrmSampleInfo actual_drm_info = {}; - // The actual subsamples may be deleted after the call to - // SbPlayerWriteSample2, so we need to store a copy. - std::vector actual_subsamples; - - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeAudio, - Pointee(AllOf(MatchesAudioConfigAndBuffer(config, buffer))), - 1)) - .WillOnce(WithArg<2>([&actual_drm_info, &actual_subsamples]( - StarboardSampleInfo* sample_infos) { - // Since this is only called when the fourth argument is 1, that - // means that sample_infos_count is 1. - StarboardSampleInfo sample_info = sample_infos[0]; - if (!sample_info.drm_info) { - return; - } - actual_drm_info = *sample_info.drm_info; - const int subsample_count = actual_drm_info.subsample_count; - if (subsample_count > 0) { - actual_subsamples.assign( - actual_drm_info.subsample_mapping, - actual_drm_info.subsample_mapping + subsample_count); - } - })); - - StarboardAudioDecoder decoder(starboard_.get()); - MockDelegate delegate; - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - EXPECT_EQ(actual_drm_info.encryption_scheme, - kStarboardDrmEncryptionSchemeAesCbc); - EXPECT_EQ(actual_drm_info.encryption_pattern.crypt_byte_block, - encryption_pattern.crypt_byte_block()); - EXPECT_EQ(actual_drm_info.encryption_pattern.skip_byte_block, - encryption_pattern.skip_byte_block()); - EXPECT_THAT(std::string(reinterpret_cast( - actual_drm_info.initialization_vector), - actual_drm_info.initialization_vector_size), - StrEq(kIv)); - EXPECT_THAT( - std::string(reinterpret_cast(actual_drm_info.identifier), - actual_drm_info.identifier_size), - StrEq(kKeyId)); - EXPECT_THAT( - actual_subsamples, - ElementsAre( - AllOf(Field(&StarboardDrmSubSampleMapping::clear_byte_count, 1), - Field(&StarboardDrmSubSampleMapping::encrypted_byte_count, 2)), - AllOf( - Field(&StarboardDrmSubSampleMapping::clear_byte_count, 3), - Field(&StarboardDrmSubSampleMapping::encrypted_byte_count, 4)))); -} - -TEST_F(StarboardAudioDecoderTest, DoesNotPushToStarboardIfDrmKeyIsUnavailable) { - // The length should be at most 16 bytes. - constexpr char kKeyId[] = "key_id"; - // This must be 16 bytes. - constexpr char kIv[] = "abcdefghijklmnop"; - // This must contain at least one subsample. - const std::vector<::media::SubsampleEntry> subsamples = { - ::media::SubsampleEntry(/*clear_bytes=*/1, /*cypher_bytes=*/2), - ::media::SubsampleEntry(/*clear_bytes=*/3, /*cypher_bytes=*/4), - }; - - // Since we do not add kKeyId to StarboardDrmKeyTracker, no buffer with this - // key ID should be pushed to starboard. - - AudioConfig config = GetBasicConfig(); - config.encryption_scheme = EncryptionScheme::kAesCtr; - - const ::media::EncryptionPattern encryption_pattern(5, 6); - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCbcsConfig(kKeyId, kIv, subsamples, - encryption_pattern); - CHECK(decrypt_config); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr<::media::DecoderBuffer> decoder_buffer = - ::media::DecoderBuffer::CopyFrom(buffer_data); - CHECK(decoder_buffer); - decoder_buffer->set_decrypt_config(std::move(decrypt_config)); - - scoped_refptr buffer = - new DecoderBufferAdapter(decoder_buffer); - - EXPECT_CALL(*starboard_, WriteSample).Times(0); - - StarboardAudioDecoder decoder(starboard_.get()); - MockDelegate delegate; - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); -} - -TEST_F(StarboardAudioDecoderTest, - PushesBufferToStarboardAfterDrmKeyIsAvailable) { - // The length should be at most 16 bytes. - constexpr char kKeyId[] = "key_id"; - // This must be 16 bytes. - constexpr char kIv[] = "abcdefghijklmnop"; - // This must contain at least one subsample. - const std::vector<::media::SubsampleEntry> subsamples = { - ::media::SubsampleEntry(/*clear_bytes=*/1, /*cypher_bytes=*/2), - ::media::SubsampleEntry(/*clear_bytes=*/3, /*cypher_bytes=*/4), - }; - - AudioConfig config = GetBasicConfig(); - config.encryption_scheme = EncryptionScheme::kAesCbc; - - const ::media::EncryptionPattern encryption_pattern(5, 6); - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCbcsConfig(kKeyId, kIv, subsamples, - encryption_pattern); - CHECK(decrypt_config); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr<::media::DecoderBuffer> decoder_buffer = - ::media::DecoderBuffer::CopyFrom(buffer_data); - CHECK(decoder_buffer); - decoder_buffer->set_decrypt_config(std::move(decrypt_config)); - - scoped_refptr buffer = - new DecoderBufferAdapter(decoder_buffer); - - StarboardDrmSampleInfo actual_drm_info = {}; - // The actual subsamples may be deleted after the call to - // SbPlayerWriteSample2, so we need to store a copy. - std::vector actual_subsamples; - - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeAudio, - Pointee(AllOf(MatchesAudioConfigAndBuffer(config, buffer))), - 1)) - .WillOnce(WithArg<2>([&actual_drm_info, &actual_subsamples]( - StarboardSampleInfo* sample_infos) { - // Since this is only called when the fourth argument is 1, that - // means that sample_infos_count is 1. - StarboardSampleInfo sample_info = sample_infos[0]; - if (!sample_info.drm_info) { - return; - } - actual_drm_info = *sample_info.drm_info; - const int subsample_count = actual_drm_info.subsample_count; - if (subsample_count > 0) { - actual_subsamples.assign( - actual_drm_info.subsample_mapping, - actual_drm_info.subsample_mapping + subsample_count); - } - })); - - StarboardAudioDecoder decoder(starboard_.get()); - MockDelegate delegate; - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - // Now that the key is available, the buffer should be pushed to starboard. - StarboardDrmKeyTracker::GetInstance().AddKey(kKeyId, "session_id"); - // The callback provided by the decoder will post a task; run until the - // callback runs. - task_environment_.RunUntilIdle(); - - EXPECT_EQ(actual_drm_info.encryption_scheme, - kStarboardDrmEncryptionSchemeAesCbc); - EXPECT_EQ(actual_drm_info.encryption_pattern.crypt_byte_block, - encryption_pattern.crypt_byte_block()); - EXPECT_EQ(actual_drm_info.encryption_pattern.skip_byte_block, - encryption_pattern.skip_byte_block()); - EXPECT_THAT(std::string(reinterpret_cast( - actual_drm_info.initialization_vector), - actual_drm_info.initialization_vector_size), - StrEq(kIv)); - EXPECT_THAT( - std::string(reinterpret_cast(actual_drm_info.identifier), - actual_drm_info.identifier_size), - StrEq(kKeyId)); - EXPECT_THAT( - actual_subsamples, - ElementsAre( - AllOf(Field(&StarboardDrmSubSampleMapping::clear_byte_count, 1), - Field(&StarboardDrmSubSampleMapping::encrypted_byte_count, 2)), - AllOf( - Field(&StarboardDrmSubSampleMapping::clear_byte_count, 3), - Field(&StarboardDrmSubSampleMapping::encrypted_byte_count, 4)))); -} - -TEST_F(StarboardAudioDecoderTest, ReturnsNulloptBeforeConfigSet) { - StarboardAudioDecoder decoder(starboard_.get()); - - EXPECT_EQ(decoder.GetAudioSampleInfo(), std::nullopt); -} - -TEST_F(StarboardAudioDecoderTest, - ReturnsPopulatedSampleInfoAfterConfigHasBeenSet) { - StarboardAudioDecoder decoder(starboard_.get()); - - AudioConfig config; - config.codec = AudioCodec::kCodecAAC; - config.channel_layout = ChannelLayout::SURROUND_5_1; - config.sample_format = SampleFormat::kSampleFormatF32; - config.bytes_per_channel = 4; - config.channel_number = 6; - config.samples_per_second = 48000; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - - EXPECT_TRUE(decoder.SetConfig(config)); - EXPECT_THAT(decoder.GetAudioSampleInfo(), - Optional(Field(&StarboardAudioSampleInfo::codec, - kStarboardAudioCodecAac))); -} - -TEST_F(StarboardAudioDecoderTest, - HandlesMultiplePushBuffersBeforeInitialization) { - const std::vector buffer_data_1 = {1, 2, 3, 4, 5}; - scoped_refptr buffer_1( - new CastDecoderBufferImpl(buffer_data_1.size())); - memcpy(buffer_1->writable_data(), buffer_data_1.data(), buffer_data_1.size()); - - const std::vector buffer_data_2 = {6, 7, 8, 9, 10}; - scoped_refptr buffer_2( - new CastDecoderBufferImpl(buffer_data_2.size())); - memcpy(buffer_2->writable_data(), buffer_data_2.data(), buffer_data_2.size()); - - const AudioConfig config = GetBasicConfig(); - - // Only the last buffer -- buffer_2 -- should be sent to starboard once the - // decoder is initialized. - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeAudio, - Pointee(MatchesAudioConfigAndBuffer(config, buffer_1)), 1)) - .Times(0); - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeAudio, - Pointee(MatchesAudioConfigAndBuffer(config, buffer_2)), 1)) - .Times(1); - - StarboardAudioDecoder decoder(starboard_.get()); - decoder.SetConfig(config); - EXPECT_EQ(decoder.PushBuffer(buffer_1.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - EXPECT_EQ(decoder.PushBuffer(buffer_2.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - MockDelegate delegate; - decoder.SetDelegate(&delegate); - - // At this point, the pending buffer (buffer_2) should be pushed. - decoder.Initialize(&fake_player_); -} - -TEST_F(StarboardAudioDecoderTest, DoesNotCallDelegateEoSWhenPushingEoSBuffer) { - const AudioConfig config = GetBasicConfig(); - - StarboardAudioDecoder decoder(starboard_.get()); - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - MockDelegate delegate; - // This should not be called, since we never call - // decoder.OnSbPlayerEndOfStream() in this test. - EXPECT_CALL(delegate, OnEndOfStream).Times(0); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(CastDecoderBufferImpl::CreateEOSBuffer().get()), - MediaPipelineBackend::BufferStatus::kBufferSuccess); -} - -TEST_F(StarboardAudioDecoderTest, CallsDelegateEoSWhenSbPlayerStreamEnds) { - const AudioConfig config = GetBasicConfig(); - - StarboardAudioDecoder decoder(starboard_.get()); - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - MockDelegate delegate; - EXPECT_CALL(delegate, OnEndOfStream).Times(1); - decoder.SetDelegate(&delegate); - decoder.OnSbPlayerEndOfStream(); -} - -TEST_F(StarboardAudioDecoderTest, ReportsStatistics) { - StarboardAudioDecoder decoder(starboard_.get()); - MockDelegate delegate; - - const AudioConfig config = GetBasicConfig(); - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr buffer( - new CastDecoderBufferImpl(buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), buffer_data.size()); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - MediaPipelineBackend::AudioDecoder::Statistics stats = {}; - decoder.GetStatistics(&stats); - EXPECT_EQ(stats.decoded_bytes, buffer_data.size()); -} - -TEST_F(StarboardAudioDecoderTest, ConvertsPcmToS16ForPushBeforeInitialization) { - // NOTE: this test relies on cast converting PCM data to S16. If the code is - // updated to read an output format from partners, we should update this test - // correspondingly (to report S16 as the desired output format). - - // This will be treated as unsigned 8 bit samples, and we expect it to be - // converted to two S16 samples. - const std::vector buffer_data = {0x00, 0xFF}; - scoped_refptr buffer( - new CastDecoderBufferImpl(buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), buffer_data.size()); - - AudioConfig original_config; - original_config.codec = AudioCodec::kCodecPCM; - original_config.channel_layout = ChannelLayout::MONO; - original_config.sample_format = SampleFormat::kSampleFormatU8; - original_config.bytes_per_channel = 1; - original_config.channel_number = 1; - original_config.samples_per_second = 44100; - original_config.encryption_scheme = EncryptionScheme::kUnencrypted; - - AudioConfig resampled_config; - resampled_config.codec = AudioCodec::kCodecPCM; - resampled_config.channel_layout = ChannelLayout::MONO; - resampled_config.sample_format = SampleFormat::kSampleFormatS16; - resampled_config.bytes_per_channel = 2; - resampled_config.channel_number = 1; - resampled_config.samples_per_second = 44100; - resampled_config.encryption_scheme = EncryptionScheme::kUnencrypted; - - // Note: this is little endian representing two S16 values corresponding to - // buffer_data above. - const std::vector expected_resampled_buffer_data = {0x00, 0x80, 0xFF, - 0x7F}; - scoped_refptr expected_resampled_buffer( - new CastDecoderBufferImpl(expected_resampled_buffer_data.size())); - memcpy(expected_resampled_buffer->writable_data(), - expected_resampled_buffer_data.data(), - expected_resampled_buffer_data.size()); - - EXPECT_CALL(*starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeAudio, - Pointee(MatchesAudioConfigAndBuffer( - resampled_config, expected_resampled_buffer)), - 1)) - .Times(1); - - StarboardAudioDecoder decoder(starboard_.get()); - decoder.SetConfig(original_config); - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - MockDelegate delegate; - decoder.SetDelegate(&delegate); - - // At this point, the pending buffer should be pushed. - decoder.Initialize(&fake_player_); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_decoder.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_decoder.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_decoder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_decoder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,257 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "starboard_decoder.h" - -#include - -#include "base/check_op.h" -#include "base/hash/hash.h" -#include "base/logging.h" -#include "base/task/bind_post_task.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/starboard/media/cdm/starboard_drm_key_tracker.h" - -namespace chromecast { -namespace media { - -using BufferStatus = ::chromecast::media::MediaPipelineBackend::BufferStatus; - -StarboardDecoder::StarboardDecoder(StarboardApiWrapper* starboard, - StarboardMediaType media_type) - : starboard_(starboard), media_type_(media_type) { - CHECK(starboard_); -} - -StarboardDecoder::~StarboardDecoder() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (drm_key_token_) { - StarboardDrmKeyTracker::GetInstance().UnregisterCallback(*drm_key_token_); - } -} - -void StarboardDecoder::Deallocate(const uint8_t* buffer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(buffer); - - auto it = copied_buffers_.find(buffer); - if (it == copied_buffers_.end()) { - // Since the MediaPipelineBackendStarboard does not know which decoder - // owns the buffer, this buffer may belong to another decoder. A no-op for - // this decoder. - return; - } - - // This frees the memory via the unique_ptr's destructor. - copied_buffers_.erase(it); -} - -void StarboardDecoder::Initialize(void* sb_player) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(sb_player); - - player_ = sb_player; - InitializeInternal(); - - if (pending_first_push_) { - LOG(INFO) << "Pushing pending " - << (media_type_ == kStarboardMediaTypeAudio ? "audio " : "video ") - << "buffer"; - const BufferStatus status = std::move(pending_first_push_).Run(); - DCHECK_EQ(status, BufferStatus::kBufferPending); - } -} - -void StarboardDecoder::Stop() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - LOG(INFO) << "Stopping " - << (media_type_ == kStarboardMediaTypeAudio ? "audio " : "video ") - << "decoder"; - - pending_first_push_.Reset(); - pending_drm_key_.Reset(); - if (drm_key_token_) { - StarboardDrmKeyTracker::GetInstance().UnregisterCallback(*drm_key_token_); - drm_key_token_ = std::nullopt; - } - - // By setting this to null, we will not push any more buffers until Initialize - // is called again. - player_ = nullptr; -} - -bool StarboardDecoder::IsInitialized() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return player_ != nullptr; -} - -void StarboardDecoder::OnBufferWritten() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(delegate_); - delegate_->OnPushBufferComplete(BufferStatus::kBufferSuccess); -} - -void StarboardDecoder::SetDecoderDelegate( - MediaPipelineBackend::Decoder::Delegate* delegate) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - delegate_ = delegate; -} - -BufferStatus StarboardDecoder::PushBufferInternal( - StarboardSampleInfo sample_info, - DrmInfoWrapper drm_info, - std::unique_ptr buffer_data, - size_t buffer_data_size) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(buffer_data); - DCHECK_GT(buffer_data_size, 0UL); - - if (!player_) { - if (pending_first_push_) { - LOG(WARNING) << "PushBuffer was called multiple times for " - << (media_type_ == kStarboardMediaTypeAudio ? "audio " - : "video ") - << "buffers before the decoder was initialized. Dropping " - "the old buffer."; - } else { - LOG(INFO) << "StarboardDecoder was not initialized before first " - "PushBuffer. Delaying push until initialization."; - } - - // Use of base::Unretained is safe here because pending_first_push_ will - // only be called by this object (implying that `this` will not have been - // destructed). - pending_first_push_ = base::BindOnce( - &StarboardDecoder::PushBufferInternal, base::Unretained(this), - std::move(sample_info), std::move(drm_info), std::move(buffer_data), - buffer_data_size); - return BufferStatus::kBufferPending; - } - - DCHECK(buffer_data); - DCHECK(delegate_); - DCHECK(!pending_first_push_); - - // For encrypted buffers, we should not push data to starboard util the - // buffer's DRM key is available to the CDM. To accomplish this, we check with - // the StarboardDrmKeyTracker singleton -- which is updated by the CDM, - // StarboardDecryptorCast -- to see whether the key is available. If the key - // is not available yet, we register a callback that will be run once the key - // becomes available. - if (StarboardDrmSampleInfo* drm_sample_info = drm_info.GetDrmSampleInfo(); - drm_sample_info != nullptr) { - const std::string drm_key( - reinterpret_cast(&drm_sample_info->identifier), - drm_sample_info->identifier_size); - if (!StarboardDrmKeyTracker::GetInstance().HasKey(drm_key)) { - // They key is not available yet; register a callback to push the buffer - // once the key becomes available. - CHECK_GE(drm_sample_info->identifier_size, 0); - const size_t key_hash = base::FastHash(base::make_span( - drm_sample_info->identifier, - static_cast(drm_sample_info->identifier_size))); - LOG(INFO) << "Waiting for DRM key with hash: " << key_hash; - pending_drm_key_ = base::BindOnce( - &StarboardDecoder::PushBufferInternal, base::Unretained(this), - std::move(sample_info), std::move(drm_info), std::move(buffer_data), - buffer_data_size); - - CHECK(base::SequencedTaskRunner::HasCurrentDefault()); - drm_key_token_ = StarboardDrmKeyTracker::GetInstance().WaitForKey( - drm_key, - base::BindPostTask( - base::SequencedTaskRunner::GetCurrentDefault(), - base::BindOnce(&StarboardDecoder::RunPendingDrmKeyCallback, - weak_factory_.GetWeakPtr()))); - return BufferStatus::kBufferPending; - } - - // The key is already available; continue the logic of pushing the buffer to - // starboard. - } - - const uint8_t* buffer_addr = buffer_data.get(); - - // Ensure that we do not delete the media data until Deallocate is called. - const bool inserted = - copied_buffers_.insert({buffer_addr, std::move(buffer_data)}).second; - DCHECK(inserted) << "Duplicate memory address in copied_buffers_: " - << static_cast(buffer_addr); - - sample_info.buffer = static_cast(buffer_addr); - sample_info.buffer_size = buffer_data_size; - sample_info.drm_info = drm_info.GetDrmSampleInfo(); - - starboard_->WriteSample(player_, media_type_, &sample_info, - /*sample_infos_count=*/1); - - // Returning kBufferPending here means that another buffer will not be pushed - // until Decoder::Delegate::OnPushBufferComplete is called. - return BufferStatus::kBufferPending; -} - -BufferStatus StarboardDecoder::PushEndOfStream() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(delegate_); - - starboard_->WriteEndOfStream(player_, media_type_); - return BufferStatus::kBufferSuccess; -} - -void* StarboardDecoder::GetPlayer() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return player_; -} - -StarboardApiWrapper& StarboardDecoder::GetStarboardApi() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return *starboard_; -} - -MediaPipelineBackend::Decoder::Delegate* StarboardDecoder::GetDelegate() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return delegate_; -} - -void StarboardDecoder::OnSbPlayerEndOfStream() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (delegate_) { - delegate_->OnEndOfStream(); - } -} - -void StarboardDecoder::OnStarboardDecodeError() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (delegate_) { - delegate_->OnDecoderError(); - } -} - -void StarboardDecoder::RunPendingDrmKeyCallback(int64_t token) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (!drm_key_token_) { - LOG(INFO) - << "Pending DRM key callback was run after drm_key_token_ was cleared."; - return; - } - - if (*drm_key_token_ != token) { - LOG(INFO) << "Pending DRM key callback was called for a token that does " - "not match the expected token. Expected token: " - << *drm_key_token_ << ", received token: " << token; - return; - } - - // Clear the token, since we are no longer waiting to run the callback. - drm_key_token_ = std::nullopt; - - LOG(INFO) << "Running DRM key callback"; - CHECK_EQ(std::move(pending_drm_key_).Run(), BufferStatus::kBufferPending); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_decoder.h chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_decoder.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_decoder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_decoder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_DECODER_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_DECODER_H_ - -#include - -#include "base/containers/flat_map.h" -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "chromecast/public/media/cast_decrypt_config.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/starboard/media/media/drm_util.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -// A base class for StarboardAudioDecoder and StarboardVideoDecoder, containing -// logic common to all decoders. It manages interactions with Starboard and the -// lifetime of buffers. -// -// This is an abstract class; child classes can implement InitializeInternal to -// perform any necessary initialization logic. -// -// All functions, including the constructor and destructor, must be called on -// the same sequence (the media thread). -class StarboardDecoder { - public: - // Disallow copy and assign. - StarboardDecoder(const StarboardDecoder&) = delete; - StarboardDecoder& operator=(const StarboardDecoder&) = delete; - - // Called when a buffer can be deallocated. - void Deallocate(const uint8_t* buffer); - - // Initializes the decoder by providing the opaque SbPlayer that will be used - // to decode/render buffers. Before this call, no buffers will be pushed to - // Starboard. Calling Pushbuffer will just queue the buffer. - // `sb_player` must not be null. - void Initialize(void* sb_player); - - // Clears any pending buffer, and sets the decoder into an un-initialized - // state. - void Stop(); - - // Returns true if the decoder is initialized, false otherwise. After Stop(), - // the decoder is no longer initialized. - bool IsInitialized(); - - // Called when a buffer has been processed by Starboard. - void OnBufferWritten(); - - // Notifies the delegate that the end of stream buffer has been rendered. This - // should be called once the SbPlayer has sent the - // kStarboardPlayerStateEndOfStream/kSbPlayerStateEndOfStream signal. - void OnSbPlayerEndOfStream(); - - // Called when the SbPlayer has encountered a decoder error. Notifies the - // delegate that an error has occurred. - void OnStarboardDecodeError(); - - protected: - // Calls to Starboard are made via `starboard`, to allow mocking in tests. - // `media_type` specifies the type of decoder that this represents (audio or - // video). - StarboardDecoder(StarboardApiWrapper* starboard, - StarboardMediaType media_type); - - virtual ~StarboardDecoder(); - - // Sets the delegate for this decoder. This delegate is informed when buffers - // have been pushed. - void SetDecoderDelegate(MediaPipelineBackend::Decoder::Delegate* delegate); - - // Pushes a buffer to starboard. Takes ownership of `buffer_data` to manage - // its lifetime: it will not be freed until Deallocate is called (or this - // object is destroyed). - // - // This function will populate sample_info.drm_info, sample_info.buffer, and - // sample_info.buffer_size before sending the sample to Starboard. The values - // will be populated based on the values of `drm_info` and `buffer_data`. - // - // `buffer_data` must not be empty (use PushEndOfStream to signal the end of a - // stream). - MediaPipelineBackend::BufferStatus PushBufferInternal( - StarboardSampleInfo sample_info, - DrmInfoWrapper drm_info, - std::unique_ptr buffer_data, - size_t buffer_data_size); - - // Sends an "end of stream" signal to starboard. - MediaPipelineBackend::BufferStatus PushEndOfStream(); - - // Returns the current SbPlayer. May return null if the current SbPlayer has - // not been set, or if the decoder has been stopped. - void* GetPlayer(); - - // Returns a StarboardApiWrapper, which can be used to interact with Starboard - // directly. - StarboardApiWrapper& GetStarboardApi() const; - - // Returns the current delegate, or null if none is currently set. - MediaPipelineBackend::Decoder::Delegate* GetDelegate() const; - - private: - // Performs any initialization logic for the child class. This will run after - // Initialize runs, and is called each time Initialize is called. - virtual void InitializeInternal() = 0; - - // Runs pending_drm_key_ if `token` matches drm_key_token_. Called once a DRM - // key is available. - void RunPendingDrmKeyCallback(int64_t token); - - SEQUENCE_CHECKER(sequence_checker_); - StarboardApiWrapper* starboard_ = nullptr; - StarboardMediaType media_type_; - // The opaque SbPlayer. - void* player_ = nullptr; - MediaPipelineBackend::Decoder::Delegate* delegate_ = nullptr; - // If PushBuffer is called before the decoder has received a handle to the - // SbPlayer, the push is delayed and this contains the call to - // PushBufferInternal. - base::OnceCallback pending_first_push_; - // This map is expected to be small (likely only one or two elements), hence - // the use of a flat_map. - // Maps from the array address to the unique_ptr that manages the array. - base::flat_map> copied_buffers_; - // A callback to be run once the necessary DRM key is available. The callback - // will push a pending buffer. - base::OnceCallback pending_drm_key_; - // If we are waiting for a DRM key to be available, this will be set. On - // destruction, we can use this token to unregister the callback with - // StarboardDrmKeyTracker. This is not necessary for correct functionality, - // but helps clean out StarboardDrmKeyTracker's list of callbacks. - std::optional drm_key_token_; - - // This should be destructed first. - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_DECODER_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_resampler.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_resampler.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,299 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "starboard_resampler.h" - -#include - -#include "base/check_op.h" -#include "base/logging.h" -#include "chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h" - -namespace chromecast { -namespace media { - -namespace { - -// A function type for converting an input sample to a double. -using ToDoubleFn = double (*)(const uint8_t* in_iter); - -// A function type for converting the double specified by `in` to an output -// sample, written to `out_iter`. -using ToOutputFn = void (*)(double in, uint8_t* out_iter); - -// Converts an unsigned 8-bit audio sample to a double. -double U8ToDouble(const uint8_t* in) { - constexpr int16_t kUnsignedInt8Offset = 0x80; - // After being shifted to signed 8 bit,the values are in [-128, 127]. - const double max_value = *in > kUnsignedInt8Offset ? 0x7F : 0x80; - return (*in - kUnsignedInt8Offset) / max_value; -} - -// Converts a signed 16-bit audio sample to a double. -double S16ToDouble(const uint8_t* in) { - const int16_t in_s16 = *reinterpret_cast(in); - const double max_value = in_s16 > 0 ? 0x7FFF : 0x8000; - return in_s16 / max_value; -} - -// Converts a Big Endian signed 16-bit audio sample to a double. -double S16BEToDouble(const uint8_t* in) { - // Reverse the bytes. - uint8_t data[2]; - data[0] = in[1]; - data[1] = in[0]; - - // Now `data` holds an S16 in little endian byte order, so we can reuse the - // logic of S16ToDouble. - return S16ToDouble(data); -} - -// Converts a signed 24-bit audio sample to a double. -double S24ToDouble(const uint8_t* in) { - // Note: we avoid bit shifting here, since bit shifting signed types is - // undefined behavior, and converting from signed to unsigned types can be - // implementation-defined. - uint8_t data[4]; - data[0] = in[0]; - data[1] = in[1]; - data[2] = in[2]; - // The highest byte of the int32_t is filled with the same value as the - // highest bit of the int24, to properly account for the sign. - data[3] = ((in[2] & 0x80) == 0) ? 0x00 : ~0x00; - const int32_t in_s24 = *reinterpret_cast(data); - const double max_value = in_s24 > 0 ? 0x7FFFFF : 0x800000; - return in_s24 / max_value; -} - -// Converts a signed 32-bit audio sample to a double. -double S32ToDouble(const uint8_t* in) { - const int32_t in_s32 = *reinterpret_cast(in); - const double max_value = in_s32 > 0 ? 0x7FFFFFFF : 0x80000000; - return in_s32 / max_value; -} - -// Converts a float audio sample to a double. -double FloatToDouble(const uint8_t* in) { - return *reinterpret_cast(in); -} - -// Converts a double audio sample to S16, writing it to `out`. -void WriteDoubleToS16(double in, uint8_t* out) { - const int32_t max_value = in > 0 ? 0x7FFF : 0x8000; - *reinterpret_cast(out) = std::round(in * max_value); -} - -// Converts a double audio sample to S32, writing it to `out`. -void WriteDoubleToS32(double in, uint8_t* out) { - const int64_t max_value = in > 0 ? 0x7FFFFFFF : 0x80000000; - *reinterpret_cast(out) = - std::round(static_cast(in) * max_value); -} - -// Converts a double audio sample to float, writing it to `out`. -void WriteDoubleToFloat(double in, uint8_t* out) { - *reinterpret_cast(out) = in; -} - -// Returns the number of bytes per channel for `format`. `format` must not be -// unknown. -// -// Note that this is different from the implementation of -// ::media::SampleFormatToBitsPerChannel(). That one maps S24 to 4 bytes instead -// of 3. -int BytesPerChannel(SampleFormat format) { - switch (format) { - case chromecast::media::kSampleFormatU8: { - return 1; - } - case chromecast::media::kSampleFormatPlanarS16: - case chromecast::media::kSampleFormatS16: { - return 2; - } - case chromecast::media::kSampleFormatS24: { - return 3; - } - case chromecast::media::kSampleFormatPlanarS32: - case chromecast::media::kSampleFormatS32: - case chromecast::media::kSampleFormatF32: - case chromecast::media::kSampleFormatPlanarF32: { - return 4; - } - default: { - LOG(FATAL) << "Unsupported sample format: " << format; - } - } -} - -// Returns the number of bytes per channel for `format`. -int BytesPerChannel(StarboardPcmSampleFormat format) { - switch (format) { - case kStarboardPcmSampleFormatS16: - return 2; - case kStarboardPcmSampleFormatS32: - case kStarboardPcmSampleFormatF32: - return 4; - } -} - -// Returns the conversion function needed to convert `in_sample_format` to -// double. `in_audio_codec` is needed because Big Endian S16 data is treated as -// its own codec (kCodecPCM_S16BE). -// -// This function crashes if an invalid in_sample_format is passed to it. -ToDoubleFn GetInputConversionFunction(SampleFormat in_sample_format, - AudioCodec in_audio_codec) { - switch (in_sample_format) { - case chromecast::media::kSampleFormatU8: { - return &U8ToDouble; - } - case chromecast::media::kSampleFormatPlanarS16: - case chromecast::media::kSampleFormatS16: { - return (in_audio_codec == kCodecPCM_S16BE) ? &S16BEToDouble - : &S16ToDouble; - } - case chromecast::media::kSampleFormatS24: { - return &S24ToDouble; - } - case chromecast::media::kSampleFormatPlanarS32: - case chromecast::media::kSampleFormatS32: { - return &S32ToDouble; - } - case chromecast::media::kSampleFormatF32: - case chromecast::media::kSampleFormatPlanarF32: { - return &FloatToDouble; - } - default: { - LOG(FATAL) << "Unsupported input format: " << in_sample_format; - } - } -} - -// Returns the conversion function needed to convert double values to -// `out_sample_format`. -ToOutputFn GetOutputConversionFunction( - StarboardPcmSampleFormat out_sample_format) { - switch (out_sample_format) { - case kStarboardPcmSampleFormatS16: { - return &WriteDoubleToS16; - } - case kStarboardPcmSampleFormatS32: { - return &WriteDoubleToS32; - } - case kStarboardPcmSampleFormatF32: { - return &WriteDoubleToFloat; - } - } -} - -// Resamples the PCM data in `buffer` from `in_sample_format` to -// `out_sample_format`. `out_size` is the size of the returned buffer, in bytes. -// `in_audio_codec` is needed because S16BE is treated as its own codec. -std::unique_ptr ResamplePCM( - const CastDecoderBuffer& buffer, - int num_channels, - SampleFormat in_sample_format, - StarboardPcmSampleFormat out_sample_format, - AudioCodec in_audio_codec, - size_t& out_size) { - DCHECK_GT(num_channels, 0); - - const int in_bytes_per_channel = BytesPerChannel(in_sample_format); - const int out_bytes_per_channel = BytesPerChannel(out_sample_format); - - const uint8_t* in_data = buffer.data(); - out_size = - (buffer.data_size() * out_bytes_per_channel) / in_bytes_per_channel; - auto out_data = std::make_unique(out_size); - - // These two functions are used to convert any input type to any output type. - // The conversion goes: - // input -> double -> output - // to reduce the number of code paths (2n vs (n choose 2)) and simplify the - // conversion logic (since converting to/from double is straightforward). - const ToDoubleFn convert_to_double = - GetInputConversionFunction(in_sample_format, in_audio_codec); - const ToOutputFn write_output_type = - GetOutputConversionFunction(out_sample_format); - - const bool is_input_planar = - in_sample_format == chromecast::media::kSampleFormatPlanarS16 || - in_sample_format == chromecast::media::kSampleFormatPlanarS32 || - in_sample_format == chromecast::media::kSampleFormatPlanarF32; - - const int num_planes = is_input_planar ? num_channels : 1; - - std::vector plane_offsets; - for (int plane = 0; plane < num_planes; ++plane) { - plane_offsets.push_back(plane * (buffer.data_size() / num_planes)); - } - - // For each input sample, this loop converts it to double and then to the - // final output format. It also handles converting from planar to interleaved, - // if necessary. - // - // Planar data is grouped by channel; interleaved data is not. For example, - // consider 2-channel data where A represents data from the first channel, and - // B represents data from the second channel. 4 samples of planar data would - // be: - // AAAABBBB - // whereas 4 samples of interleaved data would be: - // ABABABAB - for (int i = 0; - i * static_cast(in_bytes_per_channel) < buffer.data_size(); - ++i) { - const int plane = i % num_planes; - const int index_by_plane = i / num_planes; - - write_output_type(convert_to_double(in_data + plane_offsets[plane] + - index_by_plane * in_bytes_per_channel), - &out_data[i * out_bytes_per_channel]); - } - - return out_data; -} - -// Returns true if the two formats do not match, meaning resampling is -// necessary. Returns false otherwise. -bool RequiresResampling(StarboardPcmSampleFormat format_to_decode_to, - SampleFormat format_to_decode_from) { - const bool same_format = - (format_to_decode_to == kStarboardPcmSampleFormatS16 && - format_to_decode_from == kSampleFormatS16) || - (format_to_decode_to == kStarboardPcmSampleFormatS32 && - format_to_decode_from == kSampleFormatS32) || - (format_to_decode_to == kStarboardPcmSampleFormatF32 && - format_to_decode_from == kSampleFormatF32); - return !same_format; -} -} // namespace - -std::unique_ptr ResamplePCMAudioDataForStarboard( - StarboardPcmSampleFormat format_to_decode_to, - SampleFormat format_to_decode_from, - AudioCodec audio_codec, - int audio_channels, - const CastDecoderBuffer& buffer, - size_t& buffer_out_size) { - // The check for kCodecPCM is necessary because there is a separate codec, - // kCodecPCM_S16BE, which is in Big Endian format instead of Little Endian - // like all the other formats. In that case, at minimum we need to change the - // samples to Little Endian, since we do not support Big Endian output - // formats. - if (audio_codec == AudioCodec::kCodecPCM && - !RequiresResampling(format_to_decode_to, format_to_decode_from)) { - // No resampling is necessary; return a copy of the data. - const size_t size_of_buffer = buffer.data_size(); - buffer_out_size = size_of_buffer; - auto data_copy = std::make_unique(size_of_buffer); - memcpy(data_copy.get(), buffer.data(), size_of_buffer); - return data_copy; - } - - return ResamplePCM(buffer, audio_channels, format_to_decode_from, - format_to_decode_to, audio_codec, buffer_out_size); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_resampler.h chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_resampler.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_RESAMPLER_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_RESAMPLER_H_ - -#include -#include - -#include - -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/public/media/decoder_config.h" -#include "chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h" - -namespace chromecast { -namespace media { - -// Returns resampled PCM data. `format_to_decode_to` is the output format, and -// `format_to_decode_from` is the input format. `audio_codec` describes the -// input codec, and is used to handle the case of Big Endian input data, -// kCodecPCM_S16BE. `audio_channels` is the number of channels in the input -// data, and must be greater than 0. `buffer` contains the input PCM data. -// `buffer_out_size` is set to the size of the output buffer, in bytes. -// -// TODO(b/334991778): see if we can reuse existing chromium infra to do the -// conversion. -std::unique_ptr ResamplePCMAudioDataForStarboard( - StarboardPcmSampleFormat format_to_decode_to, - SampleFormat format_to_decode_from, - AudioCodec audio_codec, - int audio_channels, - const CastDecoderBuffer& buffer, - size_t& buffer_out_size); - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_RESAMPLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_resampler_test.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler_test.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_resampler_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_resampler_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,515 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/starboard_resampler.h" - -#include -#include -#include -#include - -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/starboard/chromecast/starboard_cast_api/cast_starboard_api_types.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::FloatEq; -using ::testing::Pointwise; - -TEST(StarboardResamplerTest, PCM8ToS16) { - size_t out_size; - const std::vector buffer_data = {0, 0x80, 0xFF}; - const std::vector expected_s16_data = {static_cast(0x8000), - 0, 0x7FFF}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(uint8_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(uint8_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatU8, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PCM8ToS32) { - size_t out_size; - const std::vector buffer_data = {0, 0x80, 0xFF}; - const std::vector expected_s32_data = { - static_cast(0x80000000), 0, 0x7FFFFFFF}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(uint8_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(uint8_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS32, kSampleFormatU8, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_EQ(resampled_buffer, expected_s32_data); -} - -TEST(StarboardResamplerTest, PCMU8ToFloat) { - size_t out_size; - const std::vector buffer_data = {1, 2, 3, 4}; - const std::vector expected_f32_data = {-0.9921875, -0.984375, - -0.9765625, -0.96875}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(uint8_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(uint8_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatF32, kSampleFormatU8, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_THAT(resampled_buffer, Pointwise(FloatEq(), expected_f32_data)); -} - -////// END OF U8 TO OTHER FORMATS -////// START OF S16 TO OTHER FORMATS - -TEST(StarboardResamplerTest, PCMS16ToS16) { - size_t out_size; - const std::vector buffer_data = {-32768, 0, 32767}; - const std::vector expected_s16_data = {-32768, 0, 32767}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int16_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int16_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatS16, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PCMS16ToS32) { - size_t out_size; - const std::vector buffer_data = {static_cast(0x8000), 0, - 0x7FFF}; - const std::vector expected_s32_data = { - static_cast(0x80000000), 0, 0x7FFFFFFF}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int16_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int16_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS32, kSampleFormatS16, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_EQ(resampled_buffer, expected_s32_data); -} - -TEST(StarboardResamplerTest, PCMS16ToFloat) { - size_t out_size; - const std::vector buffer_data = {static_cast(0x8000), - static_cast(0xC000), 0, - 0x3FFF, 0x7FFF}; - const std::vector expected_f32_data = {-1.0f, -0.5f, 0.0f, - 0.499984741f, 1.0f}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int16_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int16_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatF32, kSampleFormatS16, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_THAT(resampled_buffer, Pointwise(FloatEq(), expected_f32_data)); -} - -// End of Signed 16 Conversions -// Start of Signed 24 conversions - -TEST(StarboardResamplerTest, PCMS24ToS16) { - size_t out_size; - const std::vector buffer_data = {0xCC, 0xAA, 0xBB, 0, 0, - 0, 0xFF, 0xFF, 0x7F}; - const std::vector expected_s16_data = {-17493, 0, 32767}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatS24, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PCMS24ToS32) { - size_t out_size; - // Represents {0x800000, 0x000000, 0x7FFFFF}, since it's in Little Endian byte - // order. - const std::vector buffer_data = {0, 0, 0x80, 0, 0, - 0, 0xFF, 0xFF, 0x7F}; - const std::vector expected_s32_data = { - static_cast(0x80000000), 0, 0x7FFFFFFF}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS32, kSampleFormatS24, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_EQ(resampled_buffer, expected_s32_data); -} - -TEST(StarboardResamplerTest, PCMS24ToFloat) { - size_t out_size; - // Represents {0x800000, 0x000000, 0x7FFFFF}, since it's in Little Endian byte - // order. - const std::vector buffer_data = {0, 0, 0x80, 0, 0, - 0, 0xFF, 0xFF, 0x7F}; - const std::vector expected_f32_data = {-1.0f, 0.0f, 1.0f}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatF32, kSampleFormatS24, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_THAT(resampled_buffer, Pointwise(FloatEq(), expected_f32_data)); -} - -// End of Signed 24 Conversions -// Start of Signed 32 conversions - -TEST(StarboardResamplerTest, PCMS32ToS16) { - size_t out_size; - const std::vector buffer_data = {-2147483648, 0, 70000, 2147483647}; - const std::vector expected_s16_data = {-32768, 0, 1, 32767}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int32_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int32_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatS32, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + 4); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PCMS32ToS32) { - size_t out_size; - const std::vector buffer_data = {-2147483647, 0, 2147483647}; - const std::vector expected_s32_data = {-2147483647, 0, 2147483647}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int32_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int32_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS32, kSampleFormatS32, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_EQ(resampled_buffer, expected_s32_data); -} - -TEST(StarboardResamplerTest, PCMS32ToFloat) { - size_t out_size; - const std::vector buffer_data = {static_cast(0x80000000), 0, - 0x7FFFFFFF}; - const std::vector expected_f32_data = {-1.0f, 0.0f, 1.0f}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int32_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int32_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatF32, kSampleFormatS32, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_THAT(resampled_buffer, Pointwise(FloatEq(), expected_f32_data)); -} - -// End of Signed 32 Conversions -// Start of Float conversions - -TEST(StarboardResamplerTest, PCMFloatToS16) { - size_t out_size; - const std::vector buffer_data = {-1.0f, 0.0f, 1.0f}; - const std::vector expected_s16_data = {-32768, 0, 32767}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(float) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(float) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatF32, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PCMFloatToS32) { - size_t out_size; - const std::vector buffer_data = {-1.0f, 0.0f, 1.0f}; - const std::vector expected_s32_data = {-2147483648, 0, 2147483647}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(float) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(float) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS32, kSampleFormatF32, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_EQ(resampled_buffer, expected_s32_data); -} - -TEST(StarboardResamplerTest, PCMFloatToFloat) { - size_t out_size; - const std::vector buffer_data = {-1, 0.0234375, 0, 1}; - const std::vector expected_f32_data = {-1, 0.0234375, 0, 1}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(float) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(float) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatF32, kSampleFormatF32, kCodecPCM, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 4); - - EXPECT_THAT(resampled_buffer, Pointwise(FloatEq(), expected_f32_data)); -} - -// End of Float Conversions -// Start of Planar conversions - -TEST(StarboardResamplerTest, PushesBufferToStarboardPlanarPCM16) { - size_t out_size; - const std::vector buffer_data = {-32768, -32768, 16384, - 16384, 32767, 32767}; - const std::vector expected_s16_data = {-32768, 16384, 32767, - -32768, 16384, 32767}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int16_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int16_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatPlanarS16, kCodecPCM, 3, - *buffer.get(), out_size); - - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PushesBufferToStarboardPlanarPCM32) { - size_t out_size; - const std::vector buffer_data = {-2147483648, -2147483648, 1000000, - 1000000, 2000000, 2000000, - 2147483647, 2147483647}; - const std::vector expected_s16_data = {-32768, 15, 31, 32767, - -32768, 15, 31, 32767}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int32_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int32_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatPlanarS32, kCodecPCM, 4, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PushesBufferToStarboardPlanarPCMF32) { - size_t out_size; - const std::vector buffer_data = {-1, -1, 0.000465661, - 0.000465661, 1, 1}; - const std::vector expected_s16_data = {-32768, 15, 32767, - -32768, 15, 32767}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(float) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(float) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatPlanarF32, kCodecPCM, 3, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PushesBufferToStarboardPlanarPCM32Mono) { - size_t out_size; - // Everything should be shifted down by 16 bits. - const std::vector buffer_data = {static_cast(0x80000000), - 0x1000000, - 0x2000000, - 0x3000000, - 0x4000000, - 0x5000000, - 0x6000000, - 0x7000000, - 0x8000000, - 0x9000000, - 0x7FFFFFFF}; - const std::vector expected_s16_data = {static_cast(0x8000), - 0x100, - 0x200, - 0x300, - 0x400, - 0x500, - 0x600, - 0x700, - 0x800, - 0x900, - 0x7FFF}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int32_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int32_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatPlanarS32, kCodecPCM, 1, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, PushesBufferToStarboardPlanarPCM32MaxChannels) { - size_t out_size; - // Everything should be shifted down by 16 bits. - const std::vector buffer_data = { - 0, 0, 0x1000000, 0x1000000, 0x2000000, 0x2000000, - 0x3000000, 0x3000000, 0x4000000, 0x4000000, 0x5000000, 0x5000000, - 0x6000000, 0x6000000, 0x7000000, 0x7000000}; - const std::vector expected_s16_data = { - 0x0, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, - 0x0, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int32_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int32_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatPlanarS32, kCodecPCM, 8, - *buffer.get(), out_size); - - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -TEST(StarboardResamplerTest, - PushesBufferToStarboardPCM16BigEndianToLittleEndian) { - size_t out_size; - const std::vector buffer_data = {32640, 1040, 4100, 255}; - const std::vector expected_s16_data = {-32641, 4100, 1040, -256}; - - scoped_refptr buffer( - new CastDecoderBufferImpl(sizeof(int16_t) * buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), - sizeof(int16_t) * buffer_data.size()); - - std::unique_ptr ret_array = ResamplePCMAudioDataForStarboard( - kStarboardPcmSampleFormatS16, kSampleFormatS16, kCodecPCM_S16BE, 2, - *buffer.get(), out_size); - const std::vector resampled_buffer( - reinterpret_cast(ret_array.get()), - reinterpret_cast(ret_array.get()) + out_size / 2); - - EXPECT_EQ(resampled_buffer, expected_s16_data); -} - -// End of Signed 16 Conversions - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_decoder.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_decoder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,231 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "starboard_video_decoder.h" - -#include "base/check.h" -#include "base/check_op.h" -#include "base/logging.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/media/cast_decoder_buffer.h" -#include "chromecast/starboard/media/media/drm_util.h" -#include "chromecast/starboard/media/media/mime_utils.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" - -namespace chromecast { -namespace media { - -using BufferStatus = ::chromecast::media::MediaPipelineBackend::BufferStatus; - -static StarboardVideoCodec VideoCodecToStarboardCodec(VideoCodec codec) { - switch (codec) { - case kCodecH264: - return kStarboardVideoCodecH264; - case kCodecVC1: - return kStarboardVideoCodecVc1; - case kCodecMPEG2: - return kStarboardVideoCodecMpeg2; - case kCodecTheora: - return kStarboardVideoCodecTheora; - case kCodecVP8: - return kStarboardVideoCodecVp8; - case kCodecVP9: - return kStarboardVideoCodecVp9; - case kCodecHEVC: - case kCodecDolbyVisionHEVC: - return kStarboardVideoCodecH265; - case kCodecAV1: - return kStarboardVideoCodecAv1; - case kCodecDolbyVisionH264: - case kCodecMPEG4: - case kVideoCodecUnknown: - default: - LOG(ERROR) << "Unsupported video codec: " << codec; - return kStarboardVideoCodecNone; - } -} - -// Converts a cast VideoConfig to a StarboardVideoSampleInfo. MIME type is not -// properly set, since it stores a c string pointing to data that could go out -// of scope. Instead, it is hardcoded to the empty string. -static StarboardVideoSampleInfo ToVideoSampleInfo(const VideoConfig& config) { - StarboardVideoSampleInfo sample_info = {}; - - sample_info.codec = VideoCodecToStarboardCodec(config.codec); - sample_info.mime = ""; - // Unknown maximum capabilities. For adaptive playback, I don't think we can - // guarantee the max video quality that the MSP will send. - sample_info.max_video_capabilities = ""; - // We do not have info on whether a frame is actually a keyframe, so this is - // hardcoded to true for now. We should confirm that starboard implementations - // do not rely on this field, or submit a CL like crrev.com/c/4348024 to - // properly populate the field. - sample_info.is_key_frame = true; - sample_info.frame_width = config.width; - sample_info.frame_height = config.height; - - StarboardColorMetadata& color_metadata = sample_info.color_metadata; - // bits_per_channel and the chroma_*/cb_* fields below need to be derived from - // the MIME string. See b/230915942 for more info. - // Unfortunately, it doesn't look like MIME type is exposed to cast. Note that - // in Cobalt, these fields are all currently hard-coded to zero (in - // third_party/chromium/media/base/starboard_utils.cc). I don't think they're - // necessary for cast either, since cast doesn't seem to populate this info - // anywhere. - - // 0 translates to "unknown". - color_metadata.bits_per_channel = 0; - color_metadata.chroma_subsampling_horizontal = 0; - color_metadata.chroma_subsampling_vertical = 0; - color_metadata.cb_subsampling_horizontal = 0; - color_metadata.cb_subsampling_vertical = 0; - color_metadata.chroma_siting_horizontal = 0; - color_metadata.chroma_siting_vertical = 0; - - if (config.have_hdr_metadata) { - LOG(INFO) << "Video config has HDR metadata."; - - color_metadata.max_cll = config.hdr_metadata.max_content_light_level; - color_metadata.max_fall = config.hdr_metadata.max_frame_average_light_level; - - const auto& color_volume_metadata = - config.hdr_metadata.color_volume_metadata; - StarboardMediaMasteringMetadata& mastering_metadata = - color_metadata.mastering_metadata; - - mastering_metadata.primary_r_chromaticity_x = - color_volume_metadata.primary_r_chromaticity_x; - mastering_metadata.primary_r_chromaticity_y = - color_volume_metadata.primary_r_chromaticity_y; - mastering_metadata.primary_g_chromaticity_x = - color_volume_metadata.primary_g_chromaticity_x; - mastering_metadata.primary_g_chromaticity_y = - color_volume_metadata.primary_g_chromaticity_y; - mastering_metadata.primary_b_chromaticity_x = - color_volume_metadata.primary_b_chromaticity_x; - mastering_metadata.primary_b_chromaticity_y = - color_volume_metadata.primary_b_chromaticity_y; - mastering_metadata.white_point_chromaticity_x = - color_volume_metadata.white_point_chromaticity_x; - mastering_metadata.white_point_chromaticity_y = - color_volume_metadata.white_point_chromaticity_y; - mastering_metadata.luminance_max = color_volume_metadata.luminance_max; - mastering_metadata.luminance_min = color_volume_metadata.luminance_min; - } else { - color_metadata.max_cll = 0; - color_metadata.max_fall = 0; - } - - // config.primaries (::chromecast::media::PrimaryID) does not support any - // value equivalent to kSbMediaPrimaryIdCustom. Thus, we don't need to - // populate custom_primary_matrix. - color_metadata.primaries = static_cast(config.primaries); - color_metadata.transfer = static_cast(config.transfer); - color_metadata.matrix = static_cast(config.matrix); - color_metadata.range = static_cast(config.range); - - return sample_info; -} - -StarboardVideoDecoder::StarboardVideoDecoder(StarboardApiWrapper* starboard) - : StarboardDecoder(starboard, kStarboardMediaTypeVideo) {} - -StarboardVideoDecoder::~StarboardVideoDecoder() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -void StarboardVideoDecoder::InitializeInternal() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); -} - -const std::optional& -StarboardVideoDecoder::GetVideoSampleInfo() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return video_sample_info_; -} - -bool StarboardVideoDecoder::SetConfig(const VideoConfig& config) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - resolution_changed_ = - config.width != config_.width || config.height != config_.height; - if (resolution_changed_) { - LOG(INFO) << "Video resolution changed from (" << config_.width << ", " - << config_.height << ") to (" << config.width << ", " - << config.height << ")"; - } - - // Note: we do not call delegate->OnVideoResolutionChanged in this function, - // because the VideoPipelineImpl (the delegate) may not be in the kPlaying - // state. In that case, it ignores resolution changes. So we wait until - // PushBuffer; at that point, it must be in the kPlaying state. - - config_ = config; - video_sample_info_ = ToVideoSampleInfo(config_); - - codec_mime_ = - GetMimeType(config.codec, config.profile, config.codec_profile_level); - video_sample_info_->mime = codec_mime_.c_str(); - - return IsValidConfig(config_); -} - -BufferStatus StarboardVideoDecoder::PushBuffer(CastDecoderBuffer* buffer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(buffer); - - // At this point the VideoPipelineImpl (the delegate) should be in the - // kPlaying state, so it is safe to update the resolution. - MediaPipelineBackend::Decoder::Delegate* const delegate = GetDelegate(); - if (resolution_changed_ && delegate) { - delegate->OnVideoResolutionChanged( - chromecast::Size(config_.width, config_.height)); - resolution_changed_ = false; - } - - if (buffer->end_of_stream()) { - return PushEndOfStream(); - } - - DCHECK(video_sample_info_); - - const size_t copy_size = buffer->data_size(); - std::unique_ptr data_copy(new uint8_t[copy_size]); - uint8_t* const copy_addr = data_copy.get(); - memcpy(copy_addr, buffer->data(), copy_size); - - StarboardSampleInfo sample = {}; - sample.type = kStarboardMediaTypeVideo; - sample.timestamp = buffer->timestamp(); - sample.side_data = nullptr; - sample.side_data_count = 0; - sample.video_sample_info = *video_sample_info_; - - decoded_bytes_ += copy_size; - - return PushBufferInternal(std::move(sample), GetDrmInfo(*buffer), - std::move(data_copy), copy_size); -} - -void StarboardVideoDecoder::GetStatistics(Statistics* statistics) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!statistics) { - return; - } - - StarboardPlayerInfo player_info = {}; - GetStarboardApi().GetPlayerInfo(GetPlayer(), &player_info); - - statistics->decoded_bytes = decoded_bytes_; - statistics->decoded_frames = player_info.total_video_frames; - statistics->dropped_frames = player_info.dropped_video_frames; -} - -void StarboardVideoDecoder::SetDelegate(Delegate* delegate) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - SetDecoderDelegate(delegate); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_decoder.h chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_decoder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_VIDEO_DECODER_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_VIDEO_DECODER_H_ - -#include - -#include "base/containers/flat_map.h" -#include "base/sequence_checker.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "chromecast/starboard/media/media/starboard_decoder.h" - -namespace chromecast { -namespace media { - -// A VideoDecoder that sends buffers to a Starboard SbPlayer. -// -// All functions and the constructor/destructor must be called on the same -// sequence (the media thread). -class StarboardVideoDecoder - : virtual public StarboardDecoder, - virtual public MediaPipelineBackend::VideoDecoder { - public: - explicit StarboardVideoDecoder(StarboardApiWrapper* starboard); - ~StarboardVideoDecoder() override; - - // Returns the video config or nullopt if the config has not been set yet. - const std::optional& GetVideoSampleInfo(); - - // MediaPipelineBackend::VideoDecoder implementation: - bool SetConfig(const VideoConfig& config) override; - void GetStatistics(Statistics* statistics) override; - MediaPipelineBackend::BufferStatus PushBuffer( - CastDecoderBuffer* buffer) override; - void SetDelegate(Delegate* delegate) override; - - private: - // StarboardDecoder implementation: - void InitializeInternal() override; - - SEQUENCE_CHECKER(sequence_checker_); - // Since MIME type is passed as a c-string to starboard, we need to ensure - // that the backing data does not go out of scope before starboard reads it. - std::string codec_mime_; - std::optional video_sample_info_; - // If true, this decoder should report the resolution the next time PushBuffer - // is called. - bool resolution_changed_ = false; - VideoConfig config_; - // The number of bytes sent to the SbPlayer. Used for statistics. - uint64_t decoded_bytes_ = 0; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_VIDEO_DECODER_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_decoder_test.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder_test.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_decoder_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_decoder_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,693 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/starboard_video_decoder.h" - -#include - -#include "base/test/task_environment.h" -#include "chromecast/media/base/cast_decoder_buffer_impl.h" -#include "chromecast/media/cma/base/decoder_buffer_adapter.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/media/media_pipeline_backend.h" -#include "chromecast/starboard/media/cdm/starboard_drm_key_tracker.h" -#include "chromecast/starboard/media/media/starboard_api_wrapper.h" -#include "media/base/decoder_buffer.h" -#include "media/base/decrypt_config.h" -#include "media/base/encryption_scheme.h" -#include "media/base/subsample_entry.h" -#include "mock_starboard_api_wrapper.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::AllOf; -using ::testing::DoubleEq; -using ::testing::ElementsAre; -using ::testing::ElementsAreArray; -using ::testing::Eq; -using ::testing::ExplainMatchResult; -using ::testing::Field; -using ::testing::MockFunction; -using ::testing::NotNull; -using ::testing::Optional; -using ::testing::Pointee; -using ::testing::StrEq; -using ::testing::WithArg; - -// Converts between VideoCodec and StarboardVideoCodec. -StarboardVideoCodec ToStarboardVideoCodec(VideoCodec codec) { - switch (codec) { - case kCodecH264: - return kStarboardVideoCodecH264; - case kCodecVC1: - return kStarboardVideoCodecVc1; - case kCodecMPEG2: - return kStarboardVideoCodecMpeg2; - case kCodecTheora: - return kStarboardVideoCodecTheora; - case kCodecVP8: - return kStarboardVideoCodecVp8; - case kCodecVP9: - return kStarboardVideoCodecVp9; - case kCodecHEVC: - return kStarboardVideoCodecH265; - case kCodecAV1: - return kStarboardVideoCodecAv1; - default: - return kStarboardVideoCodecNone; - } -} - -// Compares a StarboardSampleInfo (arg) to a VideoConfig (config) and a -// scoped_refptr (buffer). -MATCHER_P2(MatchesVideoConfigAndBuffer, config, buffer, "") { - CHECK(buffer) << "Passed a null buffer to the matcher."; - - if (arg.type != kStarboardMediaTypeVideo) { - *result_listener << "the StarboardSampleInfo's type is not video"; - return false; - } - - // Check that the buffer's data matches. - if (!ExplainMatchResult( - ElementsAreArray(buffer->data(), buffer->data_size()), - std::tuple( - static_cast(arg.buffer), arg.buffer_size), - result_listener)) { - *result_listener << " the expected audio data"; - return false; - } - - // Check the width/height. - if (!ExplainMatchResult( - AllOf(Field(&StarboardVideoSampleInfo::frame_width, config.width), - Field(&StarboardVideoSampleInfo::frame_height, config.height)), - arg.video_sample_info, result_listener)) { - *result_listener << " the frame width/height"; - return false; - } - - // Check the rest of the fields. - return ExplainMatchResult(Eq(buffer->timestamp()), arg.timestamp, - result_listener) && - ExplainMatchResult(Eq(ToStarboardVideoCodec(config.codec)), - arg.video_sample_info.codec, result_listener) && - ExplainMatchResult(AllOf(Field(&StarboardColorMetadata::primaries, - static_cast(config.primaries)), - Field(&StarboardColorMetadata::transfer, - static_cast(config.transfer)), - Field(&StarboardColorMetadata::matrix, - static_cast(config.matrix)), - Field(&StarboardColorMetadata::range, - static_cast(config.range))), - arg.video_sample_info.color_metadata, - result_listener); -} - -// A mock delegate that can be passed to the decoder. -class MockDelegate : public MediaPipelineBackend::Decoder::Delegate { - public: - MockDelegate() = default; - ~MockDelegate() override = default; - - MOCK_METHOD(void, OnPushBufferComplete, (BufferStatus status), (override)); - MOCK_METHOD(void, OnEndOfStream, (), (override)); - MOCK_METHOD(void, OnDecoderError, (), (override)); - MOCK_METHOD(void, - OnKeyStatusChanged, - (const std::string& key_id, - CastKeyStatus key_status, - uint32_t system_code), - (override)); - MOCK_METHOD(void, OnVideoResolutionChanged, (const Size& size), (override)); -}; - -// A test fixture is used to manage the global mock state and to handle the -// lifetime of the SingleThreadTaskEnvironment. -class StarboardVideoDecoderTest : public ::testing::Test { - protected: - StarboardVideoDecoderTest() - : starboard_(std::make_unique()) { - // Ensure that tests begin with a clean slate regarding DRM keys. - StarboardDrmKeyTracker::GetInstance().ClearStateForTesting(); - } - - ~StarboardVideoDecoderTest() override = default; - - // This should be destructed last. - base::test::SingleThreadTaskEnvironment task_environment_; - // This will be passed to the MediaPipelineBackendStarboard, and all calls to - // Starboard will go through it. Thus, we can mock out those calls. - std::unique_ptr starboard_; - // Since SbPlayer is just an opaque blob to the MPB, we will simply use an int - // to represent it. - int fake_player_ = 1; -}; - -// Returns a simple VideoConfig. -VideoConfig GetBasicConfig() { - VideoConfig config; - - config.codec = VideoCodec::kCodecH264; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - config.width = 123; - config.height = 456; - - return config; -} - -TEST_F(StarboardVideoDecoderTest, PushesBufferToStarboard) { - const VideoConfig config = GetBasicConfig(); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr buffer( - new CastDecoderBufferImpl(buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), buffer_data.size()); - - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeVideo, - Pointee(MatchesVideoConfigAndBuffer(config, buffer)), 1)) - .Times(1); - - StarboardVideoDecoder decoder(starboard_.get()); - MockDelegate delegate; - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); -} - -TEST_F(StarboardVideoDecoderTest, WritesEndOfStreamToStarboard) { - EXPECT_CALL(*starboard_, - WriteEndOfStream(&fake_player_, kStarboardMediaTypeVideo)) - .Times(1); - - StarboardVideoDecoder decoder(starboard_.get()); - MockDelegate delegate; - - const VideoConfig config = GetBasicConfig(); - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(CastDecoderBufferImpl::CreateEOSBuffer().get()), - MediaPipelineBackend::BufferStatus::kBufferSuccess); -} - -TEST_F(StarboardVideoDecoderTest, PopulatesDrmInfoInSamples) { - // The length should be at most 16 bytes. - constexpr char kKeyId[] = "key_id"; - // This must be 16 bytes. - constexpr char kIv[] = "abcdefghijklmnop"; - // This must contain at least one subsample. - const std::vector<::media::SubsampleEntry> subsamples = { - ::media::SubsampleEntry(/*clear_bytes=*/1, /*cypher_bytes=*/2), - ::media::SubsampleEntry(/*clear_bytes=*/3, /*cypher_bytes=*/4), - }; - - // If we do not add this key, buffers will not be pushed to starboard. - StarboardDrmKeyTracker::GetInstance().AddKey(kKeyId, "session_id"); - - VideoConfig config = GetBasicConfig(); - config.encryption_scheme = EncryptionScheme::kAesCbc; - - const ::media::EncryptionPattern encryption_pattern(5, 6); - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCbcsConfig(kKeyId, kIv, subsamples, - encryption_pattern); - CHECK(decrypt_config); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr<::media::DecoderBuffer> decoder_buffer = - ::media::DecoderBuffer::CopyFrom(buffer_data); - CHECK(decoder_buffer); - decoder_buffer->set_decrypt_config(std::move(decrypt_config)); - - scoped_refptr buffer = - new DecoderBufferAdapter(decoder_buffer); - - StarboardDrmSampleInfo actual_drm_info = {}; - // The actual subsamples may be deleted after the call to - // SbPlayerWriteSample2, so we need to store a copy. - std::vector actual_subsamples; - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeVideo, - Pointee(AllOf(MatchesVideoConfigAndBuffer(config, buffer))), - 1)) - .WillOnce(WithArg<2>([&actual_drm_info, &actual_subsamples]( - StarboardSampleInfo* sample_infos) { - // Since this is only called when the fourth argument is 1, that - // means that sample_infos_count is 1. - StarboardSampleInfo sample_info = sample_infos[0]; - if (!sample_info.drm_info) { - return; - } - actual_drm_info = *sample_info.drm_info; - const int subsample_count = actual_drm_info.subsample_count; - if (subsample_count > 0) { - actual_subsamples.assign( - actual_drm_info.subsample_mapping, - actual_drm_info.subsample_mapping + subsample_count); - } - })); - - StarboardVideoDecoder decoder(starboard_.get()); - MockDelegate delegate; - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - EXPECT_EQ(actual_drm_info.encryption_scheme, - kStarboardDrmEncryptionSchemeAesCbc); - EXPECT_EQ(actual_drm_info.encryption_pattern.crypt_byte_block, - encryption_pattern.crypt_byte_block()); - EXPECT_EQ(actual_drm_info.encryption_pattern.skip_byte_block, - encryption_pattern.skip_byte_block()); - EXPECT_THAT(std::string(reinterpret_cast( - actual_drm_info.initialization_vector), - actual_drm_info.initialization_vector_size), - StrEq(kIv)); - EXPECT_THAT( - std::string(reinterpret_cast(actual_drm_info.identifier), - actual_drm_info.identifier_size), - StrEq(kKeyId)); - EXPECT_THAT( - actual_subsamples, - ElementsAre( - AllOf(Field(&StarboardDrmSubSampleMapping::clear_byte_count, 1), - Field(&StarboardDrmSubSampleMapping::encrypted_byte_count, 2)), - AllOf( - Field(&StarboardDrmSubSampleMapping::clear_byte_count, 3), - Field(&StarboardDrmSubSampleMapping::encrypted_byte_count, 4)))); -} - -TEST_F(StarboardVideoDecoderTest, DoesNotPushToStarboardIfDrmKeyIsUnavailable) { - // The length should be at most 16 bytes. - constexpr char kKeyId[] = "key_id"; - // This must be 16 bytes. - constexpr char kIv[] = "abcdefghijklmnop"; - // This must contain at least one subsample. - const std::vector<::media::SubsampleEntry> subsamples = { - ::media::SubsampleEntry(/*clear_bytes=*/1, /*cypher_bytes=*/2), - ::media::SubsampleEntry(/*clear_bytes=*/3, /*cypher_bytes=*/4), - }; - - // Since we do not add kKeyId to StarboardDrmKeyTracker, no buffer with this - // key ID should be pushed to starboard. - - VideoConfig config = GetBasicConfig(); - config.encryption_scheme = EncryptionScheme::kAesCtr; - - const ::media::EncryptionPattern encryption_pattern(5, 6); - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCbcsConfig(kKeyId, kIv, subsamples, - encryption_pattern); - CHECK(decrypt_config); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr<::media::DecoderBuffer> decoder_buffer = - ::media::DecoderBuffer::CopyFrom(buffer_data); - CHECK(decoder_buffer); - decoder_buffer->set_decrypt_config(std::move(decrypt_config)); - - scoped_refptr buffer = - new DecoderBufferAdapter(decoder_buffer); - - EXPECT_CALL(*starboard_, WriteSample).Times(0); - - StarboardVideoDecoder decoder(starboard_.get()); - MockDelegate delegate; - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); -} - -TEST_F(StarboardVideoDecoderTest, - PushesBufferToStarboardAfterDrmKeyIsAvailable) { - // The length should be at most 16 bytes. - constexpr char kKeyId[] = "key_id"; - // This must be 16 bytes. - constexpr char kIv[] = "abcdefghijklmnop"; - // This must contain at least one subsample. - const std::vector<::media::SubsampleEntry> subsamples = { - ::media::SubsampleEntry(/*clear_bytes=*/1, /*cypher_bytes=*/2), - ::media::SubsampleEntry(/*clear_bytes=*/3, /*cypher_bytes=*/4), - }; - - VideoConfig config = GetBasicConfig(); - config.encryption_scheme = EncryptionScheme::kAesCbc; - - const ::media::EncryptionPattern encryption_pattern(5, 6); - std::unique_ptr<::media::DecryptConfig> decrypt_config = - ::media::DecryptConfig::CreateCbcsConfig(kKeyId, kIv, subsamples, - encryption_pattern); - CHECK(decrypt_config); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr<::media::DecoderBuffer> decoder_buffer = - ::media::DecoderBuffer::CopyFrom(buffer_data); - CHECK(decoder_buffer); - decoder_buffer->set_decrypt_config(std::move(decrypt_config)); - - scoped_refptr buffer = - new DecoderBufferAdapter(decoder_buffer); - - StarboardDrmSampleInfo actual_drm_info = {}; - // The actual subsamples may be deleted after the call to - // SbPlayerWriteSample2, so we need to store a copy. - std::vector actual_subsamples; - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeVideo, - Pointee(AllOf(MatchesVideoConfigAndBuffer(config, buffer))), - 1)) - .WillOnce(WithArg<2>([&actual_drm_info, &actual_subsamples]( - StarboardSampleInfo* sample_infos) { - // Since this is only called when the fourth argument is 1, that - // means that sample_infos_count is 1. - StarboardSampleInfo sample_info = sample_infos[0]; - if (!sample_info.drm_info) { - return; - } - actual_drm_info = *sample_info.drm_info; - const int subsample_count = actual_drm_info.subsample_count; - if (subsample_count > 0) { - actual_subsamples.assign( - actual_drm_info.subsample_mapping, - actual_drm_info.subsample_mapping + subsample_count); - } - })); - - StarboardVideoDecoder decoder(starboard_.get()); - MockDelegate delegate; - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - // Now that the key is available, the buffer should be pushed to starboard. - StarboardDrmKeyTracker::GetInstance().AddKey(kKeyId, "session_id"); - // The callback provided by the decoder will post a task; run until the - // callback runs. - task_environment_.RunUntilIdle(); - - EXPECT_EQ(actual_drm_info.encryption_scheme, - kStarboardDrmEncryptionSchemeAesCbc); - EXPECT_EQ(actual_drm_info.encryption_pattern.crypt_byte_block, - encryption_pattern.crypt_byte_block()); - EXPECT_EQ(actual_drm_info.encryption_pattern.skip_byte_block, - encryption_pattern.skip_byte_block()); - EXPECT_THAT(std::string(reinterpret_cast( - actual_drm_info.initialization_vector), - actual_drm_info.initialization_vector_size), - StrEq(kIv)); - EXPECT_THAT( - std::string(reinterpret_cast(actual_drm_info.identifier), - actual_drm_info.identifier_size), - StrEq(kKeyId)); - EXPECT_THAT( - actual_subsamples, - ElementsAre( - AllOf(Field(&StarboardDrmSubSampleMapping::clear_byte_count, 1), - Field(&StarboardDrmSubSampleMapping::encrypted_byte_count, 2)), - AllOf( - Field(&StarboardDrmSubSampleMapping::clear_byte_count, 3), - Field(&StarboardDrmSubSampleMapping::encrypted_byte_count, 4)))); -} - -TEST_F(StarboardVideoDecoderTest, ReturnsNulloptBeforeConfigSet) { - StarboardVideoDecoder decoder(starboard_.get()); - - EXPECT_EQ(decoder.GetVideoSampleInfo(), std::nullopt); -} - -TEST_F(StarboardVideoDecoderTest, - ReturnsPopulatedSampleInfoAfterConfigHasBeenSet) { - StarboardVideoDecoder decoder(starboard_.get()); - - VideoConfig config; - config.codec = VideoCodec::kCodecVP8; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - - EXPECT_TRUE(decoder.SetConfig(config)); - EXPECT_THAT(decoder.GetVideoSampleInfo(), - Optional(Field(&StarboardVideoSampleInfo::codec, - kStarboardVideoCodecVp8))); -} - -TEST_F(StarboardVideoDecoderTest, PopulatesHdrInfo) { - StarboardVideoDecoder decoder(starboard_.get()); - - VideoConfig config; - config.codec = VideoCodec::kCodecVP8; - config.encryption_scheme = EncryptionScheme::kUnencrypted; - config.have_hdr_metadata = true; - config.hdr_metadata.max_content_light_level = 1; - config.hdr_metadata.max_frame_average_light_level = 2; - - auto& color_volume_metadata = config.hdr_metadata.color_volume_metadata; - color_volume_metadata.primary_r_chromaticity_x = 1; - color_volume_metadata.primary_r_chromaticity_y = 2; - color_volume_metadata.primary_g_chromaticity_x = 3; - color_volume_metadata.primary_g_chromaticity_y = 4; - color_volume_metadata.primary_b_chromaticity_x = 5; - color_volume_metadata.primary_b_chromaticity_y = 6; - color_volume_metadata.white_point_chromaticity_x = 7; - color_volume_metadata.white_point_chromaticity_y = 8; - color_volume_metadata.luminance_min = 9; - color_volume_metadata.luminance_max = 10; - - EXPECT_TRUE(decoder.SetConfig(config)); - const std::optional sample_info = - decoder.GetVideoSampleInfo(); - - ASSERT_TRUE(sample_info.has_value()); - EXPECT_EQ(sample_info->codec, kStarboardVideoCodecVp8); - EXPECT_EQ(sample_info->color_metadata.max_cll, 1UL); - EXPECT_EQ(sample_info->color_metadata.max_fall, 2UL); - EXPECT_EQ( - sample_info->color_metadata.mastering_metadata.primary_r_chromaticity_x, - 1); - EXPECT_EQ( - sample_info->color_metadata.mastering_metadata.primary_r_chromaticity_y, - 2); - EXPECT_EQ( - sample_info->color_metadata.mastering_metadata.primary_g_chromaticity_x, - 3); - EXPECT_EQ( - sample_info->color_metadata.mastering_metadata.primary_g_chromaticity_y, - 4); - EXPECT_EQ( - sample_info->color_metadata.mastering_metadata.primary_b_chromaticity_x, - 5); - EXPECT_EQ( - sample_info->color_metadata.mastering_metadata.primary_b_chromaticity_y, - 6); - EXPECT_EQ( - sample_info->color_metadata.mastering_metadata.white_point_chromaticity_x, - 7); - EXPECT_EQ( - sample_info->color_metadata.mastering_metadata.white_point_chromaticity_y, - 8); - EXPECT_EQ(sample_info->color_metadata.mastering_metadata.luminance_min, 9); - EXPECT_EQ(sample_info->color_metadata.mastering_metadata.luminance_max, 10); -} - -TEST_F(StarboardVideoDecoderTest, - HandlesMultiplePushBuffersBeforeInitialization) { - const std::vector buffer_data_1 = {1, 2, 3, 4, 5}; - scoped_refptr buffer_1( - new CastDecoderBufferImpl(buffer_data_1.size())); - memcpy(buffer_1->writable_data(), buffer_data_1.data(), buffer_data_1.size()); - - const std::vector buffer_data_2 = {6, 7, 8, 9, 10}; - scoped_refptr buffer_2( - new CastDecoderBufferImpl(buffer_data_2.size())); - memcpy(buffer_2->writable_data(), buffer_data_2.data(), buffer_data_2.size()); - - const VideoConfig config = GetBasicConfig(); - - // Only the last buffer -- buffer_2 -- should be sent to starboard once the - // decoder is initialized. - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeVideo, - Pointee(MatchesVideoConfigAndBuffer(config, buffer_1)), 1)) - .Times(0); - EXPECT_CALL( - *starboard_, - WriteSample(&fake_player_, kStarboardMediaTypeVideo, - Pointee(MatchesVideoConfigAndBuffer(config, buffer_2)), 1)) - .Times(1); - - StarboardVideoDecoder decoder(starboard_.get()); - decoder.SetConfig(config); - EXPECT_EQ(decoder.PushBuffer(buffer_1.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - EXPECT_EQ(decoder.PushBuffer(buffer_2.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - MockDelegate delegate; - decoder.SetDelegate(&delegate); - - // At this point, the pending buffer (buffer_2) should be pushed. - decoder.Initialize(&fake_player_); -} - -TEST_F(StarboardVideoDecoderTest, DoesNotCallDelegateEoSWhenPushingEoSBuffer) { - const VideoConfig config = GetBasicConfig(); - - StarboardVideoDecoder decoder(starboard_.get()); - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - MockDelegate delegate; - // This should not be called, since we never call - // decoder.OnSbPlayerEndOfStream() in this test. - EXPECT_CALL(delegate, OnEndOfStream).Times(0); - decoder.SetDelegate(&delegate); - - EXPECT_EQ(decoder.PushBuffer(CastDecoderBufferImpl::CreateEOSBuffer().get()), - MediaPipelineBackend::BufferStatus::kBufferSuccess); -} - -TEST_F(StarboardVideoDecoderTest, CallsDelegateEoSWhenSbPlayerStreamEnds) { - const VideoConfig config = GetBasicConfig(); - - StarboardVideoDecoder decoder(starboard_.get()); - - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - MockDelegate delegate; - EXPECT_CALL(delegate, OnEndOfStream).Times(1); - decoder.SetDelegate(&delegate); - decoder.OnSbPlayerEndOfStream(); -} - -TEST_F(StarboardVideoDecoderTest, ReportsStatistics) { - constexpr int kTotalVideoFrames = 3; - constexpr int kDroppedFrames = 1; - - EXPECT_CALL(*starboard_, GetPlayerInfo(&fake_player_, NotNull())) - .WillOnce(WithArg<1>([](StarboardPlayerInfo* player_info) { - *player_info = {}; - player_info->total_video_frames = kTotalVideoFrames; - player_info->dropped_video_frames = kDroppedFrames; - })); - - StarboardVideoDecoder decoder(starboard_.get()); - MockDelegate delegate; - - const VideoConfig config = GetBasicConfig(); - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - const std::vector buffer_data = {1, 2, 3, 4, 5}; - scoped_refptr buffer( - new CastDecoderBufferImpl(buffer_data.size())); - memcpy(buffer->writable_data(), buffer_data.data(), buffer_data.size()); - - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); - - MediaPipelineBackend::VideoDecoder::Statistics stats = {}; - decoder.GetStatistics(&stats); - EXPECT_EQ(stats.decoded_bytes, buffer_data.size()); - EXPECT_EQ(stats.decoded_frames, static_cast(kTotalVideoFrames)); - EXPECT_EQ(stats.dropped_frames, static_cast(kDroppedFrames)); -} - -TEST_F(StarboardVideoDecoderTest, - DoesNotInformDelegateWhenResolutionChangesBeforePushBuffer) { - constexpr int kNewWidth = 10; - constexpr int kNewHeight = 20; - - StarboardVideoDecoder decoder(starboard_.get()); - MockDelegate delegate; - - EXPECT_CALL(delegate, OnVideoResolutionChanged).Times(0); - - VideoConfig config = GetBasicConfig(); - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - // Update the config. This should NOT notify the delegate, because the - // pipeline may not be in the kPlaying state. - config.width = kNewWidth; - config.height = kNewHeight; - decoder.SetConfig(config); -} - -TEST_F(StarboardVideoDecoderTest, - InformsDelegateWhenResolutionChangesAtNextPushBuffer) { - constexpr int kNewWidth = 10; - constexpr int kNewHeight = 20; - - StarboardVideoDecoder decoder(starboard_.get()); - MockDelegate delegate; - - EXPECT_CALL(delegate, OnVideoResolutionChanged(AllOf( - Field(&chromecast::Size::width, Eq(kNewWidth)), - Field(&chromecast::Size::height, Eq(kNewHeight))))) - .Times(1); - - VideoConfig config = GetBasicConfig(); - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - decoder.SetDelegate(&delegate); - - // Update the config with the new resolution. - config.width = kNewWidth; - config.height = kNewHeight; - decoder.SetConfig(config); - - scoped_refptr buffer(new CastDecoderBufferImpl(10)); - // Pushing the buffer should trigger the call to OnVideoResolutionChanged. - EXPECT_EQ(decoder.PushBuffer(buffer.get()), - MediaPipelineBackend::BufferStatus::kBufferPending); -} - -TEST_F(StarboardVideoDecoderTest, PopulatesMimeTypeForHEVCDolbyVision) { - VideoConfig config = GetBasicConfig(); - config.codec = kCodecDolbyVisionHEVC; - config.profile = kDolbyVisionProfile5; - config.codec_profile_level = 6; - - StarboardVideoDecoder decoder(starboard_.get()); - decoder.Initialize(&fake_player_); - decoder.SetConfig(config); - - const std::optional& video_info = - decoder.GetVideoSampleInfo(); - - ASSERT_NE(video_info, std::nullopt); - EXPECT_THAT(video_info->mime, StrEq(R"-(video/mp4; codecs="dvhe.05.06")-")); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_plane.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_plane.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "starboard_video_plane.h" - -#include "base/logging.h" - -namespace chromecast { -namespace media { - -StarboardVideoPlane::StarboardVideoPlane() { - CHECK(base::SequencedTaskRunner::HasCurrentDefault()); - task_runner_ = base::SequencedTaskRunner::GetCurrentDefault(); -} - -StarboardVideoPlane::~StarboardVideoPlane() = default; - -void StarboardVideoPlane::SetGeometry(const RectF& display_rect, - Transform transform) { - if (!task_runner_->RunsTasksInCurrentSequence()) { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&StarboardVideoPlane::SetGeometry, - weak_factory_.GetWeakPtr(), display_rect, transform)); - return; - } - - // We store the current plane size so that we can run any newly-added - // callbacks with this resolution. - current_plane_ = std::make_pair(display_rect, transform); - - for (const auto& token_and_callback : token_to_callback_) { - token_and_callback.second.Run(display_rect, transform); - } -} - -int64_t StarboardVideoPlane::RegisterCallback( - GeometryChangedCallback callback) { - int64_t token = 0; - current_token_lock_.Acquire(); - token = current_token_++; - current_token_lock_.Release(); - - if (task_runner_->RunsTasksInCurrentSequence()) { - RegisterCallbackForToken(token, std::move(callback)); - } else { - task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&StarboardVideoPlane::RegisterCallbackForToken, - weak_factory_.GetWeakPtr(), token, std::move(callback))); - } - return token; -} - -void StarboardVideoPlane::RegisterCallbackForToken( - int64_t token, - GeometryChangedCallback callback) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - - if (current_plane_) { - LOG(INFO) << "Running pending geometry callback. Setting video plane to " - << current_plane_->first.width << "x" - << current_plane_->first.height << ", offset (" - << current_plane_->first.x << ", " << current_plane_->first.y - << ")"; - callback.Run(current_plane_->first, current_plane_->second); - } - token_to_callback_[token] = std::move(callback); -} - -void StarboardVideoPlane::UnregisterCallback(int64_t token) { - if (!task_runner_->RunsTasksInCurrentSequence()) { - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&StarboardVideoPlane::UnregisterCallback, - weak_factory_.GetWeakPtr(), token)); - return; - } - - token_to_callback_.erase(token); -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_plane.h chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane.h --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_plane.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_VIDEO_PLANE_H_ -#define CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_VIDEO_PLANE_H_ - -#include -#include - -#include "base/containers/flat_map.h" -#include "base/functional/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/synchronization/lock.h" -#include "base/task/sequenced_task_runner.h" -#include "chromecast/public/graphics_types.h" -#include "chromecast/public/video_plane.h" - -namespace chromecast { -namespace media { - -// A VideoPlane that can be used to register callbacks that will be run when the -// plane's geometry changes. Must be created on a sequence. -// -// Public functions can be called from any sequence. Note that registered -// callbacks will be run from the sequence on which the StarboardVideoPlane was -// constructed. To run the callback on another sequence, use base::BindPostTask -// or similar logic. -class StarboardVideoPlane : public VideoPlane { - public: - using GeometryChangedCallback = - base::RepeatingCallback; - - StarboardVideoPlane(); - - // Disallow copy and assign. - StarboardVideoPlane(const StarboardVideoPlane&) = delete; - StarboardVideoPlane& operator=(const StarboardVideoPlane&) = delete; - - ~StarboardVideoPlane() override; - - // Registers a callback that will be run when the geometry changes. Returns an - // opaque token that can be used to remove the callback later. - // - // If this plane's geometry has already been set, `callback` will be run with - // that geometry. This means that `callback` may be run before this function - // returns. - int64_t RegisterCallback(GeometryChangedCallback callback); - - // Unregisters a callback from the list of callbacks that are run when the - // geometry changes. `token` should be the value returned from a previous - // RegisterCallback call. If no matching token is found, this is a no-op. - void UnregisterCallback(int64_t token); - - // VideoPlane implementation: - void SetGeometry(const RectF& display_rect, Transform transform) override; - - private: - // A helper function that must be run on task_runner_. Registers `callback` - // with the specified `token`. - void RegisterCallbackForToken(int64_t token, - GeometryChangedCallback callback); - - base::flat_map token_to_callback_; - scoped_refptr task_runner_; - base::Lock current_token_lock_; - // This must only be accessed while current_token_lock_ is held. - int64_t current_token_ = 0; - - // The rectangle and transform representing the current video plane. If this - // is set when a new callback is registered, we will call the callback with - // this info. - std::optional> current_plane_; - - // This must be destructed first. - base::WeakPtrFactory weak_factory_{this}; -}; - -} // namespace media -} // namespace chromecast - -#endif // CHROMECAST_STARBOARD_MEDIA_MEDIA_STARBOARD_VIDEO_PLANE_H_ diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_plane_test.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane_test.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_video_plane_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_video_plane_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/starboard/media/media/starboard_video_plane.h" - -#include "base/test/bind.h" -#include "base/test/task_environment.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace media { -namespace { - -using ::testing::AllOf; -using ::testing::Field; -using ::testing::FloatEq; -using ::testing::Matcher; -using ::testing::MockFunction; - -constexpr VideoPlane::Transform kNoTransform = - VideoPlane::Transform::TRANSFORM_NONE; - -// Verifies that a RectF matches the fields of `rect`. -Matcher MatchesRect(const RectF& rect) { - return AllOf(Field(&RectF::x, FloatEq(rect.x)), - Field(&RectF::y, FloatEq(rect.y)), - Field(&RectF::width, FloatEq(rect.width)), - Field(&RectF::height, FloatEq(rect.height))); -} - -TEST(StarboardVideoPlaneTest, RegistersAndCallsCallback) { - base::test::SingleThreadTaskEnvironment task_environment; - - const RectF resolution(123.0f, 456.0f); - - StarboardVideoPlane plane; - MockFunction - cb; - EXPECT_CALL(cb, Call(MatchesRect(resolution), kNoTransform)).Times(1); - - plane.RegisterCallback(base::BindLambdaForTesting(cb.AsStdFunction())); - plane.SetGeometry(resolution, kNoTransform); -} - -TEST(StarboardVideoPlaneTest, RegistersAndUnregistersCallback) { - base::test::SingleThreadTaskEnvironment task_environment; - - const RectF resolution(123.0f, 456.0f); - - StarboardVideoPlane plane; - MockFunction - cb; - EXPECT_CALL(cb, Call).Times(0); - - const int64_t token = - plane.RegisterCallback(base::BindLambdaForTesting(cb.AsStdFunction())); - plane.UnregisterCallback(token); - plane.SetGeometry(resolution, kNoTransform); -} - -TEST(StarboardVideoPlaneTest, - SetsGeometryIfCallbackIsRegisteredAfterGeometryWasSet) { - base::test::SingleThreadTaskEnvironment task_environment; - - const RectF resolution(123.0f, 456.0f); - StarboardVideoPlane plane; - - // Here we set the geometry before any callbacks are registered. The callbacks - // should still be called with this info as soon as they're registered. - plane.SetGeometry(resolution, kNoTransform); - - MockFunction - cb; - EXPECT_CALL(cb, Call(MatchesRect(resolution), kNoTransform)).Times(1); - - plane.RegisterCallback(base::BindLambdaForTesting(cb.AsStdFunction())); -} - -} // namespace -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_volume_control.cc chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_volume_control.cc --- chromium-132.0.6834.110/chromecast/starboard/media/media/starboard_volume_control.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/starboard/media/media/starboard_volume_control.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// System volume control logic is handled by cast core, not the runtime, so -// these functions are stubbed out. - -#include "chromecast/public/volume_control.h" - -namespace chromecast { -namespace media { - -// static -void VolumeControl::Initialize(const std::vector& argv) {} - -// static -void VolumeControl::Finalize() {} - -// static -void VolumeControl::AddVolumeObserver(VolumeObserver* observer) {} - -// static -void VolumeControl::RemoveVolumeObserver(VolumeObserver* observer) {} - -// static -float VolumeControl::GetVolume(AudioContentType type) { - return 0.0f; -} - -// static -void VolumeControl::SetVolume(media::VolumeChangeSource source, - AudioContentType type, - float level) {} - -// static -bool VolumeControl::IsMuted(AudioContentType type) { - return false; -} - -// static -void VolumeControl::SetMuted(media::VolumeChangeSource source, - AudioContentType type, - bool muted) {} - -// static -void VolumeControl::SetOutputLimit(AudioContentType type, float limit) {} - -// static -float VolumeControl::VolumeToDbFS(float volume) { - return 0.0f; -} - -// static -float VolumeControl::DbFSToVolume(float db) { - return 0.0f; -} - -} // namespace media -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/fuchsia_component_restart_reason.cc chromium-132.0.6834.159/chromecast/system/reboot/fuchsia_component_restart_reason.cc --- chromium-132.0.6834.110/chromecast/system/reboot/fuchsia_component_restart_reason.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/fuchsia_component_restart_reason.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -// 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 "chromecast/system/reboot/fuchsia_component_restart_reason.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/strings/strcat.h" -#include "chromecast/public/reboot_shlib.h" - -namespace chromecast { -namespace { -constexpr char kStartedOnce[] = "component-started-once"; -constexpr char kGracefulTeardown[] = "component-graceful-teardown"; -constexpr char kSubFolder[] = "lifecycle"; - -void CreateFlagFile(const base::FilePath& file) { - if (!base::WriteFile(file, "")){ - LOG(ERROR) << "Cannot create file " << file - << ", will not correctly determine restart reason."; - } -} - -} // namespace - -FuchsiaComponentRestartReason::FuchsiaComponentRestartReason() { - if (!base::GetTempDir(&tmp_dir_)){ - LOG(ERROR) << "tmp file dir cannot be obtained."; - } - tmp_dir_ = tmp_dir_.Append(kSubFolder); - base::CreateDirectory(tmp_dir_); -} - -// Return True if it was restart instead of reboot -bool FuchsiaComponentRestartReason::GetRestartReason( - RebootShlib::RebootSource* restart_reason) { - if (!restart_checked_) { - restart_checked_ = true; - base::FilePath path_started_once = tmp_dir_.Append(kStartedOnce); - base::FilePath path_graceful_teardown = tmp_dir_.Append(kGracefulTeardown); - if (base::PathExists(path_graceful_teardown)) { - // We come out of graceful restart - restart_reason_ = RebootShlib::RebootSource::GRACEFUL_RESTART; - if (!base::DeleteFile(path_graceful_teardown)){ - LOG(ERROR) << "Cannot delete file " << path_graceful_teardown - << ", will not correctly determine restart reason."; - } - } else if (base::PathExists(path_started_once)){ - // We come out of ungraceful restart - restart_reason_ = RebootShlib::RebootSource::UNGRACEFUL_RESTART; - } else { - was_restart_ = false; - } - - // The file path is inside /tmp which is guaranteed to be removed after - // reboot to distinguish reboot from restart. - CreateFlagFile(path_started_once); - } - if (was_restart_) - *restart_reason = restart_reason_; - - return was_restart_; -} - -void FuchsiaComponentRestartReason::ResetRestartCheck() { - restart_checked_ = false; - was_restart_ = true; -} - -const base::FilePath& FuchsiaComponentRestartReason::SetFlagFileDirForTesting( - const base::FilePath& path) { - tmp_dir_ = path.Append(kSubFolder); - base::CreateDirectory(tmp_dir_); - return tmp_dir_; -} - -void FuchsiaComponentRestartReason::RegisterTeardown() { - CreateFlagFile(tmp_dir_.Append(kGracefulTeardown)); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/fuchsia_component_restart_reason.h chromium-132.0.6834.159/chromecast/system/reboot/fuchsia_component_restart_reason.h --- chromium-132.0.6834.110/chromecast/system/reboot/fuchsia_component_restart_reason.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/fuchsia_component_restart_reason.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// 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. - -#ifndef CHROMECAST_SYSTEM_REBOOT_FUCHSIA_COMPONENT_RESTART_REASON_H_ -#define CHROMECAST_SYSTEM_REBOOT_FUCHSIA_COMPONENT_RESTART_REASON_H_ - -#include "base/files/file_path.h" -#include "chromecast/public/reboot_shlib.h" - -namespace chromecast { - -// This class tracks the restart reason of the Cast component using temp files -// to indicate whether it restarts gracefully or ungracefully. On Fuchsia, the -// Cast component can restart according to plan, or by platform request, -// without the need for the device to reboot. -// No more than one instance of this class variable should be used per component -// to guarantee the correctness of the restart reason. -// -// The caller/user of this class must provide isolated-temp feature in sandbox. -class FuchsiaComponentRestartReason { - public: - FuchsiaComponentRestartReason(); - - // Whether the component restarted and if so, for which reason (graceful or - // ungraceful). - bool GetRestartReason(RebootShlib::RebootSource* restart_reason); - - // Registers a graceful teardown of the component so we can distinguish - // between the first start of a boot cycle and a restart during the same - // boot cycle. - void RegisterTeardown(); - - // This can be called once during initialization (not necessary). - // But is necessary during testing if SetUp is shared. - void ResetRestartCheck(); - - // Change tmp folder path for testing purpose. - // Not necessary for production use. - const base::FilePath& SetFlagFileDirForTesting(const base::FilePath& sub); - - private: - // To change tmp directory for testing purpose when run in parallel. - base::FilePath tmp_dir_; - - bool restart_checked_ = false; - bool was_restart_ = true; - RebootShlib::RebootSource restart_reason_{RebootShlib::RebootSource::UNKNOWN}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_SYSTEM_REBOOT_FUCHSIA_COMPONENT_RESTART_REASON_H_ diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/reboot_dummy.cc chromium-132.0.6834.159/chromecast/system/reboot/reboot_dummy.cc --- chromium-132.0.6834.110/chromecast/system/reboot/reboot_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/reboot_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/public/reboot_shlib.h" - -#include // abort() -#define NOTREACHED() abort() - -namespace chromecast { - -void RebootShlib::Initialize(const std::vector& /* argv */) {} - -void RebootShlib::Finalize() {} - -bool RebootShlib::IsSupported() { - return false; -} - -bool RebootShlib::IsRebootSourceSupported( - RebootShlib::RebootSource /* reboot_source */) { - return false; -} - -bool RebootShlib::RebootNow(RebootShlib::RebootSource /* reboot_source */) { - return false; -} - -bool RebootShlib::IsFdrForNextRebootSupported() { - return false; -} - -void RebootShlib::SetFdrForNextReboot() { - NOTREACHED(); -} - -bool RebootShlib::IsOtaForNextRebootSupported() { - return false; -} - -void RebootShlib::SetOtaForNextReboot() { - NOTREACHED(); -} - -bool RebootShlib::IsClearOtaForNextRebootSupported() { - return false; -} - -void RebootShlib::ClearOtaForNextReboot() { - NOTREACHED(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/reboot_fuchsia.cc chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia.cc --- chromium-132.0.6834.110/chromecast/system/reboot/reboot_fuchsia.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,240 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include -#include -#include -#include -#include - -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/fuchsia/fuchsia_logging.h" -#include "base/fuchsia/process_context.h" -#include "base/no_destructor.h" -#include "chromecast/public/reboot_shlib.h" -#include "chromecast/system/reboot/fuchsia_component_restart_reason.h" -#include "chromecast/system/reboot/reboot_fuchsia.h" -#include "chromecast/system/reboot/reboot_util.h" - -using fuchsia::feedback::LastReboot; -using fuchsia::feedback::LastRebootInfoProviderSyncPtr; -using fuchsia::feedback::RebootReason; -using fuchsia::hardware::power::statecontrol::Admin_Reboot_Result; -using fuchsia::hardware::power::statecontrol::AdminPtr; -using fuchsia::recovery::FactoryResetPtr; -using StateControlRebootReason = - fuchsia::hardware::power::statecontrol::RebootReason; - -namespace chromecast { - -namespace { -FuchsiaComponentRestartReason state_; - -// If true, the next reboot should trigger a factory data reset. -bool fdr_on_reboot_ = false; -} - -AdminPtr& GetAdminPtr() { - static base::NoDestructor g_admin; - return *g_admin; -} - -LastRebootInfoProviderSyncPtr& GetLastRebootInfoProviderSyncPtr() { - static base::NoDestructor g_last_reboot_info; - return *g_last_reboot_info; -} - -fuchsia::recovery::FactoryResetPtr& GetFactoryResetPtr() { - static base::NoDestructor g_factory_reset; - return *g_factory_reset; -} - -void InitializeRebootShlib(const std::vector& argv, - sys::ServiceDirectory* incoming_directory) { - incoming_directory->Connect(GetAdminPtr().NewRequest()); - incoming_directory->Connect(GetLastRebootInfoProviderSyncPtr().NewRequest()); - incoming_directory->Connect(GetFactoryResetPtr().NewRequest()); - GetAdminPtr().set_error_handler([](zx_status_t status) { - ZX_LOG(ERROR, status) << "AdminPtr disconnected"; - }); - GetFactoryResetPtr().set_error_handler([](zx_status_t status) { - ZX_LOG(ERROR, status) << "FactoryResetPtr disconnected"; - }); - InitializeRestartCheck(); -} - -base::FilePath InitializeFlagFileDirForTesting(const base::FilePath sub) { - return state_.SetFlagFileDirForTesting(sub); -} - -void InitializeRestartCheck() { - state_.ResetRestartCheck(); -} - -// RebootShlib implementation: - -// static -void RebootShlib::Initialize(const std::vector& argv) { - InitializeRebootShlib(argv, base::ComponentContextForProcess()->svc().get()); -} - -// static -void RebootShlib::Finalize() {} - -// static -bool RebootShlib::IsSupported() { - return true; -} - -// static -bool RebootShlib::IsRebootSourceSupported( - RebootShlib::RebootSource /* reboot_source */) { - return true; -} - -// static -bool RebootShlib::RebootNow(RebootSource reboot_source) { - if (fdr_on_reboot_) { - fdr_on_reboot_ = false; - - // Intentionally using async Ptr to avoid deadlock - // Otherwise caller is blocked, and if caller needs to be notified - // as well, it will go into a deadlock state. - GetFactoryResetPtr()->Reset([](zx_status_t status) { - if (status != ZX_OK) { - ZX_LOG(ERROR, status) << "Failed to trigger FDR"; - } - }); - - // FDR will perform its own reboot, return immediately. - return true; - } - - StateControlRebootReason reason; - switch (reboot_source) { - case RebootSource::API: - reason = StateControlRebootReason::USER_REQUEST; - break; - case RebootSource::OTA: - // We expect OTAs to be initiated by the platform via the - // fuchsia.hardware.power.statecontrol/Admin FIDL service. In case - // non-platform code wants to initiate OTAs too, we also support it here. - reason = StateControlRebootReason::SYSTEM_UPDATE; - break; - case RebootSource::OVERHEAT: - reason = StateControlRebootReason::HIGH_TEMPERATURE; - break; - default: - reason = StateControlRebootReason::USER_REQUEST; - break; - } - - // Intentionally using async Ptr to avoid deadlock - // Otherwise caller is blocked, and if caller needs to be notified - // as well, it will go into a deadlock state. - GetAdminPtr()->Reboot(reason, [](Admin_Reboot_Result out_result) { - if (out_result.is_err()) { - LOG(ERROR) << "Failed to reboot after requested: " - << zx_status_get_string(out_result.err()); - } - }); - return true; -} - -// static -bool RebootShlib::IsFdrForNextRebootSupported() { - return true; -} - -// static -void RebootShlib::SetFdrForNextReboot() { - fdr_on_reboot_ = true; -} - -// static -bool RebootShlib::IsOtaForNextRebootSupported() { - return false; -} - -// static -void RebootShlib::SetOtaForNextReboot() {} - -// static -bool RebootShlib::IsClearOtaForNextRebootSupported() { - return false; -} - -// static -void RebootShlib::ClearOtaForNextReboot() {} - -// RebootUtil implementation: - -// static -void RebootUtil::Initialize(const std::vector& argv) { - RebootShlib::Initialize(argv); -} - -// static -void RebootUtil::Finalize() { - RebootShlib::Finalize(); - state_.RegisterTeardown(); -} - -// static -RebootShlib::RebootSource RebootUtil::GetLastRebootSource() { - RebootShlib::RebootSource last_restart; - if (state_.GetRestartReason(&last_restart)) - return last_restart; - - LastReboot last_reboot; - zx_status_t status = GetLastRebootInfoProviderSyncPtr()->Get(&last_reboot); - if (status != ZX_OK || last_reboot.IsEmpty() || !last_reboot.has_graceful()) { - ZX_LOG(ERROR, status) << "Failed to get last reboot reason"; - return RebootShlib::RebootSource::UNKNOWN; - } - - if (!last_reboot.has_reason()) { - return last_reboot.graceful() ? RebootShlib::RebootSource::SW_OTHER - : RebootShlib::RebootSource::FORCED; - } - - switch (last_reboot.reason()) { - case RebootReason::COLD: - case RebootReason::BRIEF_POWER_LOSS: - case RebootReason::BROWNOUT: - case RebootReason::KERNEL_PANIC: - return RebootShlib::RebootSource::FORCED; - case RebootReason::SYSTEM_OUT_OF_MEMORY: - return RebootShlib::RebootSource::REPEATED_OOM; - case RebootReason::HARDWARE_WATCHDOG_TIMEOUT: - return RebootShlib::RebootSource::HW_WATCHDOG; - case RebootReason::SOFTWARE_WATCHDOG_TIMEOUT: - return RebootShlib::RebootSource::WATCHDOG; - case RebootReason::USER_REQUEST: - return RebootShlib::RebootSource::API; - case RebootReason::SYSTEM_UPDATE: - case RebootReason::RETRY_SYSTEM_UPDATE: - case RebootReason::ZBI_SWAP: - return RebootShlib::RebootSource::OTA; - case RebootReason::HIGH_TEMPERATURE: - return RebootShlib::RebootSource::OVERHEAT; - case RebootReason::SESSION_FAILURE: - return RebootShlib::RebootSource::SW_OTHER; - default: - return last_reboot.graceful() ? RebootShlib::RebootSource::SW_OTHER - : RebootShlib::RebootSource::FORCED; - } -} - -// static -bool RebootUtil::SetNextRebootSource( - RebootShlib::RebootSource /* reboot_source */) { - return false; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/reboot_fuchsia.h chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia.h --- chromium-132.0.6834.110/chromecast/system/reboot/reboot_fuchsia.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// 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. - -#ifndef CHROMECAST_SYSTEM_REBOOT_REBOOT_FUCHSIA_H_ -#define CHROMECAST_SYSTEM_REBOOT_REBOOT_FUCHSIA_H_ - -#include -#include - - -namespace sys { -class ServiceDirectory; -} // namespace sys - -namespace chromecast { - -// Injects a service directory for testing. -void InitializeRebootShlib(const std::vector& argv, - sys::ServiceDirectory* incoming_directory); - -// Initialize the restart check. Can be called to reset the values for testing -// to simulate a restart. -void InitializeRestartCheck(); - -// Change tmp file directory for testing. -base::FilePath InitializeFlagFileDirForTesting(const base::FilePath sub); - -} // namespace chromecast - -#endif // CHROMECAST_SYSTEM_REBOOT_REBOOT_FUCHSIA_H_ diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/reboot_fuchsia_test.cc chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia_test.cc --- chromium-132.0.6834.110/chromecast/system/reboot/reboot_fuchsia_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/reboot_fuchsia_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,396 +0,0 @@ -// 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/fuchsia/scoped_service_binding.h" -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/message_loop/message_pump_type.h" -#include "base/run_loop.h" -#include "base/strings/strcat.h" -#include "base/test/task_environment.h" -#include "base/threading/sequence_bound.h" -#include "base/threading/thread.h" -#include "chromecast/public/reboot_shlib.h" -#include "chromecast/system/reboot/reboot_fuchsia.h" -#include "chromecast/system/reboot/reboot_util.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace { - -using ::testing::Eq; -using ::testing::Ne; - -using fuchsia::feedback::RebootReason; -using StateControlRebootReason = - fuchsia::hardware::power::statecontrol::RebootReason; - -struct RebootReasonParam { - RebootReason reason; - RebootShlib::RebootSource source; - bool graceful; - StateControlRebootReason state_control_reason = - StateControlRebootReason::USER_REQUEST; -}; - -const RebootReasonParam kRebootReasonParams[] = { - {RebootReason::COLD, RebootShlib::RebootSource::FORCED, false}, - {RebootReason::BRIEF_POWER_LOSS, RebootShlib::RebootSource::FORCED, false}, - {RebootReason::BROWNOUT, RebootShlib::RebootSource::FORCED, false}, - {RebootReason::KERNEL_PANIC, RebootShlib::RebootSource::FORCED, false}, - {RebootReason::SYSTEM_OUT_OF_MEMORY, - RebootShlib::RebootSource::REPEATED_OOM, false}, - {RebootReason::HARDWARE_WATCHDOG_TIMEOUT, - RebootShlib::RebootSource::HW_WATCHDOG, false}, - {RebootReason::HARDWARE_WATCHDOG_TIMEOUT, - RebootShlib::RebootSource::HW_WATCHDOG, false}, - {RebootReason::SOFTWARE_WATCHDOG_TIMEOUT, - RebootShlib::RebootSource::WATCHDOG, false}, - - // Graceful reboot reasons. - {RebootReason::USER_REQUEST, RebootShlib::RebootSource::API, true, - StateControlRebootReason::USER_REQUEST}, - {RebootReason::SYSTEM_UPDATE, RebootShlib::RebootSource::OTA, true, - StateControlRebootReason::SYSTEM_UPDATE}, - {RebootReason::HIGH_TEMPERATURE, RebootShlib::RebootSource::OVERHEAT, true, - StateControlRebootReason::HIGH_TEMPERATURE}, - {RebootReason::SESSION_FAILURE, RebootShlib::RebootSource::SW_OTHER, true}, -}; - -constexpr char kStartedOnce[] = "component-started-once"; -constexpr char kGracefulTeardown[] = "component-graceful-teardown"; - -struct RestartReasonParam { - RebootShlib::RebootSource source; - bool graceful; - const char* file; -}; - -const RestartReasonParam kRestartReasonParams[] = { - {RebootShlib::RebootSource::UNGRACEFUL_RESTART, false, kStartedOnce}, - {RebootShlib::RebootSource::GRACEFUL_RESTART, true, kGracefulTeardown}, -}; - -class FakeAdmin - : public fuchsia::hardware::power::statecontrol::testing::Admin_TestBase { - public: - explicit FakeAdmin(sys::OutgoingDirectory* outgoing_directory) - : binding_(outgoing_directory, this) {} - - void GetLastRebootReason(StateControlRebootReason* reason) { - *reason = last_reboot_reason_; - } - - private: - void Reboot(StateControlRebootReason reason, RebootCallback callback) final { - last_reboot_reason_ = reason; - callback(fpromise::ok()); - } - - void NotImplemented_(const std::string& name) final { - ADD_FAILURE() << "NotImplemented_: " << name; - } - - base::ScopedServiceBinding - binding_; - StateControlRebootReason last_reboot_reason_; -}; - -class FakeLastRebootInfoProvider - : public fuchsia::feedback::testing::LastRebootInfoProvider_TestBase { - public: - explicit FakeLastRebootInfoProvider( - sys::OutgoingDirectory* outgoing_directory) - : binding_(outgoing_directory, this) {} - - void SetLastReboot(fuchsia::feedback::LastReboot last_reboot) { - last_reboot_ = std::move(last_reboot); - } - - private: - void Get(GetCallback callback) final { callback(std::move(last_reboot_)); } - - void NotImplemented_(const std::string& name) final { - ADD_FAILURE() << "NotImplemented_: " << name; - } - - base::ScopedServiceBinding - binding_; - fuchsia::feedback::LastReboot last_reboot_; -}; - -class FakeFactoryReset - : public fuchsia::recovery::testing::FactoryReset_TestBase { - public: - explicit FakeFactoryReset(sys::OutgoingDirectory* outgoing_directory) - : binding_(outgoing_directory, this) {} - - void reset_called(bool* reset_called) { *reset_called = reset_called_; } - - private: - void Reset(ResetCallback callback) final { - reset_called_ = true; - callback(ZX_OK); - } - - void NotImplemented_(const std::string& name) final { - ADD_FAILURE() << "NotImplemented_: " << name; - } - - base::ScopedServiceBinding binding_; - bool reset_called_ = false; -}; - -class RebootFuchsiaTest : public ::testing::Test { - public: - RebootFuchsiaTest() - : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), - thread_("FakeLastRebootInfoProvider_Thread") { - CHECK(thread_.StartWithOptions( - base::Thread::Options(base::MessagePumpType::IO, 0))); - } - - void SetUp() override { - // Create incoming (service) and outgoing directories that are connected. - fidl::InterfaceHandle directory; - - // The thread handling fidl calls to the fake service must also be the - // thread that we start the serve operation on. Since all fakes require the - // same output directory handle, we post a task here to begin the serve - // operation, then flush the task runner queue to ensure that output - // directory is safe to pass to the fakes. - thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&RebootFuchsiaTest::ServeOutgoingDirectory, - base::Unretained(this), directory.NewRequest())); - thread_.FlushForTesting(); - - // Initialize and publish fake fidl services. - admin_ = base::SequenceBound(thread_.task_runner(), - outgoing_directory_.get()); - last_reboot_info_provider_ = - base::SequenceBound( - thread_.task_runner(), outgoing_directory_.get()); - factory_reset_service_ = base::SequenceBound( - thread_.task_runner(), outgoing_directory_.get()); - - // Ensure that the services above finish publishing themselves. - thread_.FlushForTesting(); - - // Use a service directory backed by the fakes above for tests. - incoming_directory_ = - std::make_unique(std::move(directory)); - InitializeRebootShlib({}, incoming_directory_.get()); - EXPECT_TRUE(dir_.CreateUniqueTempDir()); - full_path_ = InitializeFlagFileDirForTesting(dir_.GetPath()); - } - - StateControlRebootReason GetLastRebootReason() { - StateControlRebootReason reason; - admin_.AsyncCall(&FakeAdmin::GetLastRebootReason).WithArgs(&reason); - thread_.FlushForTesting(); - return reason; - } - - void SetLastReboot(fuchsia::feedback::LastReboot last_reboot) { - last_reboot_info_provider_ - .AsyncCall(&FakeLastRebootInfoProvider::SetLastReboot) - .WithArgs(std::move(last_reboot)); - thread_.FlushForTesting(); - } - - bool FdrTriggered() { - bool reset_called; - factory_reset_service_.AsyncCall(&FakeFactoryReset::reset_called) - .WithArgs(&reset_called); - thread_.FlushForTesting(); - return reset_called; - } - - private: - void ServeOutgoingDirectory( - fidl::InterfaceRequest channel) { - outgoing_directory_ = std::make_unique(); - outgoing_directory_->GetOrCreateDirectory("svc")->Serve( - fuchsia::io::OpenFlags::RIGHT_READABLE | - fuchsia::io::OpenFlags::RIGHT_WRITABLE, - channel.TakeChannel()); - } - - const base::test::SingleThreadTaskEnvironment task_environment_; - std::unique_ptr outgoing_directory_; - std::unique_ptr incoming_directory_; - base::SequenceBound admin_; - base::SequenceBound last_reboot_info_provider_; - base::SequenceBound factory_reset_service_; - base::ScopedTempDir dir_; - base::FilePath full_path_; - - protected: - base::FilePath GenerateFlagFilePath(std::string_view name) { - return full_path_.Append(name); - } - - base::Thread thread_; -}; - -TEST_F(RebootFuchsiaTest, GetLastRebootSourceDefaultsToUnknown) { - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Eq(RebootShlib::RebootSource::UNKNOWN)); -} - -TEST_F(RebootFuchsiaTest, GetLastRebootSourceWithoutGranularReason) { - fuchsia::feedback::LastReboot last_reboot; - last_reboot.set_graceful(true); - EXPECT_TRUE(last_reboot.has_graceful()); - EXPECT_FALSE(last_reboot.has_reason()); - SetLastReboot(std::move(last_reboot)); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Eq(RebootShlib::RebootSource::SW_OTHER)); -} - -fuchsia::feedback::LastReboot GenerateLastReboot(bool graceful, - RebootReason reason) { - fuchsia::feedback::LastReboot last_reboot; - last_reboot.set_graceful(graceful); - last_reboot.set_reason(reason); - return last_reboot; -} - -// RetrySystemUpdate must be handled separately because it does not work with -// the RebootFuchsiaParamTest family of tests. Those tests expect -// RebootSource::OTA to map to exactly one StateControlRebootReason, which is -// now not the case. -TEST_F(RebootFuchsiaTest, RebootReasonRetrySystemUpdateTranslatesFromFuchsia) { - SetLastReboot(GenerateLastReboot(true, RebootReason::RETRY_SYSTEM_UPDATE)); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Eq(RebootShlib::RebootSource::OTA)); -} - -TEST_F(RebootFuchsiaTest, RebootReasonZbiSwapTranslatesFromFuchsia) { - SetLastReboot(GenerateLastReboot(true, RebootReason::ZBI_SWAP)); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Eq(RebootShlib::RebootSource::OTA)); -} - -TEST_F(RebootFuchsiaTest, RebootNowTriggersFdr) { - EXPECT_TRUE(RebootShlib::IsFdrForNextRebootSupported()); - - RebootShlib::SetFdrForNextReboot(); - - EXPECT_TRUE(RebootShlib::RebootNow(RebootShlib::RebootSource::API)); - EXPECT_TRUE(FdrTriggered()); -} - -class RebootFuchsiaParamTest - : public RebootFuchsiaTest, - public ::testing::WithParamInterface { - public: - RebootFuchsiaParamTest() = default; -}; - -TEST_P(RebootFuchsiaParamTest, RebootNowSendsFidlRebootReason) { - EXPECT_TRUE(RebootShlib::RebootNow(GetParam().source)); - thread_.FlushForTesting(); - EXPECT_THAT(GetLastRebootReason(), Eq(GetParam().state_control_reason)); -} - -TEST_P(RebootFuchsiaParamTest, GetLastRebootSourceTranslatesReasonFromFuchsia) { - SetLastReboot(GenerateLastReboot(GetParam().graceful, GetParam().reason)); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), Eq(GetParam().source)); -} - -INSTANTIATE_TEST_SUITE_P(RebootReasonParamSweep, - RebootFuchsiaParamTest, - ::testing::ValuesIn(kRebootReasonParams)); - -class RestartFuchsiaParamTest - : public RebootFuchsiaTest, - public ::testing::WithParamInterface { - public: - RestartFuchsiaParamTest() = default; - - void SetUp() override { - RebootFuchsiaTest::SetUp(); - base::WriteFile(GenerateFlagFilePath(GetParam().file), ""); - } -}; - -TEST_P(RestartFuchsiaParamTest, GetLastRestartReasons) { - fuchsia::feedback::LastReboot last_reboot; - last_reboot.set_graceful(true); - EXPECT_TRUE(last_reboot.has_graceful()); - EXPECT_FALSE(last_reboot.has_reason()); - SetLastReboot(std::move(last_reboot)); - - EXPECT_THAT(RebootUtil::GetLastRebootSource(), Eq(GetParam().source)); - - EXPECT_TRUE(base::PathExists(GenerateFlagFilePath(kStartedOnce))); - EXPECT_FALSE(base::PathExists(GenerateFlagFilePath(kGracefulTeardown))); - - base::WriteFile(GenerateFlagFilePath(kGracefulTeardown), ""); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), Eq(GetParam().source)); -} - -INSTANTIATE_TEST_SUITE_P(RestartReasonParamSweep, - RestartFuchsiaParamTest, - ::testing::ValuesIn(kRestartReasonParams)); - -TEST_F(RebootFuchsiaTest, ThoroughTestLastRestartReason) { - fuchsia::feedback::LastReboot last_reboot; - last_reboot.set_graceful(true); - EXPECT_TRUE(last_reboot.has_graceful()); - EXPECT_FALSE(last_reboot.has_reason()); - SetLastReboot(std::move(last_reboot)); - - EXPECT_FALSE(base::PathExists(GenerateFlagFilePath(kStartedOnce))); - EXPECT_FALSE(base::PathExists(GenerateFlagFilePath(kGracefulTeardown))); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Ne(RebootShlib::RebootSource::GRACEFUL_RESTART)); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Ne(RebootShlib::RebootSource::UNGRACEFUL_RESTART)); - - // Check files are created/deleted as expected - const auto once = GenerateFlagFilePath(kStartedOnce); - LOG(INFO) << "looking at file " << once << " " << base::PathExists(once); - EXPECT_TRUE(base::PathExists(once)); - EXPECT_FALSE(base::PathExists(GenerateFlagFilePath(kGracefulTeardown))); - - // Confirm reboot reason will not change after create files when check again - base::WriteFile(GenerateFlagFilePath(kStartedOnce), ""); - base::WriteFile(GenerateFlagFilePath(kGracefulTeardown), ""); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Ne(RebootShlib::RebootSource::GRACEFUL_RESTART)); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Ne(RebootShlib::RebootSource::UNGRACEFUL_RESTART)); - - // Emulate Reboot - RebootUtil::Finalize(); - InitializeRestartCheck(); - EXPECT_THAT(RebootUtil::GetLastRebootSource(), - Eq(RebootShlib::RebootSource::GRACEFUL_RESTART)); -} - -} // namespace -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/reboot_util.h chromium-132.0.6834.159/chromecast/system/reboot/reboot_util.h --- chromium-132.0.6834.110/chromecast/system/reboot/reboot_util.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/reboot_util.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_SYSTEM_REBOOT_REBOOT_UTIL_H_ -#define CHROMECAST_SYSTEM_REBOOT_REBOOT_UTIL_H_ - -#include -#include - -#include "base/functional/callback.h" -#include "chromecast/public/reboot_shlib.h" - -namespace chromecast { - -// A wrapper util for the RebootShlib interface. This acts as a translation -// layer between cast_shell call sites (such as the setup API, process_manager, -// and crash_uploader) and the actual RebootShlib API. -// The RebootShlib interface should never need to be used directly; instead -// prefer to use the RebootUtil interface. -class RebootUtil { - public: - static void Initialize(const std::vector& argv); - static void Finalize(); - - // Indicates if any RebootSources are supported for rebooting. - static bool IsRebootSupported(); - - // The RebootShlib::RebootSource uses weakly typed enums, so this - // can be used to validate a RebootSource value is actually valid. - static bool IsValidRebootSource(RebootShlib::RebootSource reboot_source); - - // Before calling RebootNow, the caller must check that reboot is supported - // for the RebootSource being attempted. - static bool IsRebootSourceSupported(RebootShlib::RebootSource reboot_source); - static bool RebootNow(RebootShlib::RebootSource reboot_source); - - // Before calling SetFdrForNextReboot, the caller must check that fdr - // for next reboot is supported. - static bool IsFdrForNextRebootSupported(); - static void SetFdrForNextReboot(); - - // Before calling SetOtaForNextReboot, the caller must check that ota - // for next reboot is supported. - static bool IsOtaForNextRebootSupported(); - static void SetOtaForNextReboot(); - - // Before calling IsClearOtaForNextRebootSupported, the called must check - // if clearing the ota is supported. - static bool IsClearOtaForNextRebootSupported(); - static void ClearOtaForNextReboot(); - - // Returns last reboot source. This value persists throughout each boot. - static RebootShlib::RebootSource GetLastRebootSource(); - - // This is used for logging/metrics purposes. In general, setting the next - // reboot type is handled automatically by RebootUtil, so it should not - // be necessary to set explicitly. - // Returns true if successful. - static bool SetNextRebootSource(RebootShlib::RebootSource reboot_source); - - using RebootCallback = - base::RepeatingCallback; - // Sets a callback that will be fired when a reboot is requested. This is - // used by tests to ensure that in production a reboot will occur. The - // callback returns a bool which controls the return value of RebootNow() - static void SetRebootCallbackForTest(const RebootCallback& callback); - - // Clears any previously set reboot callbacks. Should be used to clean up - // the test after any invocation of SetRebootCallbackForTest - static void ClearRebootCallbackForTest(); -}; - -} // namespace chromecast - -#endif // CHROMECAST_SYSTEM_REBOOT_REBOOT_UTIL_H_ diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/reboot_util_core.cc chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_core.cc --- chromium-132.0.6834.110/chromecast/system/reboot/reboot_util_core.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_core.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,127 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/system/reboot/reboot_util.h" - -#include "base/logging.h" -#include "base/no_destructor.h" -#include "chromecast/public/reboot_shlib.h" - -// This is a partial implementation of the reboot_util.h interface. -// The remaining methods are defined in other reboot_util_*.cc depending -// on which platform/product they are for. - -namespace chromecast { -namespace { -RebootUtil::RebootCallback& GetTestRebootCallback() { - static base::NoDestructor callback; - return *callback; -} -} // namespace - -// static -bool RebootUtil::IsRebootSupported() { - return RebootShlib::IsSupported(); -} - -// static -bool RebootUtil::IsValidRebootSource(RebootShlib::RebootSource reboot_source) { - switch (reboot_source) { - case RebootShlib::RebootSource::UNKNOWN: - case RebootShlib::RebootSource::FORCED: - case RebootShlib::RebootSource::API: - case RebootShlib::RebootSource::NIGHTLY: - case RebootShlib::RebootSource::OTA: - case RebootShlib::RebootSource::WATCHDOG: - case RebootShlib::RebootSource::PROCESS_MANAGER: - case RebootShlib::RebootSource::CRASH_UPLOADER: - case RebootShlib::RebootSource::FDR: - case RebootShlib::RebootSource::HW_WATCHDOG: - case RebootShlib::RebootSource::SW_OTHER: - case RebootShlib::RebootSource::OVERHEAT: - case RebootShlib::RebootSource::REGENERATE_CLOUD_ID: - case RebootShlib::RebootSource::REPEATED_OOM: - case RebootShlib::RebootSource::UTILITY_PROCESS_CRASH: - case RebootShlib::RebootSource::GRACEFUL_RESTART: - case RebootShlib::RebootSource::UNGRACEFUL_RESTART: - case RebootShlib::RebootSource::MULTI_SERVICE_BUG: - case RebootShlib::RebootSource::POWER_MANAGER_SHUTDOWN: - case RebootShlib::RebootSource::EXPERIMENT_CHANGE: - case RebootShlib::RebootSource::ANOMALY: - case RebootShlib::RebootSource::KERNEL_PANIC: - return true; - default: - return false; - } -} - -// static -bool RebootUtil::IsRebootSourceSupported( - RebootShlib::RebootSource reboot_source) { - return RebootShlib::IsSupported() && - RebootShlib::IsRebootSourceSupported(reboot_source); -} - -// static -bool RebootUtil::RebootNow(RebootShlib::RebootSource reboot_source) { - // If we have a testing callback avoid calling RebootShlib::RebootNow - // because it will crash our test - RebootUtil::RebootCallback& callback = GetTestRebootCallback(); - SetNextRebootSource(reboot_source); - if (callback) { - LOG(WARNING) << "Using reboot callback for test! Device will not reboot!"; - return callback.Run(reboot_source); - } - DCHECK(IsRebootSourceSupported(reboot_source)); - return RebootShlib::RebootNow(reboot_source); -} - -// static -bool RebootUtil::IsFdrForNextRebootSupported() { - return RebootShlib::IsSupported() && - RebootShlib::IsFdrForNextRebootSupported(); -} - -// static -void RebootUtil::SetFdrForNextReboot() { - DCHECK(IsFdrForNextRebootSupported()); - RebootShlib::SetFdrForNextReboot(); -} - -// static -bool RebootUtil::IsOtaForNextRebootSupported() { - return RebootShlib::IsSupported() && - RebootShlib::IsOtaForNextRebootSupported(); -} - -// static -void RebootUtil::SetOtaForNextReboot() { - DCHECK(IsOtaForNextRebootSupported()); - RebootShlib::SetOtaForNextReboot(); -} - -// static -bool RebootUtil::IsClearOtaForNextRebootSupported() { - return RebootShlib::IsSupported() && - RebootShlib::IsClearOtaForNextRebootSupported(); -} - -// static -void RebootUtil::ClearOtaForNextReboot() { - DCHECK(IsClearOtaForNextRebootSupported()); - RebootShlib::ClearOtaForNextReboot(); -} - -// static -void RebootUtil::SetRebootCallbackForTest( - const RebootUtil::RebootCallback& callback) { - GetTestRebootCallback() = callback; -} - -// static -void RebootUtil::ClearRebootCallbackForTest() { - GetTestRebootCallback().Reset(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/reboot_util_dummy.cc chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_dummy.cc --- chromium-132.0.6834.110/chromecast/system/reboot/reboot_util_dummy.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_dummy.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/system/reboot/reboot_util.h" - -namespace chromecast { - -// static -void RebootUtil::Initialize(const std::vector& argv) { - RebootShlib::Initialize(argv); -} - -// static -void RebootUtil::Finalize() { - RebootShlib::Finalize(); -} - -// static -RebootShlib::RebootSource RebootUtil::GetLastRebootSource() { - return RebootShlib::RebootSource::UNKNOWN; -} - -// static -bool RebootUtil::SetNextRebootSource( - RebootShlib::RebootSource /* reboot_source */) { - return false; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/system/reboot/reboot_util_test.cc chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_test.cc --- chromium-132.0.6834.110/chromecast/system/reboot/reboot_util_test.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/system/reboot/reboot_util_test.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/system/reboot/reboot_util.h" - -#include "base/test/mock_callback.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { - -// Ensure that we can call RebootNow during a test without crashing -// and that it properly keeps track of the reboot source. -TEST(RebootUtil, CaptureReboot) { - base::MockCallback callback; - RebootUtil::SetRebootCallbackForTest(callback.Get()); - EXPECT_CALL(callback, Run(RebootShlib::RebootSource::FORCED)) - .WillOnce(testing::Return(true)); - EXPECT_TRUE(RebootUtil::RebootNow(RebootShlib::RebootSource::FORCED)); - RebootUtil::ClearRebootCallbackForTest(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/tools/build/generate_test_lists.py chromium-132.0.6834.159/chromecast/tools/build/generate_test_lists.py --- chromium-132.0.6834.110/chromecast/tools/build/generate_test_lists.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tools/build/generate_test_lists.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,195 +0,0 @@ -#!/usr/bin/env python -# Copyright 2014 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -"""Helper script to generate unit test lists for the Chromecast build scripts. -""" - -import glob -import json -import optparse -import os -import sys - - -def GetTestNames(test_files_dir): - """Returns test names specified in the *.tests files in |test_files_dir|.""" - test_files = sorted(glob.glob(test_files_dir + "/*.tests")) - test_names = set() - for test_filename in test_files: - with open(test_filename, "r") as test_file: - for test_file_line in test_file: - # Binary name may be a simple test target (cast_net_unittests) or be a - # qualified gyp path (../base.gyp:base_unittests). - test_name = test_file_line.split(":")[-1].strip() - test_names.add(test_name) - return test_names - - -def GetTestFilters(test_files_dir, test_names, include_filters): - """Returns filters specified in the *.filters files in |test_files_dir|.""" - # GYP targets may provide a numbered priority for the filename. Sort to - # use that priority. - filter_files = sorted(glob.glob(test_files_dir + "/*.filters")) - test_filters = {} - if include_filters: - for filter_filename in filter_files: - with open(filter_filename, "r") as filter_file: - for filter_line in filter_file: - (test_name, test_filter) = filter_line.strip().split(" ", 1) - - if test_name not in test_names: - raise Exception("Filter found for unknown target: " + test_name) - - # Note: This may overwrite a previous rule. This is okay, since higher - # priority files are evaluated after lower priority files. - test_filters[test_name] = test_filter - - return test_filters - - -def CombineList(test_files_dir, list_output_file, include_filters, - additional_runtime_options): - """Writes a unit test file in a format compatible for Chromecast scripts. - - If include_filters is True, uses filters to create a test runner list - and also include additional options, if any. - Otherwise, creates a list only of the tests to build. - - Args: - test_files_dir: Path to the intermediate directory containing tests/filters. - list_output_file: Path to write the unit test file out to. - include_filters: Whether or not to include the filters when generating - the test list. - additional_runtime_options: Arguments to be applied to all tests. These are - applied before filters (so test-specific filters take precedence). - - Raises: - Exception: if filter is found for an unknown target. - """ - test_names = GetTestNames(test_files_dir) - test_filters = GetTestFilters(test_files_dir, test_names, include_filters) - test_commands = [ - "{} {} {}".format(test_name, - additional_runtime_options or "", - test_filters.get(test_name, "")) - for test_name in test_names - ] - - with open(list_output_file, "w") as f: - f.write("\n".join(sorted(test_commands))) - - -def CombineRuntimeDeps(test_files_dir, deps_output_file): - """Writes a JSON file that lists the runtime dependecies for each test. - - The output will consist of a JSON dictionary where the keys are names of the - unittests and the values are arrays of files and directories needed at runtime - by the unittest. Of note, the unittest itself is always listed as a runtime - dependency of itself. - - The paths are all relative to the root output directory (where the unittest - binaries live). - - { - "base_unittests": ["./base_unittests", "../../base/test/data/"], - "cast_media_unittests": [...], - ... - } - - Args: - test_files_dir: path to the intermediate directory containing the invidual - runtime deps files. - deps_output_file: Path to write the JSON file out to. - """ - test_names = GetTestNames(test_files_dir) - runtime_deps = {} - runtime_deps_dir = os.path.join(test_files_dir, "runtime_deps") - for runtime_deps_file in glob.glob(runtime_deps_dir + "/*_runtime_deps.txt"): - test_name = os.path.basename(runtime_deps_file).replace( - "_runtime_deps.txt", "") - if test_name not in test_names: - continue - - with open(runtime_deps_file, "r") as f: - runtime_deps[test_name] = [dep.strip() for dep in f] - - with open(deps_output_file, "w") as outfile: - json.dump( - runtime_deps, outfile, sort_keys=True, indent=2, separators=(",", ": ")) - - -def CreateList(inputs, list_output_file): - with open(list_output_file, "w") as f: - f.write("\n".join(inputs)) - - -def DoMain(argv): - """Main method. Runs helper commands for generating unit test lists.""" - parser = optparse.OptionParser( - """usage: %prog [] [] - - Valid commands: - create_list prints all given test names/args to a file, one line - per string - pack_build packs all test files from the given output directory - into a single test list file - pack_run packs all test and filter files from the given - output directory into a single test list file - """) - parser.add_option( - "-o", - action="store", - dest="list_output_file", - help="Output path in which to write the test list.") - parser.add_option( - "-d", - action="store", - dest="deps_output_file", - help="Output path in which to write the runtime deps.") - parser.add_option( - "-t", - action="store", - dest="test_files_dir", - help="Intermediate test list directory.") - parser.add_option( - "-a", - action="store", - dest="additional_runtime_options", - help="Additional options applied to all tests.") - options, inputs = parser.parse_args(argv) - - list_output_file = options.list_output_file - deps_output_file = options.deps_output_file - test_files_dir = options.test_files_dir - additional_runtime_options = options.additional_runtime_options - - if len(inputs) < 1: - parser.error("No command given.\n") - command = inputs[0] - test_names = inputs[1:] - - if not list_output_file: - parser.error("Output path (-o) is required.\n") - - if command == "create_list": - return CreateList(test_names, list_output_file) - - if command == "pack_build": - if not test_files_dir: - parser.error("pack_build require a test files directory (-t).\n") - return CombineList(test_files_dir, list_output_file, False, None) - - if command == "pack_run": - if not test_files_dir: - parser.error("pack_run require a test files directory (-t).\n") - if deps_output_file: - CombineRuntimeDeps(test_files_dir, deps_output_file) - return CombineList(test_files_dir, list_output_file, True, - additional_runtime_options) - - parser.error("Invalid command specified.") - - -if __name__ == "__main__": - DoMain(sys.argv[1:]) diff -Nru chromium-132.0.6834.110/chromecast/tools/build/package_test_deps.py chromium-132.0.6834.159/chromecast/tools/build/package_test_deps.py --- chromium-132.0.6834.110/chromecast/tools/build/package_test_deps.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tools/build/package_test_deps.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2019 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Packages test dependencies as tar.gz file.""" - -import argparse -import json -import logging -import os -import sys -import tarfile - - -parser = argparse.ArgumentParser( - description='Package test dependencies as tar.gz files.') -parser.add_argument('--output', required=True, - help='Full path to the output file.') -parser.add_argument('--deps_list_path', required=True, - help='Full path to the json dependencies file.') -parser.add_argument('--exclude_deps', required=False, - default='', - help=('Comma separated list of dependencies to exclude' - ' from tar.gz file.')) -parser.add_argument('--additional_deps', required=False, - default='', - help=('Comma separated list of additional deps' - ' to include in tar.gz.')) - - -def read_dependencies(file_path): - """Reads a json file and creates an iterable of unique dependencies. - - Args: - file_path: The path to the runtime dependencies file. - - Returns: - An iterable with unique dependencies. - """ - deps = None - with open(file_path) as deps_file: - deps = json.load(deps_file) - deps_set = set() - for _, dep_list in deps.items(): - deps_set.update(dep_list) - return deps_set - - -def filter_dependencies(dependencies, filters): - """Filters out dependencies from a dependencies iterable. - - Args: - dependencies: An iterable with the full list of dependencies. - filters: A list of dependencies to remove. - - Returns: - An iterable with the filtered dependencies. - """ - filters_list = filters.strip(',').split(',') - logging.info('Filtering: %s', filters_list) - filtered_deps = set() - for dep in dependencies: - norm_dep = os.path.normpath(dep) - if not any(norm_dep.startswith(f) for f in filters_list): - filtered_deps.add(norm_dep) - return filtered_deps - - -def create_tarfile(output_path, dependencies): - """Creates a tar.gz file and saves it to output_path. - - Args: - output_path: A string with the path to where tar.gz file will be saved to. - dependencies: An iterable with file/folders test dependencies. - """ - total_deps = len(dependencies) - if total_deps < 1: - logging.error('There are no dependencies to archive') - sys.exit(1) - step = (total_deps / 10) or 1 - logging.info('Adding %s files', total_deps) - with tarfile.open(output_path, 'w:gz') as tar_file: - for idx, dep in enumerate(dependencies): - dep = os.path.normpath(dep) - archive_name = os.path.join('tools/fuchsia/size_tests', dep) - archive_name = os.path.normpath(archive_name) - tar_file.add(dep, arcname=archive_name) - if idx % step == 0 or idx == (total_deps - 1): - logging.info('Progress: %s percent', int(round(100.0/total_deps * idx))) - - -def main(): - logging.basicConfig(level=logging.INFO) - args = parser.parse_args() - dependencies = read_dependencies(args.deps_list_path) - if args.additional_deps: - to_include = args.additional_deps.strip(',').split(',') - logging.info('Including: %s', to_include) - dependencies.update(to_include) - if args.exclude_deps: - dependencies = filter_dependencies(dependencies, args.exclude_deps) - create_tarfile(args.output, dependencies) - - -if __name__ == '__main__': - main() diff -Nru chromium-132.0.6834.110/chromecast/tools/trace.py chromium-132.0.6834.159/chromecast/tools/trace.py --- chromium-132.0.6834.110/chromecast/tools/trace.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tools/trace.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -#!/usr/bin/env python -# -# 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. -# -# This script was originally written by Alok Priyadarshi (alokp@) -# with some minor local modifications. - -import contextlib -import json -import logging -import optparse -import os -import sys -import websocket - -from tracinglib import TracingBackend, TracingBackendAndroid, TracingClient - -@contextlib.contextmanager -def Connect(options): - if options.adb_device: - backend = TracingBackendAndroid(options.adb_device) - else: - backend = TracingBackend(options.device, options.port, options.timeout, 0) - - try: - backend.Connect() - yield backend - finally: - backend.Disconnect() - - -def GetOutputFilePath(options): - filepath = os.path.expanduser(options.output) if options.output \ - else os.path.join(os.getcwd(), 'trace.json') - - dirname = os.path.dirname(filepath) - if dirname: - if not os.path.exists(dirname): - os.makedirs(dirname) - else: - filepath = os.path.join(os.getcwd(), filepath) - - return filepath - - -def _CreateOptionParser(): - parser = optparse.OptionParser(description='Record about://tracing profiles ' - 'from any running instance of Chrome.') - parser.add_option( - '-v', '--verbose', help='Verbose logging.', action='store_true') - parser.add_option( - '-p', '--port', help='Remote debugging port.', type='int', default=9222) - parser.add_option( - '-d', '--device', help='Device ip address.', type='string', - default='127.0.0.1') - parser.add_option( - '-s', '--adb-device', help='Device serial for adb.', type='string') - parser.add_option( - '-t', '--timeout', help='Websocket timeout interval.', type='int', - default=90) - - tracing_opts = optparse.OptionGroup(parser, 'Tracing options') - tracing_opts.add_option( - '-c', '--category-filter', - help='Apply filter to control what category groups should be traced.', - type='string', - default='') - tracing_opts.add_option( - '--record-continuously', - help='Keep recording until stopped. The trace buffer is of fixed size ' - 'and used as a ring buffer. If this option is omitted then ' - 'recording stops when the trace buffer is full.', - action='store_true') - tracing_opts.add_option( - '--systrace', - help='Enable system tracing.', - action='store_true', - dest='systrace', - default=True) - parser.add_option_group(tracing_opts) - - output_options = optparse.OptionGroup(parser, 'Output options') - output_options.add_option( - '-o', '--output', - help='Save trace output to file.') - parser.add_option_group(output_options) - - return parser - - -def _ProcessOptions(options): - websocket.enableTrace(options.verbose) - - -def main(): - parser = _CreateOptionParser() - options, _args = parser.parse_args() - _ProcessOptions(options) - - with Connect(options) as tracing_backend: - tracing_backend.StartTracing(options.category_filter, - options.record_continuously, options.systrace) - raw_input('Capturing trace. Press Enter to stop...') - output_path_base = GetOutputFilePath(options) - output_path = tracing_backend.StopTracing(output_path_base) - - print('Done') - print('Trace written to file://%s' % output_path) - - -if __name__ == '__main__': - sys.exit(main()) diff -Nru chromium-132.0.6834.110/chromecast/tools/tracinglib.py chromium-132.0.6834.159/chromecast/tools/tracinglib.py --- chromium-132.0.6834.110/chromecast/tools/tracinglib.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tools/tracinglib.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,298 +0,0 @@ -# Copyright 2016 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - - -"""Utilities for capturing traces for chromecast devices.""" - -import base64 -import json -import logging -import math -import requests -import subprocess -import time -import websocket - - -class TracingClient(object): - - def BufferUsage(self, buffer_usage): - percent = int(math.floor(buffer_usage * 100)) - logging.debug('Buffer Usage: %i', percent) - - -class TracingBackend(object): - """Class for starting a tracing session with cast_shell.""" - - def __init__(self, device_ip, devtools_port, timeout, - buffer_usage_reporting_interval): - """ - Args: - device_ip: IP of device to connect to. - devtools_port: Remote dev tool port to connect to. Defaults to 9222. - timeout: Time to wait to start tracing in seconds. Default 10s. - buffer_usage_reporting_interval: How often to report buffer usage. - """ - self._socket = None - self._next_request_id = 0 - self._tracing_client = None - self._tracing_data = [] - self._device_ip = device_ip - self._devtools_port = devtools_port - self._timeout = timeout - self._buffer_usage_reporting_interval = buffer_usage_reporting_interval - self._included_categories = [] - self._excluded_categories = [] - self._pending_read_ids = [] - self._stream_handle = None - self._output_file = None - - def Connect(self): - """Connect to cast_shell.""" - assert not self._socket - # Get the secure browser debugging target. - r = requests.get( - 'http://%s:%i/json/version' % (self._device_ip, self._devtools_port)) - url = r.json()['webSocketDebuggerUrl'] - print('Connect to %s ...' % url) - self._socket = websocket.create_connection(url, timeout=self._timeout) - self._next_request_id = 0 - - def Disconnect(self): - """If connected to device, disconnect from device.""" - if self._socket: - self._socket.close() - self._socket = None - - def StartTracing(self, - custom_categories=None, - record_continuously=False, - systrace=True): - """Begin a tracing session on device. - - Args: - custom_categories: Categories to filter for. None records all categories. - record_continuously: Keep tracing until stopped. If false, will exit when - buffer is full. - """ - self._tracing_client = TracingClient() - self._socket.settimeout(self._timeout) - self._ParseCustomCategories(custom_categories) - req = { - 'method': 'Tracing.start', - 'params': { - 'transferMode': - 'ReturnAsStream' if systrace else 'ReportEvents', - 'streamCompression': - 'gzip' if systrace else 'none', - 'traceConfig': { - 'enableSystrace': - systrace, - 'recordMode': - 'recordContinuously' - if record_continuously else 'recordUntilFull', - 'includedCategories': - self._included_categories, - 'excludedCategories': - self._excluded_categories, - }, - 'bufferUsageReportingInterval': - self._buffer_usage_reporting_interval, - } - } - self._SendRequest(req) - - def StopTracing(self, output_path_base): - """End a tracing session on device. - - Args: - output_path_base: Path to the file to store the trace. A .gz extension - will be appended to this path if the trace is compressed. - - Returns: - Final output filename. - """ - self._socket.settimeout(self._timeout) - req = {'method': 'Tracing.end'} - self._SendRequest(req) - self._output_path_base = output_path_base - - try: - while self._socket: - res = self._ReceiveResponse() - has_error = 'error' in res - if has_error: - logging.error('Tracing error: ' + str(res.get('error'))) - if has_error or self._HandleResponse(res): - self._tracing_client = None - if not self._stream_handle: - # Compression not supported for ReportEvents transport. - self._output_path = self._output_path_base - with open(self._output_path, 'w') as output_file: - json.dump(self._tracing_data, output_file) - self._tracing_data = [] - return self._output_path - finally: - if self._output_file: - self._output_file.close() - - def _SendRequest(self, req): - """Sends request to remote devtools. - - Args: - req: Request to send. - """ - req['id'] = self._next_request_id - self._next_request_id += 1 - data = json.dumps(req) - self._socket.send(data) - return req['id'] - - def _ReceiveResponse(self): - """Get response from remote devtools. - - Returns: - Response received. - """ - while self._socket: - data = self._socket.recv() - res = json.loads(data) - return res - - def _SendReadRequest(self): - """Sends a request to read the trace data stream.""" - req = { - 'method': 'IO.read', - 'params': { - 'handle': self._stream_handle, - 'size': 32768, - } - } - - # Send multiple reads to hide request latency. - while len(self._pending_read_ids) < 2: - self._pending_read_ids.append(self._SendRequest(req)) - - def _HandleResponse(self, res): - """Handle response from remote devtools. - - Args: - res: Recieved tresponse that should be handled. - """ - method = res.get('method') - value = res.get('params', {}).get('value') - response_id = res.get('id', None) - if 'Tracing.dataCollected' == method: - if type(value) in [str, unicode]: - self._tracing_data.append(value) - elif type(value) is list: - self._tracing_data.extend(value) - else: - logging.warning('Unexpected type in tracing data') - elif 'Tracing.bufferUsage' == method and self._tracing_client: - self._tracing_client.BufferUsage(value) - elif 'Tracing.tracingComplete' == method: - self._stream_handle = res.get('params', {}).get('stream') - compression = res.get('params', {}).get('streamCompression') - if self._stream_handle: - compression_suffix = '.gz' if compression == 'gzip' else '' - self._output_path = self._output_path_base - if not self._output_path.endswith(compression_suffix): - self._output_path += compression_suffix - self._output_file = open(self._output_path, 'w') - self._SendReadRequest() - else: - return True - elif response_id in self._pending_read_ids: - self._pending_read_ids.remove(response_id) - data = res.get('result', {}).get('data') - eof = res.get('result', {}).get('eof') - base64_encoded = res.get('result', {}).get('base64Encoded') - if base64_encoded: - data = base64.b64decode(data) - else: - data = data.encode('utf-8') - self._output_file.write(data) - if eof: - return True - else: - self._SendReadRequest() - - def _ParseCustomCategories(self, custom_categories): - """Parse a category filter into trace config format""" - - self._included_categories = [] - self._excluded_categories = [] - - # See TraceConfigCategoryFilter::InitializeFromString in chromium. - categories = (token.strip() for token in custom_categories.split(',')) - for category in categories: - if not category: - continue - if category.startswith('-'): - self._excluded_categories.append(category[1:]) - else: - self._included_categories.append(category) - - -class TracingBackendAndroid(object): - """Android version of TracingBackend.""" - def __init__(self, device): - self.device = device - - def Connect(self): - pass - - - def Disconnect(self): - pass - - def StartTracing(self, - custom_categories=None, - record_continuously=False, - systrace=True): - """Begin a tracing session on device. - - Args: - custom_categories: Categories to filter for. None records all categories. - record_continuously: Keep tracing until stopped. If false, will exit when - buffer is full. - """ - categories = (custom_categories if custom_categories else - '_DEFAULT_CHROME_CATEGORIES') - self._file = '/sdcard/Download/trace-py-{0}'.format(int(time.time())) - command = ['shell', 'am', 'broadcast', - '-a', 'com.google.android.apps.mediashell.GPU_PROFILER_START', - '-e', 'categories', categories, - '-e', 'file', self._file] - if record_continuously: - command += ['-e', 'continuous'] - - self._AdbCommand(command) - - def StopTracing(self, output_file): - """End a tracing session on device. - - Args: - output_file: Path to the file to store the trace. - """ - stop_profiling_command = ['shell', 'am', 'broadcast', - '-a', 'com.google.android.apps.mediashell.GPU_PROFILER_STOP'] - self._AdbCommand(stop_profiling_command) - - # Wait for trace file to be written - while True: - result = self._AdbCommand(['logcat', '-d']) - if 'Results are in %s' % self._file in result: - break - - self._AdbCommand(['pull', self._file, output_file]) - return output_file - - def _AdbCommand(self, command): - args = ['adb', '-s', self.device] - logging.debug(' '.join(args + command)) - result = subprocess.check_output(args + command) - logging.debug(result) - return result diff -Nru chromium-132.0.6834.110/chromecast/tracing/OWNERS chromium-132.0.6834.159/chromecast/tracing/OWNERS --- chromium-132.0.6834.110/chromecast/tracing/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tracing/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -spang@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/tracing/ftrace.cc chromium-132.0.6834.159/chromecast/tracing/ftrace.cc --- chromium-132.0.6834.110/chromecast/tracing/ftrace.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tracing/ftrace.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,217 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/tracing/ftrace.h" - -#include -#include -#include - -#include - -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/ranges/algorithm.h" -#include "base/strings/string_util.h" -#include "base/trace_event/common/trace_event_common.h" -#include "chromecast/tracing/system_tracing_common.h" - -namespace chromecast { -namespace tracing { -namespace { - -const char kPathTracefs[] = "/sys/kernel/tracing"; -const char kPathDebugfsTracing[] = "/sys/kernel/debug/tracing"; -const char kTraceFileTracingOn[] = "tracing_on"; -const char kTraceFileTraceMarker[] = "trace_marker"; -const char kTraceFileSetEvent[] = "set_event"; -const char kTraceFileTraceClock[] = "trace_clock"; -const char kTraceFileTrace[] = "trace"; -const char kTraceFileBufferSizeKb[] = "buffer_size_kb"; - -const char kBufferSizeKbRunning[] = "7040"; -const char kBufferSizeKbIdle[] = "1408"; - -// TODO(spang): Load these lists from a configuration file. -const char* const kGfxEvents[] = { - "i915:i915_flip_request", "i915:i915_flip_complete", - "i915:i915_gem_object_pwrite", "i915:intel_gpu_freq_change", - "exynos:exynos_flip_request", "exynos:exynos_flip_complete", - "exynos:exynos_page_flip_state", "drm:drm_vblank_event", -}; - -const char* const kInputEvents[] = { - "irq:irq_threaded_handler_entry", "irq:irq_threaded_handler_exit", -}; - -const char* const kIrqEvents[] = { - "irq:irq_handler_exit", "irq:irq_handler_entry", -}; - -const char* const kPowerEvents[] = { - "power:cpu_idle", - "power:cpu_frequency", - "mali:mali_dvfs_set_clock", - "mali:mali_dvfs_set_voltage", - "cpufreq_interactive:cpufreq_interactive_boost", - "cpufreq_interactive:cpufreq_interactive_unboost", - "exynos_busfreq:exynos_busfreq_target_int", - "exynos_busfreq:exynos_busfreq_target_mif", -}; - -const char* const kSchedEvents[] = { - "sched:sched_switch", "sched:sched_wakeup", -}; - -const char* const kWorkqEvents[] = { - "workqueue:workqueue_execute_start", "workqueue:workqueue_execute_end", -}; - -void AddCategoryEvents(const std::string& category, - std::vector* events) { - if (category == "gfx") { - base::ranges::copy(kGfxEvents, std::back_inserter(*events)); - return; - } - if (category == "input") { - base::ranges::copy(kInputEvents, std::back_inserter(*events)); - return; - } - if (category == TRACE_DISABLED_BY_DEFAULT("irq")) { - base::ranges::copy(kIrqEvents, std::back_inserter(*events)); - return; - } - if (category == "power") { - base::ranges::copy(kPowerEvents, std::back_inserter(*events)); - return; - } - if (category == "sched") { - base::ranges::copy(kSchedEvents, std::back_inserter(*events)); - return; - } - if (category == "workq") { - base::ranges::copy(kWorkqEvents, std::back_inserter(*events)); - return; - } - - LOG(WARNING) << "Unrecognized category: " << category; -} - -bool WriteTracingFile(const char* tracing_dir, - const char* trace_file, - std::string_view contents) { - base::FilePath path = base::FilePath(tracing_dir).Append(trace_file); - - if (!base::WriteFile(path, contents)) { - PLOG(ERROR) << "write: " << path; - return false; - } - - return true; -} - -bool EnableTraceEvent(const char* tracing_dir, std::string_view event) { - base::FilePath path = base::FilePath(tracing_dir).Append(kTraceFileSetEvent); - - // Enabling events returns EINVAL if the event does not exist. It is normal - // for driver specific events to be missing when the driver is not built in. - if (!base::AppendToFile(path, event) && errno != EINVAL) { - PLOG(ERROR) << "write: " << path; - return false; - } - - return true; -} - -const char* FindTracingDir() { - base::FilePath path = base::FilePath(kPathTracefs).Append(kTraceFileSetEvent); - if (!access(path.value().c_str(), W_OK)) - return kPathTracefs; - return kPathDebugfsTracing; -} - -} // namespace - -bool IsValidCategory(std::string_view str) { - for (std::string_view category : kCategories) { - if (category == str) { - return true; - } - } - - return false; -} - -bool StartFtrace(const std::vector& categories) { - if (categories.size() == 0) { - LOG(ERROR) << "No categories to enable"; - return false; - } - - std::vector events; - for (const auto& category : categories) - AddCategoryEvents(category, &events); - - if (events.size() == 0) { - LOG(ERROR) << "No events to enable"; - return false; - } - - const char* tracing_dir = FindTracingDir(); - - // Disable tracing and clear events. - if (!WriteTracingFile(tracing_dir, kTraceFileTracingOn, "0")) - return false; - if (!WriteTracingFile(tracing_dir, kTraceFileSetEvent, "\n")) - return false; - - // Use CLOCK_MONOTONIC so that kernel timestamps align with std::steady_clock - // and base::TimeTicks. - if (!WriteTracingFile(tracing_dir, kTraceFileTraceClock, "mono")) - return false; - - for (const auto& event : events) - EnableTraceEvent(tracing_dir, event); - - if (!WriteTracingFile(tracing_dir, kTraceFileBufferSizeKb, - kBufferSizeKbRunning)) - return false; - if (!WriteTracingFile(tracing_dir, kTraceFileTracingOn, "1")) - return false; - - return true; -} - -bool WriteFtraceTimeSyncMarker() { - return WriteTracingFile(FindTracingDir(), kTraceFileTraceMarker, - "trace_event_clock_sync: parent_ts=0"); -} - -bool StopFtrace() { - if (!WriteTracingFile(FindTracingDir(), kTraceFileTracingOn, "0")) - return false; - return true; -} - -base::ScopedFD GetFtraceData() { - base::FilePath path = - base::FilePath(FindTracingDir()).Append(kTraceFileTrace); - base::ScopedFD trace_data(HANDLE_EINTR( - open(path.value().c_str(), O_RDONLY | O_CLOEXEC | O_NONBLOCK))); - if (!trace_data.is_valid()) - PLOG(ERROR) << "open: " << path.value(); - return trace_data; -} - -bool ClearFtrace() { - const char* tracing_dir = FindTracingDir(); - if (!WriteTracingFile(tracing_dir, kTraceFileBufferSizeKb, kBufferSizeKbIdle)) - return false; - if (!WriteTracingFile(tracing_dir, kTraceFileTrace, "0")) - return false; - return true; -} - -} // namespace tracing -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/tracing/ftrace.h chromium-132.0.6834.159/chromecast/tracing/ftrace.h --- chromium-132.0.6834.110/chromecast/tracing/ftrace.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tracing/ftrace.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_TRACING_FTRACE_H_ -#define CHROMECAST_TRACING_FTRACE_H_ - -#include -#include -#include - -#include "base/files/scoped_file.h" - -namespace chromecast { -namespace tracing { - -// Returns true if |category| is valid for system tracing. -bool IsValidCategory(std::string_view category); - -// Starts ftrace for the specified categories. -// -// This must be paired with StopFtrace() or the kernel will continue tracing -// indefinitely. Returns false if an error occurs writing to tracefs - this -// usually indicates a configuration issue (e.g. tracefs not mounted). -bool StartFtrace(const std::vector& categories); - -// Writes time synchronization marker. -// -// This is used by trace-viewer to align ftrace clock with userspace -// tracing. Since CLOCK_MONOTONIC is used in both cases, this merely -// writes a zero offset. Call it at the end of tracing right before -// StopFtrace(). Returns false if an error occurs writing to tracefs. -bool WriteFtraceTimeSyncMarker(); - -// Stops ftrace. -// -// This is safe to call even if tracing isn't started. Returns false if an error -// occurs writing to tracefs. -bool StopFtrace(); - -// Opens ftrace buffer for reading. -base::ScopedFD GetFtraceData(); - -// Clears ftrace buffer. Returns false if an error occurs writing to tracefs. -bool ClearFtrace(); - -} // namespace tracing -} // namespace chromecast - -#endif // CHROMECAST_TRACING_FTRACE_H_ diff -Nru chromium-132.0.6834.110/chromecast/tracing/system_tracer.cc chromium-132.0.6834.159/chromecast/tracing/system_tracer.cc --- chromium-132.0.6834.110/chromecast/tracing/system_tracer.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tracing/system_tracer.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,270 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/tracing/system_tracer.h" - -#include -#include -#include - -#include -#include - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/logging.h" -#include "base/posix/eintr_wrapper.h" -#include "base/posix/unix_domain_socket.h" -#include "base/trace_event/trace_config.h" -#include "chromecast/chromecast_buildflags.h" -#include "chromecast/tracing/system_tracing_common.h" - -namespace chromecast { -namespace { - -constexpr size_t kBufferSize = 1UL << 16; - -base::ScopedFD CreateClientSocket() { - base::ScopedFD socket_fd( - socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0)); - if (!socket_fd.is_valid()) { - PLOG(ERROR) << "socket"; - return base::ScopedFD(); - } - - struct sockaddr_un addr = - chromecast::tracing::GetSystemTracingSocketAddress(); - - if (connect(socket_fd.get(), reinterpret_cast(&addr), - sizeof(addr))) { - PLOG(ERROR) << "connect: " << addr.sun_path; - return base::ScopedFD(); - } - - return socket_fd; -} - -class SystemTracerImpl : public SystemTracer { - public: - SystemTracerImpl() : buffer_(new char[kBufferSize]) {} - ~SystemTracerImpl() override { Cleanup(); } - - void StartTracing(std::string_view categories, - StartTracingCallback callback) override; - - void StopTracing(const StopTracingCallback& callback) override; - - private: - enum class State { - INITIAL, // Not yet started. - STARTING, // Sent start message, waiting for ack. - TRACING, // Tracing, not yet requested stop. - READING, // Trace stopped, reading output. - FINISHED, // All done. - }; - - void ReceiveStartAckAndTracePipe(); - void ReceiveTraceData(); - void FailStartTracing(); - void FailStopTracing(); - void SendPartialTraceData(); - void FinishTracing(); - void Cleanup(); - - // Current state of tracing attempt. - State state_ = State::INITIAL; - - // Unix socket connection to tracing daemon. - base::ScopedFD connection_fd_; - std::unique_ptr connection_watcher_; - - // Pipe for trace data. - base::ScopedFD trace_pipe_fd_; - std::unique_ptr trace_pipe_watcher_; - - // Read buffer (of size kBufferSize). - std::unique_ptr buffer_; - - // Callbacks for StartTracing() and StopTracing(). - StartTracingCallback start_tracing_callback_; - StopTracingCallback stop_tracing_callback_; - - // Trace data. - std::string trace_data_; -}; - -void SystemTracerImpl::StartTracing(std::string_view categories, - StartTracingCallback callback) { - start_tracing_callback_ = std::move(callback); - if (state_ != State::INITIAL) { - FailStartTracing(); - return; - } - - if (categories.size() == 0) { - // No relevant categories are enabled. - FailStartTracing(); - return; - } - - connection_fd_ = CreateClientSocket(); - if (!connection_fd_.is_valid()) { - FailStartTracing(); - return; - } - - if (!base::UnixDomainSocket::SendMsg(connection_fd_.get(), categories.data(), - categories.size(), std::vector())) { - PLOG(ERROR) << "sendmsg"; - FailStartTracing(); - return; - } - - connection_watcher_ = base::FileDescriptorWatcher::WatchReadable( - connection_fd_.get(), - base::BindRepeating(&SystemTracerImpl::ReceiveStartAckAndTracePipe, - base::Unretained(this))); - state_ = State::STARTING; -} - -void SystemTracerImpl::StopTracing(const StopTracingCallback& callback) { - stop_tracing_callback_ = callback; - if (state_ != State::TRACING) { - FailStopTracing(); - return; - } - - char stop_tracing_message[] = {0}; - if (!base::UnixDomainSocket::SendMsg( - connection_fd_.get(), stop_tracing_message, - sizeof(stop_tracing_message), std::vector())) { - PLOG(ERROR) << "sendmsg"; - FailStopTracing(); - return; - } - - trace_pipe_watcher_ = base::FileDescriptorWatcher::WatchReadable( - trace_pipe_fd_.get(), - base::BindRepeating(&SystemTracerImpl::ReceiveTraceData, - base::Unretained(this))); - state_ = State::READING; -} - -void SystemTracerImpl::ReceiveStartAckAndTracePipe() { - DCHECK_EQ(state_, State::STARTING); - - std::vector fds; - ssize_t received = base::UnixDomainSocket::RecvMsg( - connection_fd_.get(), buffer_.get(), kBufferSize, &fds); - if (received == 0) { - LOG(ERROR) << "EOF from server"; - FailStartTracing(); - return; - } - if (received < 0) { - PLOG(ERROR) << "recvmsg"; - FailStartTracing(); - return; - } - if (fds.size() != 1) { - LOG(ERROR) << "Start ack missing trace pipe"; - FailStartTracing(); - return; - } - - trace_pipe_fd_ = std::move(fds[0]); - connection_watcher_.reset(); - state_ = State::TRACING; - std::move(start_tracing_callback_).Run(Status::OK); -} - -void SystemTracerImpl::ReceiveTraceData() { - DCHECK_EQ(state_, State::READING); - - for (;;) { - ssize_t bytes = - HANDLE_EINTR(read(trace_pipe_fd_.get(), buffer_.get(), kBufferSize)); - if (bytes < 0) { - if (errno == EAGAIN) - return; // Wait for more data. - PLOG(ERROR) << "read: trace"; - FailStopTracing(); - return; - } - - if (bytes == 0) { - FinishTracing(); - return; - } - - trace_data_.append(buffer_.get(), bytes); - - static constexpr size_t kPartialTraceDataSize = 1UL << 20; // 1 MiB - if (trace_data_.size() > kPartialTraceDataSize) { - SendPartialTraceData(); - return; - } - } -} - -void SystemTracerImpl::FailStartTracing() { - std::move(start_tracing_callback_).Run(Status::FAIL); - Cleanup(); -} - -void SystemTracerImpl::FailStopTracing() { - stop_tracing_callback_.Run(Status::FAIL, ""); - Cleanup(); -} - -void SystemTracerImpl::SendPartialTraceData() { - DCHECK_EQ(state_, State::READING); - stop_tracing_callback_.Run(Status::KEEP_GOING, std::move(trace_data_)); - trace_data_ = ""; -} - -void SystemTracerImpl::FinishTracing() { - DCHECK_EQ(state_, State::READING); - stop_tracing_callback_.Run(Status::OK, std::move(trace_data_)); - Cleanup(); -} - -void SystemTracerImpl::Cleanup() { - connection_watcher_.reset(); - connection_fd_.reset(); - trace_pipe_watcher_.reset(); - trace_pipe_fd_.reset(); - start_tracing_callback_.Reset(); - stop_tracing_callback_.Reset(); - state_ = State::FINISHED; -} - -class FakeSystemTracer : public SystemTracer { - public: - FakeSystemTracer() = default; - ~FakeSystemTracer() override = default; - - void StartTracing(std::string_view categories, - StartTracingCallback callback) override { - std::move(callback).Run(Status::OK); - } - - void StopTracing(const StopTracingCallback& callback) override { - std::string trace_data = "# tracer: nop\n"; - std::move(callback).Run(Status::OK, std::move(trace_data)); - } -}; - -} // namespace - -// static -std::unique_ptr SystemTracer::Create() { -#if BUILDFLAG(IS_CAST_DESKTOP_BUILD) - return std::make_unique(); -#else - return std::make_unique(); -#endif -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/tracing/system_tracer.h chromium-132.0.6834.159/chromecast/tracing/system_tracer.h --- chromium-132.0.6834.110/chromecast/tracing/system_tracer.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tracing/system_tracer.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_TRACING_SYSTEM_TRACER_H_ -#define CHROMECAST_TRACING_SYSTEM_TRACER_H_ - -#include -#include -#include - -#include "base/files/file_descriptor_watcher_posix.h" -#include "base/files/scoped_file.h" -#include "base/functional/callback.h" - -namespace chromecast { - -class SystemTracer { - public: - static std::unique_ptr Create(); - - SystemTracer(const SystemTracer&) = delete; - SystemTracer& operator=(const SystemTracer&) = delete; - - virtual ~SystemTracer() = default; - - enum class Status { - OK, - KEEP_GOING, - FAIL, - }; - - using StartTracingCallback = base::OnceCallback; - using StopTracingCallback = - base::RepeatingCallback; - - // Start system tracing for categories in |categories| (comma separated). - virtual void StartTracing(std::string_view categories, - StartTracingCallback callback) = 0; - - // Stop system tracing. - // - // This will call |callback| on the current thread with the trace data. If - // |status| is Status::KEEP_GOING, another call will be made with additional - // data. - virtual void StopTracing(const StopTracingCallback& callback) = 0; - - protected: - SystemTracer() = default; -}; - -} // namespace chromecast - -#endif // CHROMECAST_TRACING_SYSTEM_TRACER_H_ diff -Nru chromium-132.0.6834.110/chromecast/tracing/system_tracing_common.cc chromium-132.0.6834.159/chromecast/tracing/system_tracing_common.cc --- chromium-132.0.6834.110/chromecast/tracing/system_tracing_common.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tracing/system_tracing_common.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/tracing/system_tracing_common.h" - -#include - -#include - -namespace chromecast { -namespace tracing { -namespace { - -const char kSocketPath[] = "/dev/socket/tracing/tracing"; - -} // namespace - -sockaddr_un GetSystemTracingSocketAddress() { - struct sockaddr_un addr; - memset(&addr, 0, sizeof(addr)); - static_assert(sizeof(kSocketPath) <= sizeof(addr.sun_path), - "Address too long"); - strncpy(addr.sun_path, kSocketPath, sizeof(addr.sun_path) - 1); - addr.sun_family = AF_UNIX; - return addr; -} - -} // namespace tracing -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/tracing/system_tracing_common.h chromium-132.0.6834.159/chromecast/tracing/system_tracing_common.h --- chromium-132.0.6834.110/chromecast/tracing/system_tracing_common.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tracing/system_tracing_common.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_TRACING_SYSTEM_TRACING_COMMON_H_ -#define CHROMECAST_TRACING_SYSTEM_TRACING_COMMON_H_ - -#include -#include - -#include "base/trace_event/common/trace_event_common.h" - -namespace chromecast { -namespace tracing { - -inline constexpr std::array kCategories = { - "gfx", "input", TRACE_DISABLED_BY_DEFAULT("irq"), - "power", "sched", "workq"}; - -sockaddr_un GetSystemTracingSocketAddress(); - -} // namespace tracing -} // namespace chromecast - -#endif // CHROMECAST_TRACING_SYSTEM_TRACING_COMMON_H_ diff -Nru chromium-132.0.6834.110/chromecast/tracing/tracing_service_main.cc chromium-132.0.6834.159/chromecast/tracing/tracing_service_main.cc --- chromium-132.0.6834.110/chromecast/tracing/tracing_service_main.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/tracing/tracing_service_main.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,418 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "base/at_exit.h" -#include "base/command_line.h" -#include "base/functional/bind.h" -#include "base/logging.h" -#include "base/memory/weak_ptr.h" -#include "base/message_loop/message_pump_for_io.h" -#include "base/message_loop/message_pump_type.h" -#include "base/posix/eintr_wrapper.h" -#include "base/posix/unix_domain_socket.h" -#include "base/run_loop.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "base/task/current_thread.h" -#include "base/task/single_thread_task_executor.h" -#include "base/task/single_thread_task_runner.h" -#include "base/time/time.h" -#include "chromecast/tracing/ftrace.h" -#include "chromecast/tracing/system_tracing_common.h" - -namespace chromecast { -namespace tracing { -namespace { - -constexpr size_t kMessageSize = 4096; - -base::ScopedFD CreateServerSocket() { - struct sockaddr_un addr = GetSystemTracingSocketAddress(); - - if (unlink(addr.sun_path) != 0 && errno != ENOENT) - PLOG(ERROR) << "unlink: " << addr.sun_path; - - base::ScopedFD socket_fd( - socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0)); - if (!socket_fd.is_valid()) { - PLOG(ERROR) << "socket"; - return base::ScopedFD(); - } - - if (bind(socket_fd.get(), reinterpret_cast(&addr), - sizeof(addr))) { - PLOG(ERROR) << "bind: " << addr.sun_path; - return base::ScopedFD(); - } - - if (chmod(addr.sun_path, 0666)) - PLOG(WARNING) << "chmod: " << addr.sun_path; - - static constexpr int kBacklog = 10; - if (listen(socket_fd.get(), kBacklog)) { - PLOG(ERROR) << "listen: " << addr.sun_path; - return base::ScopedFD(); - } - - return socket_fd; -} - -std::vector ParseCategories(std::string_view message) { - std::vector requested_categories = base::SplitString( - message, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); - std::vector categories; - for (const auto& category : requested_categories) { - if (IsValidCategory(category)) - categories.push_back(category); - else - LOG(WARNING) << "Unrecognized category: " << category; - } - return categories; -} - -class TraceCopyTask : public base::MessagePumpEpoll::FdWatcher { - public: - // Read 64 kB at a time (standard pipe capacity). - static constexpr size_t kCopyBufferSize = 1UL << 16; - - enum class Status { - SUCCESS, - FAILURE, - }; - - TraceCopyTask(base::ScopedFD in_fd, - base::ScopedFD out_fd, - base::OnceCallback callback) - : buffer_(new char[kCopyBufferSize]), - in_fd_(std::move(in_fd)), - out_fd_(std::move(out_fd)), - out_watcher_(FROM_HERE), - callback_(std::move(callback)) {} - ~TraceCopyTask() override {} - - void Start() { - base::CurrentIOThread::Get()->WatchFileDescriptor( - out_fd_.get(), true /* persistent */, - base::MessagePumpForIO::WATCH_WRITE, &out_watcher_, this); - } - - // base::MessagePumpEpoll::FdWatcher: - void OnFileCanReadWithoutBlocking(int fd) override { NOTREACHED(); } - void OnFileCanWriteWithoutBlocking(int fd) override { - DCHECK_EQ(out_fd_.get(), fd); - CopyTraceData(); - } - - private: - void CopyTraceData() { - for (;;) { - if (read_ == written_) { - total_copied_ += read_; - read_ = written_ = 0; - - // Read trace data from debugfs. - ssize_t read_bytes = - HANDLE_EINTR(read(in_fd_.get(), buffer_.get(), kCopyBufferSize)); - if (read_bytes == 0) { - // EOF, we're done; - Finish(Status::SUCCESS); - return; - } else if (read_bytes < 0) { - PLOG(ERROR) << "read: trace"; - Finish(Status::FAILURE); - return; - } - - read_ = read_bytes; - } - - // Write trace data to output pipe. - ssize_t written_bytes = HANDLE_EINTR( - write(out_fd_.get(), buffer_.get() + written_, read_ - written_)); - if (written_bytes < 0) { - if (errno == EAGAIN) - return; // Wait for more space. - PLOG(ERROR) << "write: pipe"; - Finish(Status::FAILURE); - return; - } - written_ += written_bytes; - } - } - - void Finish(Status status) { - out_watcher_.StopWatchingFileDescriptor(); - in_fd_.reset(); - out_fd_.reset(); - buffer_.reset(); - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(std::move(callback_), status, total_copied_)); - } - - std::unique_ptr buffer_; - size_t read_ = 0; - size_t written_ = 0; - size_t total_copied_ = 0; - - // Trace data file. - base::ScopedFD in_fd_; - - // Pipe for trace data. - base::ScopedFD out_fd_; - base::MessagePumpEpoll::FdWatchController out_watcher_; - - // Callback for when copy finishes. - base::OnceCallback callback_; -}; - -class TraceConnection : public base::MessagePumpEpoll::FdWatcher { - public: - TraceConnection(base::ScopedFD connection_fd, base::OnceClosure callback) - : recv_buffer_(new char[kMessageSize]), - connection_fd_(std::move(connection_fd)), - connection_watcher_(FROM_HERE), - callback_(std::move(callback)), - weak_ptr_factory_(this) {} - ~TraceConnection() override {} - - void Init() { - base::CurrentIOThread::Get()->WatchFileDescriptor( - connection_fd_.get(), true /* persistent */, - base::MessagePumpForIO::WATCH_READ, &connection_watcher_, this); - } - - // base::MessagePumpEpoll::FdWatcher: - void OnFileCanReadWithoutBlocking(int fd) override { - DCHECK_EQ(connection_fd_.get(), fd); - ReceiveClientMessage(); - } - void OnFileCanWriteWithoutBlocking(int fd) override { NOTREACHED(); } - - private: - enum class State { - INITIAL, // Waiting for init message - TRACING, // Ftrace started. - COPYING, // Ftrace stopped, copying trace data. - COPY_COMPLETE, // Ftrace stopped, all data written to pipe. - FINISHED, // All done. - }; - - void ReceiveClientMessage() { - std::vector fds; - ssize_t bytes = base::UnixDomainSocket::RecvMsg( - connection_fd_.get(), recv_buffer_.get(), kMessageSize, &fds); - if (bytes < 0) { - PLOG(ERROR) << "recvmsg"; - Finish(); - return; - } else if (bytes == 0) { - LOG(INFO) << "connection closed"; - Finish(); - } else { - std::string_view message(recv_buffer_.get(), bytes); - HandleClientMessage(message); - } - } - - void HandleClientMessage(std::string_view message) { - if (state_ == State::INITIAL) { - std::vector categories = ParseCategories(message); - - if (!StartFtrace(categories)) { - LOG(ERROR) << "Failed to start ftrace"; - Finish(); - return; - } - - if (!SendTracePipeToClient()) { - LOG(ERROR) << "Failed to send trace pipe"; - Finish(); - return; - } - - LOG(INFO) << "Started tracing for categories: " - << base::JoinString(categories, ","); - - state_ = State::TRACING; - } else if (state_ == State::TRACING) { - WriteFtraceTimeSyncMarker(); - StopFtrace(); - base::ScopedFD trace_data = GetFtraceData(); - if (!trace_data.is_valid()) { - LOG(ERROR) << "Failed to get trace data"; - Finish(); - return; - } - - LOG(INFO) << "Tracing stopped"; - trace_copy_task_ = std::make_unique( - std::move(trace_data), std::move(trace_pipe_), - base::BindOnce(&TraceConnection::OnFinishedCopying, - weak_ptr_factory_.GetWeakPtr())); - trace_copy_task_->Start(); - state_ = State::COPYING; - } else { - LOG(WARNING) << "Unexpected message"; - Finish(); - return; - } - } - - void OnFinishedCopying(TraceCopyTask::Status status, size_t trace_data_size) { - if (status == TraceCopyTask::Status::SUCCESS) { - LOG(INFO) << "Finished tracing (" << trace_data_size << " bytes copied)"; - state_ = State::COPY_COMPLETE; - } else { - LOG(INFO) << "I/O error copying trace data"; - } - - Finish(); - } - - bool SendTracePipeToClient() { - int pipefd[2] = {-1, -1}; - if (pipe2(pipefd, O_CLOEXEC | O_NONBLOCK)) { - PLOG(ERROR) << "pipe2"; - return false; - } - base::ScopedFD read_end(pipefd[0]); - base::ScopedFD write_end(pipefd[1]); - - const char response[] = {0}; - std::vector send_fds; - send_fds.push_back(read_end.get()); - if (!base::UnixDomainSocket::SendMsg(connection_fd_.get(), response, - sizeof(response), send_fds)) { - PLOG(ERROR) << "sendmsg"; - return false; - } - - trace_pipe_ = std::move(write_end); - return true; - } - - void Finish() { - if (state_ != State::COPY_COMPLETE) - LOG(WARNING) << "Ending tracing without sending data"; - trace_copy_task_.reset(); - state_ = State::FINISHED; - recv_buffer_.reset(); - connection_watcher_.StopWatchingFileDescriptor(); - connection_fd_.reset(); - StopFtrace(); - ClearFtrace(); - base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, std::move(callback_)); - } - - // Tracing state. - State state_ = State::INITIAL; - - // Buffer for incoming messages. - std::unique_ptr recv_buffer_; - - // Client connection. - base::ScopedFD connection_fd_; - base::MessagePumpEpoll::FdWatchController connection_watcher_; - - // Pipe for trace output. - base::ScopedFD trace_pipe_; - - // Task to send all trace output to client via a pipe. - std::unique_ptr trace_copy_task_; - - // Callback for when connection closes. - base::OnceClosure callback_; - - base::WeakPtrFactory weak_ptr_factory_; -}; - -class TracingService : public base::MessagePumpEpoll::FdWatcher { - public: - TracingService() - : server_socket_watcher_(FROM_HERE), weak_ptr_factory_(this) {} - ~TracingService() override {} - - bool Init() { - server_socket_ = CreateServerSocket(); - if (!server_socket_.is_valid()) - return false; - - base::CurrentIOThread::Get()->WatchFileDescriptor( - server_socket_.get(), true /* persistent */, - base::MessagePumpForIO::WATCH_READ, &server_socket_watcher_, this); - - return true; - } - - // base::MessagePumpEpoll::FdWatcher: - void OnFileCanReadWithoutBlocking(int fd) override { - DCHECK_EQ(server_socket_.get(), fd); - AcceptConnection(); - } - void OnFileCanWriteWithoutBlocking(int fd) override { NOTREACHED(); } - - private: - void AcceptConnection() { - base::ScopedFD connection_fd(accept4(server_socket_.get(), nullptr, nullptr, - SOCK_NONBLOCK | SOCK_CLOEXEC)); - if (!connection_fd.is_valid()) { - PLOG(ERROR) << "accept: "; - return; - } - - trace_connection_ = std::make_unique( - std::move(connection_fd), - base::BindOnce(&TracingService::OnConnectionClosed, - weak_ptr_factory_.GetWeakPtr())); - trace_connection_->Init(); - } - - void OnConnectionClosed() { trace_connection_.reset(); } - - // Socket and watcher for listening socket. - base::ScopedFD server_socket_; - base::MessagePumpEpoll::FdWatchController server_socket_watcher_; - - // Currently active tracing connection. - // There can only be one; ftrace affects the whole system. - std::unique_ptr trace_connection_; - - base::WeakPtrFactory weak_ptr_factory_; -}; - -} // namespace -} // namespace tracing -} // namespace chromecast - -int main(int argc, char** argv) { - base::AtExitManager exit_manager; - base::CommandLine::Init(argc, argv); - logging::InitLogging(logging::LoggingSettings()); - - signal(SIGPIPE, SIG_IGN); - - LOG(INFO) << "Starting system tracing service..."; - - base::SingleThreadTaskExecutor io_task_executor(base::MessagePumpType::IO); - chromecast::tracing::TracingService service; - - if (!service.Init()) - return EXIT_FAILURE; - - base::RunLoop run_loop; - run_loop.Run(); - - return EXIT_SUCCESS; -} diff -Nru chromium-132.0.6834.110/chromecast/ui/DEPS chromium-132.0.6834.159/chromecast/ui/DEPS --- chromium-132.0.6834.110/chromecast/ui/DEPS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/DEPS 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -include_rules = [ - "+chromecast/app", - "+chromecast/browser", - "+chromecast/graphics", - "+chromecast/media/cma/pipeline", - "+media/base", - "+mojo/public", - "+ui/aura", - "+ui/base", - "+ui/compositor", - "+ui/display/types", - "+ui/gfx", - "+ui/views", -] diff -Nru chromium-132.0.6834.110/chromecast/ui/OWNERS chromium-132.0.6834.159/chromecast/ui/OWNERS --- chromium-132.0.6834.110/chromecast/ui/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -seantopping@chromium.org diff -Nru chromium-132.0.6834.110/chromecast/ui/back_gesture_router.h chromium-132.0.6834.159/chromecast/ui/back_gesture_router.h --- chromium-132.0.6834.110/chromecast/ui/back_gesture_router.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/back_gesture_router.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_UI_BACK_GESTURE_ROUTER_H_ -#define CHROMECAST_UI_BACK_GESTURE_ROUTER_H_ - -namespace chromecast { - -// Helper class for exposing gesture events to a remote process. -class BackGestureRouter { - public: - class Delegate { - public: - virtual void SetCanGoBack(bool can_go_back) = 0; - }; - virtual void SetBackGestureDelegate(Delegate* delegate) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_BACK_GESTURE_ROUTER_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/brightness_animation.cc chromium-132.0.6834.159/chromecast/ui/display_settings/brightness_animation.cc --- chromium-132.0.6834.110/chromecast/ui/display_settings/brightness_animation.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/brightness_animation.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// 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 "chromecast/ui/display_settings/brightness_animation.h" - -#include -#include - -#include "base/logging.h" -#include "base/time/time.h" - -namespace chromecast { - -namespace { - -constexpr base::TimeDelta kManualAnimationDuration = base::Seconds(0); - -// Brightness changes are smoothed linearly over a 50 ms interval by the -// backlight controller IC. -const int kAnimationFrameRate = 20; - -} // namespace - -BrightnessAnimation::BrightnessAnimation( - DisplaySettingsManager::Delegate* controller) - : gfx::LinearAnimation(kManualAnimationDuration, - kAnimationFrameRate, - nullptr), - controller_(controller) { - DCHECK(controller_); - - start_brightness_ = controller_->GetDisplayBrightness(); - current_brightness_ = start_brightness_; - target_brightness_ = start_brightness_; -} - -BrightnessAnimation::~BrightnessAnimation() { - End(); -} - -void BrightnessAnimation::AnimateToNewValue(float new_target_brightness, - base::TimeDelta duration) { - start_brightness_ = controller_->GetDisplayBrightness(); - target_brightness_ = std::clamp(new_target_brightness, 0.0f, 1.0f); - DVLOG(4) << "Animating to new_target_brightness " << new_target_brightness - << " from current_brightness_=" << current_brightness_; - - if (start_brightness_ < 0.0f) { - LOG(WARNING) - << "Brightness animation started from invalid start_brightness_=" - << start_brightness_; - start_brightness_ = target_brightness_; - SetDuration(base::Seconds(0)); - } else { - // This will reset the animation timer to the beginning. - SetDuration(duration); - } - Start(); -} - -void BrightnessAnimation::AnimateToState(double state) { - state = std::clamp(state, 0.0, 1.0); - current_brightness_ = - start_brightness_ + (target_brightness_ - start_brightness_) * state; - ApplyValuesToDisplay(); -} - -void BrightnessAnimation::ApplyValuesToDisplay() { - controller_->SetDisplayBrightness(current_brightness_, false); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/brightness_animation.h chromium-132.0.6834.159/chromecast/ui/display_settings/brightness_animation.h --- chromium-132.0.6834.110/chromecast/ui/display_settings/brightness_animation.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/brightness_animation.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -// 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. - -#ifndef CHROMECAST_UI_DISPLAY_SETTINGS_BRIGHTNESS_ANIMATION_H_ -#define CHROMECAST_UI_DISPLAY_SETTINGS_BRIGHTNESS_ANIMATION_H_ - -#include "chromecast/ui/display_settings_manager.h" -#include "ui/gfx/animation/animation_delegate.h" -#include "ui/gfx/animation/linear_animation.h" - -namespace chromecast { - -// Defines a linear animation type to animate the color temperature between two -// values in a given time duration. -class BrightnessAnimation : public gfx::LinearAnimation { - public: - explicit BrightnessAnimation(DisplaySettingsManager::Delegate* controller); - BrightnessAnimation(const BrightnessAnimation&) = delete; - BrightnessAnimation& operator=(const BrightnessAnimation&) = delete; - ~BrightnessAnimation() override; - - // Starts a new brightness animation from the |current_brightness_| to the - // given |new_target_brightness| in the given |duration|. - void AnimateToNewValue(float new_target_brightness, base::TimeDelta duration); - - private: - // gfx::LinearAnimation implementation: - void AnimateToState(double state) override; - - void ApplyValuesToDisplay(); - - DisplaySettingsManager::Delegate* const controller_; - - float start_brightness_; - float current_brightness_; - float target_brightness_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_DISPLAY_SETTINGS_BRIGHTNESS_ANIMATION_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/color_temperature_animation.cc chromium-132.0.6834.159/chromecast/ui/display_settings/color_temperature_animation.cc --- chromium-132.0.6834.110/chromecast/ui/display_settings/color_temperature_animation.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/color_temperature_animation.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,122 +0,0 @@ -// 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 "chromecast/ui/display_settings/color_temperature_animation.h" - -#include -#include -#include - -#include "base/time/time.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" - -#if defined(USE_AURA) -#include "chromecast/browser/cast_display_configurator.h" -#endif // defined(USE_AURA) - -namespace chromecast { - -namespace { - -constexpr base::TimeDelta kManualAnimationDuration = base::Seconds(1); - -const int kAnimationFrameRate = 30; - -float Interpolate(const std::vector& vec, float idx) { - size_t i = idx; - if (i == idx) - return vec[i]; - float frac = idx - i; - return frac * vec[i + 1] + (1 - frac) * vec[i]; -} - -} // namespace - -ColorTemperatureAnimation::ColorTemperatureAnimation( - shell::CastDisplayConfigurator* display_configurator, - const DisplaySettingsManager::ColorTemperatureConfig& config) - : gfx::LinearAnimation(kManualAnimationDuration, - kAnimationFrameRate, - nullptr), - display_configurator_(display_configurator), - config_(config), - start_temperature_(config.neutral_temperature), - current_temperature_(config.neutral_temperature), - target_temperature_(config_.neutral_temperature) { -#if defined(USE_AURA) - DCHECK(display_configurator_); -#endif // defined(USE_AURA) - ApplyValuesToDisplay(); -} - -ColorTemperatureAnimation::~ColorTemperatureAnimation() = default; - -void ColorTemperatureAnimation::AnimateToNewValue(float new_target_temperature, - base::TimeDelta duration) { - start_temperature_ = current_temperature_; - target_temperature_ = std::clamp(new_target_temperature, 1000.0f, 20000.0f); - - if (ui::ScopedAnimationDurationScaleMode::duration_multiplier() == - ui::ScopedAnimationDurationScaleMode::ZERO_DURATION) { - // Animations are disabled. Apply the target temperature directly to the - // compositor. - current_temperature_ = target_temperature_; - ApplyValuesToDisplay(); - Stop(); - return; - } - - // This will reset the animation timer to the beginning. - SetDuration(duration); - Start(); -} - -void ColorTemperatureAnimation::AnimateToNeutral(base::TimeDelta duration) { - AnimateToNewValue(config_.neutral_temperature, duration); -} - -void ColorTemperatureAnimation::AnimateToState(double state) { - state = std::clamp(state, 0.0, 1.0); - current_temperature_ = - start_temperature_ + (target_temperature_ - start_temperature_) * state; - ApplyValuesToDisplay(); -} - -void ColorTemperatureAnimation::ApplyValuesToDisplay() { - // Clamp temperature value to table range. - float kelvin = - std::clamp(current_temperature_, config_.temperature_values.front(), - config_.temperature_values.back()); - size_t i = 0; - // Find greatest index whose value is <= |kelvin|. This is safe since |kelvin| - // is clamped to fall within the table range. - while (kelvin > config_.temperature_values[i + 1]) - ++i; - - // Backwards interpolate the index from the temperature table. - float i_interp = i + (kelvin - config_.temperature_values[i]) / - (config_.temperature_values[i + 1] - - config_.temperature_values[i]); - float red_scale = - Interpolate(config_.red_values, i_interp) / config_.full_color; - float green_scale = - Interpolate(config_.green_values, i_interp) / config_.full_color; - float blue_scale = - Interpolate(config_.blue_values, i_interp) / config_.full_color; - - DVLOG(2) << "RGB scaling: {" << red_scale << ", " << green_scale << ", " - << blue_scale << "}"; - if (display_configurator_) { -#if defined(USE_AURA) - DVLOG(1) << "Color temperature set to " << kelvin << " kelvin."; - display::ColorTemperatureAdjustment cta; - cta.srgb_matrix.vals[0][0] = red_scale; - cta.srgb_matrix.vals[1][1] = green_scale; - cta.srgb_matrix.vals[2][2] = blue_scale; - display_configurator_->SetColorTemperatureAdjustment(cta); -#endif // defined(USE_AURA) - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/color_temperature_animation.h chromium-132.0.6834.159/chromecast/ui/display_settings/color_temperature_animation.h --- chromium-132.0.6834.110/chromecast/ui/display_settings/color_temperature_animation.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/color_temperature_animation.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -// 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. - -#ifndef CHROMECAST_UI_DISPLAY_SETTINGS_COLOR_TEMPERATURE_ANIMATION_H_ -#define CHROMECAST_UI_DISPLAY_SETTINGS_COLOR_TEMPERATURE_ANIMATION_H_ - -#include "chromecast/ui/display_settings_manager.h" -#include "ui/gfx/animation/animation_delegate.h" -#include "ui/gfx/animation/linear_animation.h" - -namespace chromecast { - -namespace shell { -class CastDisplayConfigurator; -} - -// Defines a linear animation type to animate the color temperature between two -// values in a given time duration. -class ColorTemperatureAnimation : public gfx::LinearAnimation { - public: - ColorTemperatureAnimation( - shell::CastDisplayConfigurator* display_configurator, - const DisplaySettingsManager::ColorTemperatureConfig& config); - ColorTemperatureAnimation(const ColorTemperatureAnimation&) = delete; - ColorTemperatureAnimation& operator=(const ColorTemperatureAnimation&) = - delete; - ~ColorTemperatureAnimation() override; - - // Starts a new temperature animation from the |current_temperature_| to the - // given |new_target_temperature| in the given |duration|. - void AnimateToNewValue(float new_target_temperature, - base::TimeDelta duration); - - // Animate to a neutral temperature value, with no color transformations - // applied. - void AnimateToNeutral(base::TimeDelta duration); - - private: - // gfx::LinearAnimation implementation: - void AnimateToState(double state) override; - - void ApplyValuesToDisplay(); - - shell::CastDisplayConfigurator* const display_configurator_; - - const DisplaySettingsManager::ColorTemperatureConfig config_; - - float start_temperature_; - float current_temperature_; - float target_temperature_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_DISPLAY_SETTINGS_COLOR_TEMPERATURE_ANIMATION_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/gamma_configurator.cc chromium-132.0.6834.159/chromecast/ui/display_settings/gamma_configurator.cc --- chromium-132.0.6834.110/chromecast/ui/display_settings/gamma_configurator.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/gamma_configurator.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// 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 "chromecast/ui/display_settings/gamma_configurator.h" - -#include - -#include "chromecast/browser/cast_display_configurator.h" - -namespace chromecast { -namespace { - -constexpr size_t kGammaTableSize = 256; -constexpr uint16_t kMaxGammaValue = std::numeric_limits::max(); - -std::vector CreateDefaultGammaLut() { - std::vector gamma_lut; - for (size_t i = 0; i < kGammaTableSize; ++i) { - const uint16_t value = static_cast( - kMaxGammaValue * - (static_cast(kGammaTableSize - i - 1) / (kGammaTableSize - 1))); - gamma_lut.push_back({value, value, value}); - } - - return gamma_lut; -} - -std::vector InvertGammaLut( - const std::vector& gamma_lut) { - // Use default reversed linear gamma LUT for inversion - if (gamma_lut.empty()) - return CreateDefaultGammaLut(); - - // Use calibrated gamma LUT in reverse for inversion - std::vector gamma_lut_inverted(gamma_lut.rbegin(), - gamma_lut.rend()); - return gamma_lut_inverted; -} - -} // namespace - -GammaConfigurator::GammaConfigurator( - shell::CastDisplayConfigurator* display_configurator) - : display_configurator_(display_configurator) { - DCHECK(display_configurator_); -} - -GammaConfigurator::~GammaConfigurator() = default; - -void GammaConfigurator::OnCalibratedGammaLoaded( - const std::vector& gamma) { - is_initialized_ = true; - gamma_lut_ = gamma; - - if (is_inverted_) - ApplyGammaLut(); -} - -void GammaConfigurator::ApplyGammaLut() { - display::GammaAdjustment adjustment; - adjustment.curve = display::GammaCurve( - is_inverted_ ? InvertGammaLut(gamma_lut_) : gamma_lut_); - display_configurator_->SetGammaAdjustment(adjustment); -} - -void GammaConfigurator::SetColorInversion(bool invert) { - if (is_inverted_ == invert) - return; - - is_inverted_ = invert; - - if (is_initialized_) - ApplyGammaLut(); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/gamma_configurator.h chromium-132.0.6834.159/chromecast/ui/display_settings/gamma_configurator.h --- chromium-132.0.6834.110/chromecast/ui/display_settings/gamma_configurator.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/gamma_configurator.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ -// 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. - -#ifndef CHROMECAST_UI_DISPLAY_SETTINGS_GAMMA_CONFIGURATOR_H_ -#define CHROMECAST_UI_DISPLAY_SETTINGS_GAMMA_CONFIGURATOR_H_ - -#include - -#include "ui/display/types/display_color_management.h" - -namespace chromecast { - -namespace shell { -class CastDisplayConfigurator; -} // namespace shell - -class GammaConfigurator { - public: - explicit GammaConfigurator( - shell::CastDisplayConfigurator* display_configurator); - GammaConfigurator(const GammaConfigurator&) = delete; - GammaConfigurator& operator=(const GammaConfigurator&) = delete; - ~GammaConfigurator(); - - void OnCalibratedGammaLoaded( - const std::vector& gamma); - - void SetColorInversion(bool enable); - - private: - void ApplyGammaLut(); - - shell::CastDisplayConfigurator* display_configurator_; - - bool is_initialized_ = false; - bool is_inverted_ = false; - std::vector gamma_lut_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_DISPLAY_SETTINGS_GAMMA_CONFIGURATOR_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller.h chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller.h --- chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -// 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. - -#ifndef CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_H_ -#define CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_H_ - -#include - -#include "base/functional/callback.h" -#include "base/time/time.h" - -namespace chromecast { - -// This is an interface that controls the screen power. There are two stages -// when the screen is off: brightness off (zero) and power off. Whether the -// screen backlight is set to zero or the screen is powered off is abstracted in -// this class. Higher-level services generally do not care which mode it's in. -// The interface doesn't perform actual actions but invokes its delegate to turn -// on/off the screen, which is easy to isolate with mock classes and write -// unittest. -class ScreenPowerController { - public: - // The actual class that controls the brightness and the power of the - // screen. - class Delegate { - public: - using PowerToggleCallback = base::OnceCallback; - - virtual ~Delegate() = default; - // Turns the screen power on and calls the |callback| with a bool that - // indicates if the action is successful. - virtual void SetScreenPowerOn(PowerToggleCallback callback) = 0; - // Turns the screen power off and calls the |callback| with a bool that - // indicates if the action is successful. - virtual void SetScreenPowerOff(PowerToggleCallback callback) = 0; - // Turns the screen brightness on/off according to |brightness_on| with an - // animation of |duration|. - virtual void SetScreenBrightnessOn(bool brightness_on, - base::TimeDelta duration) = 0; - }; - - // The factory method that creates the derived implementation class. - static std::unique_ptr Create(Delegate* delegate); - - virtual ~ScreenPowerController() = default; - - // Turns on the screen. - virtual void SetScreenOn() = 0; - // Turns off the screen and lets the derived class decide which stage should - // the screen transfer to. - virtual void SetScreenOff() = 0; - // Sets whether the screen is allow to power off. - virtual void SetAllowScreenPowerOff(bool allow_power_off) = 0; - // Returns the state whether the screen is on/off. - virtual bool IsScreenOn() const = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_aura.cc chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura.cc --- chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_aura.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,242 +0,0 @@ -// 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 "chromecast/ui/display_settings/screen_power_controller_aura.h" - -#include "base/check.h" -#include "base/functional/callback.h" -#include "base/logging.h" -#include "base/task/sequenced_task_runner.h" -#include "base/time/time.h" - -namespace chromecast { - -namespace { - -constexpr base::TimeDelta kScreenOnOffDuration = base::Milliseconds(200); -// These delays are needed to ensure there are no visible artifacts due to the -// backlight turning on prior to the LCD fully initializing or vice-versa. -// TODO(b/161140301): Make this configurable for different products -// TODO(b/161268188): Remove these if the delays can be handled by the kernel -constexpr base::TimeDelta kDisplayPowerOnDelay = base::Milliseconds(35); -constexpr base::TimeDelta kDisplayPowerOffDelay = base::Milliseconds(85); - -} // namespace - -std::unique_ptr ScreenPowerController::Create( - Delegate* delegate) { - return std::make_unique(delegate); -} - -ScreenPowerControllerAura::ScreenPowerControllerAura( - ScreenPowerController::Delegate* delegate) - : screen_on_(true), - screen_power_on_(true), - allow_screen_power_off_(false), - pending_task_(PendingTask::kNone), - delegate_(delegate), - weak_factory_(this) { - DCHECK(delegate_); -} - -ScreenPowerControllerAura::~ScreenPowerControllerAura() = default; - -void ScreenPowerControllerAura::SetScreenOn() { - if (pending_task_ != PendingTask::kNone) { - pending_task_ = PendingTask::kOn; - return; - } - - if (!screen_on_) { - pending_task_ = PendingTask::kOn; - TriggerPendingTask(); - } -} - -void ScreenPowerControllerAura::SetScreenOff() { - if (pending_task_ != PendingTask::kNone) { - if (!allow_screen_power_off_) { - pending_task_ = PendingTask::kBrightnessOff; - } else { - pending_task_ = PendingTask::kPowerOff; - } - return; - } - - if (!allow_screen_power_off_ && (screen_on_ || !screen_power_on_)) { - pending_task_ = PendingTask::kBrightnessOff; - TriggerPendingTask(); - } else if (allow_screen_power_off_ && screen_power_on_) { - pending_task_ = PendingTask::kPowerOff; - TriggerPendingTask(); - } -} - -void ScreenPowerControllerAura::SetAllowScreenPowerOff(bool allow_power_off) { - LOG(INFO) << "SetAllowScreenPowerOff set to " - << (allow_power_off ? "true" : "false"); - allow_screen_power_off_ = allow_power_off; - switch (pending_task_) { - case PendingTask::kOn: - return; - case PendingTask::kBrightnessOff: - case PendingTask::kPowerOff: - if (!allow_screen_power_off_) { - pending_task_ = PendingTask::kBrightnessOff; - } else { - pending_task_ = PendingTask::kPowerOff; - } - return; - case PendingTask::kNone: - if (!screen_on_) { - // Set screen power off if screen is already off. - SetScreenOff(); - } - return; - } -} - -bool ScreenPowerControllerAura::IsScreenOn() const { - return screen_on_; -} - -void ScreenPowerControllerAura::TriggerPendingTask() { - switch (pending_task_) { - case PendingTask::kOn: - if (screen_on_) { - NOTREACHED(); - } else if (screen_power_on_) { - SetScreenBrightnessOn(true); - pending_task_ = PendingTask::kNone; - } else { - SetScreenPowerOn(); - } - return; - case PendingTask::kBrightnessOff: - if (screen_on_) { - SetScreenBrightnessOn(false); - pending_task_ = PendingTask::kNone; - } else if (screen_power_on_) { - pending_task_ = PendingTask::kNone; - } else { - SetScreenPowerOn(); - } - return; - case PendingTask::kPowerOff: - if (screen_on_) { - SetScreenBrightnessOn(false); - SetScreenPowerOff(); - } else if (screen_power_on_) { - SetScreenPowerOff(); - } else { - NOTREACHED(); - } - return; - case PendingTask::kNone: - NOTREACHED(); - } -} - -void ScreenPowerControllerAura::SetScreenBrightnessOn(bool brightness_on) { - delegate_->SetScreenBrightnessOn(brightness_on, kScreenOnOffDuration); - screen_on_ = brightness_on; -} - -void ScreenPowerControllerAura::SetScreenPowerOn() { - delegate_->SetScreenPowerOn( - base::BindOnce(&ScreenPowerControllerAura::OnScreenPoweredOn, - weak_factory_.GetWeakPtr())); -} - -void ScreenPowerControllerAura::SetScreenPowerOff() { - base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&ScreenPowerControllerAura::OnDisplayOffTimeoutCompleted, - weak_factory_.GetWeakPtr()), - kDisplayPowerOffDelay + kScreenOnOffDuration); -} - -void ScreenPowerControllerAura::OnScreenPoweredOn(bool succeeded) { - if (!succeeded) { - // Fatal since the user has no other way of turning the screen on if this - // failed. - LOG(FATAL) << "Failed to power on the screen"; - } - LOG(INFO) << "Screen is powered on"; - screen_power_on_ = true; - - switch (pending_task_) { - case PendingTask::kOn: - case PendingTask::kBrightnessOff: - // TODO(b/161268188): This can be simplified and the delays removed if - // backlight timing is handled by the kernel - base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( - FROM_HERE, - base::BindOnce( - &ScreenPowerControllerAura::OnDisplayOnTimeoutCompleted, - weak_factory_.GetWeakPtr()), - kDisplayPowerOnDelay); - return; - case PendingTask::kPowerOff: - TriggerPendingTask(); - return; - case PendingTask::kNone: - NOTREACHED(); - } -} - -void ScreenPowerControllerAura::OnScreenPoweredOff(bool succeeded) { - if (!succeeded) { - LOG(ERROR) << "Failed to power off the screen"; - return; - } - LOG(INFO) << "Screen is powered off"; - screen_power_on_ = false; - - switch (pending_task_) { - case PendingTask::kOn: - case PendingTask::kBrightnessOff: - TriggerPendingTask(); - return; - case PendingTask::kPowerOff: - pending_task_ = PendingTask::kNone; - return; - case PendingTask::kNone: - NOTREACHED(); - } -} - -void ScreenPowerControllerAura::OnDisplayOnTimeoutCompleted() { - switch (pending_task_) { - case PendingTask::kBrightnessOff: - pending_task_ = PendingTask::kNone; - return; - case PendingTask::kOn: - case PendingTask::kPowerOff: - TriggerPendingTask(); - return; - case PendingTask::kNone: - NOTREACHED(); - } -} - -void ScreenPowerControllerAura::OnDisplayOffTimeoutCompleted() { - switch (pending_task_) { - case PendingTask::kOn: - TriggerPendingTask(); - return; - case PendingTask::kBrightnessOff: - pending_task_ = PendingTask::kNone; - return; - case PendingTask::kPowerOff: - delegate_->SetScreenPowerOff( - base::BindOnce(&ScreenPowerControllerAura::OnScreenPoweredOff, - weak_factory_.GetWeakPtr())); - return; - case PendingTask::kNone: - NOTREACHED(); - } -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_aura.h chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura.h --- chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_aura.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ -// 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. - -#ifndef CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_AURA_H_ -#define CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_AURA_H_ - -#include "base/memory/weak_ptr.h" -#include "chromecast/ui/display_settings/screen_power_controller.h" - -namespace chromecast { - -// This class implements the ScreenPowerController with AURA enabled. The class -// doesn't depend on AURA but it will only be available if |use_aura| build flag -// is true. The class wraps the logic of the following transition graph: -// -// SetScreenOff() && !allow_screen_off -// On <==================================> Brightness Off -// /\ SetScreenOn() /\ -// || || -// || || -// || allow_screen_off || !allow_screen_off -// || || -// || || -// || SetScreenOff() && allow_screen_off \/ -// ++=====================================> Power Off -// SetScreenOn() -// -// Screen Stage Transitions -class ScreenPowerControllerAura : public ScreenPowerController { - public: - explicit ScreenPowerControllerAura(ScreenPowerController::Delegate* delegate); - ~ScreenPowerControllerAura() override; - - void SetScreenOn() override; - void SetScreenOff() override; - void SetAllowScreenPowerOff(bool allow_power_off) override; - bool IsScreenOn() const override; - - private: - enum PendingTask { - kNone = 0, - kOn, - kBrightnessOff, - kPowerOff, - }; - void TriggerPendingTask(); - void SetScreenBrightnessOn(bool brightness_on); - void SetScreenPowerOn(); - void SetScreenPowerOff(); - void OnScreenPoweredOn(bool succeeded); - void OnScreenPoweredOff(bool succeeded); - void OnDisplayOnTimeoutCompleted(); - void OnDisplayOffTimeoutCompleted(); - - bool screen_on_; - bool screen_power_on_; - bool allow_screen_power_off_; - PendingTask pending_task_; - ScreenPowerController::Delegate* delegate_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_AURA_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_aura_unittest.cc chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura_unittest.cc --- chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_aura_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_aura_unittest.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,217 +0,0 @@ -// 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 "chromecast/ui/display_settings/screen_power_controller_aura.h" - -#include - -#include "base/test/gmock_callback_support.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "chromecast/ui/display_settings/screen_power_controller.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chromecast { -namespace test { -namespace { - -using ::testing::_; - -// These constants should be the same as screen_power_controller_aura.cc. -constexpr base::TimeDelta kScreenOnOffDuration = base::Milliseconds(200); -constexpr base::TimeDelta kDisplayPowerOnDelay = base::Milliseconds(35); -constexpr base::TimeDelta kDisplayPowerOffDelay = base::Milliseconds(85); - -class MockScreenPowerControllerDelegate - : public ScreenPowerController::Delegate { - public: - ~MockScreenPowerControllerDelegate() override = default; - - // ScreenPowerController::Delegate implementation: - MOCK_METHOD(void, SetScreenPowerOn, (PowerToggleCallback callback), (override)); - MOCK_METHOD(void, SetScreenPowerOff, (PowerToggleCallback callback), (override)); - MOCK_METHOD(void, - SetScreenBrightnessOn, - (bool brightness_on, base::TimeDelta duration), - (override)); -}; - -class ScreenPowerControllerAuraTest : public ::testing::Test { - public: - ScreenPowerControllerAuraTest() - : task_env_(base::test::TaskEnvironment::TimeSource::MOCK_TIME), - delegate_(std::make_unique()), - screen_power_controller_( - ScreenPowerController::Create(delegate_.get())) {} - - protected: - void BrightnessOff() { - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(false, kScreenOnOffDuration)); - screen_power_controller_->SetScreenOff(); - } - - void PowerOff() { - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(false, kScreenOnOffDuration)); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - screen_power_controller_->SetAllowScreenPowerOff(true); - screen_power_controller_->SetScreenOff(); - task_env_.FastForwardBy(kDisplayPowerOffDelay + kScreenOnOffDuration); - } - - base::test::TaskEnvironment task_env_; - std::unique_ptr delegate_; - std::unique_ptr screen_power_controller_; -}; - -} // namespace - -TEST_F(ScreenPowerControllerAuraTest, PowerOnToBrightnessOff) { - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(false, kScreenOnOffDuration)); - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)).Times(0); - screen_power_controller_->SetScreenOff(); -} - -TEST_F(ScreenPowerControllerAuraTest, PowerOnToPowerOff) { - { - ::testing::InSequence s; - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(false, kScreenOnOffDuration)); - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - screen_power_controller_->SetAllowScreenPowerOff(true); - screen_power_controller_->SetScreenOff(); - task_env_.FastForwardBy(kDisplayPowerOffDelay + kScreenOnOffDuration); - } -} - -TEST_F(ScreenPowerControllerAuraTest, BrightnessOffToPowerOff) { - BrightnessOff(); - - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(_, _)).Times(0); - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - screen_power_controller_->SetAllowScreenPowerOff(true); - task_env_.FastForwardBy(kDisplayPowerOffDelay + kScreenOnOffDuration); -} - -TEST_F(ScreenPowerControllerAuraTest, BrightnessOffToBrightnessOn) { - BrightnessOff(); - - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(true, kScreenOnOffDuration)) - .Times(1); - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)).Times(0); - screen_power_controller_->SetScreenOn(); -} - -TEST_F(ScreenPowerControllerAuraTest, PowerOffToBrightnessOn) { - PowerOff(); - - { - ::testing::InSequence s; - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(true, kScreenOnOffDuration)) - .Times(1); - screen_power_controller_->SetScreenOn(); - task_env_.FastForwardBy(kDisplayPowerOnDelay); - } -} - -TEST_F(ScreenPowerControllerAuraTest, PowerOffToBrightnessOff) { - PowerOff(); - - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(_, _)).Times(0); - screen_power_controller_->SetAllowScreenPowerOff(false); - task_env_.FastForwardBy(kDisplayPowerOnDelay); -} - -TEST_F(ScreenPowerControllerAuraTest, PowerOnToPowerOffToPowerOn) { - { - ::testing::InSequence s; - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(false, kScreenOnOffDuration)); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(true, kScreenOnOffDuration)); - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)).Times(0); - screen_power_controller_->SetAllowScreenPowerOff(true); - screen_power_controller_->SetScreenOff(); - screen_power_controller_->SetScreenOn(); - task_env_.FastForwardBy(kDisplayPowerOffDelay + kScreenOnOffDuration + - kDisplayPowerOnDelay); - } -} - -TEST_F(ScreenPowerControllerAuraTest, PowerOnToPowerOffToBrightnessOff) { - { - ::testing::InSequence s; - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(false, kScreenOnOffDuration)); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)).Times(0); - screen_power_controller_->SetAllowScreenPowerOff(true); - screen_power_controller_->SetScreenOff(); - screen_power_controller_->SetAllowScreenPowerOff(false); - task_env_.FastForwardBy(kDisplayPowerOffDelay + kScreenOnOffDuration + - kDisplayPowerOnDelay); - } -} - -TEST_F(ScreenPowerControllerAuraTest, PowerOffToPowerOnToPowerOff) { - PowerOff(); - - { - ::testing::InSequence s; - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(_, _)).Times(0); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - screen_power_controller_->SetScreenOn(); - screen_power_controller_->SetScreenOff(); - task_env_.FastForwardBy(kDisplayPowerOffDelay + kScreenOnOffDuration + - kDisplayPowerOnDelay); - } -} - -TEST_F(ScreenPowerControllerAuraTest, DoubleTriggeredPowerOff) { - screen_power_controller_->SetAllowScreenPowerOff(true); - - { - ::testing::InSequence s; - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(false, kScreenOnOffDuration)); - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - screen_power_controller_->SetScreenOff(); - screen_power_controller_->SetScreenOff(); - task_env_.FastForwardBy(kDisplayPowerOffDelay + kScreenOnOffDuration + - kDisplayPowerOnDelay); - } -} - -TEST_F(ScreenPowerControllerAuraTest, DoubleTriggeredPowerOn) { - PowerOff(); - - { - ::testing::InSequence s; - EXPECT_CALL(*delegate_, SetScreenPowerOff(_)).Times(0); - EXPECT_CALL(*delegate_, SetScreenPowerOn(_)) - .WillOnce(base::test::RunOnceCallback<0>(true)); - EXPECT_CALL(*delegate_, SetScreenBrightnessOn(true, kScreenOnOffDuration)); - screen_power_controller_->SetScreenOn(); - screen_power_controller_->SetScreenOn(); - task_env_.FastForwardBy(kDisplayPowerOffDelay + kScreenOnOffDuration + - kDisplayPowerOnDelay); - } -} - -} // namespace test -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_default.cc chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_default.cc --- chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_default.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_default.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -// 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 "chromecast/ui/display_settings/screen_power_controller_default.h" - -#include "base/logging.h" -#include "base/time/time.h" - -namespace chromecast { - -namespace { - -constexpr base::TimeDelta kScreenOnOffDuration = base::Milliseconds(200); -} - -std::unique_ptr ScreenPowerController::Create( - Delegate* delegate) { - return std::make_unique(delegate); -} - -ScreenPowerControllerDefault::ScreenPowerControllerDefault( - ScreenPowerController::Delegate* delegate) - : screen_on_(true), delegate_(delegate) {} - -ScreenPowerControllerDefault::~ScreenPowerControllerDefault() = default; - -void ScreenPowerControllerDefault::SetScreenOn() { - if (screen_on_) { - return; - } - - LOG(INFO) << "Setting screen_on to true"; - screen_on_ = true; - delegate_->SetScreenBrightnessOn(true, kScreenOnOffDuration); -} - -void ScreenPowerControllerDefault::SetScreenOff() { - if (!screen_on_) { - return; - } - LOG(INFO) << "Setting screen_on to false"; - screen_on_ = false; - delegate_->SetScreenBrightnessOn(false, kScreenOnOffDuration); -} - -void ScreenPowerControllerDefault::SetAllowScreenPowerOff( - bool allow_power_off) { - LOG(WARNING) - << "Screen is not allowed to be powered off. Please enable AURA."; -} - -bool ScreenPowerControllerDefault::IsScreenOn() const { - return screen_on_; -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_default.h chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_default.h --- chromium-132.0.6834.110/chromecast/ui/display_settings/screen_power_controller_default.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings/screen_power_controller_default.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// 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. - -#ifndef CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_DEFAULT_H_ -#define CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_DEFAULT_H_ - -#include "base/memory/weak_ptr.h" -#include "chromecast/ui/display_settings/screen_power_controller.h" - -namespace chromecast { - -// This class implements the ScreenPowerController's default behavior. It never -// powers off the screen so most of the methods will do nothing other than -// logging and invoke delegate's methods. -class ScreenPowerControllerDefault : public ScreenPowerController { - public: - explicit ScreenPowerControllerDefault( - ScreenPowerController::Delegate* delegate); - ~ScreenPowerControllerDefault() override; - - void SetScreenOn() override; - void SetScreenOff() override; - void SetAllowScreenPowerOff(bool allow_power_off) override; - bool IsScreenOn() const override; - - private: - bool screen_on_; - ScreenPowerController::Delegate* delegate_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_DISPLAY_SETTINGS_SCREEN_POWER_CONTROLLER_DEFAULT_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings_manager.cc chromium-132.0.6834.159/chromecast/ui/display_settings_manager.cc --- chromium-132.0.6834.110/chromecast/ui/display_settings_manager.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings_manager.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// 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 "chromecast/ui/display_settings_manager.h" - -namespace chromecast { - -DisplaySettingsManager::ColorTemperatureConfig::ColorTemperatureConfig() = - default; -DisplaySettingsManager::ColorTemperatureConfig::ColorTemperatureConfig( - const ColorTemperatureConfig& other) = default; -DisplaySettingsManager::ColorTemperatureConfig::~ColorTemperatureConfig() = - default; - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings_manager.h chromium-132.0.6834.159/chromecast/ui/display_settings_manager.h --- chromium-132.0.6834.110/chromecast/ui/display_settings_manager.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings_manager.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// 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. - -#ifndef CHROMECAST_UI_DISPLAY_SETTINGS_MANAGER_H_ -#define CHROMECAST_UI_DISPLAY_SETTINGS_MANAGER_H_ - -#include - -#include "chromecast/ui/mojom/display_settings.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "ui/display/types/gamma_ramp_rgb_entry.h" - -namespace chromecast { - -class DisplaySettingsManager { - public: - struct ColorTemperatureConfig { - ColorTemperatureConfig(); - ColorTemperatureConfig(const ColorTemperatureConfig& other); - ~ColorTemperatureConfig(); - - float neutral_temperature; - float full_color; - std::vector temperature_values; - std::vector red_values; - std::vector green_values; - std::vector blue_values; - }; - - class Delegate { - public: - virtual void SetDisplayBrightness(float brightness, bool smooth) = 0; - virtual float GetDisplayBrightness() = 0; - - protected: - virtual ~Delegate() {} - }; - - virtual ~DisplaySettingsManager() = default; - - virtual void SetDelegate(Delegate* delegate) = 0; - - virtual void SetColorTemperatureConfig( - const ColorTemperatureConfig& config) = 0; - - virtual void ResetDelegate() = 0; - - virtual void SetGammaCalibration( - const std::vector& gamma) = 0; - - virtual void NotifyBrightnessChanged(float new_brightness, - float old_brightness) = 0; - - virtual void SetColorInversion(bool enable) = 0; - - virtual void AddReceiver( - mojo::PendingReceiver receiver) = 0; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_DISPLAY_SETTINGS_MANAGER_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings_manager_impl.cc chromium-132.0.6834.159/chromecast/ui/display_settings_manager_impl.cc --- chromium-132.0.6834.110/chromecast/ui/display_settings_manager_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings_manager_impl.cc 1970-01-01 00:00:00.000000000 +0000 @@ -1,214 +0,0 @@ -// 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 "chromecast/ui/display_settings_manager_impl.h" - -#include "base/check.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/logging.h" -#include "base/time/time.h" -#include "chromecast/graphics/cast_window_manager.h" -#include "chromecast/ui/display_settings/brightness_animation.h" -#include "chromecast/ui/display_settings/color_temperature_animation.h" -#include "ui/display/types/gamma_ramp_rgb_entry.h" - -#if defined(USE_AURA) -#include "chromecast/browser/cast_display_configurator.h" // nogncheck -#include "chromecast/ui/display_settings/gamma_configurator.h" -#endif // defined(USE_AURA) - -namespace chromecast { - -namespace { - -constexpr base::TimeDelta kAnimationDuration = base::Seconds(2); - -const float kMinApiBrightness = 0.0f; -const float kMaxApiBrightness = 1.0f; -const float kDefaultApiBrightness = kMaxApiBrightness; - -#if defined(USE_AURA) -// A wrapper function for converting a PowerToggleCallback to a -// display::ConfigureCallback. Calls `callback` with the resulting status. -void AsConfigureCallback( - ScreenPowerController::Delegate::PowerToggleCallback callback, - const std::vector& request_results, - bool status) { - std::move(callback).Run(status); -} -#endif // defined(USE_AURA) - -} // namespace - -DisplaySettingsManagerImpl::DisplaySettingsManagerImpl( - CastWindowManager* window_manager, - shell::CastDisplayConfigurator* display_configurator) - : window_manager_(window_manager), - display_configurator_(display_configurator), -#if defined(USE_AURA) - gamma_configurator_( - std::make_unique(display_configurator_)), -#endif // defined(USE_AURA) - brightness_(-1.0f), - screen_power_controller_(ScreenPowerController::Create(this)), - weak_factory_(this) { - DCHECK(window_manager_); -#if defined(USE_AURA) - DCHECK(display_configurator_); -#endif // defined(USE_AURA) -} - -DisplaySettingsManagerImpl::~DisplaySettingsManagerImpl() = default; - -void DisplaySettingsManagerImpl::SetDelegate( - DisplaySettingsManager::Delegate* delegate) { - brightness_animation_ = std::make_unique(delegate); -} - -void DisplaySettingsManagerImpl::ResetDelegate() { - // Skip a brightess animation to its last step and stop - // This is important for the final brightness to be cached on reboot - brightness_animation_.reset(); -} - -void DisplaySettingsManagerImpl::SetColorTemperatureConfig( - const DisplaySettingsManager::ColorTemperatureConfig& config) { - DCHECK(!color_temperature_animation_); - color_temperature_animation_ = std::make_unique( - display_configurator_, config); -} - -void DisplaySettingsManagerImpl::SetGammaCalibration( - const std::vector& gamma) { -#if defined(USE_AURA) - gamma_configurator_->OnCalibratedGammaLoaded(gamma); -#endif // defined(USE_AURA) -} - -void DisplaySettingsManagerImpl::NotifyBrightnessChanged(float new_brightness, - float old_brightness) { - for (auto& observer : observers_) - observer->OnDisplayBrightnessChanged(new_brightness); -} - -void DisplaySettingsManagerImpl::SetColorInversion(bool enable) { -#if defined(USE_AURA) - gamma_configurator_->SetColorInversion(enable); -#endif // defined(USE_AURA) -} - -void DisplaySettingsManagerImpl::AddReceiver( - mojo::PendingReceiver receiver) { - receivers_.Add(this, std::move(receiver)); -} - -void DisplaySettingsManagerImpl::SetScreenPowerOn(PowerToggleCallback callback) { -#if defined(USE_AURA) - display_configurator_->EnableDisplay( - base::BindOnce(&AsConfigureCallback, std::move(callback))); -#endif // defined(USE_AURA) -} - -void DisplaySettingsManagerImpl::SetScreenPowerOff(PowerToggleCallback callback) { -#if defined(USE_AURA) - display_configurator_->DisableDisplay( - base::BindOnce(&AsConfigureCallback, std::move(callback))); -#endif // defined(USE_AURA) -} - -void DisplaySettingsManagerImpl::SetScreenBrightnessOn( - bool brightness_on, - base::TimeDelta duration) { - UpdateBrightness(brightness_on ? brightness_ : 0, duration); - window_manager_->SetTouchInputDisabled(!brightness_on); -} - -void DisplaySettingsManagerImpl::SetColorTemperature(float temperature) { - DVLOG(4) << "Setting color temperature to " << temperature << " Kelvin."; - if (!color_temperature_animation_) { - return; - } - color_temperature_animation_->AnimateToNewValue(temperature, - kAnimationDuration); -} - -void DisplaySettingsManagerImpl::SetColorTemperatureSmooth( - float temperature, - base::TimeDelta duration) { - DVLOG(4) << "Setting color temperature to " << temperature - << " Kelvin. Duration: " << duration; - if (!color_temperature_animation_) { - return; - } - color_temperature_animation_->AnimateToNewValue(temperature, duration); -} - -void DisplaySettingsManagerImpl::ResetColorTemperature() { - if (!color_temperature_animation_) { - return; - } - color_temperature_animation_->AnimateToNeutral(kAnimationDuration); -} - -void DisplaySettingsManagerImpl::SetBrightness(float brightness) { - SetBrightnessSmooth(brightness, base::Seconds(0)); -} - -void DisplaySettingsManagerImpl::SetBrightnessSmooth(float brightness, - base::TimeDelta duration) { - if (brightness < kMinApiBrightness) { - LOG(ERROR) << "brightness " << brightness - << " is less than minimum brightness " << kMinApiBrightness - << "."; - return; - } - - if (brightness > kMaxApiBrightness) { - LOG(ERROR) << "brightness " << brightness - << " is greater than maximum brightness " << kMaxApiBrightness - << "."; - return; - } - - brightness_ = brightness; - - // If the screen is off, keep the new brightness but don't apply it - if (!screen_power_controller_->IsScreenOn()) { - return; - } - - UpdateBrightness(brightness_, duration); -} - -void DisplaySettingsManagerImpl::ResetBrightness() { - SetBrightness(kDefaultApiBrightness); -} - -void DisplaySettingsManagerImpl::SetScreenOn(bool screen_on) { - if (screen_on) { - screen_power_controller_->SetScreenOn(); - } else { - screen_power_controller_->SetScreenOff(); - } -} - -void DisplaySettingsManagerImpl::SetAllowScreenPowerOff(bool allow_power_off) { - screen_power_controller_->SetAllowScreenPowerOff(allow_power_off); -} - -void DisplaySettingsManagerImpl::AddDisplaySettingsObserver( - mojo::PendingRemote observer) { - mojo::Remote observer_remote( - std::move(observer)); - observers_.Add(std::move(observer_remote)); -} - -void DisplaySettingsManagerImpl::UpdateBrightness(float brightness, - base::TimeDelta duration) { - if (brightness_animation_) - brightness_animation_->AnimateToNewValue(brightness, duration); -} - -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/display_settings_manager_impl.h chromium-132.0.6834.159/chromecast/ui/display_settings_manager_impl.h --- chromium-132.0.6834.110/chromecast/ui/display_settings_manager_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/display_settings_manager_impl.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,105 +0,0 @@ -// 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. - -#ifndef CHROMECAST_UI_DISPLAY_SETTINGS_MANAGER_IMPL_H_ -#define CHROMECAST_UI_DISPLAY_SETTINGS_MANAGER_IMPL_H_ - -#include -#include - -#include "base/memory/weak_ptr.h" -#include "chromecast/ui/display_settings/screen_power_controller.h" -#include "chromecast/ui/display_settings_manager.h" -#include "chromecast/ui/mojom/display_settings.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver_set.h" -#include "mojo/public/cpp/bindings/remote_set.h" - -namespace chromecast { - -class CastWindowManager; -class ColorTemperatureAnimation; -class BrightnessAnimation; -class GammaAnimation; - -#if defined(USE_AURA) -class GammaConfigurator; -#endif // defined(USE_AURA) - -namespace shell { -class CastDisplayConfigurator; -} // namespace shell - -class DisplaySettingsManagerImpl : public DisplaySettingsManager, - public ScreenPowerController::Delegate, - public mojom::DisplaySettings { - public: - DisplaySettingsManagerImpl( - CastWindowManager* window_manager, - shell::CastDisplayConfigurator* display_configurator); - DisplaySettingsManagerImpl(const DisplaySettingsManagerImpl&) = delete; - DisplaySettingsManagerImpl& operator=(const DisplaySettingsManagerImpl&) = - delete; - ~DisplaySettingsManagerImpl() override; - - // DisplaySettingsManager implementation: - void SetDelegate(DisplaySettingsManager::Delegate* delegate) override; - void ResetDelegate() override; - void SetColorTemperatureConfig( - const DisplaySettingsManager::ColorTemperatureConfig& config) override; - void SetGammaCalibration( - const std::vector& gamma) override; - void NotifyBrightnessChanged(float new_brightness, - float old_brightness) override; - void SetColorInversion(bool enable) override; - void AddReceiver( - mojo::PendingReceiver receiver) override; - - // ScreenPowerController::Delegate implementation: - void SetScreenPowerOn(PowerToggleCallback callback) override; - void SetScreenPowerOff(PowerToggleCallback callback) override; - void SetScreenBrightnessOn(bool brightness_on, - base::TimeDelta duration) override; - - // mojom::DisplaySettings implementation: - void SetColorTemperature(float temperature) override; - void SetColorTemperatureSmooth(float temperature, - base::TimeDelta duration) override; - void ResetColorTemperature() override; - void SetBrightness(float brightness) override; - void SetBrightnessSmooth(float brightness, base::TimeDelta duration) override; - void ResetBrightness() override; - void SetScreenOn(bool screen_on) override; - void SetAllowScreenPowerOff(bool allow_power_off) override; - - private: - // mojom::DisplaySettingsObserver implementation: - void AddDisplaySettingsObserver( - mojo::PendingRemote observer) override; - - void UpdateBrightness(float brightness, base::TimeDelta duration); - - CastWindowManager* const window_manager_; - shell::CastDisplayConfigurator* const display_configurator_; - -#if defined(USE_AURA) - const std::unique_ptr gamma_configurator_; -#endif // defined(USE_AURA) - - float brightness_; - - std::unique_ptr screen_power_controller_; - std::unique_ptr color_temperature_animation_; - std::unique_ptr brightness_animation_; - - mojo::ReceiverSet receivers_; - mojo::RemoteSet observers_; - - base::WeakPtrFactory weak_factory_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_UI_DISPLAY_SETTINGS_MANAGER_IMPL_H_ diff -Nru chromium-132.0.6834.110/chromecast/ui/mojom/OWNERS chromium-132.0.6834.159/chromecast/ui/mojom/OWNERS --- chromium-132.0.6834.110/chromecast/ui/mojom/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/mojom/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS diff -Nru chromium-132.0.6834.110/chromecast/ui/mojom/display_settings.mojom chromium-132.0.6834.159/chromecast/ui/mojom/display_settings.mojom --- chromium-132.0.6834.110/chromecast/ui/mojom/display_settings.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/mojom/display_settings.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -// 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. - -module chromecast.mojom; - -import "mojo/public/mojom/base/time.mojom"; - -// Interface for controlling device display settings. Each setting can be reset -// to its default value via Reset() methods. -// This interface is hosted in the browser process. -interface DisplaySettings { - // Sets display temperature value. - SetColorTemperature(float kelvin); - // Same as above, but temperature will be changed smoothly over a duration. - SetColorTemperatureSmooth(float kelvin, mojo_base.mojom.TimeDelta duration); - // Resets the display temperature value to the neutral value. - ResetColorTemperature(); - - // Sets display brightness from 0.0 to 1.0. The interpretation of this value - // is up to the platform implementation. - SetBrightness(float brightness); - // Same as above, but if the second argument is set, brightness will be - // changed smoothly over a duration. - SetBrightnessSmooth(float brightness, mojo_base.mojom.TimeDelta duration); - // Resets display brightness to the default value. - ResetBrightness(); - - // Sets whether screen should be on. If set to false, then screen will always - // be off and other settings will not be applied. - SetScreenOn(bool display_on); - - // Sets whether the screen should power off when SetScreenOn(false) is called. - SetAllowScreenPowerOff(bool allow_power_off); - - // Adds an observer to DisplaySettings. - AddDisplaySettingsObserver(pending_remote observer); -}; - -// Observer for display settings changes. -interface DisplaySettingsObserver { - // Receive a new display brightness. - OnDisplayBrightnessChanged(float brightness); -}; diff -Nru chromium-132.0.6834.110/chromecast/ui/mojom/ui_service.mojom chromium-132.0.6834.159/chromecast/ui/mojom/ui_service.mojom --- chromium-132.0.6834.110/chromecast/ui/mojom/ui_service.mojom 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/mojom/ui_service.mojom 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module chromecast.mojom; - -enum ZOrder { - // Base layer for web-based system UI, or for regular apps on Chromecast. - APP = -1, - // If the main system UI is web-based, then apps running in this layer won't - // be managed by the system web UI. - UNMANAGED_APP = 0, - // Diagnostic overlay for debugging. - DEBUG_OVERLAY = 1, - // Overlay apps with transparent backgrounds. - INFO_OVERLAY = 2, - // Unused. - SOFT_KEYBOARD = 3, - // Volume bar overlay. - VOLUME = 4, - // Touch-based media controls. - MEDIA_INFO = 5, - // Touch-based settings UI. - SETTINGS = 6, - // Boot animation. - BOOT_ANIMATION_OVERLAY = 7, -}; diff -Nru chromium-132.0.6834.110/chromecast/ui/vector_icons/back30.icon chromium-132.0.6834.159/chromecast/ui/vector_icons/back30.icon --- chromium-132.0.6834.110/chromecast/ui/vector_icons/back30.icon 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/vector_icons/back30.icon 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -MOVE_TO, 4, 24, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 3, 0, -R_CUBIC_TO, 0, 9.39f, 7.61f, 17, 17, 17, -R_CUBIC_TO, 9.39f, 0, 17, -7.61f, 17, -17, -CUBIC_TO_SHORTHAND, 33.39f, 7, 24, 7, -R_H_LINE_TO, -3.5f, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 0, -3, -H_LINE_TO, 24, -R_CUBIC_TO, 11.05f, 0, 20, 8.95f, 20, 20, -R_CUBIC_TO, 0, 11.05f, -8.95f, 20, -20, 20, -CUBIC_TO_SHORTHAND, 4, 35.05f, 4, 24, -CLOSE, -MOVE_TO, 20.62f, 5.5f, -R_LINE_TO, 2.94f, 2.94f, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, -2.12f, 2.12f, -R_LINE_TO, -4, -4, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 0, -2.12f, -R_LINE_TO, 4, -4, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 2.12f, 2.12f, -LINE_TO, 20.62f, 5.5f, -CLOSE, -MOVE_TO, 18.31f, 30.27f, -R_ARC_TO, 4.67f, 4.67f, 0, 0, 1, -2.76f, -0.8f, -ARC_TO, 4.15f, 4.15f, 0, 0, 1, 14, 27.14f, -R_LINE_TO, 2.43f, -1, -R_CUBIC_TO, 0.1f, 0.96f, 0.94f, 1.67f, 1.9f, 1.62f, -R_ARC_TO, 1.7f, 1.7f, 0, 0, 0, 1.07f, -0.36f, -R_ARC_TO, 1.15f, 1.15f, 0, 0, 0, 0.46f, -1, -R_CUBIC_TO, 0, -0.92f, -0.67f, -1.38f, -2, -1.38f, -R_H_LINE_TO, -1, -R_V_LINE_TO, -2.23f, -R_H_LINE_TO, 0.94f, -R_CUBIC_TO, 0.2f, 0, 0.4f, -0.02f, 0.59f, -0.07f, -R_CUBIC_TO, 0.18f, -0.04f, 0.36f, -0.11f, 0.52f, -0.21f, -R_ARC_TO, 1.07f, 1.07f, 0, 0, 0, 0.37f, -0.38f, -R_ARC_TO, 1.19f, 1.19f, 0, 0, 0, 0.14f, -0.59f, -R_CUBIC_TO, 0, -0.29f, -0.12f, -0.57f, -0.33f, -0.78f, -R_ARC_TO, 1.23f, 1.23f, 0, 0, 0, -0.93f, -0.34f, -R_ARC_TO, 1.45f, 1.45f, 0, 0, 0, -1, 0.36f, -R_ARC_TO, 1.79f, 1.79f, 0, 0, 0, -0.52f, 0.85f, -R_LINE_TO, -2.33f, -1, -R_ARC_TO, 4.21f, 4.21f, 0, 0, 1, 0.48f, -0.92f, -R_CUBIC_TO, 0.22f, -0.31f, 0.49f, -0.59f, 0.8f, -0.82f, -R_ARC_TO, 4.17f, 4.17f, 0, 0, 1, 1.14f, -0.59f, -R_ARC_TO, 4.47f, 4.47f, 0, 0, 1, 1.49f, -0.23f, -R_ARC_TO, 4.9f, 4.9f, 0, 0, 1, 1.57f, 0.24f, -ARC_TO, 3.74f, 3.74f, 0, 0, 1, 21, 19, -R_CUBIC_TO, 0.32f, 0.27f, 0.58f, 0.62f, 0.76f, 1, -R_CUBIC_TO, 0.16f, 0.36f, 0.25f, 0.76f, 0.24f, 1.16f, -R_ARC_TO, 3.25f, 3.25f, 0, 0, 1, -0.46f, 1.7f, -R_ARC_TO, 2.54f, 2.54f, 0, 0, 1, -0.46f, 0.56f, -R_ARC_TO, 2.11f, 2.11f, 0, 0, 1, -0.51f, 0.35f, -R_V_LINE_TO, 0.17f, -R_ARC_TO, 3, 3, 0, 0, 1, 1.34f, 1, -R_ARC_TO, 3, 3, 0, 0, 1, 0.53f, 1.82f, -R_ARC_TO, 3.32f, 3.32f, 0, 0, 1, -0.29f, 1.39f, -R_ARC_TO, 3.21f, 3.21f, 0, 0, 1, -0.82f, 1.1f, -ARC_TO, 3.85f, 3.85f, 0, 0, 1, 20, 30, -R_ARC_TO, 5.31f, 5.31f, 0, 0, 1, -1.69f, 0.27f, -CLOSE, -R_MOVE_TO, 10.69f, 0, -R_ARC_TO, 4.49f, 4.49f, 0, 0, 1, -3.64f, -1.73f, -R_ARC_TO, 5.9f, 5.9f, 0, 0, 1, -1, -1.93f, -R_ARC_TO, 8.59f, 8.59f, 0, 0, 1, 0, -4.84f, -R_ARC_TO, 5.91f, 5.91f, 0, 0, 1, 1, -1.93f, -R_ARC_TO, 4.64f, 4.64f, 0, 0, 1, 7.28f, 0, -R_ARC_TO, 5.91f, 5.91f, 0, 0, 1, 1, 1.93f, -R_ARC_TO, 8.57f, 8.57f, 0, 0, 1, 0, 4.84f, -R_ARC_TO, 5.9f, 5.9f, 0, 0, 1, -1, 1.93f, -ARC_TO, 4.51f, 4.51f, 0, 0, 1, 29, 30.27f, -CLOSE, -R_MOVE_TO, 0, -2.38f, -R_ARC_TO, 1.91f, 1.91f, 0, 0, 0, 1, -0.28f, -R_ARC_TO, 2.44f, 2.44f, 0, 0, 0, 0.77f, -0.77f, -R_ARC_TO, 3.8f, 3.8f, 0, 0, 0, 0.47f, -1.17f, -R_ARC_TO, 6.83f, 6.83f, 0, 0, 0, 0, -3, -R_ARC_TO, 3.81f, 3.81f, 0, 0, 0, -0.47f, -1.17f, -R_ARC_TO, 2.44f, 2.44f, 0, 0, 0, -0.77f, -0.77f, -R_ARC_TO, 2, 2, 0, 0, 0, -2.06f, 0, -R_ARC_TO, 2.44f, 2.44f, 0, 0, 0, -0.77f, 0.77f, -R_ARC_TO, 3.81f, 3.81f, 0, 0, 0, -0.47f, 1.17f, -R_ARC_TO, 6.83f, 6.83f, 0, 0, 0, 0, 3, -R_CUBIC_TO, 0.09f, 0.41f, 0.25f, 0.81f, 0.47f, 1.17f, -R_CUBIC_TO, 0.2f, 0.31f, 0.46f, 0.57f, 0.77f, 0.77f, -R_ARC_TO, 1.9f, 1.9f, 0, 0, 0, 1.06f, 0.28f, -CLOSE diff -Nru chromium-132.0.6834.110/chromecast/ui/vector_icons/forward30.icon chromium-132.0.6834.159/chromecast/ui/vector_icons/forward30.icon --- chromium-132.0.6834.110/chromecast/ui/vector_icons/forward30.icon 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/vector_icons/forward30.icon 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -MOVE_TO, 41, 24, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 3, 0, -R_CUBIC_TO, 0, 11.05f, -8.95f, 20, -20, 20, -CUBIC_TO_SHORTHAND, 4, 35.05f, 4, 24, -CUBIC_TO_SHORTHAND, 12.95f, 4, 24, 4, -R_H_LINE_TO, 3.5f, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 0, 3, -H_LINE_TO, 24, -CUBIC_TO, 14.61f, 7, 7, 14.61f, 7, 24, -R_CUBIC_TO, 0, 9.39f, 7.61f, 17, 17, 17, -R_CUBIC_TO, 9.39f, 0, 17, -7.61f, 17, -17, -CLOSE, -MOVE_TO, 24.44f, 2.56f, -ARC_TO, 1.5f, 1.5f, 0, 0, 1, 26.56f, 0.44f, -R_LINE_TO, 4, 4, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 0, 2.12f, -R_LINE_TO, -4, 4, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, -2.12f, -2.12f, -R_LINE_TO, 2.94f, -2.94f, -R_LINE_TO, -2.94f, -2.94f, -CLOSE, -R_MOVE_TO, -6.13f, 27.71f, -R_ARC_TO, 4.67f, 4.67f, 0, 0, 1, -2.76f, -0.8f, -ARC_TO, 4.15f, 4.15f, 0, 0, 1, 14, 27.14f, -R_LINE_TO, 2.43f, -1, -R_CUBIC_TO, 0.1f, 0.96f, 0.94f, 1.67f, 1.9f, 1.62f, -R_ARC_TO, 1.7f, 1.7f, 0, 0, 0, 1.07f, -0.36f, -R_ARC_TO, 1.15f, 1.15f, 0, 0, 0, 0.46f, -1, -R_CUBIC_TO, 0, -0.92f, -0.67f, -1.38f, -2, -1.38f, -R_H_LINE_TO, -1, -R_V_LINE_TO, -2.23f, -R_H_LINE_TO, 0.94f, -R_CUBIC_TO, 0.2f, 0, 0.4f, -0.02f, 0.59f, -0.07f, -R_CUBIC_TO, 0.18f, -0.04f, 0.36f, -0.11f, 0.52f, -0.21f, -R_ARC_TO, 1.07f, 1.07f, 0, 0, 0, 0.37f, -0.38f, -R_ARC_TO, 1.19f, 1.19f, 0, 0, 0, 0.14f, -0.59f, -R_CUBIC_TO, 0, -0.29f, -0.12f, -0.57f, -0.33f, -0.78f, -R_ARC_TO, 1.23f, 1.23f, 0, 0, 0, -0.93f, -0.34f, -R_ARC_TO, 1.45f, 1.45f, 0, 0, 0, -1, 0.36f, -R_ARC_TO, 1.79f, 1.79f, 0, 0, 0, -0.52f, 0.85f, -R_LINE_TO, -2.33f, -1, -R_ARC_TO, 4.21f, 4.21f, 0, 0, 1, 0.48f, -0.92f, -R_CUBIC_TO, 0.22f, -0.31f, 0.49f, -0.59f, 0.8f, -0.82f, -R_ARC_TO, 4.17f, 4.17f, 0, 0, 1, 1.14f, -0.59f, -R_ARC_TO, 4.47f, 4.47f, 0, 0, 1, 1.49f, -0.23f, -R_ARC_TO, 4.9f, 4.9f, 0, 0, 1, 1.57f, 0.24f, -ARC_TO, 3.74f, 3.74f, 0, 0, 1, 21, 19, -R_CUBIC_TO, 0.32f, 0.27f, 0.58f, 0.62f, 0.76f, 1, -R_CUBIC_TO, 0.16f, 0.36f, 0.25f, 0.76f, 0.24f, 1.16f, -R_ARC_TO, 3.25f, 3.25f, 0, 0, 1, -0.46f, 1.7f, -R_ARC_TO, 2.54f, 2.54f, 0, 0, 1, -0.46f, 0.56f, -R_ARC_TO, 2.11f, 2.11f, 0, 0, 1, -0.51f, 0.35f, -R_V_LINE_TO, 0.17f, -R_ARC_TO, 3, 3, 0, 0, 1, 1.34f, 1, -R_ARC_TO, 3, 3, 0, 0, 1, 0.53f, 1.82f, -R_ARC_TO, 3.32f, 3.32f, 0, 0, 1, -0.29f, 1.39f, -R_ARC_TO, 3.21f, 3.21f, 0, 0, 1, -0.82f, 1.1f, -ARC_TO, 3.85f, 3.85f, 0, 0, 1, 20, 30, -R_ARC_TO, 5.31f, 5.31f, 0, 0, 1, -1.69f, 0.27f, -CLOSE, -R_MOVE_TO, 10.69f, 0, -R_ARC_TO, 4.49f, 4.49f, 0, 0, 1, -3.64f, -1.73f, -R_ARC_TO, 5.9f, 5.9f, 0, 0, 1, -1, -1.93f, -R_ARC_TO, 8.59f, 8.59f, 0, 0, 1, 0, -4.84f, -R_ARC_TO, 5.91f, 5.91f, 0, 0, 1, 1, -1.93f, -R_ARC_TO, 4.64f, 4.64f, 0, 0, 1, 7.28f, 0, -R_ARC_TO, 5.91f, 5.91f, 0, 0, 1, 1, 1.93f, -R_ARC_TO, 8.57f, 8.57f, 0, 0, 1, 0, 4.84f, -R_ARC_TO, 5.9f, 5.9f, 0, 0, 1, -1, 1.93f, -ARC_TO, 4.51f, 4.51f, 0, 0, 1, 29, 30.27f, -CLOSE, -R_MOVE_TO, 0, -2.38f, -R_ARC_TO, 1.91f, 1.91f, 0, 0, 0, 1, -0.28f, -R_ARC_TO, 2.44f, 2.44f, 0, 0, 0, 0.77f, -0.77f, -R_ARC_TO, 3.8f, 3.8f, 0, 0, 0, 0.47f, -1.17f, -R_ARC_TO, 6.83f, 6.83f, 0, 0, 0, 0, -3, -R_ARC_TO, 3.81f, 3.81f, 0, 0, 0, -0.47f, -1.17f, -R_ARC_TO, 2.44f, 2.44f, 0, 0, 0, -0.77f, -0.77f, -R_ARC_TO, 2, 2, 0, 0, 0, -2.06f, 0, -R_ARC_TO, 2.44f, 2.44f, 0, 0, 0, -0.77f, 0.77f, -R_ARC_TO, 3.81f, 3.81f, 0, 0, 0, -0.47f, 1.17f, -R_ARC_TO, 6.83f, 6.83f, 0, 0, 0, 0, 3, -R_CUBIC_TO, 0.09f, 0.41f, 0.25f, 0.81f, 0.47f, 1.17f, -R_CUBIC_TO, 0.2f, 0.31f, 0.46f, 0.57f, 0.77f, 0.77f, -R_ARC_TO, 1.9f, 1.9f, 0, 0, 0, 1.06f, 0.28f, -CLOSE diff -Nru chromium-132.0.6834.110/chromecast/ui/vector_icons/next.icon chromium-132.0.6834.159/chromecast/ui/vector_icons/next.icon --- chromium-132.0.6834.110/chromecast/ui/vector_icons/next.icon 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/vector_icons/next.icon 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -MOVE_TO, 37, 9.5f, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 3, 0, -R_V_LINE_TO, 29, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, -3, 0, -CLOSE, -MOVE_TO, 11, 12.22f, -R_V_LINE_TO, 23.56f, -LINE_TO, 29.69f, 24, -CLOSE, -R_MOVE_TO, 22.3f, 13.05f, -R_LINE_TO, -23, 14.5f, -ARC_TO, 1.5f, 1.5f, 0, 0, 1, 8, 38.5f, -R_V_LINE_TO, -29, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 2.3f, -1.27f, -R_LINE_TO, 23, 14.5f, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 0, 2.54f, -CLOSE diff -Nru chromium-132.0.6834.110/chromecast/ui/vector_icons/pause.icon chromium-132.0.6834.159/chromecast/ui/vector_icons/pause.icon --- chromium-132.0.6834.110/chromecast/ui/vector_icons/pause.icon 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/vector_icons/pause.icon 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -MOVE_TO, 30, 9.5f, -R_V_LINE_TO, 29, -R_H_LINE_TO, 1, -R_V_LINE_TO, -29, -R_H_LINE_TO, -1, -CLOSE, -MOVE_TO, 17, 9.5f, -R_V_LINE_TO, 29, -R_H_LINE_TO, 1, -R_V_LINE_TO, -29, -R_H_LINE_TO, -1, -CLOSE diff -Nru chromium-132.0.6834.110/chromecast/ui/vector_icons/play.icon chromium-132.0.6834.159/chromecast/ui/vector_icons/play.icon --- chromium-132.0.6834.110/chromecast/ui/vector_icons/play.icon 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/vector_icons/play.icon 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -MOVE_TO, 38.5f, 24, -R_LINE_TO, -23, 14.5f, -R_V_LINE_TO, -29, -R_LINE_TO, 23, 14.5f, -CLOSE diff -Nru chromium-132.0.6834.110/chromecast/ui/vector_icons/previous.icon chromium-132.0.6834.159/chromecast/ui/vector_icons/previous.icon --- chromium-132.0.6834.110/chromecast/ui/vector_icons/previous.icon 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/vector_icons/previous.icon 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -MOVE_TO, 8, 9.5f, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 3, 0, -R_V_LINE_TO, 29, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, -3, 0, -CLOSE, -MOVE_TO, 14.7f, 25.27f, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, 0, -2.54f, -R_LINE_TO, 23, -14.5f, -ARC_TO, 1.5f, 1.5f, 0, 0, 1, 40, 9.5f, -R_V_LINE_TO, 29, -R_ARC_TO, 1.5f, 1.5f, 0, 0, 1, -2.3f, 1.27f, -CLOSE, -MOVE_TO, 37, 35.78f, -V_LINE_TO, 12.22f, -LINE_TO, 18.31f, 24, -CLOSE diff -Nru chromium-132.0.6834.110/chromecast/ui/vector_icons/vector_icons.cc.template chromium-132.0.6834.159/chromecast/ui/vector_icons/vector_icons.cc.template --- chromium-132.0.6834.110/chromecast/ui/vector_icons/vector_icons.cc.template 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/vector_icons/vector_icons.cc.template 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// vector_icons.cc.template is used to generate vector_icons.cc. Edit the former -// rather than the latter. - -#include "chromecast/ui/vector_icons.h" - -#include "components/vector_icons/cc_macros.h" -#include "ui/gfx/vector_icon_types.h" - -#define DECLARE_VECTOR_COMMAND(x) using gfx::x; -DECLARE_VECTOR_COMMANDS - -namespace chromecast { -namespace vector_icons { - -TEMPLATE_PLACEHOLDER - -} // namespace vector_icons -} // namespace chromecast diff -Nru chromium-132.0.6834.110/chromecast/ui/vector_icons/vector_icons.h.template chromium-132.0.6834.159/chromecast/ui/vector_icons/vector_icons.h.template --- chromium-132.0.6834.110/chromecast/ui/vector_icons/vector_icons.h.template 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromecast/ui/vector_icons/vector_icons.h.template 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// vector_icons.h.template is used to generate vector_icons.h. Edit the former -// rather than the latter. - -#ifndef CHROMECAST_UI_VECTOR_ICONS_VECTOR_ICONS_H_ -#define CHROMECAST_UI_VECTOR_ICONS_VECTOR_ICONS_H_ - -namespace gfx { -struct VectorIcon; -} - -#define VECTOR_ICON_TEMPLATE_H(icon_name) \ -extern const gfx::VectorIcon icon_name; - -namespace chromecast { -namespace vector_icons { - -TEMPLATE_PLACEHOLDER - -} // namespace vector_icons -} // namespace chromecast - -#undef VECTOR_ICON_TEMPLATE_H - -#endif //CHROMECAST_UI_VECTOR_ICONS_VECTOR_ICONS_H_ diff -Nru chromium-132.0.6834.110/chromeos/CHROMEOS_LKGM chromium-132.0.6834.159/chromeos/CHROMEOS_LKGM --- chromium-132.0.6834.110/chromeos/CHROMEOS_LKGM 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromeos/CHROMEOS_LKGM 2025-01-27 17:37:37.000000000 +0000 @@ -1 +1 @@ -16093.73.0 \ No newline at end of file +16093.82.0 \ No newline at end of file diff -Nru chromium-132.0.6834.110/chromeos/strings/chromeos_strings_ar.xtb chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ar.xtb --- chromium-132.0.6834.110/chromeos/strings/chromeos_strings_ar.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ar.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1356,7 +1356,7 @@ مساعدة في الكتابة MSCHAP ‏لا يمكن إيقاف اسم نقطة الوصول (APN) هذا أو إزالته. يُرجى إيقاف أو إزالة أسماء نقاط الوصول المفعَّلة من نوع . -يُرجى الاتصال بإحدى الشبكات وإعادة تحميل الصفحة لعرض الصور الرمزية وتحديدها. +يُرجى الاتصال بإحدى الشبكات وإعادة تحميل الصفحة لعرض صور الأفاتار وتحديدها. تم رصد مدخل. إلى الأمام التقنية diff -Nru chromium-132.0.6834.110/chromeos/strings/chromeos_strings_de.xtb chromium-132.0.6834.159/chromeos/strings/chromeos_strings_de.xtb --- chromium-132.0.6834.110/chromeos/strings/chromeos_strings_de.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromeos/strings/chromeos_strings_de.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1425,7 +1425,7 @@ Neuen Bericht senden Heller Modus Keine Taste zugewiesen. -Nein danke +Nein, danke Status Wähle einen Tag für die automatische Zurücksetzung aus (zwischen 1 und 31, beide inklusive) Berg diff -Nru chromium-132.0.6834.110/chromeos/strings/chromeos_strings_iw.xtb chromium-132.0.6834.159/chromeos/strings/chromeos_strings_iw.xtb --- chromium-132.0.6834.110/chromeos/strings/chromeos_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromeos/strings/chromeos_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -178,7 +178,7 @@ התאמה אישית עזרה בקריאה יציאה מהתצוגה המקדימה של הטפט -לחצן לעריכת מקש הקיצור . +כפתור לעריכת מקש הקיצור . אפליקציית אבחון שיטת קלט טוב () @@ -268,7 +268,7 @@ בוחר אמוג'י נמצאת בתור : ניסיון נוסף -‏הלחצן 'הוספת ה-APN' מושבת עכשיו +‏הכפתור 'הוספת ה-APN' מושבת עכשיו ביטול משימת ההדפסה טקסט הפעלת המצב הכהה @@ -344,7 +344,7 @@ תמונת המשתמש המחובר הטראק הקודם שולחן עבודה -אפשרויות הלחצן +אפשרויות הכפתור מתבצעת הפעלה מחדש… הידרנג'אה הצעות לתוכן עזרה @@ -709,7 +709,7 @@ סיסמה ישנה מסכה של רשת משנה מיקום שמירת הסריקה -‏הלחצן 'שמירת ה-APN' מושבת עכשיו +‏הכפתור 'שמירת ה-APN' מושבת עכשיו שומר המסך של זרימה בכדור הארץ אין תוצאות מתאימות אתרנט @@ -849,7 +849,7 @@ מסך מלא ‏אם הגישה לחשבון הבית ספרי שלך תאבד, לא תהיה לך יותר גישה לאימייל ולקבצים ב-Google Drive שמשויכים לחשבון, כמו Gmail, ‏Docs, ‏Slides ועוד. אימות -לחצן האישור מושבת עכשיו +כפתור האישור מושבת עכשיו העתקת התרגום להפעיל את המצב הכהה באופן אוטומטי? תאריך שינוי @@ -934,7 +934,7 @@ GTC ‏העדכון הזה סופק על ידי יצרן המכשיר החיצוני והוא לא אומת על ידי Google. מעבר אוטומטי לעיצוב כהה בשקיעה -לחצן +כפתור בגווני סריקה UMTS @@ -966,7 +966,7 @@ מרכז הפחתת עוצמת הקול מתוך -לחצן לעריכת מקש הקיצור . +כפתור לעריכת מקש הקיצור . עדכון של השימוש בחבילת הגלישה אופס בינוני @@ -1006,7 +1006,7 @@ אסור פועל {COUNT,plural, =1{הקובץ נסרק בהצלחה ונשמר בתיקייה .}one{הקבצים נסרקו בהצלחה ונשמרו בתיקייה .}two{הקבצים נסרקו בהצלחה ונשמרו בתיקייה .}other{הקבצים נסרקו בהצלחה ונשמרו בתיקייה .}} -לחצן למחיקת מקש הקיצור . +כפתור למחיקת מקש הקיצור . נוף חלומי הקובץ לא נמצא אי אפשר ליצור שמות להקלטות של התוכן הזה @@ -1129,7 +1129,7 @@ TXT חלש () מעבר אל הגדרות החשבון -‏הלחצן 'הוספת ה-APN' מופעל עכשיו +‏הכפתור 'הוספת ה-APN' מופעל עכשיו {PAGE_NUMBER,plural, =0{לסרוק את הדף מחדש?}=1{לסרוק מחדש את דף {PAGE_NUMBER}?}one{לסרוק מחדש את דף {PAGE_NUMBER}?}two{לסרוק מחדש את דף {PAGE_NUMBER}?}other{לסרוק מחדש את דף {PAGE_NUMBER}?}} ‫3 ההנחיות והתוצאות האחרונות שלך. אפשר לגשת אליהן רק כשמשתמשים ב'טפט וסגנון'. OTP @@ -1153,7 +1153,7 @@ טאקו ביום חמישי תפוחים -לחצן האישור מופעל עכשיו +כפתור האישור מופעל עכשיו ‏ה-APN הוא מסוג . שטוח מלא חיים @@ -1300,7 +1300,7 @@ רענון התאמה אישית נקודת אינטרנט מיידית -כדי להתאים אישית את הלחצן, מקישים על מקש כלשהו. משנים את מיקום המקש באמצעות העכבר או מקשי החיצים. +כדי להתאים אישית את הכפתור, לוחצים על מקש כלשהו. משנים את מיקום המקש באמצעות העכבר או מקשי החיצים. ביום רביעי תנאים והגבלות ציאן @@ -1689,7 +1689,7 @@ תוצאות PEAP ספרים -‏הלחצן 'שמירת ה-APN' מופעל עכשיו +‏הכפתור 'שמירת ה-APN' מופעל עכשיו IPv6 ‏זמן האחזור של רזולוציית ה-DNS ארוך עריכה diff -Nru chromium-132.0.6834.110/chromeos/strings/chromeos_strings_mk.xtb chromium-132.0.6834.159/chromeos/strings/chromeos_strings_mk.xtb --- chromium-132.0.6834.110/chromeos/strings/chromeos_strings_mk.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromeos/strings/chromeos_strings_mk.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -125,7 +125,7 @@ Зголемете ја јачината на звукот син камен Сина -Подлога за допир +Допирна подлога боја на заднинско осветлување органза Не може да се ажурира diff -Nru chromium-132.0.6834.110/chromeos/strings/chromeos_strings_nl.xtb chromium-132.0.6834.159/chromeos/strings/chromeos_strings_nl.xtb --- chromium-132.0.6834.110/chromeos/strings/chromeos_strings_nl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromeos/strings/chromeos_strings_nl.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1167,7 +1167,7 @@ Transcriptie aanzetten en transcriptiemodel downloaden? IP-adres Bedankt voor je feedback. Met jouw feedback kunnen we de functionaliteit van de Chromebook verbeteren. Je feedback wordt beoordeeld door ons team. Vanwege het grote aantal rapporten kunnen we je geen antwoord sturen. -Muisknoppen +Muistoetsen Wordt uitgevoerd Afdruktaken zie je in de geschiedenis, tenzij ze handmatig worden verwijderd Je kunt geen bestanden uploaden die groter zijn dan 10 MB diff -Nru chromium-132.0.6834.110/chromeos/strings/chromeos_strings_ru.xtb chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ru.xtb --- chromium-132.0.6834.110/chromeos/strings/chromeos_strings_ru.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ru.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1167,7 +1167,7 @@ Включить расшифровку и скачать модель? IP-адрес Благодарим за отзыв. Он поможет нам улучшить Chromebook и будет рассмотрен нашей командой. Мы получаем множество обращений, поэтому не сможем вам ответить. -Клавиши управления мышью +Клавиши управления указателем Выполняется Задания печати показываются в истории до тех пор, пока вы их не удалите Невозможно загрузить файл размером больше 10 МБ. diff -Nru chromium-132.0.6834.110/chromeos/strings/chromeos_strings_ur.xtb chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ur.xtb --- chromium-132.0.6834.110/chromeos/strings/chromeos_strings_ur.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/chromeos/strings/chromeos_strings_ur.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -24,7 +24,7 @@ اسکرین سیور ڈاؤن لوڈ ہو رہا ہے ‏IP پتہ دستیاب نہیں ہے تصاویر تخلیق ہو رہی ہے... -کے بارے میں +تعارف ہم اس فارم کے ذریعے جمع کرائے گئے تاثرات کا اپنے پارٹنرز کے ساتھ بگز اور دیگر مسائل جن کی آپ ہمیں رپورٹ کرتے ہیں کو حل کرنے کے لیے اشتراک کر سکتے ہیں۔ پاس ورڈز جیسی حساس معلومات شامل نہ کریں۔ آسان بنانے کے لیے بہت کم الفاظ داخلی خرابی diff -Nru chromium-132.0.6834.110/components/browser_ui/strings/android/translations/browser_ui_strings_de.xtb chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_de.xtb --- chromium-132.0.6834.110/components/browser_ui/strings/android/translations/browser_ui_strings_de.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_de.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -448,7 +448,7 @@ Gestern Hinzufügen {TILE_COUNT,plural, =1{Mit diesem Tab fortfahren}other{Mit diesen Tabs fortfahren}} -Nein danke +Nein, danke Eine Website verwendet deine Kamera Von Google bereitgestellt Medien werden wiedergegeben diff -Nru chromium-132.0.6834.110/components/browser_ui/strings/android/translations/browser_ui_strings_gl.xtb chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_gl.xtb --- chromium-132.0.6834.110/components/browser_ui/strings/android/translations/browser_ui_strings_gl.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_gl.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -17,7 +17,7 @@ Deter Para gardar os teus datos, Google optimizou as imaxes desta páxina. Os ficheiros gardados polos sitios web aparecen aquí -Elimínanse os datos que repercuten na personalización dos anuncios +Elimínanse os datos que repercuten na personalización de anuncios Esquecer este sitio Este sitio determina o que che gusta e logo suxírelles anuncios a outros sitios Engadiuse o sitio diff -Nru chromium-132.0.6834.110/components/browser_ui/strings/android/translations/browser_ui_strings_iw.xtb chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_iw.xtb --- chromium-132.0.6834.110/components/browser_ui/strings/android/translations/browser_ui_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/browser_ui/strings/android/translations/browser_ui_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -274,7 +274,7 @@ סגירה ‏יימחקו כל הנתונים המקומיים, כולל קובצי cookie, ויתאפסו כל ההרשאות של ושל כל אתרי המשנה שלו הסרת '' -כדי לצאת ממסך מלא, יש לגרור מלמעלה ולגעת בלחצן 'הקודם'. +כדי לצאת ממסך מלא, יש לגרור מלמעלה ולגעת בכפתור 'הקודם'. ‏חסמת אתרים כך שלא יוכלו להשתמש בקובצי Cookie של צד שלישי כדי לעקוב אחריך במהלך הגלישה. בהגדרות ניתן לנהל את הגישה לקובצי Cookie של צד שלישי. כשהאפשרות מופעלת, אתרים יכולים לבקש הרשאה להשתמש במידע עליך שנשמר בהם. כשהאפשרות מושבתת, אתרים לא יכולים לבקש הרשאה להשתמש במידע עליך שנשמר בהם. הצגה @@ -379,7 +379,7 @@ GB תוכן מוגן להמשיך במצב אנונימי -כדי לצאת ממסך מלא, צריך ללחוץ על לחצן 'הקודם'. +כדי לצאת ממסך מלא, צריך ללחוץ על כפתור 'הקודם'. האתר הזה שייך לקבוצה שיש לה הרשאה לראות את הפעילות שלך. הקבוצה הוגדרה על ידי תמונות פרופיל הורדות פעילות diff -Nru chromium-132.0.6834.110/components/certificate_transparency/data/log_list.json chromium-132.0.6834.159/components/certificate_transparency/data/log_list.json --- chromium-132.0.6834.110/components/certificate_transparency/data/log_list.json 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/certificate_transparency/data/log_list.json 2025-01-27 17:37:37.000000000 +0000 @@ -1,6 +1,6 @@ { - "version": "50.75", - "log_list_timestamp": "2025-01-20T12:55:50Z", + "version": "50.83", + "log_list_timestamp": "2025-01-27T12:58:00Z", "operators": [ { "name": "Google", diff -Nru chromium-132.0.6834.110/components/policy/resources/policy_templates_zh-CN.xtb chromium-132.0.6834.159/components/policy/resources/policy_templates_zh-CN.xtb --- chromium-132.0.6834.110/components/policy/resources/policy_templates_zh-CN.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/policy/resources/policy_templates_zh-CN.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -3258,8 +3258,8 @@ 在 Chrome 42 之前,此设置名为 EnableWebBasedSignin;Chrome 43 中将完全停止支持此设置。 对于所用 SSO 解决方案与新的内嵌登录流程尚不兼容的企业客户来说,此设置非常有用。 - 如果您启用了此设置,系统将使用旧的基于网络的登录流程。 - 如果您停用了此设置或未对其进行设置,默认情况下,系统将使用新的内嵌登录流程。不过,用户仍可以通过命令行指令“--enable-web-based-signin”启用旧的基于网络的登录流程。 + 如果您启用了此设置,系统将使用旧的基于 Web 的登录流程。 + 如果您停用了此设置或未对其进行设置,默认情况下,系统将使用新的内嵌登录流程。不过,用户仍可以通过命令行指令“--enable-web-based-signin”启用旧的基于 Web 的登录流程。 日后,当内嵌登录全面支持所有 SSO 登录流程时,该实验性设置将会取消。 允许删除打印任务记录 diff -Nru chromium-132.0.6834.110/components/sessions/BUILD.gn chromium-132.0.6834.159/components/sessions/BUILD.gn --- chromium-132.0.6834.110/components/sessions/BUILD.gn 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/sessions/BUILD.gn 2025-01-27 17:37:37.000000000 +0000 @@ -195,6 +195,7 @@ "core/command_storage_manager_unittest.cc", "core/serialized_navigation_entry_unittest.cc", "core/session_id_generator_unittest.cc", + "core/tab_restore_service_helper_unittest.cc", ] if (!is_ios) { diff -Nru chromium-132.0.6834.110/components/sessions/core/tab_restore_service_helper.cc chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper.cc --- chromium-132.0.6834.110/components/sessions/core/tab_restore_service_helper.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper.cc 2025-01-27 17:37:37.000000000 +0000 @@ -563,6 +563,31 @@ return context; } +void TabRestoreServiceHelper::UpdateSavedGroupIDsForTabEntries( + std::vector>& tabs, + const std::map& group_mapping) { + for (auto& tab : tabs) { + if (tab->group.has_value() && group_mapping.contains(tab->group.value())) { + tab->saved_group_id = group_mapping.at(tab->group.value()); + } + } +} + +std::map +TabRestoreServiceHelper::CreateLocalSavedGroupIDMapping( + const std::map>& + groups) { + std::map group_mapping; + + for (const auto& [group_id, group] : groups) { + if (group->saved_group_id.has_value()) { + group_mapping[group_id] = group->saved_group_id.value(); + } + } + + return group_mapping; +} + std::vector TabRestoreServiceHelper::RestoreEntryById( LiveTabContext* context, SessionID id, @@ -617,6 +642,12 @@ TimeNow() - window.timestamp); } + // In cases where restoring from a tab restore entry that was created + // through session service, or in other cases, the tab objects saved group + // information may be missing. Add it in before repopulating tabs. + UpdateSavedGroupIDsForTabEntries( + window.tabs, CreateLocalSavedGroupIDMapping(window.tab_groups)); + // When restoring a window, either the entire window can be restored, or a // single tab within it. If the entry's ID matches the one to restore, or // the entry corresponds to an application, then the entire window will be @@ -683,6 +714,14 @@ TimeNow() - group.timestamp); } + // In cases where restoring from a tab restore entry that was created + // through session service, or in other cases, the tab objects saved group + // information may be missing. Add it in before repopulating tabs. + if (group.saved_group_id.has_value()) { + UpdateSavedGroupIDsForTabEntries( + group.tabs, {{group.group_id, group.saved_group_id.value()}}); + } + // When restoring a group, either the entire group can be restored, or a // single tab within it. If the entry's ID matches the one to restore, // then the entire group will be restored. diff -Nru chromium-132.0.6834.110/components/sessions/core/tab_restore_service_helper.h chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper.h --- chromium-132.0.6834.110/components/sessions/core/tab_restore_service_helper.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper.h 2025-01-27 17:37:37.000000000 +0000 @@ -87,6 +87,19 @@ void SetHelperObserver(Observer* observer); + // Creates a mapping of local to saved ids for groups that have a + // saved_group_id. Take in a window's group storage type, and outputs a type + // usable for UpdateSavedGroupIDsForTabEntries. + static std::map + CreateLocalSavedGroupIDMapping( + const std::map>& groups); + + // Updates the saved group IDs for tabs based on the provided group mapping. + // Used by RestoreEntryByID. + static void UpdateSavedGroupIDsForTabEntries( + std::vector>& tabs, + const std::map& group_mapping); + // Helper methods used to implement TabRestoreService. void AddObserver(TabRestoreServiceObserver* observer); void RemoveObserver(TabRestoreServiceObserver* observer); diff -Nru chromium-132.0.6834.110/components/sessions/core/tab_restore_service_helper_unittest.cc chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper_unittest.cc --- chromium-132.0.6834.110/components/sessions/core/tab_restore_service_helper_unittest.cc 1970-01-01 00:00:00.000000000 +0000 +++ chromium-132.0.6834.159/components/sessions/core/tab_restore_service_helper_unittest.cc 2025-01-27 17:37:37.000000000 +0000 @@ -0,0 +1,99 @@ +// Copyright 2025 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/sessions/core/tab_restore_service_helper.h" + +#include + +#include "testing/gtest/include/gtest/gtest.h" + +namespace sessions { + +std::unique_ptr CreateTabRestoreGroup( + tab_groups::TabGroupId group_id, + const std::optional& saved_group_id) { + auto group = std::make_unique(); + group->group_id = group_id; + + group->saved_group_id = saved_group_id; + return group; +} + +std::unique_ptr CreateTabWithGroupInfo( + tab_groups::TabGroupId group_id, + const std::optional& saved_group_id) { + auto tab = std::make_unique(); + tab->group = group_id; + tab->saved_group_id = saved_group_id; + return tab; +} + +class TabRestoreServiceHelperTest : public testing::Test {}; + +TEST_F(TabRestoreServiceHelperTest, CreateLocalSavedGroupIDMapping) { + std::map> groups; + + tab_groups::TabGroupId local_group_id_1 = + tab_groups::TabGroupId::GenerateNew(); + tab_groups::TabGroupId local_group_id_2 = + tab_groups::TabGroupId::GenerateNew(); + + base::Uuid saved_uuid_1 = base::Uuid::GenerateRandomV4(); + + groups[local_group_id_1] = + CreateTabRestoreGroup(local_group_id_1, saved_uuid_1); + groups[local_group_id_2] = + CreateTabRestoreGroup(local_group_id_2, std::nullopt); + + std::map result = + TabRestoreServiceHelper::CreateLocalSavedGroupIDMapping(groups); + + // Verify that only groups with saved_group_id appear in the mapping. + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[local_group_id_1], saved_uuid_1); +} + +TEST_F(TabRestoreServiceHelperTest, UpdateSavedGroupIDsForTabEntries) { + tab_groups::TabGroupId local_group_id_1 = + tab_groups::TabGroupId::GenerateNew(); + tab_groups::TabGroupId local_group_id_2 = + tab_groups::TabGroupId::GenerateNew(); + tab_groups::TabGroupId local_group_id_3 = + tab_groups::TabGroupId::GenerateNew(); + + base::Uuid saved_guid_1 = base::Uuid::GenerateRandomV4(); + base::Uuid saved_guid_2 = base::Uuid::GenerateRandomV4(); + + std::vector> tabs; + tabs.push_back(CreateTabWithGroupInfo(local_group_id_1, std::nullopt)); + tabs.push_back(CreateTabWithGroupInfo(local_group_id_2, std::nullopt)); + tabs.push_back(CreateTabWithGroupInfo(local_group_id_3, std::nullopt)); + tabs.push_back(std::make_unique()); + + std::map> groups; + groups[local_group_id_1] = + CreateTabRestoreGroup(local_group_id_1, saved_guid_1); + groups[local_group_id_2] = + CreateTabRestoreGroup(local_group_id_2, saved_guid_2); + groups[local_group_id_3] = + CreateTabRestoreGroup(local_group_id_3, std::nullopt); + + TabRestoreServiceHelper::UpdateSavedGroupIDsForTabEntries( + tabs, TabRestoreServiceHelper::CreateLocalSavedGroupIDMapping(groups)); + + // Verify that only tabs with a group in the mapping are updated. + ASSERT_TRUE(tabs[0]->saved_group_id.has_value()); + EXPECT_EQ(tabs[0]->saved_group_id.value(), saved_guid_1); + + ASSERT_TRUE(tabs[1]->saved_group_id.has_value()); + EXPECT_EQ(tabs[1]->saved_group_id.value(), saved_guid_2); + + // 3rd tab's group isn't in the mapping, so Tab 2 remains unchanged. + EXPECT_FALSE(tabs[2]->saved_group_id.has_value()); + + // The last tab has no group, so it should also remain nullopt. + EXPECT_FALSE(tabs[3]->saved_group_id.has_value()); +} + +} // namespace sessions diff -Nru chromium-132.0.6834.110/components/strings/components_strings_ar.xtb chromium-132.0.6834.159/components/strings/components_strings_ar.xtb --- chromium-132.0.6834.110/components/strings/components_strings_ar.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_ar.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -3012,7 +3012,7 @@ خدمات تخزين في السحابة الإلكترونية متعدد الأبعاد الطي على شكل بوابة -إثبات ملكية رقم الهاتف +تأكيد رقم هاتفك A4 Tab ‏تغيير كلمة مرور Google مزيد من المعلومات حول ميزة "مواضيع الإعلانات" diff -Nru chromium-132.0.6834.110/components/strings/components_strings_ca.xtb chromium-132.0.6834.159/components/strings/components_strings_ca.xtb --- chromium-132.0.6834.110/components/strings/components_strings_ca.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_ca.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -2243,7 +2243,7 @@ La política està establerta. no controlarà la disponibilitat del mode de desenvolupador a la pàgina d'extensions. Fes un seguiment dels preus amb Chrome Consulteu les polítiques de l'administrador -Paga més ràpidament quan es desi la targeta. Les dades de la targeta s'encripten al teu Compte de Google. +Paga més ràpidament quan es desi la targeta. Els detalls de la targeta s'encripten al teu Compte de Google. Emès per requereix un certificat arrel, però no està instal·lat. Per resoldre aquest problema, l'administrador de TI ha de consultar les instruccions per configurar . Vols afegir-la a la comparació? diff -Nru chromium-132.0.6834.110/components/strings/components_strings_da.xtb chromium-132.0.6834.159/components/strings/components_strings_da.xtb --- chromium-132.0.6834.110/components/strings/components_strings_da.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_da.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -447,7 +447,7 @@ Med henblik på at måle en annonces effektivitet deles der begrænsede typer data mellem websites, f.eks. om du har foretaget et køb, når du har besøgt et website. Adoption Åbn link på ny fane -Nu kan du bruge et virtuelt kort til at betale mere sikkert ved hjælp af Autofyld. +Nu kan du bruge et virtuelt kort til at betale mere sikkert ved hjælp af autofyld. Magi Skrifttype med enkelt tegnafstand Knappen Skift Google-adgangskode, aktivér for at ændre adgangskoden til din Google-konto diff -Nru chromium-132.0.6834.110/components/strings/components_strings_de.xtb chromium-132.0.6834.159/components/strings/components_strings_de.xtb --- chromium-132.0.6834.110/components/strings/components_strings_de.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_de.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -3792,7 +3792,7 @@ Chrome schließt aufgrund deines aktuellen Browserverlaufs auf Themen, die dich interessieren könnten. Außerdem können besuchte Websites feststellen, was dir gefällt. Websites können diese Informationen dann abfragen und dir personalisierte Werbung anzeigen. Du kannst festlegen, welche Themen und Websites für Werbung verwendet werden. Website ist vertrauenswürdig Gib den -stelligen Sicherheitscode auf der ein, damit deine Bank deine Identität bestätigen kann -Nein danke +Nein, danke Status Infofeld schließen Damit Zahlungen zukünftig schneller abgewickelt werden können, speichere deine Karte und den verschlüsselten Sicherheitscode auf deinem Gerät diff -Nru chromium-132.0.6834.110/components/strings/components_strings_fa.xtb chromium-132.0.6834.159/components/strings/components_strings_fa.xtb --- chromium-132.0.6834.110/components/strings/components_strings_fa.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_fa.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -4526,7 +4526,7 @@ سند تکی/برگ جدید درحال جستجوی دستگاه‌های بلوتوث... گواهی سرور نامعتبر است. -‏دکمه جابجایی برگه، برای جابجایی به این برگه، Enter را فشار دهید +‏دکمه جابه‌جایی برگه، برای جابه‌جایی به این برگه، Enter را فشار دهید ‏این فایل PDF غیرقابل‌دسترس است. نوشتار، با بهره‌گیری از هوش مصنوعی Google، استخراج شد ‏اطلاعات پرداخت‌ها و کارت اعتباری‌تان را در تنظیمات Chrome مدیریت کنید اگر قیمت در هر سایتی کاهش پیدا کند، هشدار ایمیلی دریافت می‌کنید diff -Nru chromium-132.0.6834.110/components/strings/components_strings_fr-CA.xtb chromium-132.0.6834.159/components/strings/components_strings_fr-CA.xtb --- chromium-132.0.6834.110/components/strings/components_strings_fr-CA.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_fr-CA.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -798,7 +798,7 @@ Le certificat du serveur a été révoqué. Cliquer sur J'aime envoie des commentaires indiquant que aimez le remplissage automatique avec l'IA Préparation et planification fiscales -Élaborer +Développer Cabriolets Afficher les règles non paramétrées Ce mode de livraison n'est pas disponible. Essayez un autre mode. diff -Nru chromium-132.0.6834.110/components/strings/components_strings_fr.xtb chromium-132.0.6834.159/components/strings/components_strings_fr.xtb --- chromium-132.0.6834.110/components/strings/components_strings_fr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_fr.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1509,7 +1509,7 @@ Ouvrir la page dans une nouvelle fenêtre de navigation privée (Ctrl+Maj+N) Saisissez le code de validation à  chiffres Informations relatives au certificat -Chrome se base sur votre historique de navigation récent pour déterminer les thèmes qui vous intéressent. +Chrome relève les thèmes qui vous intéressent grâce à votre historique de navigation. L'option "Remplir l'adresse" a été sélectionnée Gérer la saisie automatique avec l'IA Fourgons et fourgonnettes @@ -3792,7 +3792,7 @@ Ajouter Règle ignorée, car non configurée par une source cloud. La connexion est chiffrée au moyen de , avec pour l'authentification des messages et pour la méthode d'échange de clés. -Chrome se base sur votre historique de navigation récent pour déterminer les thèmes qui vous intéressent. Les sites que vous consultez peuvent aussi déterminer vos centres d'intérêt. Par la suite, les sites peuvent demander ces informations pour vous montrer des annonces personnalisées. Vous pouvez choisir les thèmes et les sites qui sont utilisés pour vous montrer des annonces. +Chrome relève les thèmes qui vous intéressent grâce à votre historique de navigation. Les sites que vous visitez peuvent aussi déterminer ce qui vous intéresse. Les sites peuvent ensuite demander ces informations pour vous montrer des annonces personnalisées. Vous pouvez choisir les thèmes et les sites qui sont utilisés pour vous montrer des annonces. Ce site est légitime Saisissez le code de sécurité à  chiffres indiqué à l' pour que votre banque puisse vérifier votre identité Non, merci @@ -4513,7 +4513,7 @@ Magazines Configuration en cours... {0,plural, =1{ peut inclure du contenu sensible}one{ fichier peut inclure du contenu sensible}other{ fichiers peuvent inclure du contenu sensible}} -Les sites que vous consultez peuvent aussi déterminer vos centres d'intérêt en fonction de votre activité sur ces sites. Par exemple, si vous consultez un site qui vend des chaussures de running pour les longues distances, le site peut déterminer que le marathon fait partie de vos centres d'intérêt. +Les sites que vous visitez peuvent aussi déterminer ce qui vous intéresse en fonction de votre activité sur ces sites. Par exemple, si vous consultez un site qui vend des chaussures de running pour les longues distances, le site peut déterminer que le marathon fait partie de vos centres d'intérêt. En savoir plus sur les annonces suggérées par les sites et la mesure des annonces Informations sur le navigateur et l'OS de l'appareil (versions du navigateur et de l'OS, par exemple) Accéder directement à vos imprimantes diff -Nru chromium-132.0.6834.110/components/strings/components_strings_hi.xtb chromium-132.0.6834.159/components/strings/components_strings_hi.xtb --- chromium-132.0.6834.110/components/strings/components_strings_hi.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_hi.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -2303,7 +2303,7 @@ कार्ड की जानकारी सिर्फ़ डिवाइस पर सेव की गई पुष्टि करने का डायलॉग बॉक्स पोलिश -पते प्रबंधित करें... +पते मैनेज करें... सही कोड डालें यह ऐप्लिकेशन वाई-फ़ाई क्रेडेंशियल इंस्टॉल करने की अनुमति मांग रहा है. सेटअप हो जाने के बाद, आपका अपने-आप वाई-फ़ाई नेटवर्क से कनेक्ट हो जाएगा. इन क्रेडेंशियल को हटाने के लिए, ऐप्लिकेशन को अनइंस्टॉल करें. इस समय वर्चुअल कार्ड उपलब्ध नहीं है, कृपया अपने बैंक से संपर्क करें @@ -4500,7 +4500,7 @@ सूचनाएं भेजने की अनुमति है खरीदारी Chrome ब्राउज़र, पासवर्ड ऑटोमैटिक भरने के लिए फ़िंगरप्रिंट का इस्तेमाल करना चाहता है -पते प्रबंधित करें +पते मैनेज करें खत्म होने की तारीख: फिर से साइन इन करें. इसके बाद, लिखने में मदद पाने के लिए इस टैब पर वापस आएं diff -Nru chromium-132.0.6834.110/components/strings/components_strings_iw.xtb chromium-132.0.6834.159/components/strings/components_strings_iw.xtb --- chromium-132.0.6834.110/components/strings/components_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -58,10 +58,10 @@ השדה הזה יכול לכלול עד רשומות. כל הרשומות הנוספות יימחקו. פארקים וגנים אזוריים הפעלה אוטומטית של 'תמונה בתוך תמונה' -‏הלחצן להמשך התהליך, מקישים על Enter כדי להמשיך בתהליך ולהציג את הפעילות הרלוונטית בהיסטוריה ב-Chrome +‏הכפתור להמשך התהליך, לוחצים על Enter כדי להמשיך בתהליך ולהציג את הפעילות הרלוונטית בהיסטוריה ב-Chrome פעולת שגיאה יש כמה שדות חובה ריקים. עליך למלא אותם לפני השמירה. -‏הלחצן לניהול סיסמאות, מפעילים אותו כדי להציג ולנהל את הסיסמאות בהגדרות Chrome +‏הכפתור לניהול סיסמאות, מפעילים אותו כדי להציג ולנהל את הסיסמאות בהגדרות Chrome A3x4 האם הכרטיס הווירטואלי לא מולא? יש ללחוץ על פרטי הכרטיס הווירטואלי כדי להעתיק אותם ללוח. צריך לבחור את ההרשאה של @@ -86,7 +86,7 @@ היסטוריית המחירים באינטרנט ‏להתחבר מחדש אל ה-Wi-Fi מוזיקת פולק ומוזיקה מסורתית -‏הלחצן לניהול הכתובות, מפעילים אותו כדי להוסיף ולנהל כתובות בהגדרות Chrome +‏הכפתור לניהול הכתובות, מפעילים אותו כדי להוסיף ולנהל כתובות בהגדרות Chrome שגיאה ביקור בדף {COUNT,plural, =0{אין אתרים}=1{‏מאתר אחד (החיבור לחשבון Google שלך ימשיך)}one{‏מ-# אתרים (החיבור לחשבון Google שלך ימשיך)}two{‏מ-# אתרים (החיבור לחשבון Google שלך ימשיך)}other{‏מ-# אתרים (החיבור לחשבון Google שלך ימשיך)}} @@ -159,7 +159,7 @@ הובלות והעתקת מקום מגורים שיטת איסוף המעקב אחר מחירים מושבת -‏לחצן 'אהבתי', מקישים על Enter כדי לשלוח משוב שאהבת את ההצעה +‏כפתור 'אהבתי', לוחצים על Enter כדי לשלוח משוב שאהבת את ההצעה תוכניות אירוח בטלוויזיה מערים 1 סירות וכלי שיט @@ -202,7 +202,7 @@ שיתוף הכרטיסייה הזו דומיין הרשמה: כתובת איסוף -כדי לנווט אל לחצני המשוב, יש להשתמש במקשי החיצים שמאלה וימינה. +כדי לנווט אל כפתורי המשוב, יש להשתמש במקשי החיצים שמאלה וימינה. האתר הזה מזהה אילו דברים אהבת ולאחר מכן מציע מודעות לאתרים אחרים ימינה אישור השם @@ -245,7 +245,7 @@ מעטפה – הזמנה שגיאת פרטיות גיל הגן -‏הלחצן לניהול הורדות ב-Chrome, מפעילים אותו כדי לנהל את הקבצים שהורדת ב-Chrome +‏הכפתור לניהול הורדות ב-Chrome, מפעילים אותו כדי לנהל את הקבצים שהורדת ב-Chrome כדי לאפשר התאמה ביקרת בתדירות גבוהה ‏האתר יכול לבקש הרשאה לחפש מכשירי Bluetooth בקרבת מקום @@ -374,7 +374,7 @@ מדיניות משתמשים יש לנסות להיכנס לדף הבית של האתר. עיכוב הפלט עד -‏ניגשים ללחצן בדיקת האבטחה ב-Chrome, מפעילים אותו כדי להיכנס לדף בדיקת האבטחה ב-Chrome בהגדרות +‏ניגשים לכפתור בדיקת האבטחה ב-Chrome, מפעילים אותו כדי להיכנס לדף בדיקת האבטחה ב-Chrome בהגדרות היסטוריה מקור לא מוכר פרוטוקול לא נתמך @@ -450,7 +450,7 @@ עכשיו אפשר להשתמש בכרטיס וירטואלי כדי לשלם בצורה מאובטחת יותר במילוי אוטומטי. קסם ‏גופן Monospace -‏הלחצן לשינוי הסיסמה ל-Google, מפעילים אותו כדי לשנות את הסיסמה לחשבון Google +‏הכפתור לשינוי הסיסמה ל-Google, מפעילים אותו כדי לשנות את הסיסמה לחשבון Google שם הרחוב השרת הזה לא הצליח להוכיח שהוא . אישור האבטחה שלו לא נחשב כמהימן על ידי מערכת ההפעלה של המכשיר. ייתכן שהסיבה לכך היא תצורה שגויה או תוקף המיירט את החיבור שלך. יש לנסות להפעיל את אבחון הרשת של Windows. @@ -528,7 +528,7 @@ עזרה לגבי הודעות שגיאה ספציפיות ‏400x600 מ"מ {COUNT,plural, =0{ללא}=1{אתר אחד}one{# אתרים}two{שני אתרים}other{# אתרים}} -‏הלחצן לשיתוף הכרטיסייה הזו, מפעילים אותו כדי לשתף את הכרטיסייה הזו על ידי שיתוף הקישור, יצירת קוד QR, הפעלת Cast ועוד +‏הכפתור לשיתוף הכרטיסייה הזו, מפעילים אותו כדי לשתף את הכרטיסייה הזו על ידי שיתוף הקישור, יצירת קוד QR, הפעלת Cast ועוד ההצעות נטענו חדשה טיפוח השיער @@ -571,7 +571,7 @@ צריך לאפס את הסיסמה עכשיו 4 ניקובים בצד שמאל ייתכן שתכונות באתרים מסוימים לא יפעלו -‏הלחצן ליצירת אירוע, מפעילים אותו כדי ליצור במהירות אירוע חדש ביומן Google +‏הכפתור ליצירת אירוע, מפעילים אותו כדי ליצור במהירות אירוע חדש ביומן Google ‏ניתן לנהל את ההרשאות והנתונים השמורים בכל האתרים בהגדרות Chrome Fabric (Glossy) המדיניות הזו משביתה באופן אוטומטי את הסנכרון במכשירים שונים עבור: . @@ -672,7 +672,7 @@ העסקה לא הושלמה. לא נמשכו כספים מהחשבון שלך. ‏אי אפשר להוריד קבצים שגדולים מ-100MB שמירת הכתובת בחשבון -‏הלחצן לעדכון Chrome, מפעילים אותו כדי לעדכן את Chrome דרך הגדרות Chrome +‏הכפתור לעדכון Chrome, מפעילים אותו כדי לעדכן את Chrome דרך הגדרות Chrome תוקפים באתר שבו ניסית לבקר עשויים להתקין תוכנות מזיקות שגונבות או מוחקות פריטים כמו הסיסמאות, התמונות, ההודעות או מספרי כרטיסי האשראי שלך. ב- מדיניות @@ -683,7 +683,7 @@ זהה (ברירת מחדל) ניקובים מרובים בחלק התחתון מה כדאי לקחת בחשבון -‏לחצן 'לא אהבתי', מקישים על Enter כדי לפתוח טופס לשליחה של משוב מפורט על הסיבה לכך שלא אהבת את ההצעה הזו +‏כפתור 'לא אהבתי', לוחצים על Enter כדי לפתוח טופס לשליחה של משוב מפורט על הסיבה לכך שלא אהבת את ההצעה הזו גב הכרטיס העדכון הסתיים. ללא הגבלה, עם כל כרטיס @@ -748,7 +748,7 @@ ‏מפתח גישה • iCloud Keychain לא הועלה אתרים שבהם מבקרים וזמני הביקורים. -הלחצן לפתיחת חלון פרטי, מפעילים אותו כדי לפתוח חלון פרטי חדש ולגלוש באופן פרטי +הכפתור לפתיחת חלון פרטי, מפעילים אותו כדי לפתוח חלון פרטי חדש ולגלוש באופן פרטי רוצה ליהנות מחוויה סוחפת? תבלינים ורטבים פחות מ-. בביקור הבא שלך, יכול להיות שאתרים מסוימים ייטענו לאט יותר. @@ -765,7 +765,7 @@ רוצה לבצע התאמה עם תמונה שהעתקת מעקב המחירים הופסק -הלחצן לפתיחת כרטיסייה פרטית, מפעילים אותו כדי לפתוח כרטיסייה פרטית חדשה ולגלוש באופן פרטי +הכפתור לפתיחת כרטיסייה פרטית, מפעילים אותו כדי לפתוח כרטיסייה פרטית חדשה ולגלוש באופן פרטי האם לאפשר ל- לפתוח את כל קישורי במקום את ? ניתן להשתמש בדף זה במצלמה ובמיקרופון סימניות אחרות @@ -862,7 +862,7 @@ הגנה על החשבון (בכפוף לתנאים) אין הרשאה (ברירת מחדל) -‏לחצן להגדרת Chrome כדפדפן ברירת המחדל, יש ללחוץ על Enter כדי להגדיר את Chrome כדפדפן ברירת המחדל של המערכת בהגדרות iOS +‏כפתור להגדרת Chrome כדפדפן ברירת המחדל, יש ללחוץ על Enter כדי להגדיר את Chrome כדפדפן ברירת המחדל של המערכת בהגדרות iOS בית וגן לבדוק את האות באזור שלך ‏בחרת לבצע אימות באמצעות Touch ID באתרים שמשתמשים ב-. יכול להיות שהספק הזה אחסן מידע על אמצעי התשלום שלך, שאותו אפשר . @@ -933,7 +933,7 @@ היסטוריה וכרטיסיות שליחה חדר אמבטיה -‏לסגירת הלחצן של הטיפ ל-Chrome, לוחצים על Enter +‏לסגירת הכפתור של הטיפ ל-Chrome, לוחצים על Enter {0,plural, =1{להעביר את הקובץ הסודי?}one{להעביר את הקבצים הסודיים?}two{להעביר את הקבצים הסודיים?}other{להעביר את הקבצים הסודיים?}} דיני עבודה והעסקה אירוע @@ -1058,7 +1058,7 @@ {0,plural, =1{אין אפשרות להוריד את הקובץ}one{אין אפשרות להוריד קבצים}two{אין אפשרות להוריד קבצים}other{אין אפשרות להוריד קבצים}} מוצרי שיזוף והגנה מהשמש ‏ההגדרות של Chrome -‏הלחצן ליצירת מסמך, מפעילים אותו כדי ליצור במהירות מסמך חדש ב-Google Docs +‏הכפתור ליצירת מסמך, מפעילים אותו כדי ליצור במהירות מסמך חדש ב-Google Docs שיטת משלוח משויך על ידי משתמש כתובת לחיוב @@ -1183,7 +1183,7 @@ פענוח התגובה נכשל נסיעות מוזלות ונסיעות בדקה ה-90 שגיאת שרת זמנית -‏הלחצן ליצירת גיליון, מפעילים אותו כדי ליצור במהירות גיליון אלקטרוני חדש ב-Google Sheets +‏הכפתור ליצירת גיליון, מפעילים אותו כדי ליצור במהירות גיליון אלקטרוני חדש ב-Google Sheets דף זה כולל טופס שעשוי להישלח באופן לא מאובטח. הנתונים ששולחים יהיו גלויים במהלך ההעברה, וקיימת סכנה שמישהו ישנה את הפרטים שהשרת יקבל. משהו השתבש במהלך השימוש בתכונה 'שיתוף בקרבת מקום' החשבון שלך מנוהל על-ידי . @@ -1230,7 +1230,7 @@ סמל הפעלת האפליקציה אין הרשאת גישה למיקום השרת הציג אישור שאינו תואם את הציפיות המובנות. ציפיות אלה נכללות עבור אתרי אינטרנט מסוימים בעלי אבטחה גבוהה כדי להגן עליך. -יש ללחוץ על לחצן הטעינה מחדש כדי לשלוח מחדש את הנתונים הדרושים לטעינת הדף. +יש ללחוץ על כפתור הטעינה מחדש כדי לשלוח מחדש את הנתונים הדרושים לטעינת הדף. תמונות ממוזערות מיקרופון פרטי גרסה של המכשיר והדפדפן @@ -1277,7 +1277,7 @@ ‏סריקת Bluetooth A2x3 הסיסמה שבה השתמשת עכשיו אותרה בפרצה באבטחת מידע. לפי מנהל הסיסמאות, מומלץ לשנות את הסיסמה הזו עכשיו. -‏הלחצן להתאמה אישית של Chrome, מפעילים אותו כדי להתאים אישית את מראה הדפדפן +‏הכפתור להתאמה אישית של Chrome, מפעילים אותו כדי להתאים אישית את מראה הדפדפן ‏יחידה ארגונית (OU) תוכניות קומיות בטלוויזיה ‏4x6 אינץ' @@ -1287,7 +1287,7 @@ גישה לקובץ ולשינויים שבוצעו לאחרונה, כולל שמות קבצים, טביעות אצבע דיגיטליות של תוכן הקובץ, מקור ההורדה ומטא-נתונים רווייה לא עומד בדרישות להגדרה ככרטיס וירטואלי -ניתן ללחוץ על לחצן הטעינה מחדש כדי לאפשר חיבור למכשירים או לשרתים ברשת הפרטית שלך. +ניתן ללחוץ על כפתור הטעינה מחדש כדי לאפשר חיבור למכשירים או לשרתים ברשת הפרטית שלך. מאובטח אימון אינטרוולים בעצימות גבוהה ‏ענן (Ash) @@ -1335,7 +1335,7 @@ העלאה בעוד שע' מחשוב מבוזר ומחשוב ענן גודל: -‏הלחצן להפעלת המשחק Chrome Dino, מפעילים אותו כדי לשחק במשחק Dino Run ב-Chrome +‏הכפתור להפעלת המשחק Chrome Dino, מפעילים אותו כדי לשחק במשחק Dino Run ב-Chrome ‏החיפושים שלך, ההתאמות הכי טובות ותוכן הדפים שלהם נשלחים אל Google. יכול להיות שבודקים אנושיים יראו אותם כדי לשפר את התכונה הזו. התכונה הזאת היא ניסיונית והתוצאות שלה לא תמיד מדויקות. מומלץ לצאת מתוכניות אחרות וכך לפנות מקום בזיכרון. לא ניתן לגשת כרגע אל . @@ -1373,7 +1373,7 @@ במסגרת מדידת הביצועים של המודעות, רק סוגים מסוימים של נתונים ישותפו בין אתרים כדי למדוד את ביצועי המודעות שלהם. למשל, אם ביצעת רכישה אחרי ביקור באתר. , פתוחה כרגע, יש להקיש על Tab ולאחר מכן על Enter כדי לעבור לכרטיסייה הפתוחה , לוחצים על Tab ואז על Enter כדי לסגור את כל החלונות הפרטיים שפתוחים כרגע -‏הלחצן להתאמה אישית של הגופנים ב-Chrome, מפעילים אותו כדי להתאים אישית את הגופנים וגודל הטקסט ב-Chrome +‏הכפתור להתאמה אישית של הגופנים ב-Chrome, מפעילים אותו כדי להתאים אישית את הגופנים וגודל הטקסט ב-Chrome לפי קבוצה לא עכשיו ‏ייתכן שמישהו אחר ישלול את הגישה שלך לחשבון Google. לגלישה בטוחה ב-Chrome, מומלץ לשנות את הסיסמה עכשיו. @@ -1451,7 +1451,7 @@ אמצעי מידע על טבלאות השוואה , , -‏הלחצן לניהול הגדרות הפרטיות ב-Google, מפעילים אותו כדי להיכנס להגדרות הפרטיות בחשבון Google +‏הכפתור לניהול הגדרות הפרטיות ב-Google, מפעילים אותו כדי להיכנס להגדרות הפרטיות בחשבון Google האפליקציה נחסמה על ידי מנהל המערכת ‏5x5 אינץ' תוכניות וסדרות טלוויזיה @@ -1472,7 +1472,7 @@ {0,plural, =1{בהתאם למדיניות האדמין, לא מומלץ להעביר את הקובץ הזה אל }one{בהתאם למדיניות האדמין, לא מומלץ להעביר את הקבצים האלה אל }two{בהתאם למדיניות האדמין, לא מומלץ להעביר את הקבצים האלה אל }other{בהתאם למדיניות האדמין, לא מומלץ להעביר את הקבצים האלה אל }} אם היא כבר רשומה כתוכנית המורשית לגשת לרשת, יש לנסות להסיר אותה מהרשימה ולהוסיף אותה שוב. -‏הלחצן 'איפה המכשיר שלי', מפעילים אותו כדי להיכנס לדף 'איתור המכשיר' בחשבון Google +‏הכפתור 'איפה המכשיר שלי', מפעילים אותו כדי להיכנס לדף 'איתור המכשיר' בחשבון Google החיבור לרשת של המכשיר הזה הוגדר על ידי מנהלי המערכת, ועשויה להיות להם אפשרות לראות את התנועה שלך ברשת, כולל האתרים שבהם ביקרת. שיתוף המסך נמשך שיתוף המסך מושהה @@ -1484,7 +1484,7 @@ אפליקציה: מדידת הביצועים של מודעה מסוימת ‏כל רשומת מחרוזת של כתובות URL חייבת להכיל כתובת URL אחת או שתיים. -‏לסגירת הלחצן של הטיפ ל-Chrome, לוחצים על Enter, +‏לסגירת הכפתור של הטיפ ל-Chrome, לוחצים על Enter, האימות בוצע בהצלחה ‏כדי לשמור על אבטחת הכרטיס שלך, עליך להזין את קוד האימות (CVC) שמופיע ב טיולים ומחנאות @@ -1515,7 +1515,7 @@ רכבים מסחריים ורכבי מיניוואן עליך לבחור שיטה לאימות הזהות שלך האדמינים הגדירו שהמערכת תשמור באחסון שלך ב- שמנוהל על ידי הארגון. אם הקבצים האלה ימחקו, יכול להיות שיתבצע מעקב אחריהם, בדיקה ושמירה שלהם. -‏הלחצן ליצירת אתר, מפעילים אותו כדי ליצור במהירות אתר חדש ב-Google Sites +‏הכפתור ליצירת אתר, מפעילים אותו כדי ליצור במהירות אתר חדש ב-Google Sites בחרת להשתמש בטביעת האצבע למילוי סיסמאות מכירת כרטיסים לאירועים האיפוס אושר. @@ -1786,7 +1786,7 @@ ביטול המעקב אחר המחירים ‏חיפוש בהיסטוריה, באמצעות AI אורך -‏הלחצן להצגת טיפים ל-Chrome, מפעילים אותו כדי לקבל מידע על התכונות של Chrome +‏הכפתור להצגת טיפים ל-Chrome, מפעילים אותו כדי לקבל מידע על התכונות של Chrome פתיחה בכרטיסייה חדשה &ביצוע מחדש של העברה שעונים @@ -1945,7 +1945,7 @@ המערכת מתעלמת מהמדיניות כי ניתן להגדיר אותה רק כמדיניות משתמש בענן. נושאים פופולריים התכונה הזאת היא ניסיונית והתוצאות שלה לא תמיד מדויקות. -‏הלחצן לניהול ההגדרות לאתרים, מפעילים אותו כדי לנהל את ההרשאות והנתונים השמורים בכל האתרים בהגדרות Chrome +‏הכפתור לניהול ההגדרות לאתרים, מפעילים אותו כדי לנהל את ההרשאות והנתונים השמורים בכל האתרים בהגדרות Chrome ‏האתר יכול לבקש הרשאה להתחבר למכשירי HID הטקסט המוצג למשתמש: ‏הסיסמה שבה השתמשת עכשיו אותרה בפרצה באבטחת מידע. כדי להגן על החשבונות שלך, לפי מנהל הסיסמאות של Google, מומלץ לבדוק את הסיסמאות השמורות שלך. @@ -2050,7 +2050,7 @@ הצגת המספר של הכרטיס הווירטואלי שלך נוצרה עכשיו מודעות שאתרים מציעים -הלחצן לסגירת החלונות הפרטיים, מפעילים אותו כדי לסגור את כל החלונות הפרטיים שפתוחים כרגע +הכפתור לסגירת החלונות הפרטיים, מפעילים אותו כדי לסגור את כל החלונות הפרטיים שפתוחים כרגע טיפול בגגות מנועי חיפוש אומנויות לחימה @@ -2206,10 +2206,10 @@ פיננסים שימוש במיקרופונים אין תוצאות -‏לחצן החלפת כרטיסיות, יש להקיש על Enter כדי לעבור לכרטיסייה הפתוחה, +‏כפתור החלפת כרטיסיות, יש ללחוץ על Enter כדי לעבור לכרטיסייה הפתוחה, פעולות להגיב לאירועי נגישות -‏הלחצן להצגת ההיסטוריה ב-Chrome, מפעילים אותו כדי להציג ולנהל את היסטוריית הגלישה בהגדרות Chrome +‏הכפתור להצגת ההיסטוריה ב-Chrome, מפעילים אותו כדי להציג ולנהל את היסטוריית הגלישה בהגדרות Chrome הרחבת רשימה ‏אפשר לבצע שינויים בהגדרות הפרטיות בפרסום ב-Chrome בחירה של מנוע החיפוש @@ -2491,7 +2491,7 @@ הוספה של כתובת חוקית הכל מוכן מכונה בענן -‏הלחצן ליצירת פתק, מפעילים אותו כדי ליצור במהירות פתק חדש ב-Google Keep +‏הכפתור ליצירת פתק, מפעילים אותו כדי ליצור במהירות פתק חדש ב-Google Keep כתובות ועוד כתובת האתר הזה באינטראנט של החברה, הארגון או מוסד הלימודים, זהה לכתובת של אתר חיצוני. @@ -2635,7 +2635,7 @@ חינוך לגיל הרך ‏אם הזנת את הסיסמה שלך באתרים אחרים, ההמלצה של Chrome היא לאפס אותה. ההורים שלך יכולים לבטל בשבילך את החסימה -‏הלחצן ליצירת טופס, מפעילים אותו כדי ליצור במהירות טופס חדש ב-Google Forms +‏הכפתור ליצירת טופס, מפעילים אותו כדי ליצור במהירות טופס חדש ב-Google Forms {NUM_CARDS,plural, =1{‏שמירת הכרטיס בחשבון Google}one{‏שמירת הכרטיסים בחשבון Google}two{‏שמירת הכרטיסים בחשבון Google}other{‏שמירת הכרטיסים בחשבון Google}} ניהול של אופן קבלת ההתראות על הנחות לגבי מוצרים במעקב ‏מעטפה – C9 @@ -2707,7 +2707,7 @@ הכניסה האחרונה בוצעה אתמול הפעלה מחדש הונפק בתאריך -‏לחצן 'אהבתי', מקישים על Enter כדי לשלוח משוב שאהבת את +‏כפתור 'אהבתי', לוחצים על Enter כדי לשלוח משוב שאהבת את צהוב כותרת: (מסונכרנים) @@ -3073,7 +3073,7 @@ מתבצע תרגום מ אל לא פעילה מוזיקה קלאסית -‏הלחצן לניהול ההגדרות בנושא נגישות, מפעילים אותו כדי להתאים אישית את כלי הנגישות בהגדרות Chrome +‏הכפתור לניהול ההגדרות בנושא נגישות, מפעילים אותו כדי להתאים אישית את כלי הנגישות בהגדרות Chrome תעשיית המזון הגליל השביעי &ביצוע מחדש של מחיקה @@ -3092,7 +3092,7 @@ ‏14x17 אינץ' אפליקציות שהותקנו או הוסרו ותדירות השימוש בהן האדמין שלך מאשר את השימוש ב באתר הזה -‏הלחצן לניהול אמצעי התשלום, מפעילים אותו כדי לנהל את פרטי כרטיסי האשראי והתשלומים שלך בהגדרות Chrome +‏הכפתור לניהול אמצעי התשלום, מפעילים אותו כדי לנהל את פרטי כרטיסי האשראי והתשלומים שלך בהגדרות Chrome זהו דף של תוסף שני ניקובים בצד ימין מילוי המסך @@ -3120,7 +3120,7 @@ חיפוש טיולי יוקרה ‏מתבצע איתור של התקני USB... -‏הלחצן לניהול הגדרות Chrome, מפעילים אותו כדי להיכנס להגדרות Chrome +‏הכפתור לניהול הגדרות Chrome, מפעילים אותו כדי להיכנס להגדרות Chrome פוטבול אוסטרלי JIS B4 לימודים בתחום המחשבים @@ -3243,7 +3243,7 @@ Gravure Cylinder ‏184x260 מ"מ יש הרשאה חד-פעמית למעקב אחר תנועות הידיים -‏הלחצן לניהול הגדרות האבטחה, מפעילים אותו כדי לנהל את הגלישה הבטוחה ועוד בהגדרות Chrome +‏הכפתור לניהול הגדרות האבטחה, מפעילים אותו כדי לנהל את הגלישה הבטוחה ועוד בהגדרות Chrome לטעון מחדש את האפליקציה? לניהול הסיסמאות… A2x4 @@ -3471,7 +3471,7 @@ פרטים נוספים: הודעה ממנהל המערכת: "" -‏לחצן 'לא אהבתי', מקישים על Enter כדי לפתוח טופס לשליחה של משוב מפורט על הסיבה לכך שלא אהבת את +‏כפתור 'לא אהבתי', לוחצים על Enter כדי לפתוח טופס לשליחה של משוב מפורט על הסיבה לכך שלא אהבת את המגש האחורי משאבים ותכנון לקריירה לא ניתן ליצור חיבור פרטי אל מפני שהתאריך והשעה () במחשב שלך שגויים. @@ -3566,7 +3566,7 @@ נתיב פרופיל ‏רכיבי handler של פרוטוקולים Labels (Security) -‏הלחצן לניהול קובצי cookie, מפעילים אותו כדי לנהל את ההעדפות לגבי קובצי cookie בהגדרות Chrome +‏הכפתור לניהול קובצי cookie, מפעילים אותו כדי לנהל את ההעדפות לגבי קובצי cookie בהגדרות Chrome אפליקציות ותוספים שהותקנו בפרופיל העבודה נבחרה האפשרות 'מחיקת הכתובת' עזרה בכתיבה @@ -3585,7 +3585,7 @@ {COUNT,plural, =0{‏קובצי cookie ייחסמו היום שוב}=1{‏קובצי cookie ייחסמו מחר שוב}one{‏יש עוד # ימים עד שקובצי cookie ייחסמו שוב}two{‏יש עוד יומיים עד שקובצי cookie ייחסמו שוב}other{‏יש עוד # ימים עד שקובצי cookie ייחסמו שוב}} שירותי ביגוד ‏(x מ"מ) -‏הלחצן לניהול הסנכרון, מפעילים אותו כדי לקבוע איזה מידע יסונכרן בהגדרות Chrome +‏הכפתור לניהול הסנכרון, מפעילים אותו כדי לקבוע איזה מידע יסונכרן בהגדרות Chrome למידע נוסף על בעיה זו. ‏המשחק Dino, צריך להקיש על מקש הרווח כדי לשחק חשבון בענן @@ -3660,7 +3660,7 @@ ‏האם להסיר את פרטי כרטיס האשראי מ-Chrome? שחור ציוד לספורט חורף -‏הלחצן 'הסרת ההצעה', יש ללחוץ על Enter כדי להסיר את ההצעה הזו +‏הכפתור 'הסרת ההצעה', יש ללחוץ על Enter כדי להסיר את ההצעה הזו טלפונים ניידים ‏ניתן לשלם במהירות באתרים ובאפליקציות בכל המכשירים באמצעות כרטיסים ששמרת ב-Google. משתנה לא ידוע '' בהגדרות האישיות המנוהלות של ''. @@ -3730,7 +3730,7 @@ רוגבי בדיוק ביקרת כאן Metal -‏לחצן למחיקת נתוני הגלישה, מופעל כדי למחוק את היסטוריית הגלישה, קובצי ה-Cookie, המטמון ועוד בהגדרות של Chrome +‏כפתור למחיקת נתוני הגלישה, מופעל כדי למחוק את היסטוריית הגלישה, קובצי ה-Cookie, המטמון ועוד בהגדרות של Chrome {0,plural, =1{הקובץ נחסם מסיבה שקשורה למדיניות}one{ קבצים נחסמו מסיבות שקשורות למדיניות}two{ קבצים נחסמו מסיבות שקשורות למדיניות}other{ קבצים נחסמו מסיבות שקשורות למדיניות}} שימוש באמצעי התשלום ששמרת למילוי טופסי תשלום זמן קצוב לתפוגה של ניסיון חוזר @@ -3867,7 +3867,7 @@ (32 סיביות) ‏12x14 אינץ' (EDP – אירופה) קיצור הדרך לא יכול להיות ריק -הלחצן לניהול מנועי חיפוש, מפעילים אותו כדי לנהל את מנוע החיפוש שמוגדר כברירת מחדל ואת החיפוש באתרים +הכפתור לניהול מנועי חיפוש, מפעילים אותו כדי לנהל את מנוע החיפוש שמוגדר כברירת מחדל ואת החיפוש באתרים צריך לטעון מחדש את הדף הזה כדי להחיל את ההגדרות המעודכנות על האתר הזה הידוק קצוות בחלק העליון ביצוע בקשה פנים-אל-פנים @@ -3905,7 +3905,7 @@ סוכני נסיעות ושירותים לנסיעות , לוחצים על Tab ואז על Enter כדי להגדיר את Chrome כדפדפן ברירת המחדל של המערכת מגש 15 -‏הלחצן להרצת בדיקת אבטחה ב-Chrome, מפעילים אותו כדי להריץ בדיקת אבטחה בהגדרות Chrome +‏הכפתור להרצת בדיקת אבטחה ב-Chrome, מפעילים אותו כדי להריץ בדיקת אבטחה בהגדרות Chrome ‏מילוי אוטומטי באמצעות AI , מקישים על Tab ואז על Enter כדי ליצור במהירות טופס חדש ב-Google Forms משחקים לקהל הרחב @@ -4028,7 +4028,7 @@ מתבצע תרגום של (לפי הזיהוי האוטומטי) ל ‏הכתובת הזו שמורה במכשיר הזה. כדי להשתמש בה בכל מוצרי Google, צריך לשמור אותה בחשבון Google שלך, . ממלאים את הכתובת ומקלידים פחות -‏הלחצן לניהול הגדרות הנגישות, מקישים על Enter כדי להתאים אישית את כלי הנגישות בהגדרות ChromeOS +‏הכפתור לניהול הגדרות הנגישות, לוחצים על Enter כדי להתאים אישית את כלי הנגישות בהגדרות ChromeOS יש להזין כתובת לחיוב האפליקציה הזו מיועדת לניידים תוכניות תעודה ותוכניות לימודיות בטלוויזיה @@ -4313,13 +4313,13 @@ גיליון האימות של פרטי הכניסה לתשלום המאובטח פתוח סגירה של בועת העזרה {COUNT,plural, =1{אמצעי תשלום אחד}one{‫# אמצעי תשלום}two{‫# אמצעי תשלום}other{‫# אמצעי תשלום}} -‏הלחצן ליצירת מצגת, מפעילים אותו כדי ליצור במהירות מצגת חדשה ב-Google Slides +‏הכפתור ליצירת מצגת, מפעילים אותו כדי ליצור במהירות מצגת חדשה ב-Google Slides מכסחות דשא יוגה ופילאטיס {0,plural, =1{להעביר את הקובץ הסודי?}one{להעביר את הקבצים הסודיים?}two{להעביר את הקבצים הסודיים?}other{להעביר את הקבצים הסודיים?}} Paper (Letterhead) A4 -‏הלחצן לתרגום הדף, מפעילים אותו כדי לתרגם את הדף הזה באמצעות Google Translate +‏הכפתור לתרגום הדף, מפעילים אותו כדי לתרגם את הדף הזה באמצעות Google Translate אופנועים &ביצוע מחדש של מחיקה Plastic (Glossy) @@ -4384,7 +4384,7 @@ שחייה מודעות שמפריעות התקרבות לתצוגה -‏הלחצן 'הסרת הצעה', יש ללחוץ על Enter כדי להסיר, +‏הכפתור 'הסרת הצעה', יש ללחוץ על Enter כדי להסיר, ‏8x10 אינץ' ‏הפעלה מחדש של Chrome ‏קוד אימות (CVC) לכרטיס הווירטואלי @@ -4531,14 +4531,14 @@ מסמך יחיד/גיליון חדש ‏מתבצע חיפוש של מכשירי Bluetooth... אישור השרת לא חוקי. -‏לחצן החלפת כרטיסיות, צריך להקיש על Enter כדי לעבור לכרטיסייה הזו +‏כפתור החלפת כרטיסיות, צריך ללחוץ על Enter כדי לעבור לכרטיסייה הזו ‏אין גישה לקובץ ה-PDF הזה. מתבצע חילוץ טקסט באמצעות AI מבית Google. ‏ניהול התשלומים ופרטי כרטיס האשראי בהגדרות Chrome קבלת התראות באימייל על הנחות באתר כלשהו Google Docs משתמש בפרוטוקול שאינו נתמך. יש לבדוק את הקוד ב ולנסות שוב -‏הלחצן להגדרת Chrome כדפדפן ברירת המחדל, מפעילים אותו כדי להגדיר את Chrome כדפדפן ברירת המחדל של המערכת +‏הכפתור להגדרת Chrome כדפדפן ברירת המחדל, מפעילים אותו כדי להגדיר את Chrome כדפדפן ברירת המחדל של המערכת נושאים מלפני יותר מ-4 שבועות נמחקים באופן אוטומטי ניקוב בפינה השמאלית התחתונה Metal (Matte) diff -Nru chromium-132.0.6834.110/components/strings/components_strings_vi.xtb chromium-132.0.6834.159/components/strings/components_strings_vi.xtb --- chromium-132.0.6834.110/components/strings/components_strings_vi.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/components_strings_vi.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -2937,7 +2937,7 @@ Phần mềm đa phương tiện Không thể truy cập . Địa chỉ này sẽ bị xoá khỏi thiết bị hiện tại cũng như các thiết bị đã đăng nhập khác -Ngân hàng của bạn hiện không hỗ trợ thẻ ảo cho phương thức thanh toán này nhưng bạn vẫn có thể thanh toán trực tuyến bằng . +Ngân hàng của bạn hiện không hỗ trợ thẻ ảo cho phương thức thanh toán này nhưng bạn vẫn có thể thanh toán trực tuyến bằng thẻ . Giấy nền trơn Địa điểm được nêu tên Trang web hiện không khả dụng diff -Nru chromium-132.0.6834.110/components/strings/privacy_sandbox_strings_fr.xtb chromium-132.0.6834.159/components/strings/privacy_sandbox_strings_fr.xtb --- chromium-132.0.6834.110/components/strings/privacy_sandbox_strings_fr.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/components/strings/privacy_sandbox_strings_fr.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -1,7 +1,7 @@ -Chrome se base sur votre historique de navigation récent pour déterminer les thèmes qui vous intéressent +Chrome relève les thèmes qui vous intéressent grâce à votre historique de navigation Lorsque vous êtes connecté à Chrome, ce paramètre contribue à préserver la confidentialité de votre adresse IP. Si Chrome soupçonne un site de vous suivre, une partie de votre trafic peut être envoyée via des serveurs de confidentialité. Règles de confidentialité de Google Chromium se base sur votre historique de navigation récent pour déterminer les thèmes qui vous intéressent diff -Nru chromium-132.0.6834.110/content/browser/web_contents/web_contents_impl.cc chromium-132.0.6834.159/content/browser/web_contents/web_contents_impl.cc --- chromium-132.0.6834.110/content/browser/web_contents/web_contents_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/content/browser/web_contents/web_contents_impl.cc 2025-01-27 17:37:37.000000000 +0000 @@ -2111,14 +2111,16 @@ } void WebContentsImpl::ResetAccessibility() { - // In contrast to the above, do not bother with frames in the back-forward - // cache since the reset is intended to generate new trees for observers of - // active frames. - GetPrimaryMainFrame()->ForEachRenderFrameHostIncludingSpeculative( + // Reset accessibility for all frames in this tree and inner trees, including + // speculative frame hosts and those in the back-forward cache. See comment in + // `SetAccessibilityMode()` for more details. + ForEachRenderFrameHostIncludingSpeculativeWithAction( [this](RenderFrameHostImpl* frame_host) { if (WebContentsImpl::FromRenderFrameHostImpl(frame_host) == this) { frame_host->AccessibilityReset(); + return FrameIterationAction::kContinue; } + return FrameIterationAction::kSkipChildren; }); } diff -Nru chromium-132.0.6834.110/debian/changelog chromium-132.0.6834.159/debian/changelog --- chromium-132.0.6834.110/debian/changelog 2025-01-22 21:36:45.000000000 +0000 +++ chromium-132.0.6834.159/debian/changelog 2025-01-29 01:26:06.000000000 +0000 @@ -1,3 +1,21 @@ +chromium (132.0.6834.159-1~deb12u1) bookworm-security; urgency=high + + [ Andres Salomon ] + * New upstream security release. + - CVE-2025-0762: Use after free in DevTools. Reported by Sakana.S. + + [ Daniel Richard G. ] + * d/copyright: Sort the list of Files-Excluded: entries, remove a few + that are no longer needed, and consolidate some others with brackets. + * d/rules: + - Use simple assignments for variables defined using $(shell ...) + to avoid recursive-expansion issues with GNU Make 4.4.1. + - Download the upstream lite tarball instead of the regular one now + that the former has everything we need. + - Delete empty directories when making the orig-source tarball. + + -- Andres Salomon Tue, 28 Jan 2025 20:26:06 -0500 + chromium (132.0.6834.110-1~deb12u1) bookworm-security; urgency=high [ Andres Salomon ] diff -Nru chromium-132.0.6834.110/debian/copyright chromium-132.0.6834.159/debian/copyright --- chromium-132.0.6834.110/debian/copyright 2025-01-15 04:25:31.000000000 +0000 +++ chromium-132.0.6834.159/debian/copyright 2025-01-29 01:26:06.000000000 +0000 @@ -7,215 +7,201 @@ *.bincfg *.clang* *.class - *.git* - *.lib - *__pycache__ - *.pkg - *.mk - *.so *.dll *.exe *.exe.* *.fst + *.git* *.jar *.java + *.lib + *.mk *.mp4 *.msi - *.wasm *.ogg + *.orig *.otf *.out *.pbtxt + *.pkg *.po - *.pyc *.pyd + *.so *.tflite *.ttf + *.wasm *.webm *.zip - *.orig - *corpus - *corpora - *testdata - *config.sub *config.guess + *config.sub + *corpora + *corpus *jquery*.min.js - docs - ios - buildtools - build/linux/debian_bullseye_* - ui/chromeos/B* - ui/chromeos/D* - ui/chromeos/devicetype_utils.cc - ui/chromeos/f* - ui/chromeos/r* - ui/chromeos/s* - ui/chromeos/t* - ui/chromeos/ui_chromeos_strings* - ui/chromeos/user* + *testdata + android_webview base/mac base/test/data base/third_party/double_conversion + build/config/freetype/freetype.gni + build/linux/debian_bullseye_* + buildtools chrome/android + chrome/browser/android/examples + chrome/browser/resources/chromeos/accessibility/common/testing + chrome/browser/resources/chromeos/[lns]* + chrome/browser/resources/default_apps chrome/build + chrome/installer/gcapi* + chrome/installer/launcher_support + chrome/installer/linux chrome/installer/mac + chrome/installer/mini_installer + chrome/installer/setup chrome/installer/test chrome/installer/tools - chrome/installer/setup - chrome/installer/linux - chrome/installer/gcapi* - chrome/installer/mini_installer - chrome/installer/launcher_support chrome/utility/safe_browsing/rar_analyzer.* - chrome/browser/android/examples - chrome/browser/resources/chromeos/accessibility/common/testing - chrome/browser/resources/chromeos/s* - chrome/browser/resources/chromeos/l* - chrome/browser/resources/chromeos/n* - chrome/browser/resources/default_apps + components/drive/chromeos + components/test/android + components/test/data + content/browser/android + docs fuchsia* - net/data/cache_tests - tools/emacs - tools/luci-go - tools/android - tools/skia_goldctl - tools/perf/contrib - tools/perf/testdata - tools/perf/page_sets - tools/perf/measurements/test_data - tools/perf/page_sets/maps_perf_test - tools/perf/page_sets/tough_scheduling_cases/*.min.js - tools/page_cycler/acid3 - tools/resultdb/result_adapter - tools/resultdb/.versions/*.cipd_version - tools/win - tools/gn headless/test/data - content/browser/android - components/test/data - components/test/android - components/drive/chromeos + ios native_client* - android_webview + net/data/cache_tests + third_party/accessibility-audit/axs_testing.js + third_party/android* third_party/angle/src/third_party/libXNVCtrl - third_party/siso - third_party/opus + third_party/angle/third_party/VK-GL-CTS + third_party/angle/third_party/glmark2 + third_party/angle/third_party/rapidjson + third_party/apache-linux + third_party/apache-portable-runtime + third_party/apache-win32 + third_party/blink/manual_tests + third_party/blink/renderer/platform/testing/data + third_party/boringssl/src/crypto/cipher_extra/test + third_party/boringssl/src/third_party/wycheproof_testvectors + third_party/breakpad/breakpad/src/client/mac + third_party/catapult + third_party/checkstyle + third_party/chromevox/third_party/sre + third_party/crashpad/crashpad/handler/win third_party/dav1d + third_party/dawn/third_party/dxc + third_party/dawn/third_party/khronos/EGL-Registry/sdk + third_party/dawn/third_party/khronos/OpenGL-Registry/ABI/new.gif + third_party/dawn/third_party/khronos/OpenGL-Registry/extensions + third_party/dawn/third_party/khronos/OpenGL-Registry/specs + third_party/dawn/third_party/ninja + third_party/dawn/third_party/webgpu-cts + third_party/dawn/tools/golang + third_party/depot_tools/ninja* + third_party/devtools-frontend/src/node_modules/.bin + third_party/devtools-frontend/src/third_party/esbuild/esbuild + third_party/devtools-frontend/src/third_party/image_diff + third_party/dom_distiller_js/dist/js/domdistiller_wrapped.js + third_party/expat/src + third_party/ffmpeg/config* + third_party/ffmpeg/doc + third_party/ffmpeg/fftools + third_party/ffmpeg/tests + third_party/ffmpeg/tools third_party/flac - third_party/harfbuzz-ng/src + third_party/fontconfig + third_party/freetype + third_party/google_input_tools/src/chrome/os/inputview/_locales/*.js third_party/harfbuzz-ng/harfbuzz.gni + third_party/harfbuzz-ng/src third_party/highway third_party/icu/source/data + third_party/instrumented_lib* third_party/libc++/src/test - third_party/llvm* third_party/libei - third_party/webgl - third_party/libpng third_party/libevent - third_party/libsecret - third_party/libxslt - third_party/freetype - build/config/freetype/freetype.gni - third_party/android* - third_party/lzma_sdk/bin - third_party/test_fonts/test_fonts* - third_party/test_fonts/README* - third_party/pyelftools - third_party/fontconfig - third_party/dawn/test - third_party/dawn/tools/golang - third_party/ninja - third_party/depot_tools/ninja* - third_party/dawn/third_party/ninja third_party/libjpeg.gni third_party/libjpeg_turbo - third_party/win_build_output - third_party/zlib/BUILD.gn - third_party/zlib/adler* - third_party/zlib/crc32* - third_party/zlib/deflate* - third_party/zlib/gzguts* - third_party/zlib/in* - third_party/zlib/trees* - third_party/zlib/z* - third_party/zlib/patches - third_party/skia/site/docs/user/api - third_party/skia/platform_tools - third_party/skia/resources/icc_profiles - third_party/skia/tools/perf-canvaskit-puppeteer/path_translate_assets/car.svg - third_party/ffmpeg/doc - third_party/ffmpeg/tests - third_party/ffmpeg/tools - third_party/ffmpeg/fftools - third_party/ffmpeg/config* - third_party/openh264/src - third_party/openh264/BUILD.gn - third_party/expat/src - third_party/unrar - third_party/apache-linux - third_party/checkstyle - third_party/speedometer/v3.0 - third_party/swiftshader/tests - third_party/swiftshader/third_party/SPIRV-Tools/tools - third_party/swiftshader/third_party/llvm-10.0 - third_party/apache-win32 - third_party/apache-portable-runtime - third_party/instrumented_lib* - third_party/angle/third_party/glmark2 - third_party/angle/third_party/rapidjson - third_party/angle/third_party/VK-GL-CTS - third_party/chromevox/third_party/sre - third_party/crashpad/crashpad/handler/win - third_party/blink/renderer/platform/testing/data - third_party/blink/manual_tests - third_party/blink/perf_tests - third_party/google_input_tools/src/chrome/os/inputview/_locales/*.js - v8/third_party/colorama - v8/third_party/googletest + third_party/libphonenumber/dist/javascript/i18n/phonenumbers/metadata.js + third_party/libphonenumber/dist/javascript/i18n/phonenumbers/metadatalite.js + third_party/libpng + third_party/libsecret third_party/libusb - third_party/libxml/mac - third_party/libxml/linux - third_party/libxml/win32 third_party/libxml/BUILD.gn + third_party/libxml/linux + third_party/libxml/mac third_party/libxml/src + third_party/libxml/win32 + third_party/libxslt + third_party/llvm* + third_party/lzma_sdk/bin + third_party/nearby/src + third_party/ninja third_party/node/linux third_party/node/node_modules.tar.gz - third_party/node/node_modules/acorn third_party/node/node_modules/@rollup - third_party/node/node_modules/mocha/mocha.js - third_party/rust-* + third_party/node/node_modules/acorn third_party/node/node_modules/chai/chai.js + third_party/node/node_modules/mocha/mocha.js + third_party/openh264/BUILD.gn + third_party/openh264/src third_party/openscreen/src/buildtools - third_party/siso/siso - third_party/accessibility-audit/axs_testing.js - third_party/catapult - third_party/webgpu-cts/src - third_party/webrtc/sdk - third_party/webrtc/data - third_party/webrtc/examples + third_party/opus third_party/pdfium/third_party/libopenjpeg - third_party/breakpad/breakpad/src/client/mac - third_party/boringssl/src/crypto/cipher_extra/test - third_party/boringssl/src/third_party/wycheproof_testvectors - third_party/dom_distiller_js/dist/js/domdistiller_wrapped.js - third_party/devtools-frontend/src/third_party/image_diff - third_party/devtools-frontend/src/node_modules/.bin - third_party/libphonenumber/dist/javascript/i18n/phonenumbers/metadata.js - third_party/libphonenumber/dist/javascript/i18n/phonenumbers/metadatalite.js + third_party/pyelftools + third_party/rust-* + third_party/siso + third_party/siso/siso + third_party/skia/platform_tools + third_party/skia/resources/icc_profiles + third_party/skia/site/docs/user/api + third_party/skia/tools/perf-canvaskit-puppeteer/path_translate_assets/car.svg + third_party/speedometer/v3.0 + third_party/swiftshader/tests + third_party/swiftshader/third_party/SPIRV-Tools/tools + third_party/swiftshader/third_party/llvm-10.0 + third_party/test_fonts/README* third_party/tflite/src/tensorflow/examples/multibox_detector/data/surfers.jpg third_party/tflite/src/tensorflow/lite/experimental/acceleration/mini_benchmark/models/blazeface_mlkit_v1.tfl third_party/tflite/src/tensorflow/python - third_party/devtools-frontend/src/third_party/esbuild/esbuild - third_party/nearby/src - third_party/sqlite/src/test + third_party/unrar third_party/updater + third_party/webgl + third_party/webgpu-cts/src + third_party/webrtc/data + third_party/webrtc/examples + third_party/webrtc/sdk + third_party/win_build_output + third_party/zlib/BUILD.gn + third_party/zlib/adler* + third_party/zlib/crc32* + third_party/zlib/deflate* + third_party/zlib/gzguts* + third_party/zlib/in* + third_party/zlib/patches + third_party/zlib/trees* + third_party/zlib/z* third_party/zstd - third_party/dawn/third_party/dxc - third_party/dawn/third_party/khronos/OpenGL-Registry/ABI/new.gif - third_party/dawn/third_party/khronos/OpenGL-Registry/extensions - third_party/dawn/third_party/khronos/OpenGL-Registry/specs - third_party/dawn/third_party/khronos/EGL-Registry/sdk - third_party/dawn/third_party/webgpu-cts + tools/android + tools/emacs + tools/gn + tools/luci-go + tools/page_cycler/acid3 + tools/perf/contrib + tools/perf/measurements/test_data + tools/perf/page_sets + tools/perf/page_sets/maps_perf_test + tools/perf/page_sets/tough_scheduling_cases/*.min.js + tools/resultdb/.versions/*.cipd_version + tools/resultdb/result_adapter + tools/skia_goldctl + tools/win + ui/chromeos/[BDfrst]* + ui/chromeos/devicetype_utils.cc + ui/chromeos/ui_chromeos_strings* + ui/chromeos/user* + v8/third_party/colorama + v8/third_party/googletest Files: * diff -Nru chromium-132.0.6834.110/debian/rules chromium-132.0.6834.159/debian/rules --- chromium-132.0.6834.110/debian/rules 2025-01-14 07:10:09.000000000 +0000 +++ chromium-132.0.6834.159/debian/rules 2025-01-29 01:26:06.000000000 +0000 @@ -20,8 +20,8 @@ # initial flags from dpkg-buildflags export DEB_CXXFLAGS_MAINT_STRIP=-g -export CXXFLAGS=$(shell dpkg-buildflags --get CXXFLAGS) -export LDFLAGS=$(shell dpkg-buildflags --get LDFLAGS) +export CXXFLAGS:=$(shell dpkg-buildflags --get CXXFLAGS) +export LDFLAGS:=$(shell dpkg-buildflags --get LDFLAGS) # more verbose linker output export LDFLAGS+=-Wl,--stats @@ -43,11 +43,11 @@ endif # disable clang plugins -defines=clang_use_chrome_plugins=false +defines:=clang_use_chrome_plugins=false # use system rust export RUSTC_BOOTSTRAP=1 -export CLANG_MVERS=$(shell $(CC) --version | sed -n 's/.* clang version //p' | cut -d. -f1) +export CLANG_MVERS:=$(shell $(CC) --version | sed -n 's/.* clang version //p' | cut -d. -f1) rust_sysroot=/usr defines+=rust_sysroot_absolute=\"$(rust_sysroot)\" defines+=rust_bindgen_root=\"$(CURDIR)/debian/bindgen/root/usr\" @@ -60,7 +60,8 @@ defines+=custom_toolchain=\"//build/toolchain/linux/unbundle:default\" # set the appropriate cpu architecture -DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH) +DEB_HOST_ARCH_value := $(shell dpkg-architecture -qDEB_HOST_ARCH) +DEB_HOST_ARCH ?= $(DEB_HOST_ARCH_value) ifeq (i386,$(DEB_HOST_ARCH)) defines+=host_cpu=\"x86\" use_vaapi=true endif @@ -218,9 +219,9 @@ ###################### upstream source downloading ############################ url=https://gsdview.appspot.com/chromium-browser-official -version=$(shell dpkg-parsechangelog -S Version | sed s/-.*//) +version:=$(shell dpkg-parsechangelog -S Version | sed s/-.*//) extract=chromium-$(version) -tarfile=$(extract).tar +tarfile=$(extract)-lite.tar tarball=$(tarfile).xz debvers=../chromium_$(version) seconds=$(debvers).seconds @@ -242,6 +243,7 @@ @$(print_elapsed); echo tar --exclude-from=$(debvers).excludes -xf ../$(tarball) rm -f $(debvers).excludes + find $(extract) -depth -type d -empty -delete @$(print_elapsed); echo cd $(extract) && ../debian/scripts/check-upstream chmod -R u+w $(extract) diff -Nru chromium-132.0.6834.110/gpu/config/gpu_lists_version.h chromium-132.0.6834.159/gpu/config/gpu_lists_version.h --- chromium-132.0.6834.110/gpu/config/gpu_lists_version.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/gpu/config/gpu_lists_version.h 2025-01-27 17:37:37.000000000 +0000 @@ -3,6 +3,6 @@ #ifndef GPU_CONFIG_GPU_LISTS_VERSION_H_ #define GPU_CONFIG_GPU_LISTS_VERSION_H_ -#define GPU_LISTS_VERSION "df453a35f099772fdb954e33551388add2ca3cde" +#define GPU_LISTS_VERSION "2d77d3fc4452661469b78f115e0aed4d71269739" #endif // GPU_CONFIG_GPU_LISTS_VERSION_H_ diff -Nru chromium-132.0.6834.110/media/cast/common/encoded_frame.h chromium-132.0.6834.159/media/cast/common/encoded_frame.h --- chromium-132.0.6834.110/media/cast/common/encoded_frame.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/common/encoded_frame.h 2025-01-27 17:37:37.000000000 +0000 @@ -12,7 +12,8 @@ #include "media/cast/common/rtp_time.h" #include "third_party/openscreen/src/cast/streaming/public/encoded_frame.h" -namespace media::cast { +namespace media { +namespace cast { // A combination of metadata and data for one encoded frame. This can contain // audio data or video data or other. @@ -61,6 +62,7 @@ base::HeapArray data; }; -} // namespace media::cast +} // namespace cast +} // namespace media #endif // MEDIA_CAST_COMMON_ENCODED_FRAME_H_ diff -Nru chromium-132.0.6834.110/media/cast/encoding/external_video_encoder.cc chromium-132.0.6834.159/media/cast/encoding/external_video_encoder.cc --- chromium-132.0.6834.110/media/cast/encoding/external_video_encoder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/external_video_encoder.cc 2025-01-27 17:37:37.000000000 +0000 @@ -90,6 +90,9 @@ // The reference time for this frame. const base::TimeTicks reference_time; + // The callback to run when the result is ready. + VideoEncoder::FrameEncodedCallback frame_encoded_callback; + // The target encode bit rate. const int target_bit_rate; @@ -101,9 +104,11 @@ InProgressExternalVideoFrameEncode( scoped_refptr v_frame, base::TimeTicks r_time, + VideoEncoder::FrameEncodedCallback callback, int bit_rate) : video_frame(std::move(v_frame)), reference_time(r_time), + frame_encoded_callback(std::move(callback)), target_bit_rate(bit_rate), start_time(base::TimeTicks::Now()) {} }; @@ -123,13 +128,11 @@ const scoped_refptr& encoder_task_runner, std::unique_ptr vea, double max_frame_rate, - EncoderStatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb) + EncoderStatusChangeCallback status_change_cb) : cast_environment_(cast_environment), task_runner_(encoder_task_runner), max_frame_rate_(max_frame_rate), status_change_cb_(std::move(status_change_cb)), - output_cb_(std::move(output_cb)), video_encode_accelerator_(std::move(vea)), encoder_active_(false), next_frame_id_(FrameId::first()), @@ -202,14 +205,17 @@ free_input_buffer_index_.push_back(index); } - void EncodeVideoFrame(scoped_refptr video_frame, - base::TimeTicks reference_time, - bool key_frame_requested) { + void EncodeVideoFrame( + scoped_refptr video_frame, + base::TimeTicks reference_time, + bool key_frame_requested, + VideoEncoder::FrameEncodedCallback frame_encoded_callback) { TRACE_EVENT0("media", "ExternalVideoEncoder::EncodeVideoFrame"); DCHECK(task_runner_->RunsTasksInCurrentSequence()); in_progress_frame_encodes_.push_back(InProgressExternalVideoFrameEncode( - video_frame, reference_time, requested_bit_rate_)); + video_frame, reference_time, std::move(frame_encoded_callback), + requested_bit_rate_)); if (!encoder_active_) { AbortLatestEncodeAttemptDueToErrors(); @@ -350,8 +356,11 @@ if (metadata.dropped_frame()) { CHECK(key_frame_encountered_); // The encoder drops a frame. - cast_environment_->PostTask(CastEnvironment::MAIN, FROM_HERE, - base::BindOnce(output_cb_, nullptr)); + InProgressExternalVideoFrameEncode& request = + in_progress_frame_encodes_.front(); + cast_environment_->PostTask( + CastEnvironment::MAIN, FROM_HERE, + base::BindOnce(std::move(request.frame_encoded_callback), nullptr)); in_progress_frame_encodes_.pop_front(); if (encoder_active_) { video_encode_accelerator_->UseOutputBitstreamBuffer( @@ -489,7 +498,8 @@ cast_environment_->Clock()->NowTicks(); cast_environment_->PostTask( CastEnvironment::MAIN, FROM_HERE, - base::BindOnce(output_cb_, std::move(encoded_frame))); + base::BindOnce(std::move(request.frame_encoded_callback), + std::move(encoded_frame))); in_progress_frame_encodes_.pop_front(); } else { @@ -531,7 +541,9 @@ std::unique_ptr no_result(nullptr); cast_environment_->PostTask( CastEnvironment::MAIN, FROM_HERE, - base::BindOnce(output_cb_, std::move(no_result))); + base::BindOnce( + std::move(in_progress_frame_encodes_.back().frame_encoded_callback), + std::move(no_result))); in_progress_frame_encodes_.pop_back(); } @@ -605,7 +617,6 @@ const double max_frame_rate_; // Must be run on MAIN thread. const EncoderStatusChangeCallback status_change_cb_; - FrameEncodedCallback output_cb_; std::unique_ptr video_encode_accelerator_; bool encoder_active_; FrameId next_frame_id_; @@ -660,11 +671,9 @@ const gfx::Size& frame_size, FrameId first_frame_id, StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb, const CreateVideoEncodeAcceleratorCallback& create_vea_cb) : cast_environment_(cast_environment), metrics_provider_(metrics_provider), - output_cb_(std::move(output_cb)), frame_size_(frame_size), bit_rate_(video_config.start_bitrate) { DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN)); @@ -673,7 +682,7 @@ DCHECK(status_change_cb); DCHECK(create_vea_cb); DCHECK_GT(bit_rate_, 0); - CHECK(output_cb_); + create_vea_cb.Run( base::BindOnce(&ExternalVideoEncoder::OnCreateVideoEncodeAccelerator, weak_factory_.GetWeakPtr(), video_config, first_frame_id, @@ -703,17 +712,20 @@ bool ExternalVideoEncoder::EncodeVideoFrame( scoped_refptr video_frame, - base::TimeTicks reference_time) { + base::TimeTicks reference_time, + FrameEncodedCallback frame_encoded_callback) { DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN)); + DCHECK(!frame_encoded_callback.is_null()); if (!client_ || video_frame->visible_rect().size() != frame_size_) { return false; } client_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&VEAClientImpl::EncodeVideoFrame, client_, - std::move(video_frame), reference_time, - key_frame_requested_)); + FROM_HERE, + base::BindOnce(&VEAClientImpl::EncodeVideoFrame, client_, + std::move(video_frame), reference_time, + key_frame_requested_, std::move(frame_encoded_callback))); key_frame_requested_ = false; return true; } @@ -810,7 +822,7 @@ DCHECK(!client_); client_ = new VEAClientImpl(cast_environment_, encoder_task_runner, std::move(vea), video_config.max_frame_rate, - std::move(wrapped_status_change_cb), output_cb_); + std::move(wrapped_status_change_cb)); metrics_provider_->Initialize(codec_profile, frame_size_, /*is_hardware_encoder=*/true); client_->task_runner()->PostTask( @@ -824,13 +836,11 @@ const FrameSenderConfig& video_config, std::unique_ptr metrics_provider, StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb, const CreateVideoEncodeAcceleratorCallback& create_vea_cb) : SizeAdaptableVideoEncoderBase(cast_environment, video_config, std::move(metrics_provider), - std::move(status_change_cb), - std::move(output_cb)), + std::move(status_change_cb)), create_vea_cb_(create_vea_cb) {} SizeAdaptableExternalVideoEncoder::~SizeAdaptableExternalVideoEncoder() = @@ -840,8 +850,7 @@ SizeAdaptableExternalVideoEncoder::CreateEncoder() { return std::make_unique( cast_environment(), video_config(), metrics_provider(), frame_size(), - next_frame_id(), CreateEncoderStatusChangeCallback(), - CreateFrameEncodedCallback(), create_vea_cb_); + next_frame_id(), CreateEncoderStatusChangeCallback(), create_vea_cb_); } QuantizerEstimator::QuantizerEstimator() = default; diff -Nru chromium-132.0.6834.110/media/cast/encoding/external_video_encoder.h chromium-132.0.6834.159/media/cast/encoding/external_video_encoder.h --- chromium-132.0.6834.110/media/cast/encoding/external_video_encoder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/external_video_encoder.h 2025-01-27 17:37:37.000000000 +0000 @@ -42,7 +42,6 @@ const gfx::Size& frame_size, FrameId first_frame_id, StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb, const CreateVideoEncodeAcceleratorCallback& create_vea_cb); ExternalVideoEncoder(const ExternalVideoEncoder&) = delete; @@ -52,7 +51,8 @@ // VideoEncoder implementation. bool EncodeVideoFrame(scoped_refptr video_frame, - base::TimeTicks reference_time) final; + base::TimeTicks reference_time, + FrameEncodedCallback frame_encoded_callback) final; void SetBitRate(int new_bit_rate) final; void GenerateKeyFrame() final; @@ -79,8 +79,6 @@ raw_ref metrics_provider_; - FrameEncodedCallback output_cb_; - // The size of the visible region of the video frames to be encoded. const gfx::Size frame_size_; @@ -104,7 +102,6 @@ const FrameSenderConfig& video_config, std::unique_ptr metrics_provider, StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb, const CreateVideoEncodeAcceleratorCallback& create_vea_cb); SizeAdaptableExternalVideoEncoder(const SizeAdaptableExternalVideoEncoder&) = diff -Nru chromium-132.0.6834.110/media/cast/encoding/size_adaptable_video_encoder_base.cc chromium-132.0.6834.159/media/cast/encoding/size_adaptable_video_encoder_base.cc --- chromium-132.0.6834.110/media/cast/encoding/size_adaptable_video_encoder_base.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/size_adaptable_video_encoder_base.cc 2025-01-27 17:37:37.000000000 +0000 @@ -20,16 +20,13 @@ const scoped_refptr& cast_environment, const FrameSenderConfig& video_config, std::unique_ptr metrics_provider, - StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb) + StatusChangeCallback status_change_cb) : cast_environment_(cast_environment), video_config_(video_config), metrics_provider_(std::move(metrics_provider)), status_change_cb_(std::move(status_change_cb)), - output_cb_(std::move(output_cb)), frames_in_encoder_(0), next_frame_id_(FrameId::first()) { - CHECK(output_cb_); cast_environment_->PostTask( CastEnvironment::MAIN, FROM_HERE, base::BindOnce(status_change_cb_, STATUS_INITIALIZED)); @@ -41,7 +38,8 @@ bool SizeAdaptableVideoEncoderBase::EncodeVideoFrame( scoped_refptr video_frame, - base::TimeTicks reference_time) { + base::TimeTicks reference_time, + FrameEncodedCallback frame_encoded_callback) { DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN)); const gfx::Size frame_size = video_frame->visible_rect().size(); @@ -61,8 +59,11 @@ return false; } - const bool is_frame_accepted = - encoder_->EncodeVideoFrame(std::move(video_frame), reference_time); + const bool is_frame_accepted = encoder_->EncodeVideoFrame( + std::move(video_frame), reference_time, + base::BindOnce(&SizeAdaptableVideoEncoderBase::OnEncodedVideoFrame, + weak_factory_.GetWeakPtr(), + std::move(frame_encoded_callback))); if (is_frame_accepted) { ++frames_in_encoder_; } @@ -99,14 +100,6 @@ weak_factory_.GetWeakPtr()); } -VideoEncoder::FrameEncodedCallback -SizeAdaptableVideoEncoderBase::CreateFrameEncodedCallback() { - DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN)); - return base::BindRepeating( - &SizeAdaptableVideoEncoderBase::OnEncodedVideoFrame, - weak_factory_.GetWeakPtr()); -} - void SizeAdaptableVideoEncoderBase::OnEncoderReplaced( VideoEncoder* replacement_encoder) {} @@ -161,6 +154,7 @@ } void SizeAdaptableVideoEncoderBase::OnEncodedVideoFrame( + FrameEncodedCallback frame_encoded_callback, std::unique_ptr encoded_frame) { DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN)); --frames_in_encoder_; @@ -171,7 +165,7 @@ metrics_provider_->IncrementEncodedFrameCount(); } - output_cb_.Run(std::move(encoded_frame)); + std::move(frame_encoded_callback).Run(std::move(encoded_frame)); } } // namespace cast diff -Nru chromium-132.0.6834.110/media/cast/encoding/size_adaptable_video_encoder_base.h chromium-132.0.6834.159/media/cast/encoding/size_adaptable_video_encoder_base.h --- chromium-132.0.6834.110/media/cast/encoding/size_adaptable_video_encoder_base.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/size_adaptable_video_encoder_base.h 2025-01-27 17:37:37.000000000 +0000 @@ -36,8 +36,7 @@ const scoped_refptr& cast_environment, const FrameSenderConfig& video_config, std::unique_ptr metrics_provider, - StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb); + StatusChangeCallback status_change_cb); SizeAdaptableVideoEncoderBase(const SizeAdaptableVideoEncoderBase&) = delete; SizeAdaptableVideoEncoderBase& operator=( @@ -47,7 +46,8 @@ // VideoEncoder implementation. bool EncodeVideoFrame(scoped_refptr video_frame, - base::TimeTicks reference_time) final; + base::TimeTicks reference_time, + FrameEncodedCallback frame_encoded_callback) final; void SetBitRate(int new_bit_rate) final; void GenerateKeyFrame() final; void EmitFrames() final; @@ -68,9 +68,6 @@ // be called by the most-recent encoder. StatusChangeCallback CreateEncoderStatusChangeCallback(); - // Returns a callback that calls OnEncodedVideoFrame(). - FrameEncodedCallback CreateFrameEncodedCallback(); - // Overridden by subclasses to create a new encoder instance that handles // frames of the size specified by |frame_size()|. virtual std::unique_ptr CreateEncoder() = 0; @@ -93,7 +90,8 @@ void OnEncoderStatusChange(OperationalStatus status); // Called by the |encoder_| with the next EncodedFrame. - void OnEncodedVideoFrame(std::unique_ptr encoded_frame); + void OnEncodedVideoFrame(FrameEncodedCallback frame_encoded_callback, + std::unique_ptr encoded_frame); const scoped_refptr cast_environment_; @@ -106,9 +104,6 @@ // Run whenever the underlying encoder reports a status change. const StatusChangeCallback status_change_cb_; - // Run whenever a frame is encoded. - const FrameEncodedCallback output_cb_; - // The underlying platform video encoder and the frame size it expects. std::unique_ptr encoder_; gfx::Size frame_size_; diff -Nru chromium-132.0.6834.110/media/cast/encoding/video_encoder.cc chromium-132.0.6834.159/media/cast/encoding/video_encoder.cc --- chromium-132.0.6834.110/media/cast/encoding/video_encoder.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/video_encoder.cc 2025-01-27 17:37:37.000000000 +0000 @@ -19,20 +19,19 @@ const FrameSenderConfig& video_config, std::unique_ptr metrics_provider, StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb, const CreateVideoEncodeAcceleratorCallback& create_vea_cb) { // If the system provides a hardware-accelerated encoder, use it. if (video_config.use_hardware_encoder) { - return std::make_unique( + return base::WrapUnique(new SizeAdaptableExternalVideoEncoder( cast_environment, video_config, std::move(metrics_provider), - std::move(status_change_cb), std::move(output_cb), create_vea_cb); + std::move(status_change_cb), create_vea_cb)); } // Otherwise we must have a software configuration. DCHECK(encoding_support::IsSoftwareEnabled(video_config.video_codec())); - return std::make_unique( - cast_environment, video_config, std::move(metrics_provider), - status_change_cb, std::move(output_cb)); + return base::WrapUnique( + new VideoEncoderImpl(cast_environment, video_config, + std::move(metrics_provider), status_change_cb)); } void VideoEncoder::EmitFrames() {} diff -Nru chromium-132.0.6834.110/media/cast/encoding/video_encoder.h chromium-132.0.6834.159/media/cast/encoding/video_encoder.h --- chromium-132.0.6834.110/media/cast/encoding/video_encoder.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/video_encoder.h 2025-01-27 17:37:37.000000000 +0000 @@ -28,7 +28,7 @@ public: // Callback used to deliver an encoded frame on the Cast MAIN thread. using FrameEncodedCallback = - base::RepeatingCallback)>; + base::OnceCallback)>; // Creates a VideoEncoder instance from the given |video_config| and based on // the current platform's hardware/library support; or null if no @@ -42,17 +42,18 @@ const FrameSenderConfig& video_config, std::unique_ptr metrics_provider, StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb, const CreateVideoEncodeAcceleratorCallback& create_vea_cb); virtual ~VideoEncoder() {} // If true is returned, the Encoder has accepted the request and will process - // it asynchronously, running |output_cb_| on the MAIN + // it asynchronously, running |frame_encoded_callback| on the MAIN // CastEnvironment thread with the result. If false is returned, nothing // happens and the callback will not be run. - virtual bool EncodeVideoFrame(scoped_refptr video_frame, - base::TimeTicks reference_time) = 0; + virtual bool EncodeVideoFrame( + scoped_refptr video_frame, + base::TimeTicks reference_time, + FrameEncodedCallback frame_encoded_callback) = 0; // Inform the encoder about the new target bit rate. virtual void SetBitRate(int new_bit_rate) = 0; diff -Nru chromium-132.0.6834.110/media/cast/encoding/video_encoder_impl.cc chromium-132.0.6834.159/media/cast/encoding/video_encoder_impl.cc --- chromium-132.0.6834.110/media/cast/encoding/video_encoder_impl.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/video_encoder_impl.cc 2025-01-27 17:37:37.000000000 +0000 @@ -39,7 +39,7 @@ scoped_refptr video_frame, base::TimeTicks reference_time, const VideoEncoderImpl::CodecDynamicConfig& dynamic_config, - VideoEncoderImpl::FrameEncodedCallback output_cb) { + VideoEncoderImpl::FrameEncodedCallback frame_encoded_callback) { DCHECK(environment->CurrentlyOn(CastEnvironment::VIDEO)); if (dynamic_config.key_frame_requested) { encoder->GenerateKeyFrame(); @@ -53,7 +53,8 @@ encoder->Encode(std::move(video_frame), reference_time, encoded_frame.get()); encoded_frame->encode_completion_time = environment->Clock()->NowTicks(); environment->PostTask(CastEnvironment::MAIN, FROM_HERE, - base::BindOnce(output_cb, std::move(encoded_frame))); + base::BindOnce(std::move(frame_encoded_callback), + std::move(encoded_frame))); } } // namespace @@ -61,14 +62,11 @@ scoped_refptr cast_environment, const FrameSenderConfig& video_config, std::unique_ptr metrics_provider, - StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb) + StatusChangeCallback status_change_cb) : cast_environment_(cast_environment) { CHECK(cast_environment_->HasVideoThread()); - CHECK(status_change_cb); - CHECK(output_cb); + DCHECK(status_change_cb); - output_cb_ = std::move(output_cb); VideoCodec codec = video_config.video_codec(); if (codec == VideoCodec::kVP8 || codec == VideoCodec::kVP9) { encoder_ = @@ -116,15 +114,17 @@ bool VideoEncoderImpl::EncodeVideoFrame( scoped_refptr video_frame, - base::TimeTicks reference_time) { + base::TimeTicks reference_time, + FrameEncodedCallback frame_encoded_callback) { DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN)); DCHECK(!video_frame->visible_rect().IsEmpty()); + DCHECK(!frame_encoded_callback.is_null()); cast_environment_->PostTask( CastEnvironment::VIDEO, FROM_HERE, base::BindOnce(&EncodeVideoFrameOnEncoderThread, cast_environment_, encoder_.get(), std::move(video_frame), reference_time, - dynamic_config_, output_cb_)); + dynamic_config_, std::move(frame_encoded_callback))); dynamic_config_.key_frame_requested = false; return true; diff -Nru chromium-132.0.6834.110/media/cast/encoding/video_encoder_impl.h chromium-132.0.6834.159/media/cast/encoding/video_encoder_impl.h --- chromium-132.0.6834.110/media/cast/encoding/video_encoder_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/video_encoder_impl.h 2025-01-27 17:37:37.000000000 +0000 @@ -35,8 +35,7 @@ scoped_refptr cast_environment, const FrameSenderConfig& video_config, std::unique_ptr metrics_provider, - StatusChangeCallback status_change_cb, - FrameEncodedCallback output_cb); + StatusChangeCallback status_change_cb); VideoEncoderImpl(const VideoEncoderImpl&) = delete; VideoEncoderImpl& operator=(const VideoEncoderImpl&) = delete; @@ -45,14 +44,14 @@ // VideoEncoder implementation. bool EncodeVideoFrame(scoped_refptr video_frame, - base::TimeTicks reference_time) final; + base::TimeTicks reference_time, + FrameEncodedCallback frame_encoded_callback) final; void SetBitRate(int new_bit_rate) final; void GenerateKeyFrame() final; private: scoped_refptr cast_environment_; CodecDynamicConfig dynamic_config_; - FrameEncodedCallback output_cb_; // This member belongs to the video encoder thread. It must not be // dereferenced on the main thread. We manage the lifetime of this member diff -Nru chromium-132.0.6834.110/media/cast/encoding/video_encoder_unittest.cc chromium-132.0.6834.159/media/cast/encoding/video_encoder_unittest.cc --- chromium-132.0.6834.110/media/cast/encoding/video_encoder_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/encoding/video_encoder_unittest.cc 2025-01-27 17:37:37.000000000 +0000 @@ -36,7 +36,8 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/openscreen/src/cast/streaming/public/encoded_frame.h" -namespace media::cast { +namespace media { +namespace cast { class VideoEncoderTest : public ::testing::TestWithParam> { @@ -86,7 +87,7 @@ RunTasksAndAdvanceClock(); } - void CreateEncoder(VideoEncoder::FrameEncodedCallback output_cb) { + void CreateEncoder() { ASSERT_EQ(STATUS_UNINITIALIZED, operational_status_); codec_params_->max_number_of_video_buffers_used = 1; video_encoder_ = VideoEncoder::Create( @@ -94,7 +95,6 @@ std::make_unique(), base::BindRepeating(&VideoEncoderTest::OnOperationalStatusChange, base::Unretained(this)), - std::move(output_cb), base::BindRepeating( &FakeVideoEncodeAcceleratorFactory::CreateVideoEncodeAccelerator, base::Unretained(vea_factory_.get()))); @@ -184,6 +184,7 @@ // complete encode/decode cycle of varied frame sizes that actually checks the // frame content. TEST_P(VideoEncoderTest, EncodesVariedFrameSizes) { + CreateEncoder(); SetVEAFactoryAutoRespond(true); ExpectVEAResponseForExternalVideoEncoder(0); @@ -207,23 +208,10 @@ base::WeakPtrFactory encoded_frames_weak_factory( &encoded_frames); - CreateEncoder(base::BindRepeating( - [](base::WeakPtr encoded_frames, - std::unique_ptr encoded_frame) { - if (encoded_frames) { - encoded_frames->emplace_back(std::move(encoded_frame)); - } - }, - encoded_frames_weak_factory.GetWeakPtr())); - // Encode several frames at each size. For encoders with a resize delay, // expect the first one or more frames are dropped while the encoder // re-inits. For all encoders, expect one key frame followed by all delta // frames. - - // Keep track of the expected times by mapping the reference time to the - // timestamp. - std::map expectations; for (const auto& frame_size : frame_sizes) { // Encode frames until there are four consecutive frames successfully // encoded. @@ -232,16 +220,29 @@ encoded_frames[encoded_frames.size() - 2] && encoded_frames[encoded_frames.size() - 3] && encoded_frames[encoded_frames.size() - 4])) { - const auto reference_time = Now(); auto video_frame = CreateTestVideoFrame(frame_size); - expectations.emplace( - reference_time, - - ToRtpTimeTicks(video_frame->timestamp(), kVideoFrequency)); - + const base::TimeTicks reference_time = Now(); + const base::TimeDelta timestamp = video_frame->timestamp(); const bool accepted_request = video_encoder()->EncodeVideoFrame( - std::move(video_frame), reference_time); - + std::move(video_frame), reference_time, + base::BindOnce( + [](base::WeakPtr encoded_frames, + RtpTimeTicks expected_rtp_timestamp, + base::TimeTicks expected_reference_time, + std::unique_ptr encoded_frame) { + if (!encoded_frames) { + return; + } + if (encoded_frame) { + EXPECT_EQ(expected_rtp_timestamp, + encoded_frame->rtp_timestamp); + EXPECT_EQ(expected_reference_time, + encoded_frame->reference_time); + } + encoded_frames->emplace_back(std::move(encoded_frame)); + }, + encoded_frames_weak_factory.GetWeakPtr(), + ToRtpTimeTicks(timestamp, kVideoFrequency), reference_time)); if (accepted_request) { ++count_frames_accepted; } @@ -270,11 +271,6 @@ continue; } - // Check that the frame has an expected reference time and RTP timestamp. - auto expectation = expectations.find(encoded_frame->reference_time); - ASSERT_NE(expectation, expectations.end()); - EXPECT_EQ(expectation->second, encoded_frame->rtp_timestamp); - if (encoded_frame->dependency == openscreen::cast::EncodedFrame::Dependency::kKeyFrame) { EXPECT_EQ(encoded_frame->frame_id, encoded_frame->referenced_frame_id); @@ -307,12 +303,12 @@ // encoders, this tests that the encoder can be safely destroyed before the task // is run that delivers the first EncodedFrame. TEST_P(VideoEncoderTest, CanBeDestroyedBeforeVEAIsCreated) { - CreateEncoder(base::BindRepeating( - [](std::unique_ptr encoded_frame) {})); + CreateEncoder(); // Send a frame to spawn creation of the ExternalVideoEncoder instance. - video_encoder()->EncodeVideoFrame(CreateTestVideoFrame(gfx::Size(128, 72)), - Now()); + video_encoder()->EncodeVideoFrame( + CreateTestVideoFrame(gfx::Size(128, 72)), Now(), + base::BindOnce([](std::unique_ptr encoded_frame) {})); // Destroy the encoder, and confirm the VEA Factory did not respond yet. DestroyEncoder(); @@ -358,4 +354,5 @@ (info.param.second ? "_Hardware" : "_Software"); }); -} // namespace media::cast +} // namespace cast +} // namespace media diff -Nru chromium-132.0.6834.110/media/cast/sender/video_sender.cc chromium-132.0.6834.159/media/cast/sender/video_sender.cc --- chromium-132.0.6834.110/media/cast/sender/video_sender.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/sender/video_sender.cc 2025-01-27 17:37:37.000000000 +0000 @@ -124,13 +124,9 @@ max_playout_delay_(video_config.max_playout_delay), playout_delay_change_cb_(std::move(playout_delay_change_cb)), feedback_cb_(feedback_cb) { - // NOTE: we bind to the `output_cb` of the video encoder using a weak pointer - // because encoding occurs on a separate thread. - video_encoder_ = VideoEncoder::Create( - cast_environment_, video_config, std::move(encoder_metrics_provider), - status_change_cb, - base::BindRepeating(&VideoSender::OnEncodedVideoFrame, AsWeakPtr()), - create_vea_cb); + video_encoder_ = VideoEncoder::Create(cast_environment_, video_config, + std::move(encoder_metrics_provider), + status_change_cb, create_vea_cb); if (!video_encoder_) { cast_environment_->PostTask( CastEnvironment::MAIN, FROM_HERE, @@ -283,10 +279,12 @@ last_reported_lossiness_, std::move(video_frame)); } - if (video_encoder_->EncodeVideoFrame(video_frame, reference_time)) { + if (video_encoder_->EncodeVideoFrame( + video_frame, reference_time, + base::BindOnce(&VideoSender::OnEncodedVideoFrame, AsWeakPtr(), + video_frame, reference_time))) { TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( - "cast.stream", "Video Encode", - TRACE_ID_LOCAL((reference_time - base::TimeTicks()).InMicroseconds()), + "cast.stream", "Video Encode", TRACE_ID_LOCAL(video_frame.get()), "rtp_timestamp", rtp_timestamp.lower_32_bits()); frames_in_encoder_++; duration_in_encoder_ += duration_added_by_next_frame; @@ -324,30 +322,25 @@ } void VideoSender::OnEncodedVideoFrame( + scoped_refptr video_frame, + const base::TimeTicks reference_time, std::unique_ptr encoded_frame) { DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN)); frames_in_encoder_--; DCHECK_GE(frames_in_encoder_, 0); - // The encoder drops a frame. - if (!encoded_frame) { - DVLOG(3) << "Dropped frame"; - return; - } // Update |duration_in_encoder_| so that |frame_sender_| doesn't regard the - // encoder as really slow. - duration_in_encoder_ = - last_enqueued_frame_reference_time_ - encoded_frame->reference_time; + // encoder is really slow. + duration_in_encoder_ = last_enqueued_frame_reference_time_ - reference_time; TRACE_EVENT_NESTABLE_ASYNC_END2( - "cast.stream", "Video Encode", - TRACE_ID_LOCAL( - (encoded_frame->reference_time - base::TimeTicks()).InMicroseconds()), + "cast.stream", "Video Encode", TRACE_ID_LOCAL(video_frame.get()), "encoder_utilization", last_reported_encoder_utilization_, "lossiness", last_reported_lossiness_); - if (encoded_frame->data.empty()) { - DVLOG(3) << "Frame with no data"; + // The encoder drops a frame. + if (!encoded_frame || encoded_frame->data.empty()) { + DVLOG(3) << "Drop frame"; return; } diff -Nru chromium-132.0.6834.110/media/cast/sender/video_sender.h chromium-132.0.6834.159/media/cast/sender/video_sender.h --- chromium-132.0.6834.110/media/cast/sender/video_sender.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/media/cast/sender/video_sender.h 2025-01-27 17:37:37.000000000 +0000 @@ -81,7 +81,9 @@ private: // Called by the |video_encoder_| with the next EncodedFrame to send. - void OnEncodedVideoFrame(std::unique_ptr encoded_frame); + void OnEncodedVideoFrame(scoped_refptr video_frame, + const base::TimeTicks reference_time, + std::unique_ptr encoded_frame); // The backing frame sender implementation. std::unique_ptr frame_sender_; diff -Nru chromium-132.0.6834.110/net/data/ssl/chrome_root_store/root_store.md chromium-132.0.6834.159/net/data/ssl/chrome_root_store/root_store.md --- chromium-132.0.6834.110/net/data/ssl/chrome_root_store/root_store.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/net/data/ssl/chrome_root_store/root_store.md 2025-01-27 17:37:37.000000000 +0000 @@ -1,7 +1,11 @@ +# Chrome Root Store Version: 17 +[TOC] + +## Trusted Roots SHA 256 Hash | Subject | NotBefore | NotAfter ---|---|---|--- 55926084ec963a64b96e2abe01ce0ba86a64fbfebcc7aab5afc155b37fd76066 | CN=Actalis Authentication Root CA,O=Actalis S.p.A./03358520967,L=Milan,C=IT | 2011-09-22 | 2030-09-22 @@ -40,15 +44,6 @@ 40f6af0346a99aa1cd1d555a4e9cce62c7f9634603ee406615833dc8c8d00367 | CN=emSign Root CA - G1,OU=emSign PKI,O=eMudhra Technologies Limited,C=IN | 2018-02-18 | 2043-02-18 86a1ecba089c4a8d3bbe2734c612ba341d813e043cf9e8a862cd5c57a36bbe6b | CN=emSign ECC Root CA - G3,OU=emSign PKI,O=eMudhra Technologies Limited,C=IN | 2018-02-18 | 2043-02-18 bc4d809b15189d78db3e1d8cf4f9726a795da1643ca5f1358e1ddb0edc0d7eb3 | CN=emSign ECC Root CA - C3,OU=emSign PKI,O=eMudhra Inc,C=US | 2018-02-18 | 2043-02-18 -02ed0eb28c14da45165c566791700d6451d7fb56f0b2ab1d3b8eb070e56edff5 | CN=Entrust Root Certification Authority - EC1,OU=See www.entrust.net/legal-terms+OU=(c) 2012 Entrust\, Inc. - for authorized use only,O=Entrust\, Inc.,C=US | 2012-12-18 | 2037-12-18 -0376ab1d54c5f9803ce4b2e201a0ee7eef7b57b636e8a93c9b8d4860c96f5fa7 | CN=AffirmTrust Commercial,O=AffirmTrust,C=US | 2010-01-29 | 2030-12-31 -0a81ec5a929777f145904af38d5d509f66b5e2c58fcdb531058b0e17f3f0b41b | CN=AffirmTrust Networking,O=AffirmTrust,C=US | 2010-01-29 | 2030-12-31 -43df5774b03e7fef5fe40d931a7bedf1bb2e6b42738c4e6d3841103d3aa7f339 | CN=Entrust Root Certification Authority - G2,OU=See www.entrust.net/legal-terms+OU=(c) 2009 Entrust\, Inc. - for authorized use only,O=Entrust\, Inc.,C=US | 2009-07-07 | 2030-12-07 -6dc47172e01cbcb0bf62580d895fe2b8ac9ad4f873801e0c10b9c837d21eb177 | CN=Entrust.net Certification Authority (2048),OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)+OU=(c) 1999 Entrust.net Limited,O=Entrust.net | 1999-12-24 | 2029-07-24 -70a73f7f376b60074248904534b11482d5bf0e698ecc498df52577ebf2e93b9a | CN=AffirmTrust Premium,O=AffirmTrust,C=US | 2010-01-29 | 2040-12-31 -73c176434f1bc6d5adf45b0e76e727287c8de57616c1e6e6141a2b2cbc7d8e4c | CN=Entrust Root Certification Authority,OU=www.entrust.net/CPS is incorporated by reference+OU=(c) 2006 Entrust\, Inc.,O=Entrust\, Inc.,C=US | 2006-11-27 | 2026-11-27 -bd71fdf6da97e4cf62d1647add2581b07d79adf8397eb4ecba9c5e8488821423 | CN=AffirmTrust Premium ECC,O=AffirmTrust,C=US | 2010-01-29 | 2040-12-31 -db3517d1f6732a2d5ab97c533ec70779ee3270a62fb4ac4238372460e6f01e88 | CN=Entrust Root Certification Authority - G4,OU=See www.entrust.net/legal-terms+OU=(c) 2015 Entrust\, Inc. - for authorized use only,O=Entrust\, Inc.,C=US | 2015-05-27 | 2037-12-27 bfff8fd04433487d6a8aa60c1a29767a9fc2bbb05e420f713a13b992891d3893 | CN=GDCA TrustAUTH R5 ROOT,O=GUANG DONG CERTIFICATE AUTHORITY CO.\,LTD.,C=CN | 2014-11-26 | 2040-12-31 179fbc148a3dd00fd24ea13458cc43bfa7f59c8182d783a513f6ebec100c8924 | CN=GlobalSign,OU=GlobalSign ECC Root CA - R5,O=GlobalSign | 2012-11-13 | 2038-01-19 2cabeafe37d06ca22aba7391c0033d25982952c453647349763a3ab5ad6ccf69 | CN=GlobalSign,OU=GlobalSign Root CA - R6,O=GlobalSign | 2014-12-10 | 2034-12-10 @@ -115,7 +110,6 @@ 08170d1aa36453901a2f959245e347db0c8d37abaabc56b81aa100dc958970db | CN=D-TRUST EV Root CA 1 2020,O=D-Trust GmbH,C=DE | 2020-02-11 | 2035-02-11 cbb9c44d84b8043e1050ea31a69f514955d7bfd2e2c6b49301019ad61d9f5058 | CN=GlobalSign Root E46,O=GlobalSign nv-sa,C=BE | 2019-03-20 | 2046-03-20 4fa3126d8d3a11d1c4855a4f807cbad6cf919d3a5a88b03bea2c6372d93c40c9 | CN=GlobalSign Root R46,O=GlobalSign nv-sa,C=BE | 2019-03-20 | 2046-03-20 -9a296a5182d1d451a2e37f439b74daafa267523329f90f9a0d2007c334e23c9a | CN=GLOBALTRUST 2020,O=e-commerce monitoring GmbH,C=AT | 2020-02-10 | 2040-06-10 3f99cc474acfce4dfed58794665e478d1547739f2e780f1bb4ca9b133097d401 | CN=HARICA TLS ECC Root CA 2021,O=Hellenic Academic and Research Institutions CA,C=GR | 2021-02-19 | 2045-02-13 d95d0e8eda79525bf9beb11b14d2100d3294985f0c62d9fabd9cd999eccb7b1d | CN=HARICA TLS RSA Root CA 2021,O=Hellenic Academic and Research Institutions CA,C=GR | 2021-02-19 | 2045-02-13 f015ce3cc239bfef064be9f1d2c417e1a0264a0a94be1f0c8d121864eb6949cc | CN=HiPKI Root CA - G1,O=Chunghwa Telecom Co.\, Ltd.,C=TW | 2019-02-22 | 2037-12-31 @@ -138,3 +132,18 @@ 7bb647a62aeeac88bf257aa522d01ffea395e0ab45c73f93f65654ec38f25a06 | CN=Sectigo Public Server Authentication Root R46,O=Sectigo Limited,C=GB | 2021-03-22 | 2046-03-21 c32ffd9f46f936d16c3673990959434b9ad60aafbb9e7cf33654f144cc1ba143 | CN=SSL.com TLS ECC Root CA 2022,O=SSL Corporation,C=US | 2022-08-25 | 2046-08-19 8faf7d2e2cb4709bb8e0b33666bf75a5dd45b5de480f8ea8d4bfe6bebc17f2ed | CN=SSL.com TLS RSA Root CA 2022,O=SSL Corporation,C=US | 2022-08-25 | 2046-08-19 +## Constrained Roots +To learn more about constraints applied to certificates included in the Chrome Root Store, click [here](https://chromium.googlesource.com/chromium/src/+/main/net/data/ssl/chrome_root_store/faq.md). + +SHA 256 Hash | Subject | NotBefore | NotAfter +---|---|---|--- +02ed0eb28c14da45165c566791700d6451d7fb56f0b2ab1d3b8eb070e56edff5 | CN=Entrust Root Certification Authority - EC1,OU=See www.entrust.net/legal-terms+OU=(c) 2012 Entrust\, Inc. - for authorized use only,O=Entrust\, Inc.,C=US | 2012-12-18 | 2037-12-18 +0376ab1d54c5f9803ce4b2e201a0ee7eef7b57b636e8a93c9b8d4860c96f5fa7 | CN=AffirmTrust Commercial,O=AffirmTrust,C=US | 2010-01-29 | 2030-12-31 +0a81ec5a929777f145904af38d5d509f66b5e2c58fcdb531058b0e17f3f0b41b | CN=AffirmTrust Networking,O=AffirmTrust,C=US | 2010-01-29 | 2030-12-31 +43df5774b03e7fef5fe40d931a7bedf1bb2e6b42738c4e6d3841103d3aa7f339 | CN=Entrust Root Certification Authority - G2,OU=See www.entrust.net/legal-terms+OU=(c) 2009 Entrust\, Inc. - for authorized use only,O=Entrust\, Inc.,C=US | 2009-07-07 | 2030-12-07 +6dc47172e01cbcb0bf62580d895fe2b8ac9ad4f873801e0c10b9c837d21eb177 | CN=Entrust.net Certification Authority (2048),OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)+OU=(c) 1999 Entrust.net Limited,O=Entrust.net | 1999-12-24 | 2029-07-24 +70a73f7f376b60074248904534b11482d5bf0e698ecc498df52577ebf2e93b9a | CN=AffirmTrust Premium,O=AffirmTrust,C=US | 2010-01-29 | 2040-12-31 +73c176434f1bc6d5adf45b0e76e727287c8de57616c1e6e6141a2b2cbc7d8e4c | CN=Entrust Root Certification Authority,OU=www.entrust.net/CPS is incorporated by reference+OU=(c) 2006 Entrust\, Inc.,O=Entrust\, Inc.,C=US | 2006-11-27 | 2026-11-27 +bd71fdf6da97e4cf62d1647add2581b07d79adf8397eb4ecba9c5e8488821423 | CN=AffirmTrust Premium ECC,O=AffirmTrust,C=US | 2010-01-29 | 2040-12-31 +db3517d1f6732a2d5ab97c533ec70779ee3270a62fb4ac4238372460e6f01e88 | CN=Entrust Root Certification Authority - G4,OU=See www.entrust.net/legal-terms+OU=(c) 2015 Entrust\, Inc. - for authorized use only,O=Entrust\, Inc.,C=US | 2015-05-27 | 2037-12-27 +9a296a5182d1d451a2e37f439b74daafa267523329f90f9a0d2007c334e23c9a | CN=GLOBALTRUST 2020,O=e-commerce monitoring GmbH,C=AT | 2020-02-10 | 2040-06-10 diff -Nru chromium-132.0.6834.110/net/http/transport_security_state_static.pins chromium-132.0.6834.159/net/http/transport_security_state_static.pins --- chromium-132.0.6834.110/net/http/transport_security_state_static.pins 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/net/http/transport_security_state_static.pins 2025-01-27 17:37:37.000000000 +0000 @@ -43,9 +43,9 @@ # hash function for preloaded entries again (we have already done so once). # -# Last updated: 2025-01-19 12:54 UTC +# Last updated: 2025-01-26 12:55 UTC PinsListTimestamp -1737291287 +1737896110 TestSPKI sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= diff -Nru chromium-132.0.6834.110/net/http/transport_security_state_static_pins.json chromium-132.0.6834.159/net/http/transport_security_state_static_pins.json --- chromium-132.0.6834.110/net/http/transport_security_state_static_pins.json 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/net/http/transport_security_state_static_pins.json 2025-01-27 17:37:37.000000000 +0000 @@ -31,7 +31,7 @@ // the 'static_spki_hashes' and 'bad_static_spki_hashes' fields in 'pinsets' // refer to, and the timestamp at which the pins list was last updated. // -// Last updated: 2025-01-19 12:54 UTC +// Last updated: 2025-01-26 12:55 UTC // { "pinsets": [ diff -Nru chromium-132.0.6834.110/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h chromium-132.0.6834.159/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h --- chromium-132.0.6834.110/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h 2025-01-27 17:37:37.000000000 +0000 @@ -66,7 +66,7 @@ WebDevToolsAgentImpl(WebLocalFrameImpl*, bool include_view_agents); ~WebDevToolsAgentImpl() override; - virtual void Trace(Visitor*) const; + void Trace(Visitor*) const override; DevToolsAgent* GetDevToolsAgent() const { return agent_.Get(); } void WillBeDestroyed(); diff -Nru chromium-132.0.6834.110/third_party/blink/renderer/core/inspector/devtools_agent.cc chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/devtools_agent.cc --- chromium-132.0.6834.110/third_party/blink/renderer/core/inspector/devtools_agent.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/devtools_agent.cc 2025-01-27 17:37:37.000000000 +0000 @@ -189,6 +189,7 @@ DevToolsAgent::~DevToolsAgent() = default; void DevToolsAgent::Trace(Visitor* visitor) const { + visitor->Trace(client_); visitor->Trace(associated_receiver_); visitor->Trace(host_remote_); visitor->Trace(associated_host_remote_); diff -Nru chromium-132.0.6834.110/third_party/blink/renderer/core/inspector/devtools_agent.h chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/devtools_agent.h --- chromium-132.0.6834.110/third_party/blink/renderer/core/inspector/devtools_agent.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/devtools_agent.h 2025-01-27 17:37:37.000000000 +0000 @@ -40,7 +40,7 @@ class CORE_EXPORT DevToolsAgent : public GarbageCollected, public mojom::blink::DevToolsAgent { public: - class Client { + class Client : public GarbageCollectedMixin { public: virtual ~Client() = default; virtual void AttachSession(DevToolsSession*, bool restore) = 0; @@ -139,7 +139,7 @@ void ReportChildTargetsImpl(bool report, bool wait_for_debugger, base::OnceClosure callback); - Client* client_; + Member const client_; // DevToolsAgent is not tied to ExecutionContext HeapMojoAssociatedReceiver associated_receiver_{this, nullptr}; diff -Nru chromium-132.0.6834.110/third_party/blink/renderer/core/inspector/worker_inspector_controller.h chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/worker_inspector_controller.h --- chromium-132.0.6834.110/third_party/blink/renderer/core/inspector/worker_inspector_controller.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/blink/renderer/core/inspector/worker_inspector_controller.h 2025-01-27 17:37:37.000000000 +0000 @@ -72,7 +72,7 @@ WorkerInspectorController& operator=(const WorkerInspectorController&) = delete; ~WorkerInspectorController() override; - void Trace(Visitor*) const; + void Trace(Visitor*) const override; CoreProbeSink* GetProbeSink() const { return probe_sink_.Get(); } DevToolsAgent* GetDevToolsAgent() const { return agent_.Get(); } diff -Nru chromium-132.0.6834.110/third_party/blink/renderer/platform/media/url_index.cc chromium-132.0.6834.159/third_party/blink/renderer/platform/media/url_index.cc --- chromium-132.0.6834.110/third_party/blink/renderer/platform/media/url_index.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/blink/renderer/platform/media/url_index.cc 2025-01-27 17:37:37.000000000 +0000 @@ -182,6 +182,11 @@ return true; } if (cors_mode_ == UrlData::CORS_UNSPECIFIED) { + // If both origins are null return true, otherwise + // SecurityOrigin::AreSameOrigin will create a unique nonce for each. + if (data_origin_.IsNull() && origin.IsNull()) { + return true; + } return SecurityOrigin::SecurityOrigin::AreSameOrigin(data_origin_, origin); } // The actual cors checks is done in the net layer. diff -Nru chromium-132.0.6834.110/third_party/blink/renderer/platform/media/url_index_unittest.cc chromium-132.0.6834.159/third_party/blink/renderer/platform/media/url_index_unittest.cc --- chromium-132.0.6834.110/third_party/blink/renderer/platform/media/url_index_unittest.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/blink/renderer/platform/media/url_index_unittest.cc 2025-01-27 17:37:37.000000000 +0000 @@ -176,4 +176,15 @@ EXPECT_NE(url_data, url_index_.GetByUrl(url, cors, UrlData::kCacheDisabled)); } +TEST_F(UrlIndexTest, ValidateDataOrigin) { + KURL url("http://foo.bar.com"); + KURL data_url; + scoped_refptr a = GetByUrl(url, UrlData::CORS_UNSPECIFIED); + EXPECT_TRUE(a->ValidateDataOrigin(data_url)); + + // First call assigns the data origin, second call will assert them are the + // same. + EXPECT_TRUE(a->ValidateDataOrigin(data_url)); +} + } // namespace blink diff -Nru chromium-132.0.6834.110/third_party/blink/renderer/platform/runtime_enabled_features.json5 chromium-132.0.6834.159/third_party/blink/renderer/platform/runtime_enabled_features.json5 --- chromium-132.0.6834.110/third_party/blink/renderer/platform/runtime_enabled_features.json5 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/blink/renderer/platform/runtime_enabled_features.json5 2025-01-27 17:37:37.000000000 +0000 @@ -1193,7 +1193,7 @@ { // crbug.com/359616070 name: "CSSRelativeColorLateResolveAlways", - status: "stable", + status: "experimental", }, { // crbug.com/365818844 @@ -4157,7 +4157,7 @@ }, { name: "SvgInlineRootPixelSnappingScaleAdjustment", - status: "stable", + status: "test", }, { name: "SvgNoPixelSnappingScaleAdjustment", diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/DIR_METADATA chromium-132.0.6834.159/third_party/closure_compiler/DIR_METADATA --- chromium-132.0.6834.110/third_party/closure_compiler/DIR_METADATA 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/DIR_METADATA 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -monorail: { - component: "UI>Browser>WebUI" -} -buganizer_public: { - component_id: 1457323 -} diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/OWNERS chromium-132.0.6834.159/third_party/closure_compiler/OWNERS --- chromium-132.0.6834.110/third_party/closure_compiler/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -# See https://crbug.com/40222185 -# For remaining CrOS usages -file://ash/webui/PLATFORM_OWNERS - -# For components/variations/proto/devtools/BUILD.gn, see -# https://crbug.com/40253708 -asvitkine@chromium.org - -# Last resort, emeritus. -dpapad@chromium.org diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/README.chromium chromium-132.0.6834.159/third_party/closure_compiler/README.chromium --- chromium-132.0.6834.110/third_party/closure_compiler/README.chromium 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/README.chromium 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -Name: Closure compiler -Short Name: closure-compiler -URL: http://github.com/google/closure-compiler -Version: 20210906.0.0 -Date: 2023-05-03 -License: Apache 2.0 -License File: LICENSE -Security Critical: no -Shipped: no - -Description: -The Closure Compiler provides warnings for illegal JavaScript and warnings for -potentially dangerous operations, helping you to produce JavaScript that is less -buggy and easier to maintain. - -Local modifications: -- Use the script third_party/closure_compiler/roll_closure_compiler to update - the versions of third_party/closure_compiler/compiler/compiler.jar and/or - third_party/closure_compiler/externs/chrome_extensions.js. -- Some externs here are for chrome-specific use; these primarily include the - *_private.js files. -- Fix bug in js_binary.py causing it to drop externs. -- Cache dependency subtrees in js_binary.py for a huge performance boost. -- Add js_unit_tests.gni for generating .html files for running unit tests. -- Forward target visibility in the js_library template. -- Forward closure_flags in js_type_check and js_unit_tests templates. diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/chromium_patch.diff chromium-132.0.6834.159/third_party/closure_compiler/chromium_patch.diff --- chromium-132.0.6834.110/third_party/closure_compiler/chromium_patch.diff 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/chromium_patch.diff 1970-01-01 00:00:00.000000000 +0000 @@ -1,1106 +0,0 @@ -diff --git b/third_party/closure_compiler/externs/chrome.js a/third_party/closure_compiler/externs/chrome.js -index 54cf6b1a2bcc..0619bdce01a4 100644 ---- b/third_party/closure_compiler/externs/chrome.js -+++ a/third_party/closure_compiler/externs/chrome.js -@@ -562,51 +562,6 @@ chrome.webstore.onInstallStageChanged; - chrome.webstore.onDownloadProgress; - - --/** -- * @see https://developer.chrome.com/extensions/runtime.html -- * @const -- */ --chrome.runtime = {}; -- -- --/** @type {{message:(string|undefined)}|undefined} */ --chrome.runtime.lastError; -- -- --/** -- * @param {string|!Object=} opt_extensionIdOrConnectInfo Either the -- * extensionId to connect to, in which case connectInfo params can be -- * passed in the next optional argument, or the connectInfo params. -- * @param {!Object=} opt_connectInfo The connectInfo object, -- * if arg1 was the extensionId to connect to. -- * @return {!Port} New port. -- */ --chrome.runtime.connect = function( -- opt_extensionIdOrConnectInfo, opt_connectInfo) {}; -- -- --/** -- * @param {string|*} extensionIdOrMessage Either the extensionId to send the -- * message to, in which case the message is passed as the next arg, or the -- * message itself. -- * @param {(*|!Object|function(*): void)=} opt_messageOrOptsOrCallback -- * One of: -- * The message, if arg1 was the extensionId. -- * The options for message sending, if arg1 was the message and this -- * argument is not a function. -- * The callback, if arg1 was the message and this argument is a function. -- * @param {(!Object|function(*): void)=} opt_optsOrCallback -- * Either the options for message sending, if arg2 was the message, -- * or the callback. -- * @param {function(*): void=} opt_callback The callback function which -- * takes a JSON response object sent by the handler of the request. -- * @return {undefined} -- */ --chrome.runtime.sendMessage = function( -- extensionIdOrMessage, opt_messageOrOptsOrCallback, opt_optsOrCallback, -- opt_callback) {}; -- -- - /** - * Returns an object representing current load times. Note that the properties - * on the object do not change and the function must be called again to get -diff --git b/third_party/closure_compiler/externs/chrome_extensions.js a/third_party/closure_compiler/externs/chrome_extensions.js -index 41b2f5b485c7..7110aaf8f223 100644 ---- b/third_party/closure_compiler/externs/chrome_extensions.js -+++ a/third_party/closure_compiler/externs/chrome_extensions.js -@@ -233,72 +233,6 @@ if (Math.random() < 1) { // always true but the compiler doesn't know that - } - - --/** -- * @see https://developer.chrome.com/extensions/accessibilityFeatures -- * @const -- */ --chrome.accessibilityFeatures = {}; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.spokenFeedback; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.largeCursor; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.stickyKeys; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.highContrast; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.screenMagnifier; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.autoclick; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.virtualKeyboard; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.caretHighlight; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.cursorHighlight; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.cursorColor; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.dockedMagnifier; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.focusHighlight; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.selectToSpeak; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.switchAccess; -- -- --/** @type {!ChromeSetting} */ --chrome.accessibilityFeatures.animationPolicy; -- - - /** - * @const -@@ -2557,6 +2491,49 @@ chrome.extension.onRequest; - /** @type {!ChromeEvent} */ - chrome.extension.onRequestExternal; - -+/** -+ * @see https://developer.chrome.com/extensions/runtime.html -+ * @const -+ */ -+chrome.runtime = {}; -+ -+ -+/** @type {{message:(string|undefined)}|undefined} */ -+chrome.runtime.lastError; -+ -+ -+/** -+ * @param {string|!Object=} opt_extensionIdOrConnectInfo Either the -+ * extensionId to connect to, in which case connectInfo params can be -+ * passed in the next optional argument, or the connectInfo params. -+ * @param {!Object=} opt_connectInfo The connectInfo object, -+ * if arg1 was the extensionId to connect to. -+ * @return {!Port} New port. -+ */ -+chrome.runtime.connect = function( -+ opt_extensionIdOrConnectInfo, opt_connectInfo) {}; -+ -+ -+/** -+ * @param {string|*} extensionIdOrMessage Either the extensionId to send the -+ * message to, in which case the message is passed as the next arg, or the -+ * message itself. -+ * @param {(*|!Object|function(*): void)=} opt_messageOrOptsOrCallback -+ * One of: -+ * The message, if arg1 was the extensionId. -+ * The options for message sending, if arg1 was the message and this -+ * argument is not a function. -+ * The callback, if arg1 was the message and this argument is a function. -+ * @param {(!Object|function(*): void)=} opt_optsOrCallback -+ * Either the options for message sending, if arg2 was the message, -+ * or the callback. -+ * @param {function(*): void=} opt_callback The callback function which -+ * takes a JSON response object sent by the handler of the request. -+ * @return {undefined} -+ */ -+chrome.runtime.sendMessage = function( -+ extensionIdOrMessage, opt_messageOrOptsOrCallback, opt_optsOrCallback, -+ opt_callback) {}; - - - /** @type {string} */ -@@ -4380,151 +4357,6 @@ chrome.idle.getAutoLockDelay = function(callback) {}; - chrome.idle.onStateChanged; - - --/** -- * Chrome Text-to-Speech API. -- * @const -- * @see https://developer.chrome.com/extensions/tts.html -- */ --chrome.tts = {}; -- -- -- --/** -- * An event from the TTS engine to communicate the status of an utterance. -- * @constructor -- */ --function TtsEvent() {} -- -- --/** @type {string} */ --TtsEvent.prototype.type; -- -- --/** @type {number} */ --TtsEvent.prototype.charIndex; -- -- --/** @type {string} */ --TtsEvent.prototype.errorMessage; -- -- --/** -- * The speech options for the TTS engine. -- * @record -- * @see https://developer.chrome.com/apps/tts#type-TtsOptions -- */ --function TtsOptions() {} -- --/** @type {boolean|undefined} */ --TtsOptions.prototype.enqueue; -- --/** @type {string|undefined} */ --TtsOptions.prototype.voiceName; -- --/** @type {string|undefined} */ --TtsOptions.prototype.extensionId; -- --/** @type {string|undefined} */ --TtsOptions.prototype.lang; -- --/** @type {number|undefined} */ --TtsOptions.prototype.rate; -- --/** @type {number|undefined} */ --TtsOptions.prototype.pitch; -- --/** @type {number|undefined} */ --TtsOptions.prototype.volume; -- --/** @type {!Array|undefined} */ --TtsOptions.prototype.requiredEventTypes; -- --/** @type {!Array|undefined} */ --TtsOptions.prototype.desiredEventTypes; -- --/** @type {!function(!TtsEvent)|undefined} */ --TtsOptions.prototype.onEvent; -- -- --/** -- * A description of a voice available for speech synthesis. -- * @constructor -- */ --function TtsVoice() {} -- -- --/** @type {string} */ --TtsVoice.prototype.voiceName; -- -- --/** @type {string} */ --TtsVoice.prototype.lang; -- -- --/** @type {string} */ --TtsVoice.prototype.gender; -- -- --/** @type {string} */ --TtsVoice.prototype.extensionId; -- -- --/** @type {Array} */ --TtsVoice.prototype.eventTypes; -- -- --/** -- * Gets an array of all available voices. -- * @param {function(Array)=} opt_callback An optional callback -- * function. -- * @return {undefined} -- */ --chrome.tts.getVoices = function(opt_callback) {}; -- -- --/** -- * Checks if the engine is currently speaking. -- * @param {function(boolean)=} opt_callback The callback function. -- * @return {undefined} -- */ --chrome.tts.isSpeaking = function(opt_callback) {}; -- -- --/** -- * Speaks text using a text-to-speech engine. -- * @param {string} utterance The text to speak, either plain text or a complete, -- * well-formed SSML document. Speech engines that do not support SSML will -- * strip away the tags and speak the text. The maximum length of the text is -- * 32,768 characters. -- * @param {TtsOptions=} options The speech options. -- * @param {function()=} callback Called right away, before speech finishes. -- * @return {undefined} -- */ --chrome.tts.speak = function(utterance, options, callback) {}; -- -- --/** -- * Stops any current speech. -- * @return {undefined} -- */ --chrome.tts.stop = function() {}; -- -- --/** -- * @const -- * @see https://developer.chrome.com/extensions/ttsEngine.html -- */ --chrome.ttsEngine = {}; -- -- --/** @type {!ChromeEvent} */ --chrome.ttsEngine.onSpeak; -- -- --/** @type {!ChromeEvent} */ --chrome.ttsEngine.onStop; -- -- - /** - * @const - * @see https://developer.chrome.com/extensions/contentSettings.html -@@ -8474,642 +8306,6 @@ chrome.fileSystem.requestFileSystem = function(options, callback) {}; - chrome.fileSystem.getVolumeList = function(callback) {}; - - --/** -- * @const -- * @see https://developer.chrome.com/extensions/fileSystemProvider -- */ --chrome.fileSystemProvider = {}; -- -- --/** -- * @enum {string} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#type-ChangeType -- */ --chrome.fileSystemProvider.ChangeType = { -- CHANGED: '', -- DELETED: '', --}; -- -- --/** -- * @enum {string} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#type-CommonActionId -- */ --chrome.fileSystemProvider.CommonActionId = { -- OFFLINE_NOT_NECESSARY: '', -- SAVE_FOR_OFFLINE: '', -- SHARE: '', --}; -- -- --/** -- * @enum {string} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#type-OpenFileMode -- */ --chrome.fileSystemProvider.OpenFileMode = { -- READ: '', -- WRITE: '', --}; -- -- --/** -- * @enum {string} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#type-ProviderError -- */ --chrome.fileSystemProvider.ProviderError = { -- ABORT: '', -- ACCESS_DENIED: '', -- EXISTS: '', -- FAILED: '', -- INVALID_OPERATION: '', -- INVALID_URL: '', -- IN_USE: '', -- IO: '', -- NOT_A_DIRECTORY: '', -- NOT_A_FILE: '', -- NOT_EMPTY: '', -- NOT_FOUND: '', -- NO_MEMORY: '', -- NO_SPACE: '', -- OK: '', -- SECURITY: '', -- TOO_MANY_OPENED: '', --}; -- -- --/** -- * @constructor -- * @see https://developer.chrome.com/extensions/fileSystemProvider#type-EntryMetadata -- */ --chrome.fileSystemProvider.EntryMetadata = function() {}; -- -- --/** @type {boolean|undefined} */ --chrome.fileSystemProvider.EntryMetadata.prototype.isDirectory; -- -- --/** @type {string|undefined} */ --chrome.fileSystemProvider.EntryMetadata.prototype.name; -- -- --/** @type {number|undefined} */ --chrome.fileSystemProvider.EntryMetadata.prototype.size; -- -- --/** @type {!Date|undefined} */ --chrome.fileSystemProvider.EntryMetadata.prototype.modificationTime; -- -- --/** @type {string|undefined} */ --chrome.fileSystemProvider.EntryMetadata.prototype.mimeType; -- -- --/** @type {string|undefined} */ --chrome.fileSystemProvider.EntryMetadata.prototype.thumbnail; -- -- --/** -- * @constructor -- * @see https://developer.chrome.com/extensions/fileSystemProvider#type-FileSystemInfo -- */ --chrome.fileSystemProvider.FileSystemInfo = function() {}; -- -- --/** @type {string} */ --chrome.fileSystemProvider.FileSystemInfo.prototype.fileSystemId; -- -- --/** @type {string} */ --chrome.fileSystemProvider.FileSystemInfo.prototype.displayName; -- -- --/** @type {boolean} */ --chrome.fileSystemProvider.FileSystemInfo.prototype.writable; -- -- --/** @type {number} */ --chrome.fileSystemProvider.FileSystemInfo.prototype.openedFilesLimit; -- -- --/** -- * @type {!Array<{ -- * openRequestId: number, -- * filePath: string, -- * mode: !chrome.fileSystemProvider.OpenFileMode, -- * }>} -- */ --chrome.fileSystemProvider.FileSystemInfo.prototype.openedFiles; -- -- --/** @type {boolean|undefined} */ --chrome.fileSystemProvider.FileSystemInfo.prototype.supportsNotifyTag; -- -- --/** -- * @type {!Array} -- */ --chrome.fileSystemProvider.FileSystemInfo.prototype.watchers; -- -- --/** -- * @param {string} fileSystemId -- * @param {function(!chrome.fileSystemProvider.FileSystemInfo): void} callback -- * @see https://developer.chrome.com/extensions/fileSystemProvider#method-get -- */ --chrome.fileSystemProvider.get = function(fileSystemId, callback) {}; -- -- --/** -- * @param {function(!Array): void} -- * callback -- * @see https://developer.chrome.com/extensions/fileSystemProvider#method-getAll -- */ --chrome.fileSystemProvider.getAll = function(callback) {}; -- -- --/** -- * @record -- * @see https://developer.chrome.com/extensions/fileSystemProvider#method-mount -- */ --chrome.fileSystemProvider.MountOptions; -- -- --/** @type {string} */ --chrome.fileSystemProvider.MountOptions.prototype.fileSystemId; -- -- --/** @type {string} */ --chrome.fileSystemProvider.MountOptions.prototype.displayName; -- -- --/** @type {boolean|undefined} */ --chrome.fileSystemProvider.MountOptions.prototype.writable; -- -- --/** @type {number|undefined} */ --chrome.fileSystemProvider.MountOptions.prototype.openedFilesLimit; -- -- --/** @type {boolean|undefined} */ --chrome.fileSystemProvider.MountOptions.prototype.supportsNotifyTag; -- -- --/** @type {boolean|undefined} */ --chrome.fileSystemProvider.MountOptions.prototype.persistent; -- -- --/** -- * @param {!chrome.fileSystemProvider.MountOptions} options -- * @param {function(): void=} callback -- * @see https://developer.chrome.com/extensions/fileSystemProvider#method-mount -- */ --chrome.fileSystemProvider.mount = function(options, callback) {}; -- -- --/** -- * @record -- * @see https://developer.chrome.com/extensions/fileSystemProvider#method-notify -- */ --chrome.fileSystemProvider.NotifyOptions; -- -- --/** @type {string} */ --chrome.fileSystemProvider.NotifyOptions.prototype.fileSystemId; -- -- --/** @type {string} */ --chrome.fileSystemProvider.NotifyOptions.prototype.observedPath; -- -- --/** @type {boolean} */ --chrome.fileSystemProvider.NotifyOptions.prototype.recursive; -- -- --/** @type {!chrome.fileSystemProvider.ChangeType} */ --chrome.fileSystemProvider.NotifyOptions.prototype.changeType; -- -- --/** -- * @type {!Array<{ -- * entryPath: string, -- * changeType: !chrome.fileSystemProvider.ChangeType, -- * }>|undefined} -- */ --chrome.fileSystemProvider.NotifyOptions.prototype.changes; -- -- --/** @type {string|undefined} */ --chrome.fileSystemProvider.NotifyOptions.prototype.tag; -- -- --/** -- * @param {!chrome.fileSystemProvider.NotifyOptions} options -- * @param {function(): void=} callback -- * @see https://developer.chrome.com/extensions/fileSystemProvider#method-notify -- */ --chrome.fileSystemProvider.notify = function(options, callback) {}; -- -- --/** -- * @record -- * @see https://developer.chrome.com/extensions/fileSystemProvider#method-unmount -- */ --chrome.fileSystemProvider.UnmountOptions; -- -- --/** @type {string} */ --chrome.fileSystemProvider.UnmountOptions.prototype.fileSystemId; -- -- --/** -- * @param {!chrome.fileSystemProvider.UnmountOptions} options -- * @param {function(): void=} callback -- */ --chrome.fileSystemProvider.unmount = function(options, callback) {}; -- --/** -- * FSP events that don't "return" values to the caller via onSuccess. -- * -- * @interface -- * @template T -- * @extends {ChromeBaseEvent} -- */ --chrome.fileSystemProvider.VoidBaseEvent; -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * operationRequestId: number, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onAbortRequested -- */ --chrome.fileSystemProvider.AbortRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.AbortRequestedEvent} */ --chrome.fileSystemProvider.onAbortRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * entryPath: string, -- * recursive: boolean, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onAddWatcherRequested -- */ --chrome.fileSystemProvider.AddWatcherRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.AddWatcherRequestedEvent} */ --chrome.fileSystemProvider.onAddWatcherRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * openRequestId: number, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onCloseFileRequested -- */ --chrome.fileSystemProvider.CloseFileRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.CloseFileRequestedEvent} */ --chrome.fileSystemProvider.onCloseFileRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onConfigureRequested -- */ --chrome.fileSystemProvider.ConfigureRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.ConfigureRequestedEvent} */ --chrome.fileSystemProvider.onConfigureRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * sourcePath: string, -- * targetPath: string, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onCopyEntryRequested -- */ --chrome.fileSystemProvider.CopyEntryRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.CopyEntryRequestedEvent} */ --chrome.fileSystemProvider.onCopyEntryRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * directoryPath: string, -- * recursive: boolean, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onCreateDirectoryRequested -- */ --chrome.fileSystemProvider.CreateDirectoryRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.CreateDirectoryRequestedEvent} */ --chrome.fileSystemProvider.onCreateDirectoryRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * filePath: string, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onCreateFileRequested -- */ --chrome.fileSystemProvider.CreateFileRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.CreateFileRequestedEvent} */ --chrome.fileSystemProvider.onCreateFileRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * entryPath: string, -- * recursive: boolean, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onDeleteEntryRequested -- */ --chrome.fileSystemProvider.DeleteEntryRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.DeleteEntryRequestedEvent} */ --chrome.fileSystemProvider.onDeleteEntryRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * entryPaths: !Array, -- * actionId: string, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onExecuteActionRequested -- */ --chrome.fileSystemProvider.ExecuteActionRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.ExecuteActionRequestedEvent} */ --chrome.fileSystemProvider.onExecuteActionRequested; -- -- --/** -- * @interface -- * @extends {ChromeBaseEvent, -- * }, -- * function( -- * !Array -- * ): void, -- * function(!chrome.fileSystemProvider.ProviderError): void -- * )>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onGetActionsRequested -- */ --chrome.fileSystemProvider.GetActionsRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.GetActionsRequestedEvent} */ --chrome.fileSystemProvider.onGetActionsRequested; -- -- --/** -- * @interface -- * @extends {ChromeBaseEvent} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onGetMetadataRequested -- */ --chrome.fileSystemProvider.GetMetadataRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.GetMetadataRequestedEvent} */ --chrome.fileSystemProvider.onGetMetadataRequested; -- -- --/** -- * @interface -- * @extends {ChromeBaseEvent} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onMountRequested -- */ --chrome.fileSystemProvider.MountRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.MountRequestedEvent} */ --chrome.fileSystemProvider.onMountRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * sourcePath: string, -- * targetPath: string, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onMoveEntryRequested -- */ --chrome.fileSystemProvider.MoveEntryRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.MoveEntryRequestedEvent} */ --chrome.fileSystemProvider.onMoveEntryRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * filePath: string, -- * mode: chrome.fileSystemProvider.OpenFileMode, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onOpenFileRequested -- */ --chrome.fileSystemProvider.OpenFileRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.OpenFileRequestedEvent} */ --chrome.fileSystemProvider.onOpenFileRequested; -- -- --/** -- * @interface -- * @extends {ChromeBaseEvent, -- * boolean -- * ): void, -- * function(!chrome.fileSystemProvider.ProviderError): void -- * )>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onReadDirectoryRequested -- */ --chrome.fileSystemProvider.ReadDirectoryRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.ReadDirectoryRequestedEvent} */ --chrome.fileSystemProvider.onReadDirectoryRequested; -- -- --/** -- * @interface -- * @extends {ChromeBaseEvent} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onReadFileRequested -- */ --chrome.fileSystemProvider.ReadFileRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.ReadFileRequestedEvent} */ --chrome.fileSystemProvider.onReadFileRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * entryPath: string, -- * recursive: boolean, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onRemoveWatcherRequested -- */ --chrome.fileSystemProvider.RemoveWatcherRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.RemoveWatcherRequestedEvent} */ --chrome.fileSystemProvider.onRemoveWatcherRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * filePath: string, -- * length: number, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onTruncateRequested -- */ --chrome.fileSystemProvider.TruncateRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.TruncateRequestedEvent} */ --chrome.fileSystemProvider.onTruncateRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onUnmountRequested -- */ --chrome.fileSystemProvider.UnmountRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.UnmountRequestedEvent} */ --chrome.fileSystemProvider.onUnmountRequested; -- -- --/** -- * @interface -- * @extends {chrome.fileSystemProvider.VoidBaseEvent<{ -- * fileSystemId: string, -- * requestId: number, -- * openRequestId: number, -- * offset: number, -- * data: !ArrayBuffer, -- * }>} -- * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onWriteFileRequested -- */ --chrome.fileSystemProvider.WriteFileRequestedEvent; -- -- --/** @type {!chrome.fileSystemProvider.WriteFileRequestedEvent} */ --chrome.fileSystemProvider.onWriteFileRequested; -- -- - /** - * @const - * @see https://developer.chrome.com/apps/syncFileSystem - -diff --git a/third_party/closure_compiler/externs/chrome_extensions.js b/third_party/closure_compiler/externs/chrome_extensions.js -index bd0fd2e51a3bb..12be61c3f581c 100644 ---- a/third_party/closure_compiler/externs/chrome_extensions.js -+++ b/third_party/closure_compiler/externs/chrome_extensions.js -@@ -10607,122 +10607,6 @@ chrome.inlineInstallPrivate = {}; - chrome.inlineInstallPrivate.install = function(id, opt_callback) {}; - - --/** -- * @see https://cs.chromium.org/chromium/src/chrome/common/extensions/api/input_method_private.json -- */ --chrome.inputMethodPrivate = {}; -- --/** -- * @enum {string} -- */ --chrome.inputMethodPrivate.InputModeType = { -- NO_KEYBOARD: '', -- TEXT: '', -- TEL: '', -- URL: '', -- EMAIL: '', -- NUMERIC: '', -- DECIMAL: '', -- SEARCH: '', --}; -- -- --/** -- * @enum {string} -- */ --chrome.inputMethodPrivate.InputContextType = { -- TEXT: '', -- SEARCH: '', -- TEL: '', -- URL: '', -- EMAIL: '', -- NUMBER: '', -- PASSWORD: '', --}; -- -- --/** -- * @enum {string} -- */ --chrome.inputMethodPrivate.AutoCapitalizeType = { -- OFF: '', -- CHARACTERS: '', -- WORDS: '', -- SENTENCES: '', --}; -- -- --/** -- * @enum {string} -- */ --chrome.inputMethodPrivate.FocusReason = { -- MOUSE: '', -- TOUCH: '', -- PEN: '', -- OTHER: '', --}; -- -- --/** @constructor */ --chrome.inputMethodPrivate.InputContext = function() {}; -- -- --/** @type {number} */ --chrome.inputMethodPrivate.InputContext.prototype.contextID; -- --/** @type {chrome.inputMethodPrivate.InputModeType} */ --chrome.inputMethodPrivate.InputContext.prototype.mode; -- --/** @type {chrome.inputMethodPrivate.InputContextType} */ --chrome.inputMethodPrivate.InputContext.prototype.type; -- -- --/** @type {boolean} */ --chrome.inputMethodPrivate.InputContext.prototype.autoCorrect; -- -- --/** @type {boolean} */ --chrome.inputMethodPrivate.InputContext.prototype.autoComplete; -- -- --/** @type {chrome.inputMethodPrivate.AutoCapitalizeType} */ --chrome.inputMethodPrivate.InputContext.prototype.autoCapitalize; -- -- --/** @type {boolean} */ --chrome.inputMethodPrivate.InputContext.prototype.spellCheck; -- -- --/** @type {boolean} */ --chrome.inputMethodPrivate.InputContext.prototype.shouldDoLearning; -- -- --/** @type {chrome.inputMethodPrivate.FocusReason} */ --chrome.inputMethodPrivate.InputContext.prototype.focusReason; -- -- --/** @type {boolean} */ --chrome.inputMethodPrivate.InputContext.prototype.hasBeenPassword; -- -- --/** -- * Commits the text currently being composed without moving the selected text -- * range. This is a no-op if the context is incorrect. -- * @param {{ -- * contextID: number -- * }} parameters Parameters for the finishComposingText API call. -- * @param {function(): void=} callback Called when the operation completes. -- */ --chrome.inputMethodPrivate.finishComposingText = function( -- parameters, callback) {}; -- -- --/** -- * Resets the current engine to its initial state. Fires an OnReset event. -- */ --chrome.inputMethodPrivate.reset = function() {}; -- -- - /** - * @const - * @see https://goo.gl/7dvJFW diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/compiler/README.md chromium-132.0.6834.159/third_party/closure_compiler/compiler/README.md --- chromium-132.0.6834.110/third_party/closure_compiler/compiler/README.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/compiler/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,563 +0,0 @@ -# [Google Closure Compiler](https://developers.google.com/closure/compiler/) - -The [Closure Compiler](https://developers.google.com/closure/compiler/) is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls. - -## Getting Started - * [Download the latest version](http://dl.google.com/closure-compiler/compiler-latest.zip) - * See the [Google Developers Site](https://developers.google.com/closure/compiler/docs/gettingstarted_app) for documentation including instructions for running the compiler from the command line. - -## Options for Getting Help -1. Post in the [Closure Compiler Discuss Group] (https://groups.google.com/forum/#!forum/closure-compiler-discuss) -2. Ask a question on [Stack Overflow](http://stackoverflow.com/questions/tagged/google-closure-compiler) -3. Consult the [FAQ](https://github.com/google/closure-compiler/wiki/FAQ) - -## Building it Yourself - -Note: The Closure Compiler requires [Java 7 or higher](http://www.java.com/). - -### Using [Ant](http://ant.apache.org/) - -1. Download the [Ant build tool](http://ant.apache.org/bindownload.cgi). - -2. At the root of the source tree, there is an Ant file named ```build.xml```. - To use it, navigate to the same directory and type the command - - ``` - ant jar - ``` - - This will produce a jar file called ```build/compiler.jar```. - -### Using [Eclipse](http://www.eclipse.org/) - -1. Download and open the [Eclipse IDE](http://www.eclipse.org/). -2. Navigate to ```File > New > Project ...``` and create a Java Projet. Give - the project a name. -3. Select ```Create project from existing source``` and choose the root of the - checked-out source tree as the existing directory. -3. Navigate to the ```build.xml``` file. You will see all the build rules in - the Outline pane. Run the ```jar``` rule to build the compiler in - ```build/compiler.jar```. - -## Running - -On the command line, type - -``` -java -jar compiler.jar -``` - -This starts the compiler in interactive mode. Type - -```javascript -var x = 17 + 25; -``` - -then hit "Enter", then hit "Ctrl-Z" (on Windows) or "Ctrl-D" (on Mac or Linux) -and "Enter" again. The Compiler will respond: - -```javascript -var x=42; -``` - -The Closure Compiler has many options for reading input from a file, writing -output to a file, checking your code, and running optimizations. To learn more, -type - -``` -java -jar compiler.jar --help -``` - -More detailed information about running the Closure Compiler is available in the -[documentation](http://code.google.com/closure/compiler/docs/gettingstarted_app.html). - -## Compiling Multiple Scripts - -If you have multiple scripts, you should compile them all together with one -compile command. - -```bash -java -jar compiler.jar --js_output_file=out.js in1.js in2.js in3.js ... -``` - -You can also use minimatch-style globs. - -```bash -# Recursively include all js files in subdirs -java -jar compiler.jar --js_output_file=out.js 'src/**.js' - -# Recursively include all js files in subdirs, exclusing test files. -# Use single-quotes, so that bash doesn't try to expand the '!' -java -jar compiler.jar --js_output_file=out.js 'src/**.js' '!**_test.js' -``` - -The Closure Compiler will concatenate the files in the order they're passed at -the command line. - -If you're using globs or many files, you may start to run into -problems with managing dependencies between scripts. In this case, you should -use the [Closure Library](https://developers.google.com/closure/library/). It -contains functions for enforcing dependencies between scripts, and Closure Compiler -will re-order the inputs automatically. - -## How to Contribute -### Reporting a bug -1. First make sure that it is really a bug and not simply the way that Closure Compiler works (especially true for ADVANCED_OPTIMIZATIONS). - * Check the [official documentation](https://developers.google.com/closure/compiler/) - * Consult the [FAQ](https://github.com/google/closure-compiler/wiki/FAQ) - * Search on [Stack Overflow](http://stackoverflow.com/questions/tagged/google-closure-compiler) and in the [Closure Compiler Discuss Group](https://groups.google.com/forum/#!forum/closure-compiler-discuss) -2. If you still think you have found a bug, make sure someone hasn't already reported it. See the list of [known issues](https://github.com/google/closure-compiler/issues). -3. If it hasn't been reported yet, post a new issue. Make sure to add enough detail so that the bug can be recreated. The smaller the reproduction code, the better. - -### Suggesting a Feature -1. Consult the [FAQ](https://github.com/google/closure-compiler/wiki/FAQ) to make sure that the behaviour you would like isn't specifically excluded (such as string inlining). -2. Make sure someone hasn't requested the same thing. See the list of [known issues](https://github.com/google/closure-compiler/issues). -3. Read up on [what type of feature requests are accepted](https://github.com/google/closure-compiler/wiki/FAQ#how-do-i-submit-a-feature-request-for-a-new-type-of-optimization). -4. Submit your reqest as an issue. - -### Submitting patches -1. All contributors must sign a contributor license agreement. See the [CONTRIBUTORS](https://raw.githubusercontent.com/google/closure-compiler/master/CONTRIBUTORS) file for details. -2. To make sure your changes are of the type that will be accepted, ask about your patch on the [Closure Compiler Discuss Group](https://groups.google.com/forum/#!forum/closure-compiler-discuss) -3. Fork the repository. -4. Make your changes. -5. Submit a pull request for your changes. A project developer will review your work and then merge your request into the project. - -## Closure Compiler License - -Copyright 2009 The Closure Compiler Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -## Dependency Licenses - -### Rhino - -Two copies of Rhino exist in this repository: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/rhino
URLhttp://www.mozilla.org/rhino
VersionTrunk
LicenseNetscape Public License and MPL / GPL dual license
DescriptionMozilla Rhino is an implementation of JavaScript for the JVM.
Local ModificationsMinor changes to parsing JSDoc that usually get pushed - up-stream to Rhino trunk.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Path - src/com/google/javascript/rhino, test/com/google/javascript/rhino -
URLhttp://www.mozilla.org/rhino
Version1.5R3, with heavy modifications
LicenseNetscape Public License and MPL / GPL dual license
DescriptionA partial copy of Mozilla Rhino. Mozilla Rhino is an -implementation of JavaScript for the JVM. The JavaScript parser and -the parse tree data structures were extracted and modified -significantly for use by Google's JavaScript compiler.
Local ModificationsThe packages have been renamespaced. All code not -relevant to parsing has been removed. A JsDoc parser and static typing -system have been added.
- -### Args4j - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/args4j.jar
URLhttps://args4j.dev.java.net/
Version2.0.26
LicenseMIT
Descriptionargs4j is a small Java class library that makes it easy to parse command line -options/arguments in your CUI application.
Local ModificationsNone
- -### Guava Libraries - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/guava.jar
URLhttp://code.google.com/p/guava-libraries/
Version17.0
LicenseApache License 2.0
DescriptionGoogle's core Java libraries.
Local ModificationsNone
- -### JSR 305 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/jsr305.jar
URLhttp://code.google.com/p/jsr-305/
Versionsvn revision 47
LicenseBSD License
DescriptionAnnotations for software defect detection.
Local ModificationsNone
- -### Jar Jar Links - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/jarjar.jar
URLhttp://jarjar.googlecode.com/
Version1.1
LicenseApache License 2.0
DescriptionA utility for repackaging Java libraries.
Local ModificationsNone
- -### JUnit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/junit.jar
URLhttp://sourceforge.net/projects/junit/
Version4.11
LicenseCommon Public License 1.0
DescriptionA framework for writing and running automated tests in Java.
Local ModificationsNone
- -### Protocol Buffers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/protobuf-java.jar
URLhttp://code.google.com/p/protobuf/
Version2.5.0
LicenseNew BSD License
DescriptionSupporting libraries for protocol buffers, -an encoding of structured data.
Local ModificationsNone
- -### Ant - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Path - lib/ant.jar, lib/ant-launcher.jar -
URLhttp://ant.apache.org/bindownload.cgi
Version1.8.1
LicenseApache License 2.0
DescriptionAnt is a Java based build tool. In theory it is kind of like "make" -without make's wrinkles and with the full portability of pure java code.
Local ModificationsNone
- -### JSON - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/json.jar
URLhttp://json.org/java/index.html
VersionJSON version 20090211
LicenseMIT license
DescriptionJSON is a set of java files for use in transmitting data in JSON format.
Local ModificationsNone
- -### Mockito - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/mockito-core.jar
URLhttps://code.google.com/p/mockito
Version1.9.5
LicenseMIT license
DescriptionMockito is an open source testing framework for Java. The framework allows the -creation of Test Double objects (called "Mock Objects") in automated unit tests -for the purpose of Test-driven Development (TDD) or Behavior Driven Development -(BDD).
Local ModificationsNone
- -### Objenesis - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Code Pathlib/objenesis.jar
URLhttp://objenesis.org
Version1.2
LicenseApache 2.0 license
DescriptionDepended by lib/mockito-core.jar, not used directly.
Local ModificationsNone
diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/compiler.py chromium-132.0.6834.159/third_party/closure_compiler/compiler.py --- chromium-132.0.6834.110/third_party/closure_compiler/compiler.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/compiler.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ -#!/usr/bin/python -# 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. - -"""Runs Closure compiler on JavaScript files to check for errors and produce -minified output.""" - -from __future__ import print_function - -import os -import subprocess - - -_CURRENT_DIR = os.path.join(os.path.dirname(__file__)) -_JAVA_PATH = os.path.join(_CURRENT_DIR, "..", "jdk", "current", "bin", "java") -assert os.path.isfile(_JAVA_PATH), "java only allowed in android builds" - -class Compiler(object): - """Runs the Closure compiler on given source files to typecheck them - and produce minified output.""" - - _JAR_COMMAND = [ - _JAVA_PATH, - "-jar", - "-Xms1024m", - "-client", - "-XX:+TieredCompilation", - ] - - def __init__(self, verbose=False): - """ - Args: - verbose: Whether this class should output diagnostic messages. - """ - self._compiler_jar = os.path.join(_CURRENT_DIR, "compiler", "compiler.jar") - self._verbose = verbose - - def _log_debug(self, msg, error=False): - """Logs |msg| to stdout if --verbose/-v is passed when invoking this script. - - Args: - msg: A debug message to log. - """ - if self._verbose: - print("(INFO) %s" % msg) - - def run_jar(self, jar, args): - """Runs a .jar from the command line with arguments. - - Args: - jar: A file path to a .jar file - args: A list of command line arguments to be passed when running the .jar. - - Return: - (exit_code, stderr) The exit code of the command (e.g. 0 for success) and - the stderr collected while running |jar| (as a string). - """ - shell_command = " ".join(self._JAR_COMMAND + [jar] + args) - self._log_debug("Running jar: %s" % shell_command) - - devnull = open(os.devnull, "w") - process = subprocess.Popen(shell_command, universal_newlines=True, - shell=True, stdout=devnull, - stderr=subprocess.PIPE) - _, stderr = process.communicate() - return process.returncode, stderr diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/OWNERS chromium-132.0.6834.159/third_party/closure_compiler/externs/OWNERS --- chromium-132.0.6834.110/third_party/closure_compiler/externs/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -khorimoto@chromium.org -rdevlin.cronin@chromium.org -stevenjb@chromium.org - -per-file accessibility_private.js=file://ui/accessibility/OWNERS -per-file automation.js=file://ui/accessibility/OWNERS -per-file braille_display_private.js=file://ui/accessibility/OWNERS -per-file input_method_private.js=file://ui/base/ime/OWNERS -per-file terminal_private.js=file://chrome/browser/extensions/api/terminal/OWNERS diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/accessibility_features.js chromium-132.0.6834.159/third_party/closure_compiler/externs/accessibility_features.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/accessibility_features.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/accessibility_features.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,133 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.accessibilityFeatures.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -// TODO(crbug.com/543822): Disable automatic extern generation until fixed. -// s/chrome.accessibilityFeatures.types.ChromeSetting/ChromeSetting/ - -/** - * @fileoverview Externs generated from namespace: accessibilityFeatures - * @externs - */ - -/** @const */ -chrome.accessibilityFeatures = {}; - -/** - *

ChromeOS only.

Spoken feedback (text-to-speech). The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-spokenFeedback - */ -chrome.accessibilityFeatures.spokenFeedback; - -/** - *

ChromeOS only.

Enlarged cursor. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-largeCursor - */ -chrome.accessibilityFeatures.largeCursor; - -/** - *

ChromeOS only.

Sticky modifier keys (like shift or alt). The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-stickyKeys - */ -chrome.accessibilityFeatures.stickyKeys; - -/** - *

ChromeOS only.

High contrast rendering mode. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-highContrast - */ -chrome.accessibilityFeatures.highContrast; - -/** - *

ChromeOS only.

Full screen magnification. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-screenMagnifier - */ -chrome.accessibilityFeatures.screenMagnifier; - -/** - *

ChromeOS only.

Auto mouse click after mouse stops moving. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-autoclick - */ -chrome.accessibilityFeatures.autoclick; - -/** - *

ChromeOS only.

Virtual on-screen keyboard. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-virtualKeyboard - */ -chrome.accessibilityFeatures.virtualKeyboard; - -/** - *

ChromeOS only.

Caret highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-caretHighlight - */ -chrome.accessibilityFeatures.caretHighlight; - -/** - *

ChromeOS only.

Cursor highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-cursorHighlight - */ -chrome.accessibilityFeatures.cursorHighlight; - -/** - *

ChromeOS only.

Cursor color. The value indicates whether the feature is enabled or not, doesn't indicate the color of it. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-cursorColor - */ -chrome.accessibilityFeatures.cursorColor; - -/** - *

ChromeOS only.

Docked magnifier. The value indicates whether docked magnifier feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-dockedMagnifier - */ -chrome.accessibilityFeatures.dockedMagnifier; - -/** - *

ChromeOS only.

Focus highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-focusHighlight - */ -chrome.accessibilityFeatures.focusHighlight; - -/** - *

ChromeOS only.

Select-to-speak. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-selectToSpeak - */ -chrome.accessibilityFeatures.selectToSpeak; - -/** - *

ChromeOS only.

Switch Access. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-switchAccess - */ -chrome.accessibilityFeatures.switchAccess; - -/** - * get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. - * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-animationPolicy - */ -chrome.accessibilityFeatures.animationPolicy; - -/** - *

ChromeOS only.

Dictation. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission.

- * @type {!ChromeSetting} - * @see https://developer.chrome.com/extensions/accessibilityFeatures#type-dictation - */ -chrome.accessibilityFeatures.dictation; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/accessibility_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/accessibility_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/accessibility_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/accessibility_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,963 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.accessibilityPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: accessibilityPrivate - * @externs - */ - -/** @const */ -chrome.accessibilityPrivate = {}; - -/** - * Information about an alert - * @typedef {{ - * message: string - * }} - */ -chrome.accessibilityPrivate.AlertInfo; - -/** - * Bounding rectangle in global screen coordinates. - * @typedef {{ - * left: number, - * top: number, - * width: number, - * height: number - * }} - */ -chrome.accessibilityPrivate.ScreenRect; - -/** - * Point in global screen coordinates. - * @typedef {{ - * x: number, - * y: number - * }} - */ -chrome.accessibilityPrivate.ScreenPoint; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.Gesture = { - CLICK: 'click', - SWIPE_LEFT1: 'swipeLeft1', - SWIPE_UP1: 'swipeUp1', - SWIPE_RIGHT1: 'swipeRight1', - SWIPE_DOWN1: 'swipeDown1', - SWIPE_LEFT2: 'swipeLeft2', - SWIPE_UP2: 'swipeUp2', - SWIPE_RIGHT2: 'swipeRight2', - SWIPE_DOWN2: 'swipeDown2', - SWIPE_LEFT3: 'swipeLeft3', - SWIPE_UP3: 'swipeUp3', - SWIPE_RIGHT3: 'swipeRight3', - SWIPE_DOWN3: 'swipeDown3', - SWIPE_LEFT4: 'swipeLeft4', - SWIPE_UP4: 'swipeUp4', - SWIPE_RIGHT4: 'swipeRight4', - SWIPE_DOWN4: 'swipeDown4', - TAP2: 'tap2', - TAP3: 'tap3', - TAP4: 'tap4', - TOUCH_EXPLORE: 'touchExplore', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.MagnifierCommand = { - MOVE_STOP: 'moveStop', - MOVE_UP: 'moveUp', - MOVE_DOWN: 'moveDown', - MOVE_LEFT: 'moveLeft', - MOVE_RIGHT: 'moveRight', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SwitchAccessCommand = { - SELECT: 'select', - NEXT: 'next', - PREVIOUS: 'previous', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.PointScanState = { - START: 'start', - STOP: 'stop', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SwitchAccessBubble = { - BACK_BUTTON: 'backButton', - MENU: 'menu', -}; - -/** - * @typedef {{ - * x: number, - * y: number - * }} - */ -chrome.accessibilityPrivate.PointScanPoint; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SwitchAccessMenuAction = { - COPY: 'copy', - CUT: 'cut', - DECREMENT: 'decrement', - DICTATION: 'dictation', - DRILL_DOWN: 'drillDown', - END_TEXT_SELECTION: 'endTextSelection', - INCREMENT: 'increment', - ITEM_SCAN: 'itemScan', - JUMP_TO_BEGINNING_OF_TEXT: 'jumpToBeginningOfText', - JUMP_TO_END_OF_TEXT: 'jumpToEndOfText', - KEYBOARD: 'keyboard', - LEFT_CLICK: 'leftClick', - MOVE_BACKWARD_ONE_CHAR_OF_TEXT: 'moveBackwardOneCharOfText', - MOVE_BACKWARD_ONE_WORD_OF_TEXT: 'moveBackwardOneWordOfText', - MOVE_CURSOR: 'moveCursor', - MOVE_DOWN_ONE_LINE_OF_TEXT: 'moveDownOneLineOfText', - MOVE_FORWARD_ONE_CHAR_OF_TEXT: 'moveForwardOneCharOfText', - MOVE_FORWARD_ONE_WORD_OF_TEXT: 'moveForwardOneWordOfText', - MOVE_UP_ONE_LINE_OF_TEXT: 'moveUpOneLineOfText', - PASTE: 'paste', - POINT_SCAN: 'pointScan', - RIGHT_CLICK: 'rightClick', - SCROLL_DOWN: 'scrollDown', - SCROLL_LEFT: 'scrollLeft', - SCROLL_RIGHT: 'scrollRight', - SCROLL_UP: 'scrollUp', - SELECT: 'select', - SETTINGS: 'settings', - START_TEXT_SELECTION: 'startTextSelection', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SyntheticKeyboardEventType = { - KEYUP: 'keyup', - KEYDOWN: 'keydown', -}; - -/** - * @typedef {{ - * ctrl: (boolean|undefined), - * alt: (boolean|undefined), - * search: (boolean|undefined), - * shift: (boolean|undefined) - * }} - */ -chrome.accessibilityPrivate.SyntheticKeyboardModifiers; - -/** - * @typedef {{ - * type: !chrome.accessibilityPrivate.SyntheticKeyboardEventType, - * keyCode: number, - * modifiers: (!chrome.accessibilityPrivate.SyntheticKeyboardModifiers|undefined) - * }} - */ -chrome.accessibilityPrivate.SyntheticKeyboardEvent; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SyntheticMouseEventType = { - PRESS: 'press', - RELEASE: 'release', - DRAG: 'drag', - MOVE: 'move', - ENTER: 'enter', - EXIT: 'exit', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SyntheticMouseEventButton = { - LEFT: 'left', - MIDDLE: 'middle', - RIGHT: 'right', - BACK: 'back', - FOWARD: 'foward', -}; - -/** - * @typedef {{ - * type: !chrome.accessibilityPrivate.SyntheticMouseEventType, - * x: number, - * y: number, - * touchAccessibility: (boolean|undefined), - * mouseButton: (!chrome.accessibilityPrivate.SyntheticMouseEventButton|undefined), - * isDoubleClick: (boolean|undefined), - * isTripleClick: (boolean|undefined), - * useRewriters: (boolean|undefined) - * }} - */ -chrome.accessibilityPrivate.SyntheticMouseEvent; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SelectToSpeakState = { - SELECTING: 'selecting', - SPEAKING: 'speaking', - INACTIVE: 'inactive', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.FocusType = { - GLOW: 'glow', - SOLID: 'solid', - DASHED: 'dashed', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.FocusRingStackingOrder = { - ABOVE_ACCESSIBILITY_BUBBLES: 'aboveAccessibilityBubbles', - BELOW_ACCESSIBILITY_BUBBLES: 'belowAccessibilityBubbles', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.AssistiveTechnologyType = { - CHROME_VOX: 'chromeVox', - SELECT_TO_SPEAK: 'selectToSpeak', - SWITCH_ACCESS: 'switchAccess', - AUTO_CLICK: 'autoClick', - MAGNIFIER: 'magnifier', - DICTATION: 'dictation', -}; - -/** - * @typedef {{ - * rects: !Array, - * type: !chrome.accessibilityPrivate.FocusType, - * color: string, - * secondaryColor: (string|undefined), - * backgroundColor: (string|undefined), - * stackingOrder: (!chrome.accessibilityPrivate.FocusRingStackingOrder|undefined), - * id: (string|undefined) - * }} - */ -chrome.accessibilityPrivate.FocusRingInfo; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.AcceleratorAction = { - FOCUS_PREVIOUS_PANE: 'focusPreviousPane', - FOCUS_NEXT_PANE: 'focusNextPane', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.AccessibilityFeature = { - DICTATION_CONTEXT_CHECKING: 'dictationContextChecking', - FACE_GAZE: 'faceGaze', - GOOGLE_TTS_HIGH_QUALITY_VOICES: 'googleTtsHighQualityVoices', - FACE_GAZE_GRAVITY_WELLS: 'faceGazeGravityWells', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SelectToSpeakPanelAction = { - PREVIOUS_PARAGRAPH: 'previousParagraph', - PREVIOUS_SENTENCE: 'previousSentence', - PAUSE: 'pause', - RESUME: 'resume', - NEXT_SENTENCE: 'nextSentence', - NEXT_PARAGRAPH: 'nextParagraph', - EXIT: 'exit', - CHANGE_SPEED: 'changeSpeed', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.SetNativeChromeVoxResponse = { - SUCCESS: 'success', - TALKBACK_NOT_INSTALLED: 'talkbackNotInstalled', - WINDOW_NOT_FOUND: 'windowNotFound', - FAILURE: 'failure', - NEED_DEPRECATION_CONFIRMATION: 'needDeprecationConfirmation', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.DictationBubbleIconType = { - HIDDEN: 'hidden', - STANDBY: 'standby', - MACRO_SUCCESS: 'macroSuccess', - MACRO_FAIL: 'macroFail', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.DictationBubbleHintType = { - TRY_SAYING: 'trySaying', - TYPE: 'type', - DELETE: 'delete', - SELECT_ALL: 'selectAll', - UNDO: 'undo', - HELP: 'help', - UNSELECT: 'unselect', - COPY: 'copy', -}; - -/** - * @typedef {{ - * visible: boolean, - * icon: !chrome.accessibilityPrivate.DictationBubbleIconType, - * text: (string|undefined), - * hints: (!Array|undefined) - * }} - */ -chrome.accessibilityPrivate.DictationBubbleProperties; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.ToastType = { - DICTATION_NO_FOCUSED_TEXT_FIELD: 'dictationNoFocusedTextField', - DICTATION_MIC_MUTED: 'dictationMicMuted', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.DlcType = { - TTS_BN_BD: 'ttsBnBd', - TTS_CS_CZ: 'ttsCsCz', - TTS_DA_DK: 'ttsDaDk', - TTS_DE_DE: 'ttsDeDe', - TTS_EL_GR: 'ttsElGr', - TTS_EN_AU: 'ttsEnAu', - TTS_EN_GB: 'ttsEnGb', - TTS_EN_US: 'ttsEnUs', - TTS_ES_ES: 'ttsEsEs', - TTS_ES_US: 'ttsEsUs', - TTS_FI_FI: 'ttsFiFi', - TTS_FIL_PH: 'ttsFilPh', - TTS_FR_FR: 'ttsFrFr', - TTS_HI_IN: 'ttsHiIn', - TTS_HU_HU: 'ttsHuHu', - TTS_ID_ID: 'ttsIdId', - TTS_IT_IT: 'ttsItIt', - TTS_JA_JP: 'ttsJaJp', - TTS_KM_KH: 'ttsKmKh', - TTS_KO_KR: 'ttsKoKr', - TTS_NB_NO: 'ttsNbNo', - TTS_NE_NP: 'ttsNeNp', - TTS_NL_NL: 'ttsNlNl', - TTS_PL_PL: 'ttsPlPl', - TTS_PT_BR: 'ttsPtBr', - TTS_PT_PT: 'ttsPtPt', - TTS_SI_LK: 'ttsSiLk', - TTS_SK_SK: 'ttsSkSk', - TTS_SV_SE: 'ttsSvSe', - TTS_TH_TH: 'ttsThTh', - TTS_TR_TR: 'ttsTrTr', - TTS_UK_UA: 'ttsUkUa', - TTS_VI_VN: 'ttsViVn', - TTS_YUE_HK: 'ttsYueHk', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.TtsVariant = { - LITE: 'lite', - STANDARD: 'standard', -}; - -/** - * @typedef {{ - * js_pumpkin_tagger_bin_js: ArrayBuffer, - * tagger_wasm_main_js: ArrayBuffer, - * tagger_wasm_main_wasm: ArrayBuffer, - * en_us_action_config_binarypb: ArrayBuffer, - * en_us_pumpkin_config_binarypb: ArrayBuffer, - * fr_fr_action_config_binarypb: ArrayBuffer, - * fr_fr_pumpkin_config_binarypb: ArrayBuffer, - * it_it_action_config_binarypb: ArrayBuffer, - * it_it_pumpkin_config_binarypb: ArrayBuffer, - * de_de_action_config_binarypb: ArrayBuffer, - * de_de_pumpkin_config_binarypb: ArrayBuffer, - * es_es_action_config_binarypb: ArrayBuffer, - * es_es_pumpkin_config_binarypb: ArrayBuffer - * }} - */ -chrome.accessibilityPrivate.PumpkinData; - -/** - * @typedef {{ - * model: ArrayBuffer, - * wasm: ArrayBuffer - * }} - */ -chrome.accessibilityPrivate.FaceGazeAssets; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.ScrollDirection = { - UP: 'up', - DOWN: 'down', - LEFT: 'left', - RIGHT: 'right', -}; - -/** - * @enum {string} - */ -chrome.accessibilityPrivate.FacialGesture = { - BROW_INNER_UP: 'browInnerUp', - BROWS_DOWN: 'browsDown', - EYE_SQUINT_LEFT: 'eyeSquintLeft', - EYE_SQUINT_RIGHT: 'eyeSquintRight', - EYES_BLINK: 'eyesBlink', - EYES_LOOK_DOWN: 'eyesLookDown', - EYES_LOOK_LEFT: 'eyesLookLeft', - EYES_LOOK_RIGHT: 'eyesLookRight', - EYES_LOOK_UP: 'eyesLookUp', - JAW_LEFT: 'jawLeft', - JAW_OPEN: 'jawOpen', - JAW_RIGHT: 'jawRight', - MOUTH_FUNNEL: 'mouthFunnel', - MOUTH_LEFT: 'mouthLeft', - MOUTH_PUCKER: 'mouthPucker', - MOUTH_RIGHT: 'mouthRight', - MOUTH_SMILE: 'mouthSmile', - MOUTH_UPPER_UP: 'mouthUpperUp', -}; - -/** - * Information about a detected facial gesture. - * @typedef {{ - * gesture: !chrome.accessibilityPrivate.FacialGesture, - * confidence: number - * }} - */ -chrome.accessibilityPrivate.GestureInfo; - -/** - * Property to indicate whether event source should default to touch. - * @type {number} - */ -chrome.accessibilityPrivate.IS_DEFAULT_EVENT_SOURCE_TOUCH; - -/** - * Called to translate localeCodeToTranslate into human-readable string in the - * locale specified by displayLocaleCode - * @param {string} localeCodeToTranslate - * @param {string} displayLocaleCode - * @return {string} The human-readable locale string in the provided locale. - */ -chrome.accessibilityPrivate.getDisplayNameForLocale = function(localeCodeToTranslate, displayLocaleCode) {}; - -/** - * Called to request battery status from Chrome OS system. - * @param {function(string): void} callback Returns battery description as a - * string. - */ -chrome.accessibilityPrivate.getBatteryDescription = function(callback) {}; - -/** - * Called to request an install of the Pumpkin semantic parser for Dictation. - * @param {function(!chrome.accessibilityPrivate.PumpkinData): void} callback - * Runs when Pumpkin download finishes. - */ -chrome.accessibilityPrivate.installPumpkinForDictation = function(callback) {}; - -/** - * Called to request an install of the FaceGaze assets DLC, which contains files - * (e.g. the FaceLandmarker model) required for FaceGaze to work. - * @param {function(!chrome.accessibilityPrivate.FaceGazeAssets): void} callback - * Runs when the DLC download finishes. - */ -chrome.accessibilityPrivate.installFaceGazeAssets = function(callback) {}; - -/** - * Enables or disables native accessibility support. Once disabled, it is up to - * the calling extension to provide accessibility for web contents. - * @param {boolean} enabled True if native accessibility support should be - * enabled. - */ -chrome.accessibilityPrivate.setNativeAccessibilityEnabled = function(enabled) {}; - -/** - * Sets the given accessibility focus rings for this extension. - * @param {!Array} focusRings Array - * of focus rings to draw. - * @param {!chrome.accessibilityPrivate.AssistiveTechnologyType} atType - * Associates these focus rings with this feature type. - */ -chrome.accessibilityPrivate.setFocusRings = function(focusRings, atType) {}; - -/** - * Sets the bounds of the accessibility highlight. - * @param {!Array} rects Array of - * rectangles to draw the highlight around. - * @param {string} color CSS-style hex color string beginning with # like - * #FF9982 or #EEE. - */ -chrome.accessibilityPrivate.setHighlights = function(rects, color) {}; - -/** - * Informs the system where Chrome Vox's focus is in screen coordinates when - * Magnifier is enabled. No-op when Magnifier is not enabled. Causes - * chrome.accessibilityPrivate.onChromeVoxFocusChanged to be fired within the - * AccessibilityCommon component extension. - * @param {!chrome.accessibilityPrivate.ScreenRect} bounds Bounds of current - * ChromeVox focus ring. - */ -chrome.accessibilityPrivate.setChromeVoxFocus = function(bounds) {}; - -/** - * Informs the system where Select to Speak's reading focus is in screen - * coordinates when Magnifier is enabled. No-op when Magnifier is not enabled. - * Causes chrome.accessibilityPrivate.onSelectToSpeakFocusChanged to be fired - * within the AccessibilityCommon component extension. - * @param {!chrome.accessibilityPrivate.ScreenRect} bounds Bounds of currently - * spoken word (if available) or node (if the spoken node is not a text - * node). - */ -chrome.accessibilityPrivate.setSelectToSpeakFocus = function(bounds) {}; - -/** - * Sets the calling extension as a listener of all keyboard events optionally - * allowing the calling extension to capture/swallow the key event via DOM apis. - * Returns false via callback when unable to set the listener. - * @param {boolean} enabled True if the caller wants to listen to key events; - * false to stop listening to events. Note that there is only ever one - * extension listening to key events. - * @param {boolean} capture True if key events should be swallowed natively and - * not propagated if preventDefault() gets called by the extension's - * background page. - */ -chrome.accessibilityPrivate.setKeyboardListener = function(enabled, capture) {}; - -/** - * Darkens or undarkens the screen. - * @param {boolean} darken True to darken screen; false to undarken screen. - */ -chrome.accessibilityPrivate.darkenScreen = function(darken) {}; - -/** - * When enabled, forwards key events to the Switch Access extension - * @param {boolean} shouldForward - */ -chrome.accessibilityPrivate.forwardKeyEventsToSwitchAccess = function(shouldForward) {}; - -/** - * Shows the Switch Access menu next to the specified rectangle and with the - * given actions - * @param {!chrome.accessibilityPrivate.SwitchAccessBubble} bubble Which bubble - * to show/hide - * @param {boolean} show True if the bubble should be shown, false otherwise - * @param {!chrome.accessibilityPrivate.ScreenRect=} anchor A rectangle - * indicating the bounds of the object the menu should be displayed next to. - * @param {!Array=} actions - * The actions to be shown in the menu. - */ -chrome.accessibilityPrivate.updateSwitchAccessBubble = function(bubble, show, anchor, actions) {}; - -/** - * Sets point scanning state Switch Access. - * @param {!chrome.accessibilityPrivate.PointScanState} state The point scanning - * state to set. - */ -chrome.accessibilityPrivate.setPointScanState = function(state) {}; - -/** - * Sets current ARC app to use native ARC support. - * @param {boolean} enabled True for ChromeVox (native), false for TalkBack. - * @param {function(!chrome.accessibilityPrivate.SetNativeChromeVoxResponse): void} - * callback - */ -chrome.accessibilityPrivate.setNativeChromeVoxArcSupportForCurrentApp = function(enabled, callback) {}; - -/** - * Sends a fabricated key event. - * @param {!chrome.accessibilityPrivate.SyntheticKeyboardEvent} keyEvent The - * event to send. - * @param {boolean=} useRewriters If true, uses rewriters for the key event; - * only allowed if used from Dictation or FaceGaze. Otherwise indicates that - * rewriters should be skipped. - * @param {boolean=} isRepeat If true, sets the key event to repeat, which - * should occur if the key event should be held. Otherwise, the key event - * should not repeat. - */ -chrome.accessibilityPrivate.sendSyntheticKeyEvent = function( - keyEvent, useRewriters, isRepeat) {}; - -/** - * Enables or disables mouse events in accessibility extensions - * @param {boolean} enabled True if accessibility component extensions should - * receive mouse events. - */ -chrome.accessibilityPrivate.enableMouseEvents = function(enabled) {}; - -/** - * Sets the cursor position on the screen in absolute screen coordinates. - * @param {!chrome.accessibilityPrivate.ScreenPoint} point The screen point at - * which to put the cursor. - */ -chrome.accessibilityPrivate.setCursorPosition = function(point) {}; - -/** - * Sends a fabricated mouse event. - * @param {!chrome.accessibilityPrivate.SyntheticMouseEvent} mouseEvent The - * event to send. - */ -chrome.accessibilityPrivate.sendSyntheticMouseEvent = function(mouseEvent) {}; - -/** - * Called by the Select-to-Speak extension when Select-to-Speak has changed - * states, between selecting with the mouse, speaking, and inactive. - * @param {!chrome.accessibilityPrivate.SelectToSpeakState} state - */ -chrome.accessibilityPrivate.setSelectToSpeakState = function(state) {}; - -/** - * Called by the Select-to-Speak extension to request a clipboard copy in the - * active Lacros Google Docs tab for the copy-paste fallback. - * @param {string} url URL of the Google Docs tab. - */ -chrome.accessibilityPrivate.clipboardCopyInActiveLacrosGoogleDoc = function(url) {}; - -/** - * Called by the Accessibility Common extension when - * onScrollableBoundsForPointRequested has found a scrolling container. |rect| - * will be the bounds of the nearest scrollable ancestor of the node at the - * point requested using onScrollableBoundsForPointRequested. - * @param {!chrome.accessibilityPrivate.ScreenRect} rect - */ -chrome.accessibilityPrivate.handleScrollableBoundsForPointFound = function(rect) {}; - -/** - * Called by the Accessibility Common extension to move |rect| within the - * magnifier viewport (e.g. when focus has changed). If |rect| is already - * completely within the viewport, magnifier doesn't move. If any edge of |rect| - * is outside the viewport (e.g. if rect is larger than or extends partially - * beyond the viewport), magnifier will center the overflowing dimensions of the - * viewport on center of |rect| (e.g. center viewport vertically if |rect| - * extends beyond bottom of screen). - * @param {!chrome.accessibilityPrivate.ScreenRect} rect Rect to ensure visible - * in the magnified viewport. - */ -chrome.accessibilityPrivate.moveMagnifierToRect = function(rect) {}; - -/** - * Called by the Accessibility Common extension to center magnifier at |point|. - * @param {!chrome.accessibilityPrivate.ScreenPoint} point - */ -chrome.accessibilityPrivate.magnifierCenterOnPoint = function(point) {}; - -/** - * Toggles dictation between active and inactive states. - */ -chrome.accessibilityPrivate.toggleDictation = function() {}; - -/** - * Shows or hides the virtual keyboard. - * @param {boolean} isVisible - */ -chrome.accessibilityPrivate.setVirtualKeyboardVisible = function(isVisible) {}; - -/** - * Opens a specified settings subpage. To open a page with url - * chrome://settings/manageAccessibility/tts, pass in the substring - * 'manageAccessibility/tts'. - * @param {string} subpage - */ -chrome.accessibilityPrivate.openSettingsSubpage = function(subpage) {}; - -/** - * Performs an accelerator action. - * @param {!chrome.accessibilityPrivate.AcceleratorAction} acceleratorAction - */ -chrome.accessibilityPrivate.performAcceleratorAction = function(acceleratorAction) {}; - -/** - * Checks to see if an accessibility feature is enabled. - * @param {!chrome.accessibilityPrivate.AccessibilityFeature} feature - * @param {function(boolean): void} callback Returns whether feature is enabled. - */ -chrome.accessibilityPrivate.isFeatureEnabled = function(feature, callback) {}; - -/** - * Updates properties of the Select-to-speak panel. - * @param {boolean} show True to show panel, false to hide it - * @param {!chrome.accessibilityPrivate.ScreenRect=} anchor A rectangle - * indicating the bounds of the object the panel should be displayed next - * to. - * @param {boolean=} isPaused True if Select-to-speak playback is paused. - * @param {number=} speed Current reading speed (TTS speech rate). - */ -chrome.accessibilityPrivate.updateSelectToSpeakPanel = function(show, anchor, isPaused, speed) {}; - -/** - * Shows a confirmation dialog. - * @param {string} title The title of the confirmation dialog. - * @param {string} description The description to show within the confirmation - * dialog. - * @param {?string|undefined} cancelName The human-readable name of the cancel - * button. - * @param {function(boolean): void} callback Called when the dialog is confirmed - * or cancelled. - */ -chrome.accessibilityPrivate.showConfirmationDialog = function(title, description, cancelName, callback) {}; - -/** - * Gets the DOM key string for the given key code, taking into account the - * current input method locale, and assuming the key code is for U.S. input. For - * example, the key code for '/' would return the string '!' if the current - * input method is French. - * @param {number} keyCode - * @param {function(string): void} callback Called with the resulting Dom key - * string. - */ -chrome.accessibilityPrivate.getLocalizedDomKeyStringForKeyCode = function(keyCode, callback) {}; - -/** - * Updates Dictation's bubble UI. - * @param {!chrome.accessibilityPrivate.DictationBubbleProperties} properties - * Properties for the updated Dictation bubble UI. - */ -chrome.accessibilityPrivate.updateDictationBubble = function(properties) {}; - -/** - * Cancels the current and queued speech from ChromeVox. - */ -chrome.accessibilityPrivate.silenceSpokenFeedback = function() {}; - -/** - * Returns the contents of a DLC. - * @param {!chrome.accessibilityPrivate.DlcType} dlc The DLC of interest. - * @param {function(ArrayBuffer): void} callback A callback that is run when the - * contents are returned. - */ -chrome.accessibilityPrivate.getDlcContents = function(dlc, callback) {}; - -/** - * Returns the contents of a TTS DLC. - * @param {!chrome.accessibilityPrivate.DlcType} dlc The DLC of interest. - * @param {!chrome.accessibilityPrivate.TtsVariant} variant The TTS voice - * variant. - * @param {function(ArrayBuffer): void} callback A callback that is run when the - * contents are returned. - */ -chrome.accessibilityPrivate.getTtsDlcContents = function(dlc, variant, callback) {}; - -/** - * Returns the bounds of the displays in density-independent pixels in screen - * coordinates. - * @param {function(!Array): void} - * callback A callback that is run when the result is returned. - */ -chrome.accessibilityPrivate.getDisplayBounds = function(callback) {}; - -/** - * Gets whether new browser windows and tabs should be in Lacros browser. - * @param {function(boolean): void} callback A callback that is run when the - * result is returned. - */ -chrome.accessibilityPrivate.isLacrosPrimary = function(callback) {}; - -/** - * Displays an accessibility-related toast. - * @param {!chrome.accessibilityPrivate.ToastType} type The type of toast to - * show. - */ -chrome.accessibilityPrivate.showToast = function(type) {}; - -/** - * Scrolls at the target location in the specified direction. - * @param {!chrome.accessibilityPrivate.ScreenPoint} target - * @param {!chrome.accessibilityPrivate.ScrollDirection} direction - */ -chrome.accessibilityPrivate.scrollAtPoint = function(target, direction) {}; - -/** - * Fired when FaceGaze processes a video frame, detects facial gestures from the - * frame, then sends information about the recognized facial gesture to the - * settings. - * @param {!Array} gestureInfo The - * recognized facial gestures and their associated confidence values. - */ -chrome.accessibilityPrivate.sendGestureInfoToSettings = function(gestureInfo) {}; - -/** - * Updates FaceGaze's bubble UI. - * @param {string} text The text to be displayed in the bubble UI. - * @param {boolean=} isWarning True if the bubble UI contains a warning about - * state. - */ -chrome.accessibilityPrivate.updateFaceGazeBubble = function(text, isWarning) {}; - -/** - * Turns on/off the DragEventRewriter, which rewrites kMouseMoved events into - * kMouseDragged events. - * @param {boolean} enabled Whether or not the DragEventRewriter should be - * enabled. - */ -chrome.accessibilityPrivate.enableDragEventRewriter = function(enabled) {}; - -/** - * Fired whenever ChromeVox should output introduction. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onIntroduceChromeVox; - -/** - * Fired when the ChromeVox focus changes and Magnifier is enabled. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onChromeVoxFocusChanged; - -/** - * Fired when an accessibility gesture is detected by the touch exploration - * controller. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onAccessibilityGesture; - -/** - * Fired when the Select to Speak context menu is clicked from outside the - * context of the Select to Speak extension. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onSelectToSpeakContextMenuClicked; - -/** - * Fired when the Select to Speak reading focus changes and Magnifier is - * enabled. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onSelectToSpeakFocusChanged; - -/** - * Fired when Chrome OS wants to change the Select-to-Speak state, between - * selecting with the mouse, speaking, and inactive. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onSelectToSpeakStateChangeRequested; - -/** - * Fired when Chrome OS wants to send an updated list of keys currently pressed - * to Select to Speak. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onSelectToSpeakKeysPressedChanged; - -/** - * Fired when Chrome OS wants to send a mouse event Select to Speak. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onSelectToSpeakMouseChanged; - -/** - * Fired when an action is performed in the Select-to-speak panel. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onSelectToSpeakPanelAction; - -/** - * Fired when Chrome OS has received a key event corresponding to a Switch - * Access command. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onSwitchAccessCommand; - -/** - * Fired when Chrome OS has received the final point of point scanning. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onPointScanSet; - -/** - * Fired when Chrome OS has received a key event corresponding to a Magnifier - * command. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onMagnifierCommand; - -/** - * Fired when an internal component within accessibility wants to force speech - * output for an accessibility extension. Do not use without approval from - * accessibility owners. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onAnnounceForAccessibility; - -/** - * Fired when an internal component within accessibility wants to find the - * nearest scrolling container at a given screen coordinate. Used in Automatic - * Clicks. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onScrollableBoundsForPointRequested; - -/** - * Fired when Chrome OS magnifier bounds are updated. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onMagnifierBoundsChanged; - -/** - * Fired when a custom spoken feedback on the active window gets enabled or - * disabled. Called from ARC++ accessibility. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onCustomSpokenFeedbackToggled; - -/** - * Fired when ChromeVox should show its tutorial. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onShowChromeVoxTutorial; - -/** - * Fired when Dictation is activated or deactivated using a keyboard shortcut, - * the button in the tray, or after a call from - * accessibilityPrivate.toggleDictation - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onToggleDictation; - -/** - * Fired only from the FaceGaze settings when the settings page requests to - * receive or stop receiving gesture detection information from FaceGaze. - * @type {!ChromeEvent} - */ -chrome.accessibilityPrivate.onToggleGestureInfoForSettings; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/arc_apps_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/arc_apps_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/arc_apps_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/arc_apps_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.arcAppsPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: arcAppsPrivate - * @externs - */ - -/** @const */ -chrome.arcAppsPrivate = {}; - -/** - * @typedef {{ - * packageName: string - * }} - */ -chrome.arcAppsPrivate.AppInfo; - -/** - * Returns info of the installed ARC apps that are launchable, including ready - * and non-ready apps. - * @param {function(!Array): void} callback - */ -chrome.arcAppsPrivate.getLaunchableApps = function(callback) {}; - -/** - * Launches the ARC app with its package name. The app is launched immediately - * if it's ready, otherwise it will be launched when it becomes ready. The - * callback is called as soon as the launch is scheduled. - * @param {string} packageName - * @param {function(): void=} callback - */ -chrome.arcAppsPrivate.launchApp = function(packageName, callback) {}; - -/** - * Fires when a new app can be launched via $(ref:launchApp). - * @type {!ChromeEvent} - */ -chrome.arcAppsPrivate.onInstalled; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/audio.js chromium-132.0.6834.159/third_party/closure_compiler/externs/audio.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/audio.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/audio.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,186 +0,0 @@ -// 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. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.audio.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: audio - * @externs - */ - -/** @const */ -chrome.audio = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/audio#type-StreamType - */ -chrome.audio.StreamType = { - INPUT: 'INPUT', - OUTPUT: 'OUTPUT', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/audio#type-DeviceType - */ -chrome.audio.DeviceType = { - HEADPHONE: 'HEADPHONE', - MIC: 'MIC', - USB: 'USB', - BLUETOOTH: 'BLUETOOTH', - HDMI: 'HDMI', - INTERNAL_SPEAKER: 'INTERNAL_SPEAKER', - INTERNAL_MIC: 'INTERNAL_MIC', - FRONT_MIC: 'FRONT_MIC', - REAR_MIC: 'REAR_MIC', - KEYBOARD_MIC: 'KEYBOARD_MIC', - HOTWORD: 'HOTWORD', - LINEOUT: 'LINEOUT', - POST_MIX_LOOPBACK: 'POST_MIX_LOOPBACK', - POST_DSP_LOOPBACK: 'POST_DSP_LOOPBACK', - ALSA_LOOPBACK: 'ALSA_LOOPBACK', - OTHER: 'OTHER', -}; - -/** - * @typedef {{ - * id: string, - * streamType: !chrome.audio.StreamType, - * deviceType: !chrome.audio.DeviceType, - * displayName: string, - * deviceName: string, - * isActive: boolean, - * level: number, - * stableDeviceId: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/audio#type-AudioDeviceInfo - */ -chrome.audio.AudioDeviceInfo; - -/** - * @typedef {{ - * streamTypes: (!Array|undefined), - * isActive: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/audio#type-DeviceFilter - */ -chrome.audio.DeviceFilter; - -/** - * @typedef {{ - * level: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/audio#type-DeviceProperties - */ -chrome.audio.DeviceProperties; - -/** - * @typedef {{ - * input: (!Array|undefined), - * output: (!Array|undefined) - * }} - * @see https://developer.chrome.com/extensions/audio#type-DeviceIdLists - */ -chrome.audio.DeviceIdLists; - -/** - * @typedef {{ - * streamType: !chrome.audio.StreamType, - * isMuted: boolean - * }} - * @see https://developer.chrome.com/extensions/audio#type-MuteChangedEvent - */ -chrome.audio.MuteChangedEvent; - -/** - * @typedef {{ - * deviceId: string, - * level: number - * }} - * @see https://developer.chrome.com/extensions/audio#type-LevelChangedEvent - */ -chrome.audio.LevelChangedEvent; - -/** - * Gets a list of audio devices filtered based on |filter|. - * @param {?chrome.audio.DeviceFilter|undefined} filter Device properties by - * which to filter the list of returned audio devices. If the filter is - * not set or set to {}, returned device list will contain - * all available audio devices. - * @param {function(!Array): void} callback - * Reports the requested list of audio devices. - * @see https://developer.chrome.com/extensions/audio#method-getDevices - */ -chrome.audio.getDevices = function(filter, callback) {}; - -/** - * Sets lists of active input and/or output devices. - * @param {!chrome.audio.DeviceIdLists} ids

Specifies IDs of devices that - * should be active. If either the input or output list is not set, - * devices in that category are unaffected.

It is an - * error to pass in a non-existent device ID.

- * @param {function(): void} callback - * @see https://developer.chrome.com/extensions/audio#method-setActiveDevices - */ -chrome.audio.setActiveDevices = function(ids, callback) {}; - -/** - * Sets the properties for the input or output device. - * @param {string} id - * @param {!chrome.audio.DeviceProperties} properties - * @param {function(): void} callback - * @see https://developer.chrome.com/extensions/audio#method-setProperties - */ -chrome.audio.setProperties = function(id, properties, callback) {}; - -/** - * Gets the system-wide mute state for the specified stream type. - * @param {!chrome.audio.StreamType} streamType Stream type for which mute state - * should be fetched. - * @param {function(boolean): void} callback Callback reporting whether mute is - * set or not for specified stream type. - * @see https://developer.chrome.com/extensions/audio#method-getMute - */ -chrome.audio.getMute = function(streamType, callback) {}; - -/** - * Sets mute state for a stream type. The mute state will apply to all audio - * devices with the specified audio stream type. - * @param {!chrome.audio.StreamType} streamType Stream type for which mute state - * should be set. - * @param {boolean} isMuted New mute value. - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/audio#method-setMute - */ -chrome.audio.setMute = function(streamType, isMuted, callback) {}; - -/** - * Fired when sound level changes for an active audio device. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/audio#event-onLevelChanged - */ -chrome.audio.onLevelChanged; - -/** - * Fired when the mute state of the audio input or output changes. Note that - * mute state is system-wide and the new value applies to every audio device - * with specified stream type. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/audio#event-onMuteChanged - */ -chrome.audio.onMuteChanged; - -/** - * Fired when audio devices change, either new devices being added, or existing - * devices being removed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/audio#event-onDeviceListChanged - */ -chrome.audio.onDeviceListChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/bluetooth.js chromium-132.0.6834.159/third_party/closure_compiler/externs/bluetooth.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/bluetooth.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/bluetooth.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,193 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.bluetooth.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: bluetooth - * @externs - */ - -/** @const */ -chrome.bluetooth = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/bluetooth#type-VendorIdSource - */ -chrome.bluetooth.VendorIdSource = { - BLUETOOTH: 'bluetooth', - USB: 'usb', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/bluetooth#type-DeviceType - */ -chrome.bluetooth.DeviceType = { - COMPUTER: 'computer', - PHONE: 'phone', - MODEM: 'modem', - AUDIO: 'audio', - CAR_AUDIO: 'carAudio', - VIDEO: 'video', - PERIPHERAL: 'peripheral', - JOYSTICK: 'joystick', - GAMEPAD: 'gamepad', - KEYBOARD: 'keyboard', - MOUSE: 'mouse', - TABLET: 'tablet', - KEYBOARD_MOUSE_COMBO: 'keyboardMouseCombo', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/bluetooth#type-FilterType - */ -chrome.bluetooth.FilterType = { - ALL: 'all', - KNOWN: 'known', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/bluetooth#type-Transport - */ -chrome.bluetooth.Transport = { - INVALID: 'invalid', - CLASSIC: 'classic', - LE: 'le', - DUAL: 'dual', -}; - -/** - * @typedef {{ - * address: string, - * name: string, - * powered: boolean, - * available: boolean, - * discovering: boolean - * }} - * @see https://developer.chrome.com/extensions/bluetooth#type-AdapterState - */ -chrome.bluetooth.AdapterState; - -/** - * @typedef {{ - * address: string, - * name: (string|undefined), - * deviceClass: (number|undefined), - * vendorIdSource: (!chrome.bluetooth.VendorIdSource|undefined), - * vendorId: (number|undefined), - * productId: (number|undefined), - * deviceId: (number|undefined), - * type: (!chrome.bluetooth.DeviceType|undefined), - * paired: (boolean|undefined), - * connected: (boolean|undefined), - * connecting: (boolean|undefined), - * connectable: (boolean|undefined), - * uuids: (!Array|undefined), - * inquiryRssi: (number|undefined), - * inquiryTxPower: (number|undefined), - * transport: (!chrome.bluetooth.Transport|undefined), - * batteryPercentage: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/bluetooth#type-Device - */ -chrome.bluetooth.Device; - -/** - * @typedef {{ - * filterType: (!chrome.bluetooth.FilterType|undefined), - * limit: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/bluetooth#type-BluetoothFilter - */ -chrome.bluetooth.BluetoothFilter; - -/** - * Get information about the Bluetooth adapter. - * @param {function(!chrome.bluetooth.AdapterState): void} callback Called with - * an AdapterState object describing the adapter state. - * @see https://developer.chrome.com/extensions/bluetooth#method-getAdapterState - */ -chrome.bluetooth.getAdapterState = function(callback) {}; - -/** - * Get information about a Bluetooth device known to the system. - * @param {string} deviceAddress Address of device to get. - * @param {function(!chrome.bluetooth.Device): void} callback Called with the - * Device object describing the device. - * @see https://developer.chrome.com/extensions/bluetooth#method-getDevice - */ -chrome.bluetooth.getDevice = function(deviceAddress, callback) {}; - -/** - * Get a list of Bluetooth devices known to the system, including paired and - * recently discovered devices. - * @param {?chrome.bluetooth.BluetoothFilter|undefined} filter Some criteria to - * filter the list of returned bluetooth devices. If the filter is not set - * or set to {}, returned device list will contain all - * bluetooth devices. Right now this is only supported in ChromeOS, for - * other platforms, a full list is returned. - * @param {function(!Array): void} callback Called - * when the search is completed. - * @see https://developer.chrome.com/extensions/bluetooth#method-getDevices - */ -chrome.bluetooth.getDevices = function(filter, callback) {}; - -/** - *

Start discovery. Newly discovered devices will be returned via the - * onDeviceAdded event. Previously discovered devices already known to the - * adapter must be obtained using getDevices and will only be updated using the - * |onDeviceChanged| event if information about them changes.

Discovery - * will fail to start if this application has already called startDiscovery. - * Discovery can be resource intensive: stopDiscovery should be called as soon - * as possible.

- * @param {function(): void=} callback Called to indicate success or failure. - * @see https://developer.chrome.com/extensions/bluetooth#method-startDiscovery - */ -chrome.bluetooth.startDiscovery = function(callback) {}; - -/** - * Stop discovery. - * @param {function(): void=} callback Called to indicate success or failure. - * @see https://developer.chrome.com/extensions/bluetooth#method-stopDiscovery - */ -chrome.bluetooth.stopDiscovery = function(callback) {}; - -/** - * Fired when the state of the Bluetooth adapter changes. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/bluetooth#event-onAdapterStateChanged - */ -chrome.bluetooth.onAdapterStateChanged; - -/** - * Fired when information about a new Bluetooth device is available. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/bluetooth#event-onDeviceAdded - */ -chrome.bluetooth.onDeviceAdded; - -/** - * Fired when information about a known Bluetooth device has changed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/bluetooth#event-onDeviceChanged - */ -chrome.bluetooth.onDeviceChanged; - -/** - * Fired when a Bluetooth device that was previously discovered has been out of - * range for long enough to be considered unavailable again, and when a paired - * device is removed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/bluetooth#event-onDeviceRemoved - */ -chrome.bluetooth.onDeviceRemoved; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/bluetooth_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/bluetooth_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/bluetooth_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/bluetooth_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,209 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.bluetoothPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -// TODO(crbug.com/543822): Disable automatic extern generation until fixed. -// s/chrome.bluetoothPrivate.bluetooth.Device/chrome.bluetooth.Device/ -// s/chrome.bluetoothPrivate.bluetooth.Transport/chrome.bluetooth.Transport/ - -/** - * @fileoverview Externs generated from namespace: bluetoothPrivate - * @externs - */ - -/** @const */ -chrome.bluetoothPrivate = {}; - -/** - * @enum {string} - */ -chrome.bluetoothPrivate.PairingEventType = { - REQUEST_PINCODE: 'requestPincode', - DISPLAY_PINCODE: 'displayPincode', - REQUEST_PASSKEY: 'requestPasskey', - DISPLAY_PASSKEY: 'displayPasskey', - KEYS_ENTERED: 'keysEntered', - CONFIRM_PASSKEY: 'confirmPasskey', - REQUEST_AUTHORIZATION: 'requestAuthorization', - COMPLETE: 'complete', -}; - -/** - * @enum {string} - */ -chrome.bluetoothPrivate.ConnectResultType = { - ALREADY_CONNECTED: 'alreadyConnected', - AUTH_CANCELED: 'authCanceled', - AUTH_FAILED: 'authFailed', - AUTH_REJECTED: 'authRejected', - AUTH_TIMEOUT: 'authTimeout', - FAILED: 'failed', - IN_PROGRESS: 'inProgress', - SUCCESS: 'success', - UNKNOWN_ERROR: 'unknownError', - UNSUPPORTED_DEVICE: 'unsupportedDevice', - NOT_READY: 'notReady', - ALREADY_EXISTS: 'alreadyExists', - NOT_CONNECTED: 'notConnected', - DOES_NOT_EXIST: 'doesNotExist', - INVALID_ARGS: 'invalidArgs', - NON_AUTH_TIMEOUT: 'nonAuthTimeout', - NO_MEMORY: 'noMemory', - JNI_ENVIRONMENT: 'jniEnvironment', - JNI_THREAD_ATTACH: 'jniThreadAttach', - WAKELOCK: 'wakelock', - UNEXPECTED_STATE: 'unexpectedState', - SOCKET_ERROR: 'socketError', -}; - -/** - * @enum {string} - */ -chrome.bluetoothPrivate.PairingResponse = { - CONFIRM: 'confirm', - REJECT: 'reject', - CANCEL: 'cancel', -}; - -/** - * @enum {string} - */ -chrome.bluetoothPrivate.TransportType = { - LE: 'le', - BREDR: 'bredr', - DUAL: 'dual', -}; - -/** - * @typedef {{ - * pairing: !chrome.bluetoothPrivate.PairingEventType, - * device: !chrome.bluetooth.Device, - * pincode: (string|undefined), - * passkey: (number|undefined), - * enteredKey: (number|undefined) - * }} - */ -chrome.bluetoothPrivate.PairingEvent; - -/** - * @typedef {{ - * name: (string|undefined), - * powered: (boolean|undefined), - * discoverable: (boolean|undefined) - * }} - */ -chrome.bluetoothPrivate.NewAdapterState; - -/** - * @typedef {{ - * device: !chrome.bluetooth.Device, - * response: !chrome.bluetoothPrivate.PairingResponse, - * pincode: (string|undefined), - * passkey: (number|undefined) - * }} - */ -chrome.bluetoothPrivate.SetPairingResponseOptions; - -/** - * @typedef {{ - * transport: (!chrome.bluetoothPrivate.TransportType|undefined), - * uuids: ((string|!Array)|undefined), - * rssi: (number|undefined), - * pathloss: (number|undefined) - * }} - */ -chrome.bluetoothPrivate.DiscoveryFilter; - -/** - * Changes the state of the Bluetooth adapter. - * @param {!chrome.bluetoothPrivate.NewAdapterState} adapterState The new state - * of the adapter. - * @param {function(): void=} callback Called when all the state changes have - * been completed. - */ -chrome.bluetoothPrivate.setAdapterState = function(adapterState, callback) {}; - -/** - * @param {!chrome.bluetoothPrivate.SetPairingResponseOptions} options - * @param {function(): void=} callback - */ -chrome.bluetoothPrivate.setPairingResponse = function(options, callback) {}; - -/** - * Tears down all connections to the given device. - * @param {string} deviceAddress - * @param {function(): void=} callback - */ -chrome.bluetoothPrivate.disconnectAll = function(deviceAddress, callback) {}; - -/** - * Forgets the given device. - * @param {string} deviceAddress - * @param {function(): void=} callback - */ -chrome.bluetoothPrivate.forgetDevice = function(deviceAddress, callback) {}; - -/** - * Set or clear discovery filter. - * @param {!chrome.bluetoothPrivate.DiscoveryFilter} discoveryFilter - * @param {function(): void=} callback - */ -chrome.bluetoothPrivate.setDiscoveryFilter = function(discoveryFilter, callback) {}; - -/** - * Connects to the given device. This will only throw an error if the device - * address is invalid or the device is already connected. Otherwise this will - * succeed and invoke |callback| with ConnectResultType. - * @param {string} deviceAddress - * @param {function(!chrome.bluetoothPrivate.ConnectResultType): void=} callback - */ -chrome.bluetoothPrivate.connect = function(deviceAddress, callback) {}; - -/** - * Pairs the given device. - * @param {string} deviceAddress - * @param {function(): void=} callback - */ -chrome.bluetoothPrivate.pair = function(deviceAddress, callback) {}; - -/** - * Record that a pairing attempt finished. Ignores cancellations. - * @param {!chrome.bluetooth.Transport} transport - * @param {number} pairingDurationMs - * @param {!chrome.bluetoothPrivate.ConnectResultType=} result - */ -chrome.bluetoothPrivate.recordPairing = function(transport, pairingDurationMs, result) {}; - -/** - * Record that a user-initiated reconnection attempt to an already paired device - * finished. Ignores cancellations. - * @param {!chrome.bluetoothPrivate.ConnectResultType=} result - */ -chrome.bluetoothPrivate.recordReconnection = function(result) {}; - -/** - * Record that a user selected a device to connect to. - * @param {number} selectionDurationMs - * @param {boolean} wasPaired - * @param {!chrome.bluetooth.Transport} transport - */ -chrome.bluetoothPrivate.recordDeviceSelection = function(selectionDurationMs, wasPaired, transport) {}; - -/** - * Fired when a pairing event occurs. - * @type {!ChromeEvent} - */ -chrome.bluetoothPrivate.onPairing; - -/** - * Fired when a Bluetooth device changed its address. - * @type {!ChromeEvent} - */ -chrome.bluetoothPrivate.onDeviceAddressChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/braille_display_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/braille_display_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/braille_display_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/braille_display_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.brailleDisplayPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: brailleDisplayPrivate - * @externs - */ - -/** @const */ -chrome.brailleDisplayPrivate = {}; - -/** - * @enum {string} - */ -chrome.brailleDisplayPrivate.KeyCommand = { - LINE_UP: 'line_up', - LINE_DOWN: 'line_down', - PAN_LEFT: 'pan_left', - PAN_RIGHT: 'pan_right', - TOP: 'top', - BOTTOM: 'bottom', - ROUTING: 'routing', - SECONDARY_ROUTING: 'secondary_routing', - DOTS: 'dots', - CHORD: 'chord', - STANDARD_KEY: 'standard_key', -}; - -/** - * @typedef {{ - * command: !chrome.brailleDisplayPrivate.KeyCommand, - * displayPosition: (number|undefined), - * brailleDots: (number|undefined), - * standardKeyCode: (string|undefined), - * standardKeyChar: (string|undefined), - * spaceKey: (boolean|undefined), - * altKey: (boolean|undefined), - * shiftKey: (boolean|undefined), - * ctrlKey: (boolean|undefined) - * }} - */ -chrome.brailleDisplayPrivate.KeyEvent; - -/** - * @typedef {{ - * available: boolean, - * textRowCount: (number|undefined), - * textColumnCount: (number|undefined), - * cellSize: (number|undefined) - * }} - */ -chrome.brailleDisplayPrivate.DisplayState; - -/** - * Gets the current display state. - * @param {function(!chrome.brailleDisplayPrivate.DisplayState): void} callback - */ -chrome.brailleDisplayPrivate.getDisplayState = function(callback) {}; - -/** - * Write the given dot patterns to the display. The buffer contains one byte - * for each braille cell on the display, starting from the leftmost cell. Each - * byte contains a bit pattern indicating which dots should be raised in the - * corresponding cell with the low-order bit representing dot 1 and so on until - * bit 7 which corresponds to dot 8. If the number of bytes in the buffer is - * not equal to the display size, the buffer will either be clipped or padded - * with blank cells on the right. The buffer is a 2D array compressed into 1D. - * The |columns| and |rows| parameters give the original 2D dimensions of the - * buffer. To access an element cells[r][c], simply access cells[r * columns + - * c]. - * @param {ArrayBuffer} cells - * @param {number} columns - * @param {number} rows - */ -chrome.brailleDisplayPrivate.writeDots = function(cells, columns, rows) {}; - -/** - * Updates the single user-preferred braille device with the given bluetooth - * device address and starts or restarts the Brltty daemon. - * @param {string} address - */ -chrome.brailleDisplayPrivate.updateBluetoothBrailleDisplayAddress = function(address) {}; - -/** - * Fired when a braille display is connected or disconnected. - * @type {!ChromeEvent} - */ -chrome.brailleDisplayPrivate.onDisplayStateChanged; - -/** - * Fired when an input event is received from the display. - * @type {!ChromeEvent} - */ -chrome.brailleDisplayPrivate.onKeyEvent; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/chai-3.5.js chromium-132.0.6834.159/third_party/closure_compiler/externs/chai-3.5.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/chai-3.5.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/chai-3.5.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,556 +0,0 @@ -/* - * Copyright 2016 The Closure Compiler Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @fileoverview Externs definitions for Chai, 3.5 branch. - * - * This file defines both the BDD and TDD APIs. The BDD API should be complete. - * - * This file defines some virtual types for the chained methods, please don't - * use these types directly, but follow the official API guidelines. - * - * @externs - * @see http://chaijs.com/ - */ - -/** @const */ -var chai = {}; - -/** - * @constructor - * @param {*} obj - * @param {string=} msg - * @param {!Function=} ssfi - * @param {boolean=} lockSsfi - */ -chai.Assertion = function(obj, msg, ssfi, lockSsfi) {}; - -// Below are the externs for the BDD expect API: http://chaijs.com/api/bdd/ - -/** - * @param {*} subject - * @param {string=} opt_description - * @return {!chai.Assertion} - */ -var expect = function(subject, opt_description) {}; - - -/** @type {!chai.Assertion} */ chai.Assertion.prototype.to; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.be; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.been; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.is; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.that; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.which; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.and; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.has; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.have; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.with; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.at; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.of; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.same; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.not; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.deep; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.any; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.all; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.length; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.itself; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.ok; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.true; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.false; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.null; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.undefined; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.NaN; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.exist; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.empty; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.arguments; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.extensible; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.sealed; -/** @type {!chai.Assertion} */ chai.Assertion.prototype.frozen; - - -/** - * @param {string} type - * @param {string=} opt_message - * @return {!chai.Assertion} - */ -chai.Assertion.prototype.a = function(type, opt_message) {}; - -/** - * @param {string} type - * @param {string=} opt_message - */ -chai.Assertion.prototype.an = function(type, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.include = function(value, opt_message) {}; - -/** @type {!chai.Assertion} */ chai.Assertion.prototype.include.all; - -/** - * @param {*} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.includes = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.contain = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.contains = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.equal = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.eql = function(value, opt_message) {}; - -/** - * @param {number} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.above = function(value, opt_message) {}; - -/** - * @param {number} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.least = function(value, opt_message) {}; - -/** - * @param {number} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.below = function(value, opt_message) {}; - -/** - * @param {number} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.most = function(value, opt_message) {}; - -/** - * @param {number} start - * @param {number} finish - * @param {string=} opt_message - */ -chai.Assertion.prototype.within = function(start, finish, opt_message) {}; - -/** - * @param {function(new: Object)} constructor - * @param {string=} opt_message - */ -chai.Assertion.prototype.instanceof = function(constructor, opt_message) {}; - -/** - * @param {function(new: Object)} constructor - * @param {string=} opt_message - */ -chai.Assertion.prototype.an.instanceof = function(constructor, opt_message) {}; - -/** - * @param {string} name - * @param {*=} opt_value - * @param {string=} opt_message - */ -chai.Assertion.prototype.property = function(name, opt_value, opt_message) {}; - -/** - * @param {string} name - * @param {string=} opt_message - */ -chai.Assertion.prototype.ownProperty = function(name, opt_message) {}; - -/** - * @param {string} name - * @param {!Object=} opt_descriptor - * @param {string=} opt_message - */ -chai.Assertion.prototype.ownPropertyDescriptor = function( - name, opt_descriptor, opt_message) {}; - -/** - * @param {number} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.lengthOf = function(value, opt_message) {}; - -/** - * @param {!RegExp} re - * @param {string=} opt_message - */ -chai.Assertion.prototype.match = function(re, opt_message) {}; - -/** - * @param {string} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.string = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.keys = function(value, opt_message) {}; - -/** - * Note: incomplete definition because it is tricky. - * @param {...*} var_args - */ -chai.Assertion.prototype.throw = function(var_args) {}; - -/** - * @param {string} method - * @param {string=} opt_message - */ -chai.Assertion.prototype.respondTo = function(method, opt_message) {}; - -/** - * @param {function(*): boolean} matcher - * @param {string=} opt_message - */ -chai.Assertion.prototype.satisfy = function(matcher, opt_message) {}; - -/** - * @param {!Array<*>} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.members = function(value, opt_message) {}; - -/** - * @param {!Array<*>} value - * @param {string=} opt_message - */ -chai.Assertion.prototype.oneOf = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string} name - * @param {string=} opt_message - */ -chai.Assertion.prototype.change = function(value, name, opt_message) {}; - -/** - * @param {*} value - * @param {string} name - * @param {string=} opt_message - */ -chai.Assertion.prototype.increase = function(value, name, opt_message) {}; - -/** - * @param {*} value - * @param {string} name - * @param {string=} opt_message - */ -chai.Assertion.prototype.decrease = function(value, name, opt_message) {}; - -// Below are the externs for the TDD expect API: http://chaijs.com/api/assert/ - -/** @const */ -var assert = {}; - -/** - * @param {*} actual - * @param {*} expected - * @param {string=} opt_message - * @param {string=} opt_operator - */ -assert.fail = function(actual, expected, opt_message, opt_operator) {}; - -/** - * @param {*} object - * @param {string=} opt_message - */ -assert.isOk = function(object, opt_message) {}; - -/** - * @param {*} object - * @param {string=} opt_message - */ -assert.isNotOk = function(object, opt_message) {}; - -/** - * @param {*} actual - * @param {*} expected - * @param {string=} opt_message - */ -assert.equal = function(actual, expected, opt_message) {}; - -/** - * @param {*} actual - * @param {*} expected - * @param {string=} opt_message - */ -assert.strictEqual = function(actual, expected, opt_message) {}; - -/** - * @param {*} actual - * @param {*} expected - * @param {string=} opt_message - */ -assert.notStrictEqual = function(actual, expected, opt_message) {}; - -/** - * @param {*} actual - * @param {*} expected - * @param {string=} opt_message - */ -assert.notEqual = function(actual, expected, opt_message) {}; - -/** - * @param {*} actual - * @param {*} expected - * @param {string=} opt_message - */ -assert.deepEqual = function(actual, expected, opt_message) {}; - -/** - * @param {*} actual - * @param {*} expected - * @param {string=} opt_message - */ -assert.notDeepEqual = function(actual, expected, opt_message) {}; - -/** - * @param {*} valueToCheck - * @param {*} valueToBeAbove - * @param {string=} opt_message - */ -assert.isAbove = function(valueToCheck, valueToBeAbove, opt_message) {}; - -/** - * @param {*} valueToCheck - * @param {*} valueToBeBelow - * @param {string=} opt_message - */ -assert.isBelow = function(valueToCheck, valueToBeBelow, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isTrue = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isNotTrue = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isFalse = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isNotFalse = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isNaN = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isUndefined = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isDefined = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isFunction = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isNotFunction = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} message - */ -assert.isNotNull = function(value, message) {} - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.isNull = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.exists = function(value, opt_message) {}; - -/** - * @param {*} value - * @param {string=} opt_message - */ -assert.notExists = function(value, opt_message) {}; - -/** - * @param {*} object - * @param {function(new: Object)} constructor - * @param {string=} opt_message - */ -assert.instanceOf = function(object, constructor, opt_message) {}; - -/** - * @param {!Array<*>|string} haystack - * @param {*} needle - * @param {string=} opt_message - */ -assert.include = function(haystack, needle, opt_message) {}; - -/** - * @param {!Array<*>|string} haystack - * @param {*} needle - * @param {string=} opt_message - */ -assert.notInclude = function(haystack, needle, opt_message) {}; - -/** - * @param {*} needle - * @param {!Array<*>} haystack - * @param {string=} opt_message - */ -assert.oneOf = function(needle, haystack, opt_message) {}; - -/** - * @param {*} collection - * @param {number} length - * @param {string=} message - */ -assert.lengthOf = function(collection, length, message) {}; - -/** - * @param {*} object - * @param {!RegExp} re - * @param {string=} opt_message - */ -assert.match = function(object, re, opt_message) {}; - -/** - * @param {?Object|undefined} object - * @param {string} property - * @param {*} value - * @param {string=} opt_message - */ -assert.propertyVal = function(object, property, value, opt_message) {}; - -/** - * @param {function()} fn - * @param {function(new: Object)|string|!RegExp} constructor - * @param {string|!RegExp=} opt_regexp - * @param {string=} opt_message - */ -assert.throws = function(fn, constructor, opt_regexp, opt_message) {}; - -/** - * @param {function()} fn - * @param {function(new: Object)|string|!RegExp} constructor - * @param {string|!RegExp=} opt_regexp - * @param {string=} opt_message - */ -assert.doesNotThrow = function(fn, constructor, opt_regexp, opt_message) {}; - -/** - * @param {!Array<*>} set1 - * @param {!Array<*>} set2 - * @param {string=} opt_message - */ -assert.sameMembers = function(set1, set2, opt_message) {}; - -/** - * @param {!Array<*>} set1 - * @param {!Array<*>} set2 - * @param {string=} opt_message - */ -assert.sameDeepMembers = function(set1, set2, opt_message) {}; - -// Below are the externs for the APIs to build custom assertions: -// http://www.chaijs.com/api/plugins/ - -/** - * @param {string} name - * @param {!Function} getter - */ -chai.Assertion.addMethod = function(name, getter) {}; - -/** - * @param {string} name - * @param {function()} getter - */ -chai.Assertion.addProperty = function(name, getter) {}; - -/** @type {*} */ -chai.Assertion.prototype._obj; - -/** - * @param {boolean} expr - * @param {string} msg - * @param {string} negateMsg - * @param {*} expected - * @param {*=} actual - * @param {boolean=} showDiff - */ -chai.Assertion.prototype.assert = function( - expr, msg, negateMsg, expected, actual, showDiff) {}; - -/** @const */ -chai.assert = assert; - -/** @const */ -chai.expect = expect; - -/** @const */ -chai.util = {}; - -/** - * @param {!chai.Assertion} obj - * @param {string} key - * @param {*=} value - */ -chai.util.flag = function(obj, key, value) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/chrome.js chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/chrome.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,643 +0,0 @@ -// SSSSSSSSSSSSSSS TTTTTTTTTTTTTTTTTTTTTTT OOOOOOOOO PPPPPPPPPPPPPPPPP -// SS:::::::::::::::ST:::::::::::::::::::::T OO:::::::::OO P::::::::::::::::P -// S:::::SSSSSS::::::ST:::::::::::::::::::::T OO:::::::::::::OO P::::::PPPPPP:::::P -// S:::::S SSSSSSST:::::TT:::::::TT:::::TO:::::::OOO:::::::OPP:::::P P:::::P -// S:::::S TTTTTT T:::::T TTTTTTO::::::O O::::::O P::::P P:::::P -// S:::::S T:::::T O:::::O O:::::O P::::P P:::::P -// S::::SSSS P::::PPPPPP:::::P -// SS::::::SSSSS This file is generated. To update it, P:::::::::::::PP -// SSS::::::::SS run roll_closure_compiler. P::::PPPPPPPPP -// SSSSSS::::S P::::P -// S:::::S T:::::T O:::::O O:::::O P::::P -// S:::::S T:::::T O::::::O O::::::O P::::P -// SSSSSSS S:::::S TT:::::::TT O:::::::OOO:::::::OPP::::::PP -// S::::::SSSSSS:::::S T:::::::::T OO:::::::::::::OO P::::::::P -// S:::::::::::::::SS T:::::::::T OO:::::::::OO P::::::::P -// SSSSSSSSSSSSSSS TTTTTTTTTTT OOOOOOOOO PPPPPPPPPP -/* - * Copyright 2013 The Closure Compiler Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @fileoverview Definitions for globals in Chrome. This file describes the - * externs API for the chrome.* object when running in a normal browser - * context. For APIs available in Chrome Extensions, see chrome_extensions.js - * in this directory. - * @externs - */ - - -/** - * namespace - * @const - */ -var chrome = {}; - - -/** - * @see http://developer.chrome.com/apps/runtime.html#type-Port - * @constructor - */ -function Port() {} - - -/** @type {string} */ -Port.prototype.name; - - -/** @type {!ChromeEvent} */ -Port.prototype.onDisconnect; - - -/** @type {!ChromeEvent} */ -Port.prototype.onMessage; - - -/** @type {!MessageSender|undefined} */ -Port.prototype.sender; - - -/** - * @param {*} obj Message object. - * @return {undefined} - */ -Port.prototype.postMessage = function(obj) {}; - - -/** @return {undefined} */ -Port.prototype.disconnect = function() {}; - - -/** - * Base event type without listener methods. - * - * This interface exists for event interfaces whose addListeners() method takes - * more than one parameter. Those interfaces must inherit from this one, so they - * can supply their own custom listener method declarations. - * - * Event interfaces whose addListeners() method takes just one parameter should - * inherit from ChromeBaseEvent instead. It extends this interface. - * - * @see https://developer.chrome.com/extensions/events - * @interface - */ -function ChromeBaseEventNoListeners() {} - - -/** - * @param {!Array} rules - * @param {function(!Array): void=} callback - * @see https://developer.chrome.com/extensions/events#method-Event-addRules - */ -ChromeBaseEventNoListeners.prototype.addRules = function(rules, callback) {}; - - -/** - * Returns currently registered rules. - * - * NOTE: The API allows the first argument to be omitted. - * That cannot be correctly represented here, so we end up incorrectly - * allowing 2 callback arguments. - * @param {!Array|function(!Array): void} ruleIdentifiersOrCb - * @param {function(!Array): void=} callback - * @see https://developer.chrome.com/extensions/events#method-Event-getRules - */ -ChromeBaseEventNoListeners.prototype.getRules = - function(ruleIdentifiersOrCb, callback) {}; - - -/** - * Removes currently registered rules. - * - * NOTE: The API allows the either or both arguments to be omitted. - * That cannot be correctly represented here, so we end up incorrectly - * allowing 2 callback arguments. - * @param {(!Array|function(): void)=} ruleIdentifiersOrCb - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/events#method-Event-removeRules - */ -ChromeBaseEventNoListeners.prototype.removeRules = - function(ruleIdentifiersOrCb, callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/events#type-Rule - * @record - */ -function Rule() {} - - -/** @type {string|undefined} */ -Rule.prototype.id; - - -/** @type {!Array|undefined} */ -Rule.prototype.tags; - - -/** @type {!Array<*>} */ -Rule.prototype.conditions; - - -/** @type {!Array<*>} */ -Rule.prototype.actions; - - -/** @type {number|undefined} */ -Rule.prototype.priority; - - -/** - * @see https://developer.chrome.com/extensions/events#type-UrlFilter - * @record - */ -function UrlFilter() {} - - -/** @type {string|undefined} */ -UrlFilter.prototype.hostContains; - - -/** @type {string|undefined} */ -UrlFilter.prototype.hostEquals; - - -/** @type {string|undefined} */ -UrlFilter.prototype.hostPrefix; - - -/** @type {string|undefined} */ -UrlFilter.prototype.hostSuffix; - - -/** @type {string|undefined} */ -UrlFilter.prototype.pathContains; - - -/** @type {string|undefined} */ -UrlFilter.prototype.pathEquals; - - -/** @type {string|undefined} */ -UrlFilter.prototype.pathPrefix; - - -/** @type {string|undefined} */ -UrlFilter.prototype.pathSuffix; - - -/** @type {string|undefined} */ -UrlFilter.prototype.queryContains; - - -/** @type {string|undefined} */ -UrlFilter.prototype.queryEquals; - - -/** @type {string|undefined} */ -UrlFilter.prototype.queryPrefix; - - -/** @type {string|undefined} */ -UrlFilter.prototype.querySuffix; - - -/** @type {string|undefined} */ -UrlFilter.prototype.urlContains; - - -/** @type {string|undefined} */ -UrlFilter.prototype.urlEquals; - - -/** @type {string|undefined} */ -UrlFilter.prototype.urlMatches; - - -/** @type {string|undefined} */ -UrlFilter.prototype.originAndPathMatches; - - -/** @type {string|undefined} */ -UrlFilter.prototype.urlPrefix; - - -/** @type {string|undefined} */ -UrlFilter.prototype.urlSuffix; - - -/** @type {!Array|undefined} */ -UrlFilter.prototype.schemes; - - -/** @type {!Array<(number|!Array)>|undefined} */ -UrlFilter.prototype.ports; - - -/** - * Base event type from which all others inherit. - * - * LISTENER must be a function type that returns void. - * - * @see https://developer.chrome.com/extensions/events - * @interface - * @extends {ChromeBaseEventNoListeners} - * @template LISTENER - */ -function ChromeBaseEvent() {} - - -/** - * @param {LISTENER} callback - * @return {undefined} - * @see https://developer.chrome.com/extensions/events#method-Event-addListener - */ -ChromeBaseEvent.prototype.addListener = function(callback) {}; - - -/** - * @param {LISTENER} callback - * @return {undefined} - * @see https://developer.chrome.com/extensions/events#method-Event-removeListener - */ -ChromeBaseEvent.prototype.removeListener = function(callback) {}; - - -/** - * @param {LISTENER} callback - * @return {boolean} - * @see https://developer.chrome.com/extensions/events#method-Event-hasListener - */ -ChromeBaseEvent.prototype.hasListener = function(callback) {}; - - -/** - * @return {boolean} - * @see https://developer.chrome.com/extensions/events#method-Event-hasListeners - */ -ChromeBaseEvent.prototype.hasListeners = function() {}; - - -/** - * Event whose listeners take unspecified parameters. - * - * TODO(bradfordcsmith): Definitions using this type are failing to provide - * information about the parameters that will actually be supplied to the - * listener and should be updated to use a more specific event type. - * @see https://developer.chrome.com/extensions/events - * @interface - * @extends {ChromeBaseEvent} - */ -function ChromeEvent() {} - - -/** - * Event whose listeners take no parameters. - * - * @see https://developer.chrome.com/extensions/events - * @interface - * @extends {ChromeBaseEvent} - */ -function ChromeVoidEvent() {} - - -/** - * Event whose listeners take a string parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -function ChromeStringEvent() {} - - -/** - * Event whose listeners take a boolean parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -function ChromeBooleanEvent() {} - - -/** - * Event whose listeners take a number parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -function ChromeNumberEvent() {} - - -/** - * Event whose listeners take an Object parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -function ChromeObjectEvent() {} - - -/** - * Event whose listeners take a string array parameter. - * @interface - * @extends {ChromeBaseEvent)>} - */ -function ChromeStringArrayEvent() {} - - -/** - * Event whose listeners take two strings as parameters. - * @interface - * @extends {ChromeBaseEvent} - */ -function ChromeStringStringEvent() {} - - -/** - * @see http://developer.chrome.com/extensions/runtime.html#type-MessageSender - * @constructor - */ -function MessageSender() {} - - -/** @type {!Tab|undefined} */ -MessageSender.prototype.tab; - - -/** @type {number|undefined} */ -MessageSender.prototype.frameId; - - -/** @type {string|undefined} */ -MessageSender.prototype.id; - - -/** @type {string|undefined} */ -MessageSender.prototype.url; - - -/** @type {string|undefined} */ -MessageSender.prototype.nativeApplication; - - -/** @type {string|undefined} */ -MessageSender.prototype.tlsChannelId; - - -/** @type {string|undefined} */ -MessageSender.prototype.origin; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tabs#type-MutedInfoReason - */ -var MutedInfoReason = { - USER: '', - CAPTURE: '', - EXTENSION: '', -}; - - -/** - * @see https://developer.chrome.com/extensions/tabs#type-MutedInfo - * @constructor - */ -var MutedInfo = function() {}; - - -/** @type {boolean} */ -MutedInfo.prototype.muted; - - -/** @type {!MutedInfoReason|string|undefined} */ -MutedInfo.prototype.reason; - - -/** @type {string|undefined} */ -MutedInfo.prototype.extensionId; - - - - -/** - * @see https://developer.chrome.com/extensions/tabs#type-Tab - * @constructor - */ -function Tab() {} - - -// TODO: Make this field optional once dependent projects have been updated. -/** @type {number} */ -Tab.prototype.id; - - -/** @type {number} */ -Tab.prototype.index; - - -/** @type {number} */ -Tab.prototype.windowId; - - -// TODO: Make this field optional once dependent projects have been updated. -/** @type {number} */ -Tab.prototype.openerTabId; - - -/** @type {boolean} */ -Tab.prototype.highlighted; - - -/** @type {boolean} */ -Tab.prototype.active; - - -/** @type {boolean} */ -Tab.prototype.pinned; - - -/** @type {boolean|undefined} */ -Tab.prototype.audible; - - -/** @type {boolean} */ -Tab.prototype.discarded; - - -/** @type {boolean} */ -Tab.prototype.autoDiscardable; - - -/** @type {!MutedInfo|undefined} */ -Tab.prototype.mutedInfo; - - -// TODO: Make this field optional once dependent projects have been updated. -/** @type {string} */ -Tab.prototype.url; - - -/** @type {string|undefined} */ -Tab.prototype.pendingUrl; - - -// TODO: Make this field optional once dependent projects have been updated. -/** @type {string} */ -Tab.prototype.title; - - -// TODO: Make this field optional once dependent projects have been updated. -/** @type {string} */ -Tab.prototype.favIconUrl; - - -// TODO: Make this field optional once dependent projects have been updated. -/** @type {string} */ -Tab.prototype.status; - - -/** @type {boolean} */ -Tab.prototype.incognito; - - -/** @type {number|undefined} */ -Tab.prototype.width; - - -/** @type {number|undefined} */ -Tab.prototype.height; - - -/** @type {string|undefined} */ -Tab.prototype.sessionId; - - -/** @const */ -chrome.app = {}; - -/** - * @see https://developer.chrome.com/webstore/inline_installation#already-installed - * @type {boolean} - */ -chrome.app.isInstalled; - -/** - * @const - * @see https://developer.chrome.com/apps/webstore - */ -chrome.webstore = {}; - - -/** - * @param {string|function()|function(string, string=)=} - * opt_urlOrSuccessCallbackOrFailureCallback Either the URL to install or - * the succcess callback taking no arg or the failure callback taking an - * error string arg. - * @param {function()|function(string, string=)=} - * opt_successCallbackOrFailureCallback Either the succcess callback taking - * no arg or the failure callback taking an error string arg. - * @param {function(string, string=)=} opt_failureCallback The failure callback. - * @return {undefined} - */ -chrome.webstore.install = function( - opt_urlOrSuccessCallbackOrFailureCallback, - opt_successCallbackOrFailureCallback, - opt_failureCallback) {}; - - -/** @type {!ChromeStringEvent} */ -chrome.webstore.onInstallStageChanged; - - -/** @type {!ChromeNumberEvent} */ -chrome.webstore.onDownloadProgress; - - -/** - * Returns an object representing current load times. Note that the properties - * on the object do not change and the function must be called again to get - * up-to-date data. - * - * @return {!ChromeLoadTimes} - */ -chrome.loadTimes = function() {}; - - - -/** - * The data object given by chrome.loadTimes(). - * @constructor - */ -function ChromeLoadTimes() {} - - -/** @type {number} */ -ChromeLoadTimes.prototype.requestTime; - - -/** @type {number} */ -ChromeLoadTimes.prototype.startLoadTime; - - -/** @type {number} */ -ChromeLoadTimes.prototype.commitLoadTime; - - -/** @type {number} */ -ChromeLoadTimes.prototype.finishDocumentLoadTime; - - -/** @type {number} */ -ChromeLoadTimes.prototype.finishLoadTime; - - -/** @type {number} */ -ChromeLoadTimes.prototype.firstPaintTime; - - -/** @type {number} */ -ChromeLoadTimes.prototype.firstPaintAfterLoadTime; - - -/** @type {number} */ -ChromeLoadTimes.prototype.navigationType; - - -/** - * True iff the resource was fetched over SPDY. - * @type {boolean} - */ -ChromeLoadTimes.prototype.wasFetchedViaSpdy; - - -/** @type {boolean} */ -ChromeLoadTimes.prototype.wasNpnNegotiated; - - -/** @type {string} */ -ChromeLoadTimes.prototype.npnNegotiatedProtocol; - - -/** @type {boolean} */ -ChromeLoadTimes.prototype.wasAlternateProtocolAvailable; - - -/** @type {string} */ -ChromeLoadTimes.prototype.connectionInfo; - - -/** - * @param {string|!ArrayBuffer|!Object} message - * @see https://developers.google.com/native-client/devguide/tutorial - * @return {undefined} - */ -HTMLEmbedElement.prototype.postMessage = function(message) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/chrome_extensions.js chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome_extensions.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/chrome_extensions.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome_extensions.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,11243 +0,0 @@ -// SSSSSSSSSSSSSSS TTTTTTTTTTTTTTTTTTTTTTT OOOOOOOOO PPPPPPPPPPPPPPPPP -// SS:::::::::::::::ST:::::::::::::::::::::T OO:::::::::OO P::::::::::::::::P -// S:::::SSSSSS::::::ST:::::::::::::::::::::T OO:::::::::::::OO P::::::PPPPPP:::::P -// S:::::S SSSSSSST:::::TT:::::::TT:::::TO:::::::OOO:::::::OPP:::::P P:::::P -// S:::::S TTTTTT T:::::T TTTTTTO::::::O O::::::O P::::P P:::::P -// S:::::S T:::::T O:::::O O:::::O P::::P P:::::P -// S::::SSSS P::::PPPPPP:::::P -// SS::::::SSSSS This file is generated. To update it, P:::::::::::::PP -// SSS::::::::SS run roll_closure_compiler. P::::PPPPPPPPP -// SSSSSS::::S P::::P -// S:::::S T:::::T O:::::O O:::::O P::::P -// S:::::S T:::::T O::::::O O::::::O P::::P -// SSSSSSS S:::::S TT:::::::TT O:::::::OOO:::::::OPP::::::PP -// S::::::SSSSSS:::::S T:::::::::T OO:::::::::::::OO P::::::::P -// S:::::::::::::::SS T:::::::::T OO:::::::::OO P::::::::P -// SSSSSSSSSSSSSSS TTTTTTTTTTT OOOOOOOOO PPPPPPPPPP -/* - * Copyright 2009 The Closure Compiler Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @fileoverview Definitions for the Chromium extensions API. - * - * This is the externs file for the Chrome Extensions API. - * See http://developer.chrome.com/extensions/ - * - * There are several problematic issues regarding Chrome extension APIs and - * this externs files, including: - * A. When to add packages to this file - * B. Optional parameters - * C. Pseudo-types - * D. Events - * E. Nullability - * F. Private APIs - * G. Enums - * - * The best practices for each are described in more detail below. It should be - * noted that, due to historical reasons, and the evolutionary nature of this - * file, much this file currently violates the best practices described below. - * As changes are made, the changes should adhere to the best practices. - * - * A. When to Add Packages to this File? - * Packages in chrome.experimental.* should *not* be added to this file. The - * experimental APIs change very quickly, so rather than add them here, make a - * separate externs file for your project, then move the API here when it moves - * out of experimental. - * - * Some non-experimental APIs are still evolving or are not full documented. It - * is still advantageous to include these in this file as doing so avoids a - * proliferation of project-private externs files containing duplicated info. In - * these cases, use comments to describe the situation. - * - * B. Optional Parameters - * The Chrome extension APIs make extensive use of interior optional parameters - * that are not at the end of the parameter list, while the JS Compiler's type - * system requires optional parameters to be at the end. This creates a bit of - * tension: - * - * 1. If a method has N required params, then the parameter declarations - * should have N required params. - * 2. If, due to interior optional params, a parameter can be of more than - * one type, its at-param should: - * a. be named to indicate both possibilities, eg, extensionIdOrRequest, - * or getInfoOrCallback. - * b. the type should include both types, in the same order as the parts - * of the name, even when one type subsumes the other, eg, {string|*} - * or {Object|function(string)}. - * See chrome.runtime.sendMessage for a complex example as sendMessage takes - * three params with the first and third being optional. - * - * C. Pseudo-types - * The Chrome APIs define many types that are actually pseudo-types, that - * is, they can't be instantiated by name. The extension APIs also pass untyped - * objects (a bag of properties) to callbacks. - * - * The Chrome extension APIs include at least three different situations: - * - * 1. an object that must be created by an extension developer and passed - * into a Chrome extension API and for which there is no constructor. - * 2. an instance of a type that is created inside the extension libraries - * and passed out to a callback/listener or returned by an extension API - * (the constructor implicity lives within the library). - * 3. like #2, but a bag-of-properties object that is passed out to a - * callback/listener or returned by an extension API so there is no - * defined type. - * - * For #1, use a record type so object literals and objects created via - * goog.object are acceptable. (Note: a named record type may be declared using - * the at-record syntax; an anonymous record type may be described using the - * {foo: !Foo, ...} syntax. Anonymous record types may be named using an - * at-typedef annotation. See - * https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System - * for more information.) For example, the Permissions type defined at - * http://developer.chrome.com/extensions/permissions.html#type-Permissions - * could be: - * - * / ** - * * at-typedef {?{ - * * permissions: (!Array|undefined), - * * origins: (!Array|undefined), - * * }} - * * / - * chrome.permissions.Permissions; - * - * Using record types provides type-safety for the fields that are defined in - * the object literal and also defined in the record type. Note that record - * types define a minimal interface and will not complain about extraneous - * (often misspelled) fields. - * - * Also, record types are non-nullable by default. The "{?{" - * creates a nullable record-type typedef so ! has the same meaning in usages - * as it does for real types. - * - * For #2, use a standard constructor, even though no constructor is provided - * and extension writers will never instantiate an instance, as using a first - * class type provides the strongest type checking. For example, see the Port - * type defined at http://developer.chrome.com/apps/runtime.html#type-Port. - * Always qualify the type name to reduce top-level pollution in this file: - * - * Do: - * chrome.runtime.Port = function() {} - * Don't: - * function Port() {} - * - * Note that, unfortunately, the actual Port class definition in this file - * does not follow this recommendation. - * - * For #3, the introduction of arrow functions that are frequently used for - * callbacks has changed things. Prior to arrow functions, the Best Practices - * recommended using !Object since that's what in the docs. It was tempting to - * define a real type within this file and treat this situation as identical to - * #2, but that meant a new type was being defined in this file and developers - * did not expect to find required new types in extension files. - * - * Arrow functions change things. The common use of them does not include - * specifying a type for the callback's param, so the compiler infers the type - * from the externs file. This is good and happens automatically with no actions - * required of the developer. Futhermore, since the param has a type, field - * references can use dot access, obj.someField, vs bracket access, - * obj['someField'] as required for !Object. - * - * So, for #3, the best practice is to define a record type for the parameter. - * See chrome.proxy.settings.GetResponse for an example. As mentioned above in - * the section for #1, there are three common ways to introduce a record type - * and any of them are acceptable. Of course, if a type is going to be used more - * than once, it should be named. - * - * While the externs file will define an undocumented record type for a - * callback's param, using !Object as specified in the docs will continue to - * work. This is crucial when a callback is a regular function, as opposed to an - * arrow function (whose parameter's type can be inferred). - * - * D. Events - * Most packages define a set of events with the standard set of methods: - * addListener, removeListener, hasListener and hasListeners. ChromeVoidEvent - * is the appropriate type when an event's listeners do not take any - * parameters, however, many events take parameters specific to that event. - * - * For those cases, create a record type for the event that extends - * ChromeBaseEvent with the correct listener function type filled in. - * See any of the Event type definitions below that extend ChromeBaseEvent for - * an example. - * - * In some cases the addListener method takes more than one argument, so - * inheritance from ChromeBaseEvent will not work. In those cases extend - * ChromeBaseEventNoListeners instead and add the listener interfaces - * explicitly. See any of the Event type definitions below that extend - * ChromeBaseEventNoListeners for an example. - * - * E. Nullability - * We treat the Chrome Extension API pages as "the truth". Not-null types should - * be used in the following situations: - * - * 1. Parameters and return values that are not explicitly declared to handle - * null. - * 2. Static event instances, for example, chrome.runtime.onConnect's type - * should be: !chrome.runtime.PortEvent. - * 3. Optional params as there is little value to passing null when the - * parameter can be omitted, of course, if null is explicitly declared - * to be meaningful, then a nullable type should be used. - * - * F. Private APIs - * Private Chrome APIs (such as those that end in "Private") should go at the - * bottom of this file. - * - * G. Enums - * An enum's type name and the name of its members must be included in an - * externs file, but the values of its members are ignored by the compiler. - * To make it clear enums are not being *defined* in this file, we set - * string enum values to the empty string (at this time, there are no - * known enums of other types). - * - * As of Mar 2016, the chrome extension docs are incomplete wrt to enums - * as they don't list the member names, only their string values. This means - * extension authors will tend to use string literals. Therefore, whereever - * an enum type should be used, we support either the enum or a string. Once - * the docs are complete, new uses of enums will no longer need the "or string" - * portion of the type. - * - * Finally, most places in this file where enums should be used are using only - * string. This is historical and is no longer the recommended practice. - * - * See enum chrome.wallpaper.WallpaperLayout and chrome.wallpaper.setWallpaper's - * param for examples. - * - * @externs - * - */ - - -/* - * Ensure projects don't execute this file. - * The throw is to catch executions of this file, however, without the guard, - * the compiler's flow analysis stops at the throw, even for an externs file. - * Therefore, the Math.random() guard fools the compiler during externs - * processing. - */ -if (Math.random() < 1) { // always true but the compiler doesn't know that - throw 'Externs file "chrome_extensions.js" should not be executed'; -} - - - -/** - * @const - * @see http://developer.chrome.com/apps/app.runtime.html - */ -chrome.app.runtime = {}; - - - -/** - * @constructor - * @see http://developer.chrome.com/apps/app_runtime.html - */ -chrome.app.runtime.LaunchItem = function() {}; - - -/** @type {!FileEntry} */ -chrome.app.runtime.LaunchItem.prototype.entry; - - -/** @type {string} */ -chrome.app.runtime.LaunchItem.prototype.type; - - -/** @type {!ChromeObjectEvent} */ -chrome.app.runtime.onEmbedRequested; - - -/** - * @constructor - * @see https://developer.chrome.com/apps/app_runtime#event-onLaunched - */ -chrome.app.runtime.LaunchData = function() {}; - - -/** @type {!Array<{entry: !FileEntry, type: (string|undefined)}>|undefined} */ -chrome.app.runtime.LaunchData.prototype.items; - - -/** @type {boolean|undefined} */ -chrome.app.runtime.LaunchData.prototype.isKioskSession; - - -/** @type {string|undefined} */ -chrome.app.runtime.LaunchData.prototype.source; - - -/** @type {!ChromeBaseEvent} */ -chrome.app.runtime.onLaunched; - - -/** - * @type {!ChromeEvent} - * @see http://developer.chrome.com/apps/app.runtime.html#event-onRestarted - */ -chrome.app.runtime.onRestarted; - - -/** - * @const - * @see http://developer.chrome.com/apps/app.window.html - */ -chrome.app.window = {}; - - -/** - * @see https://developer.chrome.com/apps/app_window#method-getAll - * @return {!Array} - */ -chrome.app.window.getAll = function() {}; - - -/** - * @see https://developer.chrome.com/apps/app_window#method-get - * @param {string} id - * @return {chrome.app.window.AppWindow} - */ -chrome.app.window.get = function(id) {}; - - - -/** - * @constructor - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - */ -chrome.app.window.AppWindow = function() {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.focus = function() {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.fullscreen = function() {}; - - -/** - * @return {boolean} - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - */ -chrome.app.window.AppWindow.prototype.isFullscreen = function() {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.minimize = function() {}; - - -/** - * @return {boolean} - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - */ -chrome.app.window.AppWindow.prototype.isMinimized = function() {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.maximize = function() {}; - - -/** - * @return {boolean} - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - */ -chrome.app.window.AppWindow.prototype.isMaximized = function() {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.restore = function() {}; - - -/** - * @param {number} left The new left position, in pixels. - * @param {number} top The new top position, in pixels. - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.moveTo = function(left, top) {}; - - -/** - * @param {number} width The new width, in pixels. - * @param {number} height The new height, in pixels. - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.resizeTo = function(width, height) {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.drawAttention = function() {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.clearAttention = function() {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.close = function() {}; - - -/** - * @param {boolean=} opt_focus Should the window be focused? Defaults to true. - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.show = function(opt_focus) {}; - - -/** - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.hide = function() {}; - - -/** - * @return {!chrome.app.window.ContentBounds} The current window bounds. - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - */ -chrome.app.window.AppWindow.prototype.getBounds = function() {}; - - -/** - * @param {!chrome.app.window.ContentBounds} bounds The new window bounds. - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.setBounds = function(bounds) {}; - - -/** - * @return {boolean} - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - */ -chrome.app.window.AppWindow.prototype.isAlwaysOnTop = function() {}; - - -/** - * @param {boolean} alwaysOnTop Set whether the window should stay above most - * other windows. - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.setAlwaysOnTop = function(alwaysOnTop) {}; - - -/** - * @param {boolean} alwaysVisible Set whether the window is visible on all - * workspaces. - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.setVisibleOnAllWorkspaces = function( - alwaysVisible) {}; - - -/** - * @param {boolean} wantAllKeys Set whether the window should get all keyboard - * events including system keys that are usually not sent. - * @see http://developer.chrome.com/apps/app.window.html#type-AppWindow - * @return {undefined} - */ -chrome.app.window.AppWindow.prototype.setInterceptAllKeys = function( - wantAllKeys) {}; - - -/** @type {!ChromeEvent} */ -chrome.app.window.AppWindow.prototype.onBoundsChanged; - - -/** @type {!ChromeEvent} */ -chrome.app.window.AppWindow.prototype.onClosed; - - -/** @type {!ChromeEvent} */ -chrome.app.window.AppWindow.prototype.onFullscreened; - - -/** @type {!ChromeEvent} */ -chrome.app.window.AppWindow.prototype.onMinimized; - - -/** @type {!ChromeEvent} */ -chrome.app.window.AppWindow.prototype.onMaximized; - - -/** @type {!ChromeEvent} */ -chrome.app.window.AppWindow.prototype.onRestored; - - -/** @type {!Window} */ -chrome.app.window.AppWindow.prototype.contentWindow; - - -/** @type {string} */ -chrome.app.window.AppWindow.prototype.id; - - -/** @type {!chrome.app.window.Bounds} */ -chrome.app.window.AppWindow.prototype.innerBounds; - - -/** @type {!chrome.app.window.Bounds} */ -chrome.app.window.AppWindow.prototype.outerBounds; - - -/** - * @typedef {?{ - * left: number, - * top: number, - * width: number, - * height: number, - * minWidth: (number|undefined), - * minHeight: (number|undefined), - * maxWidth: (number|undefined), - * maxHeight: (number|undefined), - * setPosition: function(number, number), - * setSize: function(number, number), - * setMinimumSize: function(number, number), - * setMaximumSize: function(number, number) - * }} - * @see http://developer.chrome.com/apps/app.window.html#type-Bounds - */ -chrome.app.window.Bounds; - - -/** - * @typedef {?{ - * left: (number|undefined), - * top: (number|undefined), - * width: (number|undefined), - * height: (number|undefined), - * minWidth: (number|undefined), - * minHeight: (number|undefined), - * maxWidth: (number|undefined), - * maxHeight: (number|undefined) - * }} - * @see http://developer.chrome.com/apps/app_window#type-BoundsSpecification - */ -chrome.app.window.BoundsSpecification; - - -/** - * @typedef {?{ - * left: (number|undefined), - * top: (number|undefined), - * width: (number|undefined), - * height: (number|undefined) - * }} - * @see http://developer.chrome.com/apps/app_window#type-ContentBounds - */ -chrome.app.window.ContentBounds; - - -/** - * @typedef {?{ - * type: (string|undefined), - * color: (string|undefined), - * activeColor: (string|undefined), - * inactiveColor: (string|undefined) - * }} - * @see http://developer.chrome.com/apps/app_window#type-FrameOptions - */ -chrome.app.window.FrameOptions; - - -/** - * @typedef {?{ - * id: (string|undefined), - * innerBounds: (!chrome.app.window.BoundsSpecification|undefined), - * outerBounds: (!chrome.app.window.BoundsSpecification|undefined), - * minWidth: (number|undefined), - * minHeight: (number|undefined), - * maxWidth: (number|undefined), - * maxHeight: (number|undefined), - * frame: (!chrome.app.window.FrameOptions|string|undefined), - * bounds: (!chrome.app.window.ContentBounds|undefined), - * state: (string|undefined), - * hidden: (boolean|undefined), - * resizable: (boolean|undefined), - * singleton: (boolean|undefined), - * alwaysOnTop: (boolean|undefined), - * focused: (boolean|undefined), - * visibleOnAllWorkspaces: (boolean|undefined) - * }} - * @see http://developer.chrome.com/apps/app.window.html#method-create - */ -chrome.app.window.CreateWindowOptions; - - -/** - * @param {string} url URL to create. - * @param {!chrome.app.window.CreateWindowOptions=} opt_options The options for - * the new window. - * @param {function(!chrome.app.window.AppWindow)=} opt_createWindowCallback - * Callback to be run. - * @see http://developer.chrome.com/apps/app.window.html#method-create - * @return {undefined} - */ -chrome.app.window.create = function( - url, opt_options, opt_createWindowCallback) {}; - - -/** - * Returns an AppWindow object for the current script context (ie JavaScript - * 'window' object). - * @return {!chrome.app.window.AppWindow} - * @see http://developer.chrome.com/apps/app.window.html#method-current - */ -chrome.app.window.current = function() {}; - - -/** - * @type {!ChromeEvent} - * @see http://developer.chrome.com/apps/app.window.html#event-onBoundsChanged - */ -chrome.app.window.onBoundsChanged; - - -/** - * @type {!ChromeEvent} - * @see http://developer.chrome.com/apps/app.window.html#event-onClosed - */ -chrome.app.window.onClosed; - - -/** - * @type {!ChromeEvent} - * @see http://developer.chrome.com/apps/app.window.html#event-onFullscreened - */ -chrome.app.window.onFullscreened; - - -/** - * @type {!ChromeEvent} - * @see http://developer.chrome.com/apps/app.window.html#event-onMaximized - */ -chrome.app.window.onMaximized; - - -/** - * @type {!ChromeEvent} - * @see http://developer.chrome.com/apps/app.window.html#event-onMinimized - */ -chrome.app.window.onMinimized; - - -/** - * @type {!ChromeEvent} - * @see http://developer.chrome.com/apps/app.window.html#event-onRestored - */ -chrome.app.window.onRestored; - - -/** - * Private API. - * - * @const - * @see https://code.google.com/p/chromium/codesearch#chromium/src/chrome/common/extensions/api/audio_modem.idl - * @see go/chrome-modem - */ -chrome.audioModem = {}; - - -/** - * @typedef {?{ - * tokenLength: number, - * crc: (boolean|undefined), - * parity: (boolean|undefined) - * }} - */ -chrome.audioModem.TokenEncoding; - - -/** - * @typedef {?{ - * timeoutMillis: number, - * band: string, - * encoding: !chrome.audioModem.TokenEncoding - * }} - */ -chrome.audioModem.RequestParams; - - -/** @constructor */ -chrome.audioModem.ReceivedToken = function() {}; - - -/** @type {!ArrayBuffer} */ -chrome.audioModem.ReceivedToken.prototype.token; - - -/** @type {string} */ -chrome.audioModem.ReceivedToken.prototype.band; - - -/** - * @param {!chrome.audioModem.RequestParams} params - * @param {!ArrayBuffer} token - * @param {function(string)} callback - * @return {undefined} - */ -chrome.audioModem.transmit = function(params, token, callback) {}; - - -/** - * @param {string} band - * @param {function(string)} callback - * @return {undefined} - */ -chrome.audioModem.stopTransmit = function(band, callback) {}; - - -/** - * @param {!chrome.audioModem.RequestParams} params - * @param {function(string)} callback - * @return {undefined} - */ -chrome.audioModem.receive = function(params, callback) {}; - - -/** - * @param {string} band - * @param {function(string)} callback - * @return {undefined} - */ -chrome.audioModem.stopReceive = function(band, callback) {}; - - -/** - * @interface - * @extends {ChromeBaseEvent)>} - */ -chrome.audioModem.ReceivedEvent = function() {}; - - -/** @type {!chrome.audioModem.ReceivedEvent} */ -chrome.audioModem.onReceived; - - -/** @type {!ChromeStringEvent} */ -chrome.audioModem.onTransmitFail; - - -/** - * @see https://developer.chrome.com/apps/bluetooth - */ -chrome.bluetooth = {}; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/bluetooth#type-AdapterState - */ -chrome.bluetooth.AdapterState = function() {}; - - -/** @type {string} */ -chrome.bluetooth.AdapterState.prototype.address; - - -/** @type {string} */ -chrome.bluetooth.AdapterState.prototype.name; - - -/** @type {boolean} */ -chrome.bluetooth.AdapterState.prototype.powered; - - -/** @type {boolean} */ -chrome.bluetooth.AdapterState.prototype.available; - - -/** @type {boolean} */ -chrome.bluetooth.AdapterState.prototype.discovering; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/bluetooth#type-Device - */ -chrome.bluetooth.Device = function() {}; - - -/** @type {string} */ -chrome.bluetooth.Device.prototype.address; - - -/** @type {string|undefined} */ -chrome.bluetooth.Device.prototype.name; - - -/** @type {number|undefined} */ -chrome.bluetooth.Device.prototype.deviceClass; - - -/** @type {string|undefined} */ -chrome.bluetooth.Device.prototype.vendorIdSource; - - -/** @type {string|undefined} */ -chrome.bluetooth.Device.prototype.vendorId; - - -/** @type {number|undefined} */ -chrome.bluetooth.Device.prototype.productId; - - -/** @type {number|undefined} */ -chrome.bluetooth.Device.prototype.deviceId; - - -/** @type {string|undefined} */ -chrome.bluetooth.Device.prototype.type; - - -/** @type {boolean|undefined} */ -chrome.bluetooth.Device.prototype.paired; - - -/** @type {boolean|undefined} */ -chrome.bluetooth.Device.prototype.connected; - - -/** @type {boolean|undefined} */ -chrome.bluetooth.Device.prototype.connecting; - - -/** @type {boolean|undefined} */ -chrome.bluetooth.Device.prototype.connectable; - - -/** @type {!Array|undefined} */ -chrome.bluetooth.Device.prototype.uuids; - - -/** @type {number|undefined} */ -chrome.bluetooth.Device.prototype.inquiryRssi; - - -/** @type {number|undefined} */ -chrome.bluetooth.Device.prototype.inquiryTxPower; - - -/** - * @param {function(!chrome.bluetooth.AdapterState)} callback - * @see https://developer.chrome.com/apps/bluetooth#method-getAdapterState - * @return {undefined} - */ -chrome.bluetooth.getAdapterState = function(callback) {}; - - -/** - * @param {string} deviceAddress - * @param {function(!chrome.bluetooth.Device)} callback - * @see https://developer.chrome.com/apps/bluetooth#method-getDevice - * @return {undefined} - */ -chrome.bluetooth.getDevice = function(deviceAddress, callback) {}; - - -/** - * @param {function(!Array)} callback - * @see https://developer.chrome.com/apps/bluetooth#method-getDevices - * @return {undefined} - */ -chrome.bluetooth.getDevices = function(callback) {}; - - -/** - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetooth#method-startDiscovery - * @return {undefined} - */ -chrome.bluetooth.startDiscovery = function(opt_callback) {}; - - -/** - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetooth#method-stopDiscovery - * @return {undefined} - */ -chrome.bluetooth.stopDiscovery = function(opt_callback) {}; - - - -/** - * Event whose listeners take an AdapaterState parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetooth.AdapterStateEvent = function() {}; - - -/** - * @type {!chrome.bluetooth.AdapterStateEvent} - * @see https://developer.chrome.com/apps/bluetooth#event-onAdapterStateChanged - */ -chrome.bluetooth.onAdapterStateChanged; - - -/** - * Event whose listeners take an Device parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetooth.DeviceEvent = function() {}; - - -/** - * @type {!chrome.bluetooth.DeviceEvent} - * @see https://developer.chrome.com/apps/bluetooth#event-onDeviceAdded - */ -chrome.bluetooth.onDeviceAdded; - - -/** - * @type {!chrome.bluetooth.DeviceEvent} - * @see https://developer.chrome.com/apps/bluetooth#event-onDeviceChanged - */ -chrome.bluetooth.onDeviceChanged; - - -/** - * @type {!chrome.bluetooth.DeviceEvent} - * @see https://developer.chrome.com/apps/bluetooth#event-onDeviceRemoved - */ -chrome.bluetooth.onDeviceRemoved; - - -/** - * @const - * @see https://developer.chrome.com/apps/bluetoothSocket - */ -chrome.bluetoothSocket = {}; - - -/** - * @typedef {{ - * persistent: (boolean|undefined), - * name: (string|undefined), - * bufferSize: (number|undefined) - * }} - * @see https://developer.chrome.com/apps/bluetoothSocket#type-SocketProperties - */ -chrome.bluetoothSocket.SocketProperties; - - -/** - * @typedef {{ - * channel: (number|undefined), - * psm: (number|undefined), - * backlog: (number|undefined) - * }} - * @see https://developer.chrome.com/apps/bluetoothSocket#type-ListenOptions - */ -chrome.bluetoothSocket.ListenOptions; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/bluetoothSocket#type-SocketInfo - */ -chrome.bluetoothSocket.SocketInfo = function() {}; - - -/** @type {number} */ -chrome.bluetoothSocket.SocketInfo.prototype.socketId; - - -/** @type {boolean} */ -chrome.bluetoothSocket.SocketInfo.prototype.persistent; - - -/** @type {string|undefined} */ -chrome.bluetoothSocket.SocketInfo.prototype.name; - - -/** @type {number|undefined} */ -chrome.bluetoothSocket.SocketInfo.prototype.bufferSize; - - -/** @type {boolean} */ -chrome.bluetoothSocket.SocketInfo.prototype.paused; - - -/** @type {boolean} */ -chrome.bluetoothSocket.SocketInfo.prototype.connected; - - -/** @type {string|undefined} */ -chrome.bluetoothSocket.SocketInfo.prototype.address; - - -/** @type {string|undefined} */ -chrome.bluetoothSocket.SocketInfo.prototype.uuid; - - -/** - * @param {!chrome.bluetoothSocket.SocketProperties| - * function(!{socketId: number})} propertiesOrCallback - * @param {function(!{socketId: number})=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-create - * @return {undefined} - */ -chrome.bluetoothSocket.create = function(propertiesOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {!chrome.bluetoothSocket.SocketProperties} properties - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-update - * @return {undefined} - */ -chrome.bluetoothSocket.update = function(socketId, properties, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {boolean} paused - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-setPaused - * @return {undefined} - */ -chrome.bluetoothSocket.setPaused = function(socketId, paused, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {string} uuid - * @param {!chrome.bluetoothSocket.ListenOptions|function()} optionsOrCallback - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-listenUsingRfcomm - * @return {undefined} - */ -chrome.bluetoothSocket.listenUsingRfcomm = function( - socketId, uuid, optionsOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {string} uuid - * @param {!chrome.bluetoothSocket.ListenOptions|function()} optionsOrCallback - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-listenUsingL2cap - * @return {undefined} - */ -chrome.bluetoothSocket.listenUsingL2cap = function( - socketId, uuid, optionsOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {string} address - * @param {string} uuid - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-connect - * @return {undefined} - */ -chrome.bluetoothSocket.connect = function(socketId, address, uuid, callback) {}; - - -/** - * @param {number} socketId - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-disconnect - * @return {undefined} - */ -chrome.bluetoothSocket.disconnect = function(socketId, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-close - * @return {undefined} - */ -chrome.bluetoothSocket.close = function(socketId, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {!ArrayBuffer} data - * @param {function(number)=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-send - * @return {undefined} - */ -chrome.bluetoothSocket.send = function(socketId, data, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {function(!chrome.bluetoothSocket.SocketInfo)} callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-getInfo - * @return {undefined} - */ -chrome.bluetoothSocket.getInfo = function(socketId, callback) {}; - - -/** - * @param {function(!Array)} callback - * @see https://developer.chrome.com/apps/bluetoothSocket#method-getSockets - * @return {undefined} - */ -chrome.bluetoothSocket.getSockets = function(callback) {}; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/bluetoothSocket#event-onAccept - */ -chrome.bluetoothSocket.AcceptEventData = function() {}; - - -/** @type {number} */ -chrome.bluetoothSocket.AcceptEventData.prototype.socketId; - - -/** @type {number} */ -chrome.bluetoothSocket.AcceptEventData.prototype.clientSocketId; - - - -/** - * Event whose listeners take a AcceptEventData parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetoothSocket.AcceptEvent = function() {}; - - -/** @type {!chrome.bluetoothSocket.AcceptEvent} */ -chrome.bluetoothSocket.onAccept; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/bluetoothSocket#event-onAcceptError - */ -chrome.bluetoothSocket.AcceptErrorEventData = function() {}; - - -/** @type {number} */ -chrome.bluetoothSocket.AcceptErrorEventData.prototype.socketId; - - -/** @type {string} */ -chrome.bluetoothSocket.AcceptErrorEventData.prototype.errorMessage; - - -/** @type {string} */ -chrome.bluetoothSocket.AcceptErrorEventData.prototype.error; - - - -/** - * Event whose listeners take a AcceptErrorEventData parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetoothSocket.AcceptErrorEvent = function() {}; - - -/** @type {!chrome.bluetoothSocket.AcceptErrorEvent} */ -chrome.bluetoothSocket.onAcceptError; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/bluetoothSocket#event-onReceive - */ -chrome.bluetoothSocket.ReceiveEventData = function() {}; - - -/** @type {number} */ -chrome.bluetoothSocket.ReceiveEventData.prototype.socketId; - - -/** @type {!ArrayBuffer} */ -chrome.bluetoothSocket.ReceiveEventData.prototype.data; - - - -/** - * Event whose listeners take a ReceiveEventData parameter. - * @interface - * @extends - * {ChromeBaseEvent} - */ -chrome.bluetoothSocket.ReceiveEvent = function() {}; - - -/** @type {!chrome.bluetoothSocket.ReceiveEvent} */ -chrome.bluetoothSocket.onReceive; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/bluetoothSocket#event-onReceiveError - */ -chrome.bluetoothSocket.ReceiveErrorEventData = function() {}; - - -/** @type {number} */ -chrome.bluetoothSocket.ReceiveErrorEventData.prototype.socketId; - - -/** @type {string} */ -chrome.bluetoothSocket.ReceiveErrorEventData.prototype.errorMessage; - - -/** @type {string} */ -chrome.bluetoothSocket.ReceiveErrorEventData.prototype.error; - - - -/** - * Event whose listeners take a ReceiveErrorEventData parameter. - * @interface - * @extends {ChromeBaseEvent< - * function(!chrome.bluetoothSocket.ReceiveErrorEventData)>} - */ -chrome.bluetoothSocket.ReceiveErrorEvent = function() {}; - - -/** @type {!chrome.bluetoothSocket.ReceiveErrorEvent} */ -chrome.bluetoothSocket.onReceiveError; - - -/** - * @see https://developer.chrome.com/apps/bluetoothLowEnergy - * @const - */ -chrome.bluetoothLowEnergy = {}; - - -/** - * @typedef {?{ - * uuid: string, - * isPrimary: boolean, - * instanceId: (string|undefined), - * deviceAddress: (string|undefined) - * }} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#type-Service - */ -chrome.bluetoothLowEnergy.Service; - - -/** - * @constructor - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#type-Request - */ -chrome.bluetoothLowEnergy.Request = function() {}; - - -/** @type {number} */ -chrome.bluetoothLowEnergy.Request.prototype.requestId; - - -/** @type {!Object} */ -chrome.bluetoothLowEnergy.Request.prototype.device; - - -/** @type {!ArrayBuffer|undefined} */ -chrome.bluetoothLowEnergy.Request.prototype.value; - - -/** - * @typedef {?{ - * uuid: string, - * service: (!chrome.bluetoothLowEnergy.Service|undefined), - * properties: !Array, - * instanceId: (string|undefined), - * value: (!ArrayBuffer|undefined) - * }} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#type-Characteristic - */ -chrome.bluetoothLowEnergy.Characteristic; - - -/** - * @typedef {?{ - * uuid: string, - * characteristic: (!chrome.bluetoothLowEnergy.Characteristic|undefined), - * permissions: !Array, - * instanceId: (string|undefined), - * value: (!ArrayBuffer|undefined) - * }} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#type-Descriptor - */ -chrome.bluetoothLowEnergy.Descriptor; - - -/** - * @typedef {?{ - * persistent: boolean - * }} - */ -chrome.bluetoothLowEnergy.ConnectionProperties; - - -/** - * @param {string} deviceAddress - * @param {!chrome.bluetoothLowEnergy.ConnectionProperties|function()} - * propertiesOrCallback - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-connect - * @return {undefined} - */ -chrome.bluetoothLowEnergy.connect = function( - deviceAddress, propertiesOrCallback, opt_callback) {}; - -/** - * @param {string} deviceAddress - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-disconnect - * @return {undefined} - */ -chrome.bluetoothLowEnergy.disconnect = function(deviceAddress, opt_callback) {}; - - -/** - * @param {string} serviceId - * @param {function(!chrome.bluetoothLowEnergy.Service)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-getService - * @return {undefined} - */ -chrome.bluetoothLowEnergy.getService = function(serviceId, callback) {}; - - -/** - * @param {!chrome.bluetoothLowEnergy.Service} service - * @param {function(string)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-createService - * @return {undefined} - */ -chrome.bluetoothLowEnergy.createService = function(service, callback) {}; - - -/** - * @param {string} deviceAddress - * @param {function(!Array)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-getServices - * @return {undefined} - */ -chrome.bluetoothLowEnergy.getServices = function(deviceAddress, callback) {}; - - -/** - * @param {string} characteristicId - * @param {function(!chrome.bluetoothLowEnergy.Characteristic)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-getCharacteristic - * @return {undefined} - */ -chrome.bluetoothLowEnergy.getCharacteristic = function( - characteristicId, callback) {}; - - -/** - * @param {!chrome.bluetoothLowEnergy.Characteristic} characteristic - * @param {string} serviceId - * @param {function(string)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-createCharacteristic - * @return {undefined} - */ -chrome.bluetoothLowEnergy.createCharacteristic = function( - characteristic, serviceId, callback) {}; - - -/** - * @param {string} serviceId - * @param {function(!Array)} - * callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-getCharacteristics - * @return {undefined} - */ -chrome.bluetoothLowEnergy.getCharacteristics = function(serviceId, callback) {}; - - -/** - * @param {string} serviceId - * @param {function(!Array)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-getIncludedServices - * @return {undefined} - */ -chrome.bluetoothLowEnergy.getIncludedServices = function( - serviceId, callback) {}; - - -/** - * @param {string} descriptorId - * @param {function(!chrome.bluetoothLowEnergy.Descriptor)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-getDescriptor - * @return {undefined} - */ -chrome.bluetoothLowEnergy.getDescriptor = function(descriptorId, callback) {}; - - -/** - * @param {!chrome.bluetoothLowEnergy.Descriptor} descriptor - * @param {string} characteristicId - * @param {function(string)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-createDescriptor - * @return {undefined} - */ -chrome.bluetoothLowEnergy.createDescriptor = function( - descriptor, characteristicId, callback) {}; - - -/** - * @param {string} characteristicId - * @param {function(!Array)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-getDescriptors - * @return {undefined} - */ -chrome.bluetoothLowEnergy.getDescriptors = function( - characteristicId, callback) {}; - - -/** - * @param {string} characteristicId - * @param {function(!chrome.bluetoothLowEnergy.Characteristic)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-readCharacteristicValue - * @return {undefined} - */ -chrome.bluetoothLowEnergy.readCharacteristicValue = function( - characteristicId, callback) {}; - - -/** - * @param {string} characteristicId - * @param {!ArrayBuffer} value - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-writeCharacteristicValue - * @return {undefined} - */ -chrome.bluetoothLowEnergy.writeCharacteristicValue = function( - characteristicId, value, callback) {}; - - -/** - * @typedef {?{ - * persistent: boolean - * }} - */ -chrome.bluetoothLowEnergy.NotificationSessionProperties; - -/** - * @param {string} characteristicId - * @param {!chrome.bluetoothLowEnergy.NotificationSessionProperties|function()} - * propertiesOrCallback - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-startCharacteristicNotifications - * @return {undefined} - */ -chrome.bluetoothLowEnergy.startCharacteristicNotifications = function( - characteristicId, propertiesOrCallback, opt_callback) {}; - - -/** - * @param {string} characteristicId - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-stopCharacteristicNotifications - * @return {undefined} - */ -chrome.bluetoothLowEnergy.stopCharacteristicNotifications = function( - characteristicId, opt_callback) {}; - - -/** - * @typedef {?{ - * value: !ArrayBuffer, - * shouldIndicate: (boolean|undefined) - * }} - */ -chrome.bluetoothLowEnergy.NotificationIndication; - - -/** - * @param {string} characteristicId - * @param {!chrome.bluetoothLowEnergy.NotificationIndication} notification - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-notifyCharacteristicValueChanged - * @return {undefined} - */ -chrome.bluetoothLowEnergy.notifyCharacteristicValueChanged = function( - characteristicId, notification, callback) {}; - - -/** - * @param {string} descriptorId - * @param {function(!chrome.bluetoothLowEnergy.Descriptor)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-readDescriptorValue - * @return {undefined} - */ -chrome.bluetoothLowEnergy.readDescriptorValue = function( - descriptorId, callback) {}; - - -/** - * @param {string} descriptorId - * @param {!ArrayBuffer} value - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-writeDescriptorValue - * @return {undefined} - */ -chrome.bluetoothLowEnergy.writeDescriptorValue = function( - descriptorId, value, callback) {}; - - -/** - * @param {string} serviceId - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-registerService - * @return {undefined} - */ -chrome.bluetoothLowEnergy.registerService = function(serviceId, callback) {}; - - -/** - * @param {string} serviceId - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-unregisterService - * @return {undefined} - */ -chrome.bluetoothLowEnergy.unregisterService = function(serviceId, callback) {}; - - -/** - * @param {string} serviceId - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-removeService - * @return {undefined} - */ -chrome.bluetoothLowEnergy.removeService = function(serviceId, opt_callback) {}; - - -/** - * @typedef {?{ - * type: string, - * serviceUuids: (!Array|undefined), - * manufacturerData: (!Array<{id: number, data: !Array}>|undefined), - * solicitUuids: (!Array|undefined), - * serviceData: (!Array<{uuid: string, data: !Array}>|undefined) - * }} - */ -chrome.bluetoothLowEnergy.Advertisement; - - -/** - * @param {!chrome.bluetoothLowEnergy.Advertisement} advertisement - * @param {function(number)} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-registerAdvertisement - */ -chrome.bluetoothLowEnergy.registerAdvertisement = function( - advertisement, callback) {}; - - -/** - * @param {number} advertisementId - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-unregisterAdvertisement - */ -chrome.bluetoothLowEnergy.unregisterAdvertisement = function( - advertisementId, callback) {}; - - -/** - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-resetAdvertising - */ -chrome.bluetoothLowEnergy.resetAdvertising = function(callback) {}; - - -/** - * @param {number} minInterval - * @param {number} maxInterval - * @param {function()} callback - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#method-setAdvertisingInterval - */ -chrome.bluetoothLowEnergy.setAdvertisingInterval = function( - minInterval, maxInterval, callback) {}; - - -/** - * @typedef {?{ - * requestId: number, - * isError: boolean, - * value: (!ArrayBuffer|undefined) - * }} - */ -chrome.bluetoothLowEnergy.RequestResponse; - - -/** @param {!chrome.bluetoothLowEnergy.RequestResponse} response */ -chrome.bluetoothLowEnergy.sendRequestResponse = function(response) {}; - - -/** - * Event whose listeners take a Service parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetoothLowEnergy.ServiceEvent = function() {}; - - -/** - * @type {!chrome.bluetoothLowEnergy.ServiceEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onServiceAdded - */ -chrome.bluetoothLowEnergy.onServiceAdded; - - -/** - * @type {!chrome.bluetoothLowEnergy.ServiceEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onServiceChanged - */ -chrome.bluetoothLowEnergy.onServiceChanged; - - -/** - * @type {!chrome.bluetoothLowEnergy.ServiceEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onServiceRemoved - */ -chrome.bluetoothLowEnergy.onServiceRemoved; - - -/** - * Event whose listeners take a Characteristic parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetoothLowEnergy.CharacteristicEvent = function() {}; - - -/** - * @type {!chrome.bluetoothLowEnergy.CharacteristicEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onCharacteristicValueChanged - */ -chrome.bluetoothLowEnergy.onCharacteristicValueChanged; - - -/** - * Event whose listeners take a Descriptor parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetoothLowEnergy.DescriptorEvent = function() {}; - - -/** - * @type {!chrome.bluetoothLowEnergy.DescriptorEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onDescriptorValueChanged - */ -chrome.bluetoothLowEnergy.onDescriptorValueChanged; - - -/** - * Event whose listeners take a Request parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetoothLowEnergy.RequestEvent = function() {}; - - -/** - * @type {!chrome.bluetoothLowEnergy.RequestEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onCharacteristicReadRequest - */ -chrome.bluetoothLowEnergy.onCharacteristicReadRequest; - - -/** - * @type {!chrome.bluetoothLowEnergy.RequestEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onCharacteristicWriteRequest - */ -chrome.bluetoothLowEnergy.onCharacteristicWriteRequest; - - -/** - * @type {!chrome.bluetoothLowEnergy.RequestEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onDescriptorReadRequest - */ -chrome.bluetoothLowEnergy.onDescriptorReadRequest; - - -/** - * @type {!chrome.bluetoothLowEnergy.RequestEvent} - * @see https://developer.chrome.com/apps/bluetoothLowEnergy#event-onDescriptorWriteRequest - */ -chrome.bluetoothLowEnergy.onDescriptorWriteRequest; - -/** - * @const - * @see https://developer.chrome.com/extensions/browsingData - */ -chrome.browsingData = {}; - -/** - * @typedef {?{ - * since: (number|undefined), - * originTypes: ({ - * unprotectedWeb: (boolean|undefined), - * protectedWeb: (boolean|undefined), - * extension: (boolean|undefined) - * }|undefined), - * }} - * @see https://developer.chrome.com/extensions/browsingData#type-RemovalOptions - */ -chrome.browsingData.RemovalOptions; - -/** - * @typedef {?{ - * appcache: (boolean|undefined), - * cache: (boolean|undefined), - * cookies: (boolean|undefined), - * downloads: (boolean|undefined), - * fileSystems: (boolean|undefined), - * formData: (boolean|undefined), - * history: (boolean|undefined), - * indexedDB: (boolean|undefined), - * localStorage: (boolean|undefined), - * serverBoundCertificates: (boolean|undefined), - * passwords: (boolean|undefined), - * pluginData: (boolean|undefined), - * serviceWorkers: (boolean|undefined), - * webSQL: (boolean|undefined), - * }} - * @see https://developer.chrome.com/extensions/browsingData#type-DataTypeSet - */ -chrome.browsingData.DataTypeSet; - -/** - * @typedef {?{ - * options: !chrome.browsingData.RemovalOptions, - * dataToRemove: !chrome.browsingData.DataTypeSet, - * dataRemovalPermitted: !chrome.browsingData.DataTypeSet, - * }} - */ -chrome.browsingData.SettingsResponse; - -/** - * @param {function(!chrome.browsingData.SettingsResponse): void} callback - * @see https://developer.chrome.com/extensions/browsingData#method-settings - */ -chrome.browsingData.settings = function(callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {!chrome.browsingData.DataTypeSet} dataToRemove - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-remove - */ -chrome.browsingData.remove = function(options, dataToRemove, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeAppcache - */ -chrome.browsingData.removeAppcache = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeCache - */ -chrome.browsingData.removeCache = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeCookies - */ -chrome.browsingData.removeCookies = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeDownloads - */ -chrome.browsingData.removeDownloads = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeFileSystems - */ -chrome.browsingData.removeFileSystems = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeFormData - */ -chrome.browsingData.removeFormData = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeHistory - */ -chrome.browsingData.removeHistory = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeIndexedDB - */ -chrome.browsingData.removeIndexedDB = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeLocalStorage - */ -chrome.browsingData.removeLocalStorage = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removePluginData - */ -chrome.browsingData.removePluginData = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removePasswords - */ -chrome.browsingData.removePasswords = function(options, callback) {}; - -/** - * @param {!chrome.browsingData.RemovalOptions} options - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/browsingData#method-removeWebSQL - */ -chrome.browsingData.removeWebSQL = function(options, callback) {}; - -/** - * @see http://developer.chrome.com/extensions/commands.html - * @const - */ -chrome.commands = {}; - - -/** - * @param {function(Array): void} callback Callback function. - * @return {undefined} - */ -chrome.commands.getAll = function(callback) {}; - - -/** @type {!ChromeEvent} */ -chrome.commands.onCommand; - - -/** - * @see https://developer.chrome.com/apps/copresence - * @const - */ -chrome.copresence = {}; - - -/** - * @typedef {?{ - * lowPower: (boolean|undefined), - * onlyBroadcast: (boolean|undefined), - * onlyScan: (boolean|undefined), - * audible: (boolean|undefined) - * }} - * @see https://developer.chrome.com/apps/copresence#type-Strategy - */ -chrome.copresence.Strategy; - - -/** - * @typedef {?{ - * type: string, - * payload: ArrayBuffer - * }} - * @see https://developer.chrome.com/apps/copresence#type-Message - */ -chrome.copresence.Message; - - -/** - * @typedef {?{ - * onlyEarshot: (boolean|undefined) - * }} - * https://developer.chrome.com/apps/copresence#type-AccessPolicy - */ -chrome.copresence.AccessPolicy; - - -/** - * @typedef {?{ - * id: string, - * message: !chrome.copresence.Message, - * timeToLiveMillis: (number|undefined), - * policy: (!chrome.copresence.AccessPolicy|undefined), - * strategies: (!chrome.copresence.Strategy|undefined) - * }} - * @see https://developer.chrome.com/apps/copresence#type-PublishOperation - */ -chrome.copresence.PublishOperation; - - -/** @typedef {?{type: string}} */ -chrome.copresence.SubscriptionFilter; - - -/** - * @typedef {?{ - * id: string, - * filter: !chrome.copresence.SubscriptionFilter, - * timeToLiveMillis: (number|undefined), - * strategies: (!chrome.copresence.Strategy|undefined) - * }} - * @see https://developer.chrome.com/apps/copresence#type-SubscribeOperation - */ -chrome.copresence.SubscribeOperation; - - -/** - * @typedef {?{ - * unpublishId: string - * }} - * @see https://developer.chrome.com/apps/copresence#type-UnpublishOperation - */ -chrome.copresence.UnpublishOperation; - - -/** - * @typedef {?{ - * unsubscribeId: string - * }} - * @see https://developer.chrome.com/apps/copresence#type-UnsubscribeOperation - */ -chrome.copresence.UnsubscribeOperation; - - -/** - * @typedef {?{ - * publish: (!chrome.copresence.PublishOperation|undefined), - * subscribe: (!chrome.copresence.SubscribeOperation|undefined), - * unpublish: (!chrome.copresence.UnpublishOperation|undefined), - * unsubscribe: (!chrome.copresence.UnsubscribeOperation|undefined) - * }} - * @see https://developer.chrome.com/apps/copresence#type-Operation - */ -chrome.copresence.Operation; - - -/** - * @param {!Array} operations - * @param {function(string): void} callback - * @see https://developer.chrome.com/apps/copresence#method-execute - * @return {undefined} - */ -chrome.copresence.execute = function(operations, callback) {}; - - - -/** - * Event whose listeners take a subscription id and received messages as a - * parameter. - * @interface - * @extends {ChromeBaseEvent)>} - * @see https://developer.chrome.com/apps/copresence#event-onMessagesReceived - */ -chrome.copresence.MessagesReceivedEvent = function() {}; - - -/** - * @type {!chrome.copresence.MessagesReceivedEvent} - * @see https://developer.chrome.com/apps/copresence#event-onMessagesReceived - */ -chrome.copresence.onMessagesReceived; - - -/** - * @type {!ChromeStringEvent} - * @see https://developer.chrome.com/apps/copresence#event-onStatusUpdated - */ -chrome.copresence.onStatusUpdated; - - -/** @const */ -chrome.devtools = {}; - - -/** - * @see https://developer.chrome.com/extensions/devtools_inspectedWindow - * @const - */ -chrome.devtools.inspectedWindow = {}; - - -/** - * @constructor - * @see https://developer.chrome.com/extensions/devtools_inspectedWindow#type-Resource - */ -chrome.devtools.inspectedWindow.Resource = function() {}; - -/** @type {string} */ -chrome.devtools.inspectedWindow.Resource.prototype.url; - -/** @param {function(string, string): void} callback */ -chrome.devtools.inspectedWindow.Resource.prototype.getContent = function( - callback) {}; - -/** - * @param {string} content - * @param {boolean} commit - * @param {function(!Object): void=} callback - */ -chrome.devtools.inspectedWindow.Resource.prototype.setContent = function( - content, commit, callback) {}; - - -/** - * @type {number} - * @see https://developer.chrome.com/extensions/devtools_inspectedWindow#property-tabId - */ -chrome.devtools.inspectedWindow.tabId; - - -/** - * @typedef {?{ - * frameUrl: (string|undefined), - * useContentScriptContext: (boolean|undefined), - * contextSecurityOrigin: (string|undefined) - * }} - */ -chrome.devtools.inspectedWindow.EvalOptions; - -/** - * @param {string} expression - * @param {!chrome.devtools.inspectedWindow.EvalOptions=} options - * @param {function(!Object, !Object): void=} callback - * @see https://developer.chrome.com/extensions/devtools_inspectedWindow#method-eval - */ -chrome.devtools.inspectedWindow.eval = function( - expression, options, callback) {}; - - -/** - * @typedef {?{ - * ignoreCache: (boolean|undefined), - * userAgent: (string|undefined), - * injectedScript: (string|undefined) - * }} - */ -chrome.devtools.inspectedWindow.ReloadOptions; - -/** - * @param {!chrome.devtools.inspectedWindow.ReloadOptions=} reloadOptions - * @see https://developer.chrome.com/extensions/devtools_inspectedWindow#method-reload - */ -chrome.devtools.inspectedWindow.reload = function(reloadOptions) {}; - - -/** - * @param {function(!Array): void} - * callback - * @see https://developer.chrome.com/extensions/devtools_inspectedWindow#method-getResources - */ -chrome.devtools.inspectedWindow.getResources = function(callback) {}; - - -/** - * @interface - * @extends {ChromeBaseEvent< - * function(!chrome.devtools.inspectedWindow.Resource)>} - */ -chrome.devtools.inspectedWindow.ResourceEvent = function() {}; - -/** - * @see https://developer.chrome.com/extensions/devtools_inspectedWindow#event-onResourceAdded - * @type {!chrome.devtools.inspectedWindow.ResourceEvent} - */ -chrome.devtools.inspectedWindow.onResourceAdded; - - -/** - * @interface - * @extends {ChromeBaseEvent< - * function(!chrome.devtools.inspectedWindow.Resource, string)>} - */ -chrome.devtools.inspectedWindow.ResourceContentEvent = function() {}; - -/** - * @see https://developer.chrome.com/extensions/devtools_inspectedWindow#event-onResourceContentCommitted - * @type {!chrome.devtools.inspectedWindow.ResourceContentEvent} - */ -chrome.devtools.inspectedWindow.onResourceContentCommitted; - - -/** - * @see https://developer.chrome.com/docs/extensions/reference/devtools_network/ - * @const - */ -chrome.devtools.network = {}; - -/** - * @see https://developer.chrome.com/docs/extensions/reference/devtools_network/#type-Request - * @constructor - */ -chrome.devtools.network.Request = function() {}; - -/** - * @interface - * @extends {ChromeBaseEvent< - * function(!chrome.devtools.network.Request)>} - */ -chrome.devtools.network.RequestEvent = function() {}; - -/** - * @see https://developer.chrome.com/docs/extensions/reference/devtools_network/#event-onRequestFinished - * @type {!chrome.devtools.network.RequestEvent} - */ -chrome.devtools.network.onRequestFinished - - -/** - * @see https://developer.chrome.com/extensions/enterprise_platformKeys - * @const - */ -chrome.enterprise = {}; - - -/** - * @constructor - * deviceAttributes allows for reading device attributes. - * @see https://developer.chrome.com/extensions/enterprise_deviceAttributes. - */ -chrome.enterprise.deviceAttributes = function() {}; - - -/** - * @param {function(string): void} callback Called with the device identifier - * of the directory API when received. - * @return {undefined} - */ -chrome.enterprise.deviceAttributes.getDirectoryDeviceId = function(callback) {}; - - -/** - * @param {function(string): void} callback Called with the serial number of the - * device. - * @return {undefined} - */ -chrome.enterprise.deviceAttributes.getDeviceSerialNumber = function( - callback) {}; - - -/** - * @param {function(string): void} callback Called with the Asset ID of the - * device. - * @return {undefined} - */ -chrome.enterprise.deviceAttributes.getDeviceAssetId = function(callback) {}; - - -/** - * @param {function(string): void} callback Called with the Annotated Location - * of the device. - * @return {undefined} - */ -chrome.enterprise.deviceAttributes.getDeviceAnnotatedLocation = function( - callback) {}; - - -/** - * @constructor - * platformKeys allows for generating hardware-backed keys and the installation - * of certificates for these keys. - * @see https://developer.chrome.com/extensions/enterprise_platformKeys. - */ -chrome.enterprise.platformKeys = function() {}; - - -/** - * @constructor - * @see https://developer.chrome.com/extensions/enterprise_platformKeys#type-Token - */ -chrome.enterprise.Token = function() {}; - - -/** - * @type {string} Unique id for the Token, either "user" or "system." - */ -chrome.enterprise.Token.prototype.id; - - -/** - * @type {!webCrypto.SubtleCrypto} Implements the WebCrypto's - * SubtleCrypto interface. The cryptographic operations, including key - * generation, are hardware-backed. - */ -chrome.enterprise.Token.prototype.subtleCrypto; - - -/** - * @param {!ArrayBuffer} challenge A challenge as emitted by the Verified Access - * Web API. - * @param {boolean|function(!ArrayBuffer): void} registerKeyOrCallback Either a - * flag indicating whether to register the key, in which case the callback - * is passed as the next arg, or the callback. If a flag is set, the current - * Enterprise Machine Key is registered with the "system" token and - * relinquishes the Enterprise Machine Key role. The key can then be - * associated with a certificate and used like any other signing key. This - * key is 2048-bit RSA. Subsequent calls to this function will then generate - * a new Enterprise Machine Key. - * @param {function(!ArrayBuffer=): void=} callback The callback (called back - * with the challenge response), if arg2 was the registerKey flag. - * @return {undefined} - */ -chrome.enterprise.platformKeys.challengeMachineKey = function( - challenge, registerKeyOrCallback, callback) {}; - - -/** - * @param {!ArrayBuffer} challenge A challenge as emitted by the Verified Access - * Web API. - * @param {boolean} registerKey If set, the current Enterprise User Key is - * registered with the "user" token and relinquishes the Enterprise User - * Key role. The key can then be associated with a certificate and used like - * any other signing key. This key is 2048-bit RSA. Subsequent calls to this - * function will then generate a new Enterprise User Key. - * @param {function(!ArrayBuffer): void} callback Called back with the - * challenge response. - * @return {undefined} - */ -chrome.enterprise.platformKeys.challengeUserKey = function( - challenge, registerKey, callback) {}; - - -/** - * @param {function(!Array): void} callback Called - * with an array of Tokens. - * @return {undefined} - */ -chrome.enterprise.platformKeys.getTokens = function(callback) {}; - - -/** - * @param {string} tokenId Id of cetificate token either "user" or "system". - * @param {(function(!Array): void)} callback Array of DER - * encoded x.509 certificates. - * @return {undefined} - */ -chrome.enterprise.platformKeys.getCertificates = function(tokenId, callback) {}; - - -/** - * @param {string} tokenId The id of a Token returned by getTokens. - * @param {!ArrayBuffer} certificate The DER encoding of a X.509 certificate. - * @param {function(): void=} opt_callback Called back when this operation is - * finished. - * @return {undefined} - */ -chrome.enterprise.platformKeys.importCertificate = function( - tokenId, certificate, opt_callback) {}; - - -/** - * @param {string} tokenId The id of a Token returned by getTokens. - * @param {!ArrayBuffer} certificate The DER encoding of a X.509 certificate. - * @param {(function(): void)=} opt_callback Called back when this operation is - * finished. - * @return {undefined} - */ -chrome.enterprise.platformKeys.removeCertificate = function( - tokenId, certificate, opt_callback) {}; - -/** - * reportingPrivate is a Private API for reporting Chrome browser status to - * admin console. - * @see https://cs.chromium.org/chromium/src/chrome/common/extensions/api/enterprise_reporting_private.idl - */ -chrome.enterprise.reportingPrivate = {}; - -/** - * Uploads the status of Chrome browser to the admin console by sending - * request to the DMServer. Sets runtime.lastError on failure. - * @param {!Object} report Object to report to admin console. - * @param {(function(): void)=} callback Called back when this operation is - * finished. - */ -chrome.enterprise.reportingPrivate.uploadChromeDesktopReport = function( - report, callback) {}; - -/** - * Gets the identity of device that Chrome browser is running on. The ID is - * retrieved from the local device and used by the Google admin console. - * @param {(function(!string): void)=} callback Called with the device ID. - */ -chrome.enterprise.reportingPrivate.getDeviceId = function(callback) {}; - -/** - * Returns a random secret stored in a platform specific storage. - * @param {(function(!ArrayBuffer): void)=} callback Called with the result. - */ -chrome.enterprise.reportingPrivate.getPersistentSecret = function(callback) {}; - -/** - * Returns byte string associated with the data item stored in a platform - * specific storage. - * @param {!string} item Item name (can have containers separated by '/'). - * @param {(function((!ArrayBuffer|undefined)): void)=} callback Called back with the - * response. - */ -chrome.enterprise.reportingPrivate.getDeviceData = function(item, callback) {}; - -/** - * Stores byte string associated with the data item in a platform - * specific storage. - * @param {!string} item Item name (can have containers separated by '/'). - * @param {!ArrayBuffer|undefined} data Byte string to associate with the data item. - * @param {(function(): void)=} callback Called back with the response. - */ -chrome.enterprise.reportingPrivate.setDeviceData = function( - item, data, callback) {}; - -/** - * Represents a device info property type. - * @enum {string} - */ -chrome.enterprise.reportingPrivate.SettingValue = { - UNKNOWN: '', - DISABLED: '', - ENABLED: '', -}; - -/** - * Type of the object returned by getDeviceInfo. - * @typedef {?{ - * osName: string, - * osVersion: string, - * deviceHostName: string, - * deviceModel: string, - * serialNumber: string, - * screenLockSecured: chrome.enterprise.reportingPrivate.SettingValue, - * diskEncrypted: chrome.enterprise.reportingPrivate.SettingValue, - * macAddresses: (!Array|undefined), - * }} - */ -chrome.enterprise.reportingPrivate.DeviceInfo; - -/** - * Returns the device information object. - * @param {(function(!chrome.enterprise.reportingPrivate.DeviceInfo): void)=} - * callback Called back with the response. - */ -chrome.enterprise.reportingPrivate.getDeviceInfo = function(callback) {}; - -/** - * Represents possible states for the EnterpriseRealTimeUrlCheckMode policy - * @enum {number} - */ -chrome.enterprise.reportingPrivate.RealtimeUrlCheckMode = { - DISABLED: 0, - ENABLED_MAIN_FRAME: 0, -}; - -/** - * Type of the object returned by getContextInfo. - * @typedef {?{ - * browserAffiliationIds: (!Array|undefined), - * profileAffiliationIds: (!Array|undefined), - * onFileAttachedProviders: (!Array|undefined), - * onFileDownloadedProviders: (!Array|undefined), - * onBulkDataEntryProviders: (!Array|undefined), - * onSecurityEventProviders: (!Array|undefined), - * realtimeUrlCheckMode: chrome.enterprise.reportingPrivate.RealtimeUrlCheckMode, - * browserVersion: string, - * }} - */ -chrome.enterprise.reportingPrivate.ContextInfo; - -/** - * Returns the context information object. - * @param {(function(!chrome.enterprise.reportingPrivate.ContextInfo): void)} - * callback Called back with the response. - */ -chrome.enterprise.reportingPrivate.getContextInfo = function(callback) {}; - - -/** - * Possible states for the Certificate status. - * @enum {number} - */ -chrome.enterprise.reportingPrivate.CertificateStatus = { - OK: 0, - POLICY_UNSET: 1, -}; - -/** - * Type of the object returned by getCertificate. - * @typedef {?{ - * status: chrome.enterprise.reportingPrivate.CertificateStatus, - * encodedCertificate: (!ArrayBuffer|undefined), - * }} - */ -chrome.enterprise.reportingPrivate.Certificate; - -/** - * Returns the certificate object. - * @param {!string} url URL for which certificate needs to be fetched. - * @param {(function(!chrome.enterprise.reportingPrivate.Certificate): void)} - * callback Called back with the response. - */ -chrome.enterprise.reportingPrivate.getCertificate = function(url, callback) {}; - -/** - * @see https://developer.chrome.com/extensions/extension.html - * @const - */ -chrome.extension = {}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/extension#type-ViewType - */ -chrome.extension.ViewType = { - TAB: '', - POPUP: '', -}; - - -/** @type {{message:(string|undefined)}|undefined} */ -chrome.extension.lastError = {}; - - -/** @type {boolean|undefined} */ -chrome.extension.inIncognitoContext; - - -// TODO: change Object to !Object when it's clear nobody is passing in null -// TODO: change Port to !Port since it should never be null -/** - * @param {string|Object=} opt_extensionIdOrConnectInfo Either the - * extensionId to connect to, in which case connectInfo params can be - * passed in the next optional argument, or the connectInfo params. - * @param {Object=} opt_connectInfo The connectInfo object, - * if arg1 was the extensionId to connect to. - * @return {Port} New port. - */ -chrome.extension.connect = function( - opt_extensionIdOrConnectInfo, opt_connectInfo) {}; - - -/** - * @return {Window} The global JS object for the background page. - */ -chrome.extension.getBackgroundPage = function() {}; - - -/** - * @param {string} path A path to a resource within an extension expressed - * relative to it's install directory. - * @return {string} The fully-qualified URL to the resource. - */ -chrome.extension.getURL = function(path) {}; - - -/** - * @typedef {?{ - * type: (!chrome.extension.ViewType|string|undefined), - * windowId: (number|undefined), - * tabId: (number|undefined) - * }} - */ -chrome.extension.ViewInfo; - -/** - * @param {?chrome.extension.ViewInfo=} opt_fetchProperties - * @return {Array} The global JS objects for each content view. - */ -chrome.extension.getViews = function(opt_fetchProperties) {}; - - -/** - * @param {function(boolean): void} callback Callback function. - * @return {undefined} - */ -chrome.extension.isAllowedFileSchemeAccess = function(callback) {}; - - -/** - * @param {function(boolean): void} callback Callback function. - * @return {undefined} - */ -chrome.extension.isAllowedIncognitoAccess = function(callback) {}; - - -/** - * @param {string|*} extensionIdOrRequest Either the extensionId to send the - * request to, in which case the request is passed as the next arg, or the - * request. - * @param {*=} opt_request The request value, if arg1 was the extensionId. - * @param {function(*): void=} opt_callback The callback function which - * takes a JSON response object sent by the handler of the request. - * @return {undefined} - */ -chrome.extension.sendMessage = function( - extensionIdOrRequest, opt_request, opt_callback) {}; - - -/** - * @param {number|*=} opt_arg1 Either the extensionId to send the request to, - * in which case the request is passed as the next arg, or the request. - * @param {*=} opt_request The request value, if arg1 was the extensionId. - * @param {function(*): void=} opt_callback The callback function which - * takes a JSON response object sent by the handler of the request. - * @return {undefined} - */ -chrome.extension.sendRequest = function(opt_arg1, opt_request, opt_callback) {}; - - -/** - * @param {string} data - * @return {undefined} - */ -chrome.extension.setUpdateUrlData = function(data) {}; - - -/** @type {!ChromeEvent} */ -chrome.extension.onConnect; - - -/** @type {!ChromeEvent} */ -chrome.extension.onConnectExternal; - - -/** @type {!ChromeEvent} */ -chrome.extension.onMessage; - - -/** @type {!ChromeEvent} */ -chrome.extension.onRequest; - - -/** @type {!ChromeEvent} */ -chrome.extension.onRequestExternal; - -/** - * @see https://developer.chrome.com/extensions/runtime.html - * @const - */ -chrome.runtime = {}; - - -/** @type {{message:(string|undefined)}|undefined} */ -chrome.runtime.lastError; - - -/** - * @param {string|!Object=} opt_extensionIdOrConnectInfo Either the - * extensionId to connect to, in which case connectInfo params can be - * passed in the next optional argument, or the connectInfo params. - * @param {!Object=} opt_connectInfo The connectInfo object, - * if arg1 was the extensionId to connect to. - * @return {!Port} New port. - */ -chrome.runtime.connect = function( - opt_extensionIdOrConnectInfo, opt_connectInfo) {}; - - -/** - * @param {string|*} extensionIdOrMessage Either the extensionId to send the - * message to, in which case the message is passed as the next arg, or the - * message itself. - * @param {(*|!Object|function(*): void)=} opt_messageOrOptsOrCallback - * One of: - * The message, if arg1 was the extensionId. - * The options for message sending, if arg1 was the message and this - * argument is not a function. - * The callback, if arg1 was the message and this argument is a function. - * @param {(!Object|function(*): void)=} opt_optsOrCallback - * Either the options for message sending, if arg2 was the message, - * or the callback. - * @param {function(*): void=} opt_callback The callback function which - * takes a JSON response object sent by the handler of the request. - * @return {undefined} - */ -chrome.runtime.sendMessage = function( - extensionIdOrMessage, opt_messageOrOptsOrCallback, opt_optsOrCallback, - opt_callback) {}; - - -/** @type {string} */ -chrome.runtime.id; - - -/** - * @param {function(!Window=): void} callback Callback function. - * @return {undefined} - */ -chrome.runtime.getBackgroundPage = function(callback) {}; - - -/** - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.runtime.openOptionsPage = function(opt_callback) {}; - - -/** - * Manifest information returned from chrome.runtime.getManifest. See - * https://developer.chrome.com/extensions/manifest.html and - * https://developer.chrome.com/apps/manifest.html - * - * Note that: - * 1) There are several other fields not included here. They should be - * added to these externs as needed. - * 2) There are some distinct fields for app vs extension manifests. The - * below manifest definition contains the union of all fields; unique - * fields should be annotated as such (see e.g. kiosk_only property - * below). - * @constructor - */ -chrome.runtime.Manifest = function() {}; - - -/** @type {string} */ -chrome.runtime.Manifest.prototype.name; - - -/** @type {string} */ -chrome.runtime.Manifest.prototype.version; - - -/** @type {string|undefined} */ -chrome.runtime.Manifest.prototype.version_name; - - -/** @type {number|undefined} */ -chrome.runtime.Manifest.prototype.manifest_version; - - -/** @type {string|undefined} */ -chrome.runtime.Manifest.prototype.description; - - -/** @type {!Object} */ -chrome.runtime.Manifest.prototype.icons; - - -/** @type {!chrome.runtime.Manifest.Oauth2|undefined} */ -chrome.runtime.Manifest.prototype.oauth2; - - -/** @type {!Array<(string|!Object)>} */ -chrome.runtime.Manifest.prototype.permissions; - - -/** - * App-only manifest field. - * @see https://developer.chrome.com/apps/manifest - * @type {boolean|undefined} - */ -chrome.runtime.Manifest.prototype.kiosk_only; - -/** - * App-only manifest field. - * @see https://developer.chrome.com/apps/manifest - * @type {boolean|undefined} - */ -chrome.runtime.Manifest.prototype.kiosk_enabled; - -/** @type {string|undefined} */ -chrome.runtime.Manifest.prototype.replacement_web_app; - - - -/** - * Oauth2 info in the manifest. - * See http://developer.chrome.com/apps/app_identity.html#update_manifest. - * @constructor - */ -chrome.runtime.Manifest.Oauth2 = function() {}; - - -/** @type {string} */ -chrome.runtime.Manifest.Oauth2.prototype.client_id; - - -/**@type {!Array} */ -chrome.runtime.Manifest.Oauth2.prototype.scopes; - - -/** - * https://developer.chrome.com/extensions/runtime.html#method-getManifest - * https://developer.chrome.com/apps/runtime#method-getManifest - * @return {!chrome.runtime.Manifest} The full manifest file of the app or - * extension. - */ -chrome.runtime.getManifest = function() {}; - - -/** - * @param {string} path A path to a resource within an extension expressed - * relative to it's install directory. - * @return {string} The fully-qualified URL to the resource. - */ -chrome.runtime.getURL = function(path) {}; - - -/** - * @param {string} url This may be used to clean up server-side data, do - * analytics, and implement surveys. Maximum 255 characters. - * @return {undefined} - */ -chrome.runtime.setUninstallURL = function(url) {}; - - -/** - * Reloads the app or extension. - * @return {undefined} - */ -chrome.runtime.reload = function() {}; - - -/** - * @see https://developer.chrome.com/apps/runtime#method-requestUpdateCheck - * @param {function(string, !{version: string}=): void} callback Called with - * "throttled", "no_update", or "update_available". If an update is - * available, the object contains more information about the available - * update. - * @return {undefined} - */ -chrome.runtime.requestUpdateCheck = function(callback) {}; - - -/** - * Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's - * no-op. - * @return {undefined} - */ -chrome.runtime.restart = function() {}; - - -/** - * @see https://developer.chrome.com/extensions/runtime#method-restartAfterDelay - * @param {number} seconds Time to wait in seconds before rebooting the device, - * or -1 to cancel a scheduled reboot. - * @param {function():void=} opt_callback A callback to be invoked when a - * restart request was successfully rescheduled. - * @return {undefined} - */ -chrome.runtime.restartAfterDelay = function(seconds, opt_callback) {}; - - -/** - * @see http://developer.chrome.com/extensions/runtime.html#method-connectNative - * @param {string} application Name of the registered native messaging host to - * connect to, like 'com.google.your_product'. - * @return {!Port} New port. - */ -chrome.runtime.connectNative = function(application) {}; - - -/** - * @see http://developer.chrome.com/extensions/runtime.html#method-sendNativeMessage - * @param {string} application Name of the registered native messaging host to - * connect to, like 'com.google.your_product'. - * @param {Object} message The message that will be passed to the native - * messaging host. - * @param {function(*)=} opt_callback Called with the response message sent by - * the native messaging host. If an error occurs while connecting to the - * native messaging host, the callback will be called with no arguments and - * chrome.runtime.lastError will be set to the error message. - * @return {undefined} - */ -chrome.runtime.sendNativeMessage = function( - application, message, opt_callback) {}; - - -/** - * The operating system chrome is running on. - * @see https://developer.chrome.com/apps/runtime#type-PlatformOs - * @enum {string} - */ -chrome.runtime.PlatformOs = { - ANDROID: '', - CROS: '', - LINUX: '', - MAC: '', - OPENBSD: '', - WIN: '', -}; - - -/** - * The machine's processor architecture. - * @see https://developer.chrome.com/apps/runtime#type-PlatformArch - * @enum {string} - */ -chrome.runtime.PlatformArch = { - ARM: '', - ARM64: '', - MIPS: '', - MIPS64: '', - X86_32: '', - X86_64: '', -}; - - -/** - * The native client architecture. - * @see https://developer.chrome.com/apps/runtime#type-PlatformNaclArch - * @enum {string} - */ -chrome.runtime.PlatformNaclArch = { - ARM: '', - MIPS: '', - MIPS64: '', - X86_32: '', - X86_64: '', -}; - - -/** - * @see https://developer.chrome.com/apps/runtime#type-PlatformInfo - * @typedef {{ - * os: !chrome.runtime.PlatformOs, - * arch: !chrome.runtime.PlatformArch, - * nacl_arch: !chrome.runtime.PlatformNaclArch, - * }} - */ -chrome.runtime.PlatformInfo; - - -/** - * @see https://developer.chrome.com/extensions/runtime#type-PlatformInfo - * @param {function(!chrome.runtime.PlatformInfo)} callback - * @return {undefined} - */ -chrome.runtime.getPlatformInfo = function(callback) {}; - - -/** - * @param {function(!DirectoryEntry)} callback - * @return {undefined} - */ -chrome.runtime.getPackageDirectoryEntry = function(callback) {}; - - -/** @type {!chrome.runtime.PortEvent} */ -chrome.runtime.onConnect; - - -/** @type {!chrome.runtime.PortEvent} */ -chrome.runtime.onConnectExternal; - - -/** @type {!chrome.runtime.PortEvent} */ -chrome.runtime.onConnectNative; - - -/** @type {!ChromeObjectEvent} */ -chrome.runtime.onInstalled; - - -/** @type {!chrome.runtime.MessageSenderEvent} */ -chrome.runtime.onMessage; - - -/** @type {!chrome.runtime.MessageSenderEvent} */ -chrome.runtime.onMessageExternal; - - -/** @type {!ChromeEvent} */ -chrome.runtime.onStartup; - - -/** @type {!ChromeEvent} */ -chrome.runtime.onSuspend; - - -/** @type {!ChromeEvent} */ -chrome.runtime.onSuspendCanceled; - - -/** @type {!ChromeObjectEvent} */ -chrome.runtime.onUpdateAvailable; - - -/** @type {!ChromeStringEvent} */ -chrome.runtime.onRestartRequired; - - - -/** - * Event whose listeners take a Port parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.runtime.PortEvent = function() {}; - - -/** - * Event whose listeners take a MessageSender and additional parameters. - * @see http://developer.chrome.com/dev/apps/runtime.html#event-onMessage - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.runtime.MessageSenderEvent = function() {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/tabs - */ -chrome.tabs = {}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tabs#type-TabStatus - */ -chrome.tabs.TabStatus = { - COMPLETE: '', - LOADING: '', -}; - - -/** - * @const {number} - * @see https://developer.chrome.com/extensions/tabs#property-TAB_ID_NONE - */ -chrome.tabs.TAB_ID_NONE = -1; - - -/** - * @typedef {?{ - * code: (string|undefined), - * file: (string|undefined), - * allFrames: (boolean|undefined), - * matchAboutBlank: (boolean|undefined), - * runAt: (string|undefined) - * }} - */ -chrome.tabs.InjectDetails; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-captureVisibleTab - * @param {number|!chrome.types.ImageDetails|function(string):void} - * windowIdOrOptionsOrCallback One of: - * The target window. - * An object defining details about the format and quality of an image, in - * which case the window defaults to the current window. - * A callback function which accepts the data URL string of a JPEG encoding - * of the visible area of the captured tab. - * @param {(!chrome.types.ImageDetails|function(string):void)=} - * opt_optionsOrCallback Either an object defining details about the - * format and quality of an image, or a callback function which accepts the - * data URL string of a JPEG encoding of the visible area of the captured - * tab. - * @param {function(string):void=} opt_callback A callback function which - * accepts the data URL string of a JPEG encoding of the visible area of the - * captured tab. - * @return {undefined} - */ -chrome.tabs.captureVisibleTab = function( - windowIdOrOptionsOrCallback, opt_optionsOrCallback, opt_callback) {}; - - -/** - * @param {number} tabId Tab Id. - * @param {{name: (string|undefined)}=} connectInfo Info Object. - * @return {Port} New port. - */ -chrome.tabs.connect = function(tabId, connectInfo) {}; - - -/** - * @typedef {?{ - * windowId: (number|undefined), - * index: (number|undefined), - * url: (string|undefined), - * active: (boolean|undefined), - * pinned: (boolean|undefined), - * openerTabId: (number|undefined) - * }} - */ -chrome.tabs.CreateProperties; - - -/** - * @param {!chrome.tabs.CreateProperties} createProperties Info object. - * @param {function(!Tab): void=} opt_callback The callback function. - * @return {undefined} - */ -chrome.tabs.create = function(createProperties, opt_callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-detectLanguage - * @param {number|function(string): void} tabIdOrCallback The tab id, or a - * callback function that will be invoked with the language of the active - * tab in the current window. - * @param {function(string): void=} opt_callback An optional callback function - * that will be invoked with the language of the tab specified as first - * argument. - * @return {undefined} - */ -chrome.tabs.detectLanguage = function(tabIdOrCallback, opt_callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-discard - * @param {number|function(!Tab): void} tabIdOrCallback - * @param {function(!Tab): void=} opt_callback - */ -chrome.tabs.discard; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-executeScript - * @param {number|!chrome.tabs.InjectDetails} tabIdOrDetails - * Either the id of the tab in which to run the script, or an object - * containing the details of the script to run, in which case the script - * will be executed in the active tab of the current window. - * @param {(!chrome.tabs.InjectDetails|function(!Array<*>):void)=} - * opt_detailsOrCallback Either an object containing the details of the - * script to run, if the tab id was speficied as first argument, or a - * callback that will be invoked with the result of the execution of the - * script in every injected frame. - * @param {function(!Array<*>):void=} opt_callback A callback that will be - * invoked with the result of the execution of the script in every - * injected frame. - * @return {undefined} - */ -chrome.tabs.executeScript = function( - tabIdOrDetails, opt_detailsOrCallback, opt_callback) {}; - - -/** - * @param {number} tabId Tab id. - * @param {function(!Tab): void} callback Callback. - * @return {undefined} - */ -chrome.tabs.get = function(tabId, callback) {}; - - -/** - * Note (2014-05-21): Because this function is deprecated, the types of it's - * parameters were not upgraded to make the first parameter optional and to mark - * the Array and Tab in the callback as non-null. - * - * @param {number?} windowId Window id. - * @param {function(Array): void} callback Callback. - * @deprecated Please use tabs.query {windowId: windowId}. - * @return {undefined} - */ -chrome.tabs.getAllInWindow = function(windowId, callback) {}; - - -/** - * @param {function(!Tab=): void} callback Callback. - * @return {undefined} - */ -chrome.tabs.getCurrent = function(callback) {}; - - -/** - * Note (2014-05-21): Because this function is deprecated, the types of it's - * parameters were not upgraded to make the first parameter optional and to mark - * the Array and Tab in the callback as non-null. - * - * @param {number?} windowId Window id. - * @param {function(Tab): void} callback Callback. - * @deprecated Please use tabs.query({active: true}). - * @return {undefined} - */ -chrome.tabs.getSelected = function(windowId, callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-getZoom - * @param {number|function(number): void} tabIdOrCallback - * @param {function(number): void=} opt_callback - * @return {undefined} - */ -chrome.tabs.getZoom = function(tabIdOrCallback, opt_callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/tabs#type-ZoomSettings - * @typedef {?{ - * mode: (string|undefined), - * scope: (string|undefined), - * defaultZoomFactor: (number|undefined), - * }} - */ -chrome.tabs.ZoomSettings; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-getZoomSettings - * @param {number|function(!chrome.tabs.ZoomSettings): void} tabIdOrCallback - * @param {function(!chrome.tabs.ZoomSettings): void=} opt_callback - */ -chrome.tabs.getZoomSettings = function(tabIdOrCallback, opt_callback) {}; - - -/** - * @typedef {?{ - * windowId: (number|undefined), - * tabs: (number|!Array) - * }} - */ -chrome.tabs.HighlightInfo; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-highlight - * @param {!chrome.tabs.HighlightInfo} highlightInfo - * @param {function(!ChromeWindow): void=} callback Callback function invoked - * for each window whose tabs were highlighted. - * @return {undefined} - */ -chrome.tabs.highlight = function(highlightInfo, callback) {}; - - -/** - * @link https://developer.chrome.com/extensions/tabs#method-insertCSS - * @param {number|!chrome.tabs.InjectDetails} tabIdOrDetails - * Either the id of the tab in which to run the script, or an object - * containing the details of the CSS to insert, in which case the script - * will be executed in the active tab of the current window. - * @param {(!chrome.tabs.InjectDetails|function():void)=} - * opt_detailsOrCallback Either an object containing the details of the - * CSS to insert, if the tab id was speficied as first argument, or a - * callback that will be invoked after the CSS has been injected. - * @param {function():void=} opt_callback A callback that will be invoked after - * the CSS has been injected. - * @return {undefined} - */ -chrome.tabs.insertCSS = function( - tabIdOrDetails, opt_detailsOrCallback, opt_callback) {}; - - -/** - * @typedef {?{ - * windowId: (number|undefined), - * index: number - * }} - */ -chrome.tabs.MoveProperties; - - -/** - * @param {number|!Array} tabId Tab id or array of tab ids. - * @param {!chrome.tabs.MoveProperties} moveProperties - * @param {function((!Tab|!Array)): void=} opt_callback Callback. - * @return {undefined} - */ -chrome.tabs.move = function(tabId, moveProperties, opt_callback) {}; - - -/** - * @typedef {?{ - * active: (boolean|undefined), - * pinned: (boolean|undefined), - * audible: (boolean|undefined), - * muted: (boolean|undefined), - * highlighted: (boolean|undefined), - * discarded: (boolean|undefined), - * autoDiscardable: (boolean|undefined), - * currentWindow: (boolean|undefined), - * lastFocusedWindow: (boolean|undefined), - * status: (!chrome.tabs.TabStatus|string|undefined), - * title: (string|undefined), - * url: (!Array|string|undefined), - * windowId: (number|undefined), - * windowType: (string|undefined), - * index: (number|undefined) - * }} - */ -chrome.tabs.QueryInfo; - - -/** - * @param {!chrome.tabs.QueryInfo} queryInfo - * @param {function(!Array): void} callback Callback. - * @return {undefined} - */ -chrome.tabs.query = function(queryInfo, callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-query - * @param {number} tabId The ID of the tab which is to be duplicated. - * @param {(function(!Tab=):void)=} opt_callback A callback to be invoked with - * details about the duplicated tab. - * @return {undefined} - */ -chrome.tabs.duplicate = function(tabId, opt_callback) {}; - - -/** - * @typedef {?{ - * bypassCache: (boolean|undefined) - * }} - */ -chrome.tabs.ReloadProperties; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-reload - * @param {(number|!chrome.tabs.ReloadProperties|function():void)=} - * opt_tabIdOrReloadPropertiesOrCallback One of: - * The ID of the tab to reload; defaults to the selected tab of the current - * window. - * An object specifying boolean flags to customize the reload operation. - * A callback to be invoked when the reload is complete. - * @param {(!chrome.tabs.ReloadProperties|function():void)=} - * opt_reloadPropertiesOrCallback Either an object specifying boolean flags - * to customize the reload operation, or a callback to be invoked when the - * reload is complete, if no object needs to be specified. - * @param {function():void=} opt_callback A callback to be invoked when the - * reload is complete. - * @return {undefined} - */ -chrome.tabs.reload = function( - opt_tabIdOrReloadPropertiesOrCallback, opt_reloadPropertiesOrCallback, - opt_callback) {}; - - -/** - * @param {number|!Array} tabIds A tab ID or an array of tab IDs. - * @param {function(): void=} opt_callback Callback. - * @return {undefined} - */ -chrome.tabs.remove = function(tabIds, opt_callback) {}; - - -/** - * @typedef {?{ - * frameId: (number|undefined) - * }} - */ -chrome.tabs.SendMessageOptions; - - -/** - * @param {number} tabId Tab id. - * @param {*} request The request value of any type. - * @param {(!chrome.tabs.SendMessageOptions|function(*): void)=} - * opt_optionsOrCallback The object with an optional "frameId" or the - * callback function. - * @param {function(*): void=} opt_callback The callback function which - * takes a JSON response object sent by the handler of the request. - * @return {undefined} - */ -chrome.tabs.sendMessage = function( - tabId, request, opt_optionsOrCallback, opt_callback) {}; - - -/** - * @param {number} tabId Tab id. - * @param {*} request The request value of any type. - * @param {function(*): void=} opt_callback The callback function which - * takes a JSON response object sent by the handler of the request. - * @deprecated Please use runtime.sendMessage. - * @return {undefined} - */ -chrome.tabs.sendRequest = function(tabId, request, opt_callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-setZoom - * @param {number} tabIdOrZoomFactor - * @param {(number|function(): void)=} opt_zoomFactorOrCallback - * @param {function(): void=} opt_callback - * @return {undefined} - */ -chrome.tabs.setZoom = function( - tabIdOrZoomFactor, opt_zoomFactorOrCallback, opt_callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-setZoomSettings - * @param {number|!chrome.tabs.ZoomSettings} tabIdOrZoomSettings - * @param {(!chrome.tabs.ZoomSettings|function(): void)=} - * opt_zoomSettingsOrCallback - * @param {function(): void=} opt_callback - */ -chrome.tabs.setZoomSettings = function( - tabIdOrZoomSettings, opt_zoomSettingsOrCallback, opt_callback) {}; - - -/** - * @typedef {?{ - * url: (string|undefined), - * active: (boolean|undefined), - * highlighted: (boolean|undefined), - * pinned: (boolean|undefined), - * openerTabId: (number|undefined) - * }} - */ -chrome.tabs.UpdateProperties; - - -/** - * @see https://developer.chrome.com/extensions/tabs#method-update - * @param {number|!chrome.tabs.UpdateProperties} tabIdOrUpdateProperties - * Either the id of the tab to update, or an object with new property - * values, in which case the selected tab of the current window will be - * updated. - * @param {(!chrome.tabs.UpdateProperties|function(Tab):void)=} - * opt_updatePropertiesOrCallback Either an object with new property values, - * if the tabId was specified as first parameter, or an optional callback - * that will be invoked with information about the tab being updated. - * @param {function(!Tab=): void=} opt_callback An optional callback that will - * be invoked with information about the tab being updated. - * @return {undefined} - */ -chrome.tabs.update = function( - tabIdOrUpdateProperties, opt_updatePropertiesOrCallback, opt_callback) {}; - - -/** - * @type {!ChromeEvent} - * @deprecated Please use tabs.onActivated. - */ -chrome.tabs.onActiveChanged; - - -/** @type {!ChromeEvent} */ -chrome.tabs.onActivated; - - -/** @type {!ChromeEvent} */ -chrome.tabs.onAttached; - - -/** @type {!ChromeEvent} */ -chrome.tabs.onCreated; - - -/** @type {!ChromeEvent} */ -chrome.tabs.onDetached; - - -/** - * @type {!ChromeEvent} - * @deprecated Please use tabs.onHighlighted. - */ -chrome.tabs.onHighlightChanged; - - -/** - * @type {!ChromeEvent} - */ -chrome.tabs.onHighlighted; - - -/** @type {!ChromeEvent} */ -chrome.tabs.onMoved; - - -/** @type {!ChromeEvent} */ -chrome.tabs.onRemoved; - - -/** @type {!ChromeEvent} */ -chrome.tabs.onUpdated; - - -/** @type {!ChromeEvent} */ -chrome.tabs.onReplaced; - -// DEPRECATED: -// TODO(user): Remove once all usage has been confirmed to have ended. - - -/** - * @type {!ChromeEvent} - * @deprecated Please use tabs.onActivated. - */ -chrome.tabs.onSelectionChanged; - - -/** - * @see https://developer.chrome.com/extensions/tabs#event-onZoomChange - * @type {!ChromeObjectEvent} - */ -chrome.tabs.onZoomChange; - - -/** - * @see https://developer.chrome.com/extensions/topSites - * @const - */ -chrome.topSites = {}; - - - -/** - * @constructor - * @see https://developer.chrome.com/extensions/topSites#type-MostVisitedURL - */ -chrome.topSites.MostVisitedURL = function() {}; - - -/** @type {string} */ -chrome.topSites.MostVisitedURL.prototype.url; - - -/** @type {string} */ -chrome.topSites.MostVisitedURL.prototype.title; - - -/** - * Gets a list of top sites. - * @param {function(!Array)} callback Invoked - * with a list of most visited URLs. - * @see https://developer.chrome.com/extensions/topSites#method-get - * @return {undefined} - */ -chrome.topSites.get = function(callback) {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/windows.html - */ -chrome.windows = {}; - - -/** - * @param {Object=} opt_createData May have many keys to specify parameters. - * Or the callback. - * @param {function(ChromeWindow): void=} opt_callback Callback. - * @return {undefined} - */ -chrome.windows.create = function(opt_createData, opt_callback) {}; - - -/** - * @param {number} id Window id. - * @param {Object=} opt_getInfo May have 'populate' key. Or the callback. - * @param {function(!ChromeWindow): void=} opt_callback Callback when - * opt_getInfo is an object. - * @return {undefined} - */ -chrome.windows.get = function(id, opt_getInfo, opt_callback) {}; - - -/** - * @param {Object=} opt_getInfo May have 'populate' key. Or the callback. - * @param {function(!Array): void=} opt_callback Callback. - * @return {undefined} - */ -chrome.windows.getAll = function(opt_getInfo, opt_callback) {}; - - -/** - * @param {Object=} opt_getInfo May have 'populate' key. Or the callback. - * @param {function(ChromeWindow): void=} opt_callback Callback. - * @return {undefined} - */ -chrome.windows.getCurrent = function(opt_getInfo, opt_callback) {}; - - -/** - * @param {Object=} opt_getInfo May have 'populate' key. Or the callback. - * @param {function(ChromeWindow): void=} opt_callback Callback. - * @return {undefined} - */ -chrome.windows.getLastFocused = function(opt_getInfo, opt_callback) {}; - - -/** - * @param {number} tabId Tab Id. - * @param {function(): void=} opt_callback Callback. - * @return {undefined} - */ -chrome.windows.remove = function(tabId, opt_callback) {}; - - -/** - * @param {number} tabId Tab Id. - * @param {Object} updateProperties An object which may have many keys for - * various options. - * @param {function(!ChromeWindow): void=} opt_callback Callback. - * @return {undefined} - */ -chrome.windows.update = function(tabId, updateProperties, opt_callback) {}; - - -/** @type {!ChromeEvent} */ -chrome.windows.onCreated; - - -/** @type {!ChromeEvent} */ -chrome.windows.onFocusChanged; - - -/** @type {!ChromeEvent} */ -chrome.windows.onRemoved; - - -/** - * @see https://developer.chrome.com/extensions/windows.html#property-WINDOW_ID_NONE - * @type {number} - */ -chrome.windows.WINDOW_ID_NONE; - - -/** - * @see https://developer.chrome.com/extensions/windows.html#property-WINDOW_ID_CURRENT - * @type {number} - */ -chrome.windows.WINDOW_ID_CURRENT; - - -/** - * @const - * @see https://developer.chrome.com/extensions/i18n.html - */ -chrome.i18n = {}; - - -/** - * @param {function(Array): void} callback The callback function which - * accepts an array of the accept languages of the browser, such as - * 'en-US','en','zh-CN'. - * @return {undefined} - */ -chrome.i18n.getAcceptLanguages = function(callback) {}; - - -/** - * @param {string} messageName - * @param {(string|Array)=} opt_args - * @param {{escapeLt: boolean}=} opt_options - * @return {string} - * @see https://developer.chrome.com/extensions/i18n#method-getMessage - */ -chrome.i18n.getMessage = function(messageName, opt_args, opt_options) {}; - - -/** - * @return {string} - */ -chrome.i18n.getUILanguage = function() {}; - - -/** - * @param {string} text User input string to be detected. - * @param {function(!Object)} callback The callback for passing back the - * language detection result. - * @return {undefined} - */ -chrome.i18n.detectLanguage = function(text, callback) {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/pageAction.html - */ -chrome.pageAction = {}; - - -/** - * @param {number} tabId Tab Id. - * @return {undefined} - */ -chrome.pageAction.hide = function(tabId) {}; - - -/** - * @param {Object} details An object which has 'tabId' and either - * 'imageData' or 'path'. - * @param {(function(): void)=} callback The callback function. If an error - * occurs setting the icon, chrome.runtime.lastError will be set to the error - * message. - * @return {undefined} - */ -chrome.pageAction.setIcon = function(details, callback) {}; - - -/** - * @param {Object} details An object which may have 'popup' or 'tabId' as keys. - * @return {undefined} - */ -chrome.pageAction.setPopup = function(details) {}; - - -/** - * @param {Object} details An object which has 'tabId' and 'title'. - * @return {undefined} - */ -chrome.pageAction.setTitle = function(details) {}; - - -/** - * @param {number} tabId Tab Id. - * @param {(function(): void)=} callback The callback function. If an error - * occurs showing the pageAction, chrome.runtime.lastError will be set to the - * error message. - * @return {undefined} - */ -chrome.pageAction.show = function(tabId, callback) {}; - - -/** @type {!ChromeEvent} */ -chrome.pageAction.onClicked; - - -/** - * @const - * @see https://developer.chrome.com/apps/browser - */ -chrome.browser = {}; - - -/** - * @param {{url: string}} details An object with a single 'url' key. - * @param {(function(): void)=} opt_callback The callback function. If an error - * occurs opening the URL, chrome.runtime.lastError will be set to the error - * message. - * @return {undefined} - */ -chrome.browser.openTab = function(details, opt_callback) {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/browserAction.html - */ -chrome.browserAction = {}; - - -/** - * @typedef {?{ - * tabId: (number|undefined) - * }} - */ -chrome.browserAction.Tab; - - -/** - * @typedef {Array} - * @see https://developer.chrome.com/extensions/browserAction#type-ColorArray - */ -chrome.browserAction.ColorArray; - - -/** - * @typedef {{ - * imageData: (!ImageData|!Object|undefined), - * path: (string|!Object|undefined), - * tabId: (number|undefined) - * }} - */ -chrome.browserAction.SetIconImageData; - - -/** - * @param {{ - * title: string, - * tabId: (number|undefined) - * }} details - * @see https://developer.chrome.com/extensions/browserAction#method-setTitle - * @return {undefined} - */ -chrome.browserAction.setTitle = function(details) {}; - - -/** - * @param {!chrome.browserAction.Tab} details - * @param {function(string): void} callback - * @see https://developer.chrome.com/extensions/browserAction#method-getTitle - * @return {undefined} - */ -chrome.browserAction.getTitle = function(details, callback) {}; - - -/** - * @param {!chrome.browserAction.SetIconImageData} details - * @param {function(): void=} opt_callback - * @see https://developer.chrome.com/extensions/browserAction#method-setIcon - * @return {undefined} - */ -chrome.browserAction.setIcon = function(details, opt_callback) {}; - - -/** - * @param {{ - * tabId: (number|undefined), - * popup: string - * }} details - * @see https://developer.chrome.com/extensions/browserAction#method-setPopup - * @return {undefined} - */ -chrome.browserAction.setPopup = function(details) {}; - - -/** - * @param {!chrome.browserAction.Tab} details - * @param {function(string): void} callback - * @see https://developer.chrome.com/extensions/browserAction#method-getPopup - * @return {undefined} - */ -chrome.browserAction.getPopup = function(details, callback) {}; - - -/** - * @param {{ - * text: string, - * tabId: (number|undefined) - * }} details - * @see https://developer.chrome.com/extensions/browserAction#method-setBadgeText - * @return {undefined} - */ -chrome.browserAction.setBadgeText = function(details) {}; - - -/** - * @param {!chrome.browserAction.Tab} details - * @param {function(string): void} callback - * @see https://developer.chrome.com/extensions/browserAction#method-getBadgeText - * @return {undefined} - */ -chrome.browserAction.getBadgeText = function(details, callback) {}; - - -/** - * @param {{ - * color: (string|chrome.browserAction.ColorArray), - * tabId: (number|undefined) - * }} details - * @see https://developer.chrome.com/extensions/browserAction#method-setBadgeBackgroundColor - * @return {undefined} - */ -chrome.browserAction.setBadgeBackgroundColor = function(details) {}; - - -/** - * @param {!chrome.browserAction.Tab} details - * @param {function(chrome.browserAction.ColorArray): void} callback - * @see https://developer.chrome.com/extensions/browserAction#method-getBadgeBackgroundColor - * @return {undefined} - */ -chrome.browserAction.getBadgeBackgroundColor = function(details, callback) {}; - - -/** - * @param {number=} opt_tabId - * @see https://developer.chrome.com/extensions/browserAction#method-enable - * @return {undefined} - */ -chrome.browserAction.enable = function(opt_tabId) {}; - - -/** - * @param {number=} opt_tabId - * @see https://developer.chrome.com/extensions/browserAction#method-disable - * @return {undefined} - */ -chrome.browserAction.disable = function(opt_tabId) {}; - - -/** - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.browserAction.BrowserActionTabEvent = function() {}; - - -/** - * @type {!chrome.browserAction.BrowserActionTabEvent} - * @see https://developer.chrome.com/extensions/browserAction#event-onClicked - */ -chrome.browserAction.onClicked; - - -/** - * @const - * @see https://developer.chrome.com/extensions/bookmarks.html - */ -chrome.bookmarks = {}; - - -/** - * @typedef {?{ - * parentId: (string|undefined), - * index: (number|undefined), - * url: (string|undefined), - * title: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/bookmarks#method-create - */ -chrome.bookmarks.CreateDetails; - - -/** - * @typedef {?{ - * query: (string|undefined), - * url: (string|undefined), - * title: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/bookmarks#method-search - */ -chrome.bookmarks.SearchDetails; - - -/** - * @param {(string|Array)} idOrIdList - * @param {function(Array): void} callback The - * callback function which accepts an array of BookmarkTreeNode. - * @return {Array} - */ -chrome.bookmarks.get = function(idOrIdList, callback) {}; - - -/** - * @param {string} id - * @param {function(Array): void} callback The - * callback function which accepts an array of BookmarkTreeNode. - * @return {Array} - */ -chrome.bookmarks.getChildren = function(id, callback) {}; - - -/** - * @param {number} numberOfItems The number of items to return. - * @param {function(Array): void} callback The - * callback function which accepts an array of BookmarkTreeNode. - * @return {Array} - */ -chrome.bookmarks.getRecent = function(numberOfItems, callback) {}; - - -/** - * @param {function(Array): void} callback The - * callback function which accepts an array of BookmarkTreeNode. - * @return {Array} - */ -chrome.bookmarks.getTree = function(callback) {}; - - -/** - * @param {string} id The ID of the root of the subtree to retrieve. - * @param {function(Array): void} callback The - * callback function which accepts an array of BookmarkTreeNode. - * @return {Array} - */ -chrome.bookmarks.getSubTree = function(id, callback) {}; - - -/** - * @param {string|!chrome.bookmarks.SearchDetails} query - * @param {function(Array): void} callback - * @return {Array} - */ -chrome.bookmarks.search = function(query, callback) {}; - - -/** - * @param {chrome.bookmarks.CreateDetails} bookmark - * @param {function(BookmarkTreeNode): void=} opt_callback The - * callback function which accepts a BookmarkTreeNode object. - * @return {undefined} - */ -chrome.bookmarks.create = function(bookmark, opt_callback) {}; - - -/** - * @param {string} id - * @param {Object} destination An object which has optional 'parentId' and - * optional 'index'. - * @param {function(BookmarkTreeNode): void=} opt_callback - * The callback function which accepts a BookmarkTreeNode object. - * @return {undefined} - */ -chrome.bookmarks.move = function(id, destination, opt_callback) {}; - - -/** - * @param {string} id - * @param {Object} changes An object which may have 'title' as a key. - * @param {function(BookmarkTreeNode): void=} opt_callback The - * callback function which accepts a BookmarkTreeNode object. - * @return {undefined} - */ -chrome.bookmarks.update = function(id, changes, opt_callback) {}; - - -/** - * @param {string} id - * @param {function(): void=} opt_callback - * @return {undefined} - */ -chrome.bookmarks.remove = function(id, opt_callback) {}; - - -/** - * @param {string} id - * @param {function(): void=} opt_callback - * @return {undefined} - */ -chrome.bookmarks.removeTree = function(id, opt_callback) {}; - - -/** - * @param {function(): void=} opt_callback - * @return {undefined} - */ -chrome.bookmarks.import = function(opt_callback) {}; - - -/** - * @param {function(): void=} opt_callback - * @return {undefined} - */ -chrome.bookmarks.export = function(opt_callback) {}; - - -/** @type {!ChromeEvent} */ -chrome.bookmarks.onChanged; - - -/** @type {!ChromeEvent} */ -chrome.bookmarks.onChildrenReordered; - - -/** @type {!ChromeEvent} */ -chrome.bookmarks.onCreated; - - -/** @type {!ChromeEvent} */ -chrome.bookmarks.onImportBegan; - - -/** @type {!ChromeEvent} */ -chrome.bookmarks.onImportEnded; - - -/** @type {!ChromeEvent} */ -chrome.bookmarks.onMoved; - - -/** @type {!ChromeEvent} */ -chrome.bookmarks.onRemoved; - - -/** - * @typedef {?{ - * content: string, - * description: string - * }} - */ -var SuggestResult; - - -/** - * @const - * @see https://developer.chrome.com/extensions/omnibox.html - */ -chrome.omnibox = {}; - - - -/** - * @interface - * @extends {ChromeBaseEvent))>} - */ -chrome.omnibox.InputChangedEvent = function() {}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/omnibox#type-OnInputEnteredDisposition - */ -chrome.omnibox.OnInputEnteredDisposition = { - CURRENT_TAB: '', - NEW_BACKGROUND_TAB: '', - NEW_FOREGROUND_TAB: '', -}; - - -/** - * @interface - * @extends {ChromeBaseEvent< - * function(string,!chrome.omnibox.OnInputEnteredDisposition)>} - */ -chrome.omnibox.InputEnteredEvent = function() {}; - - -/** - * @param {{description: string}} suggestion A partial SuggestResult object. - * @return {undefined} - */ -chrome.omnibox.setDefaultSuggestion = function(suggestion) {}; - - -/** @type {!ChromeEvent} */ -chrome.omnibox.onInputCancelled; - - -/** @type {!chrome.omnibox.InputChangedEvent} */ -chrome.omnibox.onInputChanged; - - -/** @type {!chrome.omnibox.InputEnteredEvent} */ -chrome.omnibox.onInputEntered; - - -/** @type {!ChromeEvent} */ -chrome.omnibox.onInputStarted; - - -/** - * @const - * @see https://developer.chrome.com/extensions/dev/contextMenus.html - */ -chrome.contextMenus = {}; - - -/** - * @typedef {?{ - * type: (string|undefined), - * id: (string|undefined), - * title: (string|undefined), - * checked: (boolean|undefined), - * contexts: (!Array|undefined), - * onclick: (function(!Object, !Tab)|undefined), - * parentId: (number|string|undefined), - * documentUrlPatterns: (!Array|undefined), - * targetUrlPatterns: (!Array|undefined), - * enabled: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/contextMenus#method-create - */ -chrome.contextMenus.CreateProperties; - - -/** - * @typedef {?{ - * type: (string|undefined), - * title: (string|undefined), - * checked: (boolean|undefined), - * contexts: (!Array|undefined), - * onclick: (function(!Object, !Tab)|undefined), - * parentId: (number|string|undefined), - * documentUrlPatterns: (!Array|undefined), - * targetUrlPatterns: (!Array|undefined), - * enabled: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/contextMenus#method-update - */ -chrome.contextMenus.UpdateProperties; - - -/** - * @param {!chrome.contextMenus.CreateProperties} createProperties - * @param {function()=} opt_callback - * @return {(number|string)} The id of the newly created window. - * @see https://developer.chrome.com/extensions/contextMenus#method-create - */ -chrome.contextMenus.create = function(createProperties, opt_callback) {}; - - -/** - * @param {(number|string)} id - * @param {!chrome.contextMenus.UpdateProperties} updateProperties - * @param {function()=} opt_callback - * @see https://developer.chrome.com/extensions/contextMenus#method-update - * @return {undefined} - */ -chrome.contextMenus.update = function(id, updateProperties, opt_callback) {}; - - -/** - * @param {(number|string)} menuItemId - * @param {function()=} opt_callback - * @see https://developer.chrome.com/extensions/contextMenus#method-remove - * @return {undefined} - */ -chrome.contextMenus.remove = function(menuItemId, opt_callback) {}; - - -/** - * @param {function()=} opt_callback - * @see https://developer.chrome.com/extensions/contextMenus#method-removeAll - * @return {undefined} - */ -chrome.contextMenus.removeAll = function(opt_callback) {}; - - -/** - * @interface - * @extends {ChromeBaseEvent} - * @see https://developer.chrome.com/extensions/contextMenus#event-onClicked - */ -chrome.contextMenus.ClickedEvent = function() {}; - - -/** - * @type {!chrome.contextMenus.ClickedEvent} - * @see https://developer.chrome.com/extensions/contextMenus#event-onClicked - */ -chrome.contextMenus.onClicked; - - -/** - * @const - * @see https://developer.chrome.com/extensions/dev/cookies.html - */ -chrome.cookies = {}; - - -/** - * This typedef is used for the parameters to chrome.cookies.get, - * chrome.cookies.remove, and for the parameter to remove's callback. These uses - * all identify a single cookie uniquely without specifying its content, and the - * objects are identical except for the storeId being optional vs required. - * If greater divergence occurs, then going to two typedefs is recommended. - * - * @typedef {?{ - * url: string, - * name: string, - * storeId: (string|undefined) - * }} - */ -chrome.cookies.CookieIdentifier; - - -/** - * @param {!chrome.cookies.CookieIdentifier} details - * @param {function(Cookie=): void} callback - * @return {undefined} - */ -chrome.cookies.get = function(details, callback) {}; - - -/** - * @param {Object} details - * @param {function(Array): void} callback - * @return {undefined} - */ -chrome.cookies.getAll = function(details, callback) {}; - - -/** - * @param {function(Array): void} callback - * @return {undefined} - */ -chrome.cookies.getAllCookieStores = function(callback) {}; - - -/** - * @param {!chrome.cookies.CookieIdentifier} details - * @param {function(chrome.cookies.CookieIdentifier): void=} opt_callback If - * removal failed for any reason, the parameter will be "null", and - * "chrome.runtime.lastError" will be set. - * @return {undefined} - */ -chrome.cookies.remove = function(details, opt_callback) {}; - - -/** - * @typedef {?{ - * url: string, - * name: (string|undefined), - * value: (string|undefined), - * domain: (string|undefined), - * path: (string|undefined), - * secure: (boolean|undefined), - * httpOnly: (boolean|undefined), - * expirationDate: (number|undefined), - * storeId: (string|undefined) - * }} - */ -chrome.cookies.CookieSetDetails; - - -/** - * @param {!chrome.cookies.CookieSetDetails} details - * @param {function(Cookie): void=} opt_callback If setting failed for any - * reason, the parameter will be "null", and "chrome.runtime.lastError" will - * be set. - * @return {undefined} - */ -chrome.cookies.set = function(details, opt_callback) {}; - - -/** - * @see https://developer.chrome.com/extensions/cookies.html#event-onChanged - * @type {!ChromeEvent} - */ -chrome.cookies.onChanged; - - - -/** @constructor */ -function CookieChangeInfo() {} - - -/** @type {boolean} */ -CookieChangeInfo.prototype.removed; - - -/** @type {Cookie} */ -CookieChangeInfo.prototype.cookie; - - -/** @type {string} */ -CookieChangeInfo.prototype.cause; - - -/** - * @const - * @see https://developer.chrome.com/extensions/management - */ -chrome.management = {}; - - -/** - * @typedef {?{ - * showConfirmDialog: (boolean|undefined) - * }} - */ -chrome.management.InstallOptions; - - -/** - * @param {function(!Array): void=} opt_callback Optional - * callback function. - * @return {undefined} - */ -chrome.management.getAll = function(opt_callback) {}; - - -/** - * @param {string} id - * @param {function(!ExtensionInfo): void=} opt_callback Optional callback - * function. - * @return {undefined} - */ -chrome.management.get = function(id, opt_callback) {}; - - -/** - * @param {function(!ExtensionInfo): void=} opt_callback Optional - * callback function - * @return {undefined} - */ -chrome.management.getSelf = function(opt_callback) {}; - - -/** - * @param {string} id The id of an already installed extension. - * @param {function(!Array)=} opt_callback Optional callback function. - * @return {undefined} - */ -chrome.management.getPermissionWarningsById = function(id, opt_callback) {}; - - -/** - * @param {string} manifestStr Extension's manifest JSON string. - * @param {function(!Array)=} opt_callback Optional callback function. - * @return {undefined} - */ -chrome.management.getPermissionWarningsByManifest = function( - manifestStr, opt_callback) {}; - - -/** - * @param {string} id The id of an already installed extension. - * @param {boolean} enabled Whether this item should be enabled. - * @param {function(): void=} opt_callback Optional callback function. - * @return {undefined} - */ -chrome.management.setEnabled = function(id, enabled, opt_callback) {}; - - -/** - * @param {string} id The id of an already installed extension. - * @param {(!chrome.management.InstallOptions|function(): void)=} - * opt_optionsOrCallback An optional uninstall options object or an optional - * callback function. - * @param {function(): void=} opt_callback Optional callback function. - * @return {undefined} - */ -chrome.management.uninstall = function( - id, opt_optionsOrCallback, opt_callback) {}; - - -/** - * @param {(!chrome.management.InstallOptions|function(): void)=} - * opt_optionsOrCallback An optional uninstall options object or an optional - * callback function. - * @param {function(): void=} opt_callback An optional callback function. - * @return {undefined} - */ -chrome.management.uninstallSelf = function( - opt_optionsOrCallback, opt_callback) {}; - - -/** - * @param {string} id The id of an already installed extension. - * @param {function(): void=} opt_callback Optional callback function. - * @return {undefined} - */ -chrome.management.launchApp = function(id, opt_callback) {}; - - -/** - * @param {string} id The id of an already installed extension. - * @param {function(): void=} opt_callback Optional callback function. - * @return {undefined} - */ -chrome.management.createAppShortcut = function(id, opt_callback) {}; - - -/** - * @param {string} id The id of an already installed extension. - * @param {string} launchType The LaunchType enum value to set. Make sure this - * value is in ExtensionInfo.availableLaunchTypes because the available - * launch types vary on different platforms and configurations. - * @param {function(): void=} opt_callback Optional callback function. - * @return {undefined} - */ -chrome.management.setLaunchType = function(id, launchType, opt_callback) {}; - - -/** - * @param {string} url The URL of a web page. The scheme of the URL can only be - * "http" or "https". - * @param {string} title The title of the generated app. - * @param {function(!ExtensionInfo): void=} opt_callback Optional callback - * function. - * @return {undefined} - */ -chrome.management.generateAppForLink = function(url, title, opt_callback) {}; - - -/** - * @param {function():void=} callback - * @return {undefined} - */ -chrome.management.installReplacementWebApp = function(callback) {}; - -/** - * Event whose listeners take an ExtensionInfo parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -function ChromeExtensionInfoEvent() {}; - - -/** @type {!ChromeExtensionInfoEvent} */ -chrome.management.onInstalled; - - -/** @type {!ChromeStringEvent} */ -chrome.management.onUninstalled; - - -/** @type {!ChromeExtensionInfoEvent} */ -chrome.management.onEnabled; - - -/** @type {!ChromeExtensionInfoEvent} */ -chrome.management.onDisabled; - - -/** - * @const - * @see https://developer.chrome.com/extensions/idle.html - */ -chrome.idle = {}; - - -/** - * @param {number} thresholdSeconds Threshold in seconds, used to determine - * when a machine is in the idle state. - * @param {function(string): void} callback Callback to handle the state. - * @return {undefined} - */ -chrome.idle.queryState = function(thresholdSeconds, callback) {}; - - -/** - * @param {number} intervalInSeconds Threshold, in seconds, used to determine - * when the system is in an idle state. - * @return {undefined} - */ -chrome.idle.setDetectionInterval = function(intervalInSeconds) {}; - -/** - * @param {function(number): void} callback Callback to receive the delay - * @return {undefined} - */ -chrome.idle.getAutoLockDelay = function(callback) {}; - -/** @type {!ChromeEvent} */ -chrome.idle.onStateChanged; - - -/** - * @const - * @see https://developer.chrome.com/extensions/contentSettings.html - */ -chrome.contentSettings = {}; - - -/** @type {!ContentSetting} */ -chrome.contentSettings.cookies; - - -/** @type {!ContentSetting} */ -chrome.contentSettings.images; - - -/** @type {!ContentSetting} */ -chrome.contentSettings.javascript; - - -/** @type {!ContentSetting} */ -chrome.contentSettings.plugins; - - -/** @type {!ContentSetting} */ -chrome.contentSettings.popups; - - -/** @type {!ContentSetting} */ -chrome.contentSettings.notifications; - - -/** - * @const - * @see https://developer.chrome.com/extensions/fileBrowserHandler - */ -chrome.fileBrowserHandler = {}; - - -/** - * @typedef {?{ - * suggestedName: string, - * allowedFileExtensions: (!Array|undefined) - * }} - */ -chrome.fileBrowserHandler.SelectFileSelectionParams; - - -/** - * Prompts user to select file path under which file should be saved. - * @see https://developer.chrome.com/extensions/fileBrowserHandler#method-selectFile - * @param {!chrome.fileBrowserHandler.SelectFileSelectionParams} selectionParams - * Parameters that will be used while selecting the file. - * @param {function(!Object)} callback Function called upon completion. - * @return {undefined} - */ -chrome.fileBrowserHandler.selectFile = function(selectionParams, callback) {}; - - -/** - * @interface - * @extends {ChromeBaseEvent} - * @see https://developer.chrome.com/extensions/fileBrowserHandler#event-onExecute - */ -chrome.fileBrowserHandler.ExecuteEvent = function() {}; - - -/** - * Fired when file system action is executed from ChromeOS file browser. - * @see https://developer.chrome.com/extensions/fileBrowserHandler#event-onExecute - * @type {!chrome.fileBrowserHandler.ExecuteEvent} - */ -chrome.fileBrowserHandler.onExecute; - - -/** - * @const - * @see https://developer.chrome.com/extensions/gcm - */ -chrome.gcm = {}; - - -/** - * @see https://developer.chrome.com/extensions/gcm#property-MAX_MESSAGE_SIZE - * @type {number} - */ -chrome.gcm.MAX_MESSAGE_SIZE; - - -/** - * Registers the application with GCM. The registration ID will be returned by - * the callback. If register is called again with the same list of senderIds, - * the same registration ID will be returned. - * @see https://developer.chrome.com/extensions/gcm#method-register - * @param {!Array} senderIds A list of server IDs that are allowed to - * send messages to the application. - * @param {function(string): void} callback Function called when - * registration completes with registration ID as argument. - * @return {undefined} - */ -chrome.gcm.register = function(senderIds, callback) {}; - - -/** - * Unregisters the application from GCM. - * @see https://developer.chrome.com/extensions/gcm#method-unregister - * @param {function(): void} callback Called when unregistration is done. - * @return {undefined} - */ -chrome.gcm.unregister = function(callback) {}; - - -/** - * Sends an upstream message using GCM. - * @see https://developer.chrome.com/extensions/gcm#method-send - * @param {!chrome.gcm.Message} message Message to be sent. - * @param {function(string): void} callback Called with message ID. - * @return {undefined} - */ -chrome.gcm.send = function(message, callback) {}; - - -/** - * Outgoing message. - * @typedef {?{ - * destinationId: string, - * messageId: string, - * timeToLive: (number|undefined), - * data: !Object - * }} - */ -chrome.gcm.Message; - - -/** - * An event, fired when a message is received through GCM. - * @see https://developer.chrome.com/extensions/gcm#event-onMessage - * @type {!chrome.gcm.OnMessageEvent} - */ -chrome.gcm.onMessage; - - -/** - * An event, fired when GCM server had to delete messages to the application - * from its queue in order to manage its size. - * @see https://developer.chrome.com/extensions/gcm#event-onMessagesDeleted - * @type {!ChromeEvent} - */ -chrome.gcm.onMessagesDeleted; - - -/** - * An event indicating problems with sending messages. - * @see https://developer.chrome.com/extensions/gcm#event-onSendError - * @type {!chrome.gcm.OnSendErrorEvent} - */ -chrome.gcm.onSendError; - - - -/** - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.gcm.OnMessageEvent = function() {}; - - -/** - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.gcm.OnSendErrorEvent = function() {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/history.html - */ -chrome.history = {}; - - -/** - * @param {Object} details Object with a 'url' key. - * @return {undefined} - */ -chrome.history.addUrl = function(details) {}; - - -/** - * @param {function(): void} callback Callback function. - * @return {undefined} - */ -chrome.history.deleteAll = function(callback) {}; - - -/** - * @param {Object} range Object with 'startTime' - * and 'endTime' keys. - * @param {function(): void} callback Callback function. - * @return {undefined} - */ -chrome.history.deleteRange = function(range, callback) {}; - - -/** - * @param {Object} details Object with a 'url' key. - * @return {undefined} - */ -chrome.history.deleteUrl = function(details) {}; - - -/** - * @param {Object} details Object with a 'url' key. - * @param {function(!Array): void} callback Callback function. - * @return {!Array} - */ -chrome.history.getVisits = function(details, callback) {}; - - -/** - * @param {Object} query Object with a 'text' (string) - * key and optional 'startTime' (number), 'endTime' (number) and - * 'maxResults' keys. - * @param {function(!Array): void} callback Callback function. - * @return {!Array} - */ -chrome.history.search = function(query, callback) {}; - - -/** @type {!ChromeEvent} */ -chrome.history.onVisitRemoved; - - -/** @type {!ChromeEvent} */ -chrome.history.onVisited; - - -/** - * @const - * @see http://developer.chrome.com/apps/identity.html - */ -chrome.identity = {}; - - -/** @typedef {?{id: string}} */ -chrome.identity.AccountInfo; - - -/** - * @param {function(!Array): void} callback - * @return {undefined} - */ -chrome.identity.getAccounts = function(callback) {}; - - -/** - * @param {(!chrome.identity.TokenDetails|function(string=): void)} - * detailsOrCallback Token options or a callback function if no options are - * specified. - * @param {function(string=): void=} opt_callback A callback function if options - * are specified. - * @return {undefined} - */ -chrome.identity.getAuthToken = function(detailsOrCallback, opt_callback) {}; - - -/** - * @typedef {?{ - * interactive: (boolean|undefined), - * account: (!chrome.identity.AccountInfo|undefined), - * scopes: (!Array|undefined) - * }} - */ -chrome.identity.TokenDetails; - - -/** - * @param {!chrome.identity.InvalidTokenDetails} details - * @param {function(): void=} opt_callback - * @return {undefined} - */ -chrome.identity.removeCachedAuthToken = function(details, opt_callback) {}; - - -/** @typedef {?{token: string}} */ -chrome.identity.InvalidTokenDetails; - - -/** - * @param {!chrome.identity.WebAuthFlowDetails} details - * @param {function(string=): void} callback - * @return {undefined} - */ -chrome.identity.launchWebAuthFlow = function(details, callback) {}; - - -/** @typedef {?{url: string, interactive: (boolean|undefined)}} */ -chrome.identity.WebAuthFlowDetails; - - -/** @typedef {?{id: string, email: string}} */ -chrome.identity.ProfileUserInfo; - -/** - * @enum {string} - * See https://developer.chrome.com/docs/extensions/reference/identity/#type-AccountStatus - */ -chrome.identity.AccountStatus = { - SYNC: '', - ANY: '', -}; - -/** - * See https://developer.chrome.com/docs/extensions/reference/identity/#type-ProfileDetails - * @typedef {{accountStatus: (!chrome.identity.AccountStatus|undefined)}} - */ -chrome.identity.ProfileDetails; - -/** - * @param {!chrome.identity.ProfileDetails|function(!chrome.identity.ProfileUserInfo):void} accountStatusOrCallback - * Either the accountStatus of the primary profile account or the callback - * @param {function(!chrome.identity.ProfileUserInfo):void=} opt_callback if - * the accountStatus is provided - * @return {undefined} - */ -chrome.identity.getProfileUserInfo = function(accountStatusOrCallback, opt_callback) {}; - - - -/** - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.identity.OnSignInChangedEvent = function() {}; - - -/** @type {!chrome.identity.OnSignInChangedEvent} */ -chrome.identity.onSignInChanged; - - -/** - * @param {string=} opt_path - * @return {string} - */ -chrome.identity.getRedirectURL = function(opt_path) {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/input.ime.html - */ -chrome.input = {}; - - -/** @const */ -chrome.input.ime = {}; - - -/** - * @typedef {?{ - * left: number, - * top: number, - * width: number, - * height: number - * }} - * @see https://developer.chrome.com/extensions/input_ime#type-CreateWindowOptions - */ -chrome.input.ime.Bounds; - - -/** - * @typedef {?{ - * windowType: chrome.input.ime.WindowType, - * url: (string|undefined), - * bounds: (chrome.input.ime.Bounds|undefined) - * }} - * @see https://developer.chrome.com/extensions/input_ime#type-CreateWindowOptions - */ -chrome.input.ime.CreateWindowOptions; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/system.display#type-MirrorMode - */ -chrome.input.ime.WindowType = { - NORMAL: '', - FOLLOW_CURSOR: '', -}; - - -/** - * The OnKeyEvent event takes an extra argument. - * - * The addListener() method for this class takes more than one argument, so it - * isn't possible to just extend ChromeBaseEvent here. - * @interface - * @extends {ChromeBaseEventNoListeners} - */ -function ChromeInputImeOnKeyEventEvent() {} - - -/** - * @param {function(string, !ChromeKeyboardEvent): (boolean|undefined)} callback - * callback. - * @param {Array=} opt_extraInfoSpec Array of extra information. - * @return {undefined} - */ -ChromeInputImeOnKeyEventEvent.prototype.addListener = function( - callback, opt_extraInfoSpec) {}; - - -/** - * @param {function(string, !ChromeKeyboardEvent): (boolean|undefined)} callback - * callback. - * @return {undefined} - */ -ChromeInputImeOnKeyEventEvent.prototype.removeListener = function(callback) {}; - - -/** - * @param {function(string, !ChromeKeyboardEvent): (boolean|undefined)} callback - * callback. - * @return {boolean} - */ -ChromeInputImeOnKeyEventEvent.prototype.hasListener = function(callback) {}; - - -/** - * @return {boolean} - */ -ChromeInputImeOnKeyEventEvent.prototype.hasListeners = function() {}; - - -/** - * @param {function(boolean): void=} callback Callback function. - * @return {undefined} - */ -chrome.input.ime.activate = function(callback) {}; - - -/** - * @param {!Object} parameters An object with a - * 'contextID' (number) key. - * @param {function(boolean): void=} callback Callback function. - * @return {undefined} - */ -chrome.input.ime.clearComposition = function(parameters, callback) {}; - - -/** - * @param {!Object} parameters An object with - * 'contextID' (number) and 'text' (string) keys. - * @param {function(boolean): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.input.ime.commitText = function(parameters, opt_callback) {}; - - -/** - * @param {!chrome.input.ime.CreateWindowOptions} options Options of the created - * IME window. - * @param {function(Window): void=} callback Callback function. - * @return {undefined} - */ -chrome.input.ime.createWindow = function(options, callback) {}; - - -/** - * @param {function(boolean): void} callback Callback function. - * @return {undefined} - */ -chrome.input.ime.deactivate = function(callback) {}; - - -/** - * @param {!Object} parameters An object with - * 'contextID' (number) and 'text' (string) keys. - * @param {function(boolean): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.input.ime.deleteSurroundingText = function(parameters, opt_callback) {}; - - -/** - * @return {undefined} - */ -chrome.input.ime.hideInputView = function() {}; - - -/** - * @param {function(boolean): void=} callback Callback function. - * @return {undefined} - */ -chrome.input.ime.hideWindow = function(callback) {}; - - -/** - * @param {!Object>} - * parameters An object with 'contextID' (number) and 'keyData' - * (Array) keys. - * @param {function(boolean): void=} callback Callback function. - * @return {undefined} - */ -chrome.input.ime.sendKeyEvents = function(parameters, callback) {}; - - -/** - * @param {!Object)>} - * parameters An object with 'engineID' (string) and 'properties' - * (Object) keys. - * @param {function(boolean): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.input.ime.setCandidateWindowProperties = function( - parameters, opt_callback) {}; - - -/** - * @param {!Object)>} - * parameters An object with 'contextID' (number) and 'candidates' - * (array of object) keys. - * @param {function(boolean): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.input.ime.setCandidates = function(parameters, opt_callback) {}; - - -/** - * @param {!Object)>} - * parameters An object with 'contextID' (number), 'text' (string), - * 'selectionStart (number), 'selectionEnd' (number), 'cursor' (number), - * and 'segments' (array of object) keys. - * @param {function(boolean): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.input.ime.setComposition = function(parameters, opt_callback) {}; - - -/** - * @param {!Object} parameters An object with - * 'contextID' (number) and 'candidateID' (number) keys. - * @param {function(boolean): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.input.ime.setCursorPosition = function(parameters, opt_callback) {}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/input.ime#type-AssistiveWindowType - */ -chrome.input.ime.AssistiveWindowType = { - UNDO: '', -}; - - -/** - * Properties of the assistive window. - * @typedef {{ - * type: !chrome.input.ime.AssistiveWindowType, - * visible: boolean - * }} - * @see https://developer.chrome.com/extensions/input.ime#type-AssistiveWindowProperties - */ -chrome.input.ime.AssistiveWindowProperties; - - -/** - * Shows/Hides an assistive window with the given properties. - * @param {{ - * contextID: number, - * properties: !chrome.input.ime.AssistiveWindowProperties - * }} parameters - * @param {function(boolean): void=} callback Called when the operation - * completes. - * @see https://developer.chrome.com/extensions/input.ime#method-setAssistiveWindowProperties - */ -chrome.input.ime.setAssistiveWindowProperties = function( - parameters, callback) {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/input.ime#type-AssistiveWindowButton - */ -chrome.input.ime.AssistiveWindowButton = { - UNDO: '', - ADD_TO_DICTIONARY: '', -}; - - -/** - * This event is sent when a button in an assistive window is clicked. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/input.ime#event-onAssistiveWindowButtonClicked - */ -chrome.input.ime.onAssistiveWindowButtonClicked; - - -/** - * @param {!Object>)>} - * parameters An object with 'engineID' (string) and 'items' - * (array of object) keys. - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.input.ime.setMenuItems = function(parameters, opt_callback) {}; - - -/** - * @param {function(boolean): void=} callback Callback function. - * @return {undefined} - */ -chrome.input.ime.showWindow = function(callback) {}; - - -/** - * @param {!Object>)>} - * parameters An object with 'engineID' (string) and 'items' - * (array of object) keys. - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.input.ime.updateMenuItems = function(parameters, opt_callback) {}; - - -/** - * @param {string} requestId Request id of the event that was handled. This - * should come from keyEvent.requestId. - * @param {boolean} response True if the keystroke was handled, false if not. - * @return {undefined} - */ -chrome.input.ime.keyEventHandled = function(requestId, response) {}; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onActivate; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onBlur; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onCandidateClicked; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onDeactivated; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onFocus; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onInputContextUpdate; - - -/** @type {!ChromeInputImeOnKeyEventEvent} */ -chrome.input.ime.onKeyEvent; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onMenuItemActivated; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onReset; - - -/** @type {!ChromeEvent} */ -chrome.input.ime.onSurroundingTextChanged; - - -/** - * namespace - * @see http://developer.chrome.com/apps/mediaGalleries - * @const - */ -chrome.mediaGalleries = {}; - - -/** - * @param {{interactive: (string|undefined)}|function(!Array)} - * detailsOrCallback A details object for whether the request should be - * interactive if permissions haven't been granted yet or the callback. - * @param {function(!Array)=} opt_callback A success callback if - * no details were supplied as arg1. - * @return {undefined} - */ -chrome.mediaGalleries.getMediaFileSystems = function( - detailsOrCallback, opt_callback) {}; - - -/** - * @param {function(!Array, string)} callback Callback function. - * @return {undefined} - */ -chrome.mediaGalleries.addUserSelectedFolder = function(callback) {}; - - -/** - * @param {string} galleryId ID of the media gallery. - * @param {function()=} opt_callback Optional callback function. - * @return {undefined} - */ -chrome.mediaGalleries.dropPermissionForMediaFileSystem = function( - galleryId, opt_callback) {}; - - -chrome.mediaGalleries.startMediaScan = function() {}; - - -chrome.mediaGalleries.cancelMediaScan = function() {}; - - -/** - * @param {function(!Array)} callback Callback function. - * @return {undefined} - */ -chrome.mediaGalleries.addScanResults = function(callback) {}; - - -/** - * @typedef {{ - * name: string, - * galleryId: string, - * deviceId: (string|undefined), - * isRemovable: boolean, - * isMediaDevice: boolean, - * isAvailable: boolean - * }} - */ -chrome.mediaGalleries.MediaFileSystemMetadata; - - -/** - * @param {!FileSystem} mediaFileSystem The file system to get metadata for. - * @return {!chrome.mediaGalleries.MediaFileSystemMetadata} - */ -chrome.mediaGalleries.getMediaFileSystemMetadata = function(mediaFileSystem) {}; - - -/** - * @param {function(!Array)} - * callback Callback function. - * @return {undefined} - */ -chrome.mediaGalleries.getAllMediaFileSystemMetadata = function(callback) {}; - - -/** - * @typedef {{ - * mimeType: string, - * height: (number|undefined), - * width: (number|undefined), - * xResolution: (number|undefined), - * yResolution: (number|undefined), - * duration: (number|undefined), - * rotation: (number|undefined), - * cameraMake: (string|undefined), - * cameraModel: (string|undefined), - * exposureTimeSeconds: (number|undefined), - * flashFired: (boolean|undefined), - * fNumber: (number|undefined), - * focalLengthMm: (number|undefined), - * isoEquivalent: (number|undefined), - * album: (string|undefined), - * artist: (string|undefined), - * comment: (string|undefined), - * copyright: (string|undefined), - * disc: (number|undefined), - * genre: (string|undefined), - * language: (string|undefined), - * title: (string|undefined), - * track: (number|undefined), - * rawTags: !Array, - * attachedImages: !Array - * }} - */ -chrome.mediaGalleries.MetaData; - - -/** @const */ -chrome.mediaGalleries.metadata = {}; - - -/** @constructor */ -chrome.mediaGalleries.metadata.RawTag = function() {}; - - -/** @type {string} */ -chrome.mediaGalleries.metadata.RawTag.prototype.type; - - -/** @type {!Object} */ -chrome.mediaGalleries.metadata.RawTag.prototype.tags; - - -/** - * @param {!Blob} mediaFile The media file for which to get metadata. - * @param {{metadataType: (string|undefined)}| - * function(!chrome.mediaGalleries.MetaData)} optionsOrCallback The options - * for the metadata to retrieve or the callback to invoke with the metadata. - * The metadataType should either be 'all' or 'mimeTypeOnly'. Defaults to - * 'all' if the metadataType is omitted. - * @param {function(!chrome.mediaGalleries.MetaData)=} opt_callback If options - * were passed as arg2, the callback to invoke with the metadata. - * @return {undefined} - */ -chrome.mediaGalleries.getMetadata = function( - mediaFile, optionsOrCallback, opt_callback) {}; - - -/** - * @typedef {function({galleryId: string, success: boolean}): void} - */ -chrome.mediaGalleries.AddGalleryWatchCallback; - - -/** - * @param {string} galleryId The media gallery's ID. - * @param {!chrome.mediaGalleries.AddGalleryWatchCallback} callback Fired with - * success or failure result. - * @return {undefined} - */ -chrome.mediaGalleries.addGalleryWatch = function(galleryId, callback) {}; - - -/** - * @param {string} galleryId The media gallery's ID. - * @return {undefined} - */ -chrome.mediaGalleries.removeGalleryWatch = function(galleryId) {}; - - -/** - * @param {function(!Array): void} callback Callback function notifies - * which galleries are being watched. - * @return {undefined} - */ -chrome.mediaGalleries.getAllGalleryWatch = function(callback) {}; - - -chrome.mediaGalleries.removeAllGalleryWatch = function() {}; - - - -/** - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.mediaGalleries.GalleryChangeEvent = function() {}; - - -/** - * @typedef {function({type: string, galleryId: string}): void} - */ -chrome.mediaGalleries.GalleryChangeCallback; - - -/** - * @type {!chrome.mediaGalleries.GalleryChangeEvent} - */ -chrome.mediaGalleries.onGalleryChanged; - - -/** - * @typedef {{ - * type: string, - * galleryCount: (number|undefined), - * audioCount: (number|undefined), - * imageCount: (number|undefined), - * videoCount: (number|undefined) - * }} - */ -chrome.mediaGalleries.OnScanProgressDetails; - - - -/** - * Event whose listeners take a chrome.mediaGalleries.OnScanProgressDetails - * parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.mediaGalleries.ScanProgressEvent = function() {}; - - -/** @type {!chrome.mediaGalleries.ScanProgressEvent} */ -chrome.mediaGalleries.onScanProgress; - - -/** - * @const - * @see https://developer.chrome.com/extensions/pageCapture.html - */ -chrome.pageCapture = {}; - - -/** - * @param {Object} details Object with a 'tabId' (number) key. - * @param {function(Blob=): void} callback Callback function. - * @return {undefined} - */ -chrome.pageCapture.saveAsMHTML = function(details, callback) {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/permissions.html - */ -chrome.permissions = {}; - - -/** - * @typedef {{ - * permissions: (Array|undefined), - * origins: (Array|undefined) - * }} - * @see http://developer.chrome.com/extensions/permissions.html#type-Permissions - */ -chrome.permissions.Permissions; - - -/** - * @param {!chrome.permissions.Permissions} permissions - * @param {function(boolean): void} callback Callback function. - * @return {undefined} - */ -chrome.permissions.contains = function(permissions, callback) {}; - - -/** - * @param {function(!chrome.permissions.Permissions): void} callback - * Callback function. - * @return {undefined} - */ -chrome.permissions.getAll = function(callback) {}; - - -/** - * @param {!chrome.permissions.Permissions} permissions - * @param {function(boolean): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.permissions.remove = function(permissions, opt_callback) {}; - - -/** - * @param {!chrome.permissions.Permissions} permissions - * @param {function(boolean): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.permissions.request = function(permissions, opt_callback) {}; - - -/** @type {!ChromeEvent} */ -chrome.permissions.onAdded; - - -/** @type {!ChromeEvent} */ -chrome.permissions.onRemoved; - - -/** - * @const - * @see https://developer.chrome.com/extensions/platformKeys - */ -chrome.platformKeys = {}; - - -/** - * @see https://developer.chrome.com/extensions/platformKeys#type-Match - * @constructor - */ -chrome.platformKeys.Match = function() {}; - - -/** @type {!ArrayBuffer} */ -chrome.platformKeys.Match.prototype.certificate; - - -/** @type {!Object} */ -chrome.platformKeys.Match.prototype.keyAlgorithm; - - -/** - * @typedef {?{ - * certificateTypes: !Array, - * certificateAuthorities: !Array - * }} - */ -chrome.platformKeys.SelectCertificateDetailRequest; - - -/** - * @typedef {?{ - * request: !chrome.platformKeys.SelectCertificateDetailRequest, - * clientCerts: (!Array|undefined), - * interactive: boolean - * }} - * - * @see https://developer.chrome.com/extensions/platformKeys#method-selectClientCertificates - */ -chrome.platformKeys.SelectCertificateDetails; - - -/** - * @param {!chrome.platformKeys.SelectCertificateDetails} details - * @param {!function(!Array)} callback - */ -chrome.platformKeys.selectClientCertificates = function(details, callback) {}; - - -/** - * @param {!ArrayBuffer} certificate - * @param {!Object} parameters - * @param {!function(!Object, ?Object)} callback - */ -chrome.platformKeys.getKeyPair = function(certificate, parameters, callback) {}; - - -/** - * @return {!Object} - */ -chrome.platformKeys.subtleCrypto = function() {}; - - -/** - * @typedef {?{ - * serverCertificateChain: !Array, - * hostname: string - * }} - * - * @see https://developer.chrome.com/extensions/platformKeys#method-verifyTLSServerCertificate - */ -chrome.platformKeys.VerifyServerCertificateDetails; - - -/** - * @param {!chrome.platformKeys.VerifyServerCertificateDetails} details - * @param {!function(!Object)} callback - */ -chrome.platformKeys.verifyTLSServerCertificate = function(details, callback) {}; - - -/** - * @const - * @see http://developer.chrome.com/dev/extensions/power.html - */ -chrome.power = {}; - - -/** - * @param {string} level A string describing the degree to which power - * management should be disabled, should be either "system" or "display". - * @return {undefined} - */ -chrome.power.requestKeepAwake = function(level) {}; - - -/** - * Releases a request previously made via requestKeepAwake(). - * @return {undefined} - */ -chrome.power.releaseKeepAwake = function() {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/privacy.html - */ -chrome.privacy = {}; - - -/** @type {!Object} */ -chrome.privacy.network; - - -/** @type {!Object} */ -chrome.privacy.services; - - -/** @type {!Object} */ -chrome.privacy.websites; - - -/** - * @const - * @see https://developer.chrome.com/extensions/proxy.html - */ -chrome.proxy = {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/proxy#property-settings - */ -chrome.proxy.settings = {}; - - -/** - * @typedef {?{ - * incognito: (boolean|undefined), - * }} - */ -chrome.proxy.settings.GetParameter; - - -/** - * @typedef {{ - * value: *, - * levelOfControl: string, - * incognitoSpecific: (boolean|undefined), - * }} - */ -chrome.proxy.settings.GetResponse; - - -/** - * @param {!chrome.proxy.settings.GetParameter} details - * @param {(function(!chrome.proxy.settings.GetResponse): void)=} callback - */ -chrome.proxy.settings.get = function(details, callback) {}; - - -/** - * @param {{ - * value: *, - * scope: (string|undefined), - * }} details - * @param {(function(): void)=} callback - */ -chrome.proxy.settings.set = function(details, callback) {}; - - -/** - * @param {{ - * scope: (string|undefined), - * }} details - * @param {(function(): void)=} callback - */ -chrome.proxy.settings.clear = function(details, callback) {}; - - -/** @type {!ChromeEvent} */ -chrome.proxy.onProxyError; - - -/** - * @const - * @see http://developer.chrome.com/apps/socket.html - */ -chrome.socket = {}; - - - -/** - * @constructor - */ -chrome.socket.CreateInfo = function() {}; - - -/** @type {number} */ -chrome.socket.CreateInfo.prototype.socketId; - - - -/** - * @constructor - */ -chrome.socket.ReadInfo = function() {}; - - -/** @type {number} */ -chrome.socket.ReadInfo.prototype.resultCode; - - -/** @type {!ArrayBuffer} */ -chrome.socket.ReadInfo.prototype.data; - - - -/** - * @constructor - */ -chrome.socket.WriteInfo = function() {}; - - -/** @type {number} */ -chrome.socket.WriteInfo.prototype.bytesWritten; - - - -/** - * @constructor - */ -chrome.socket.RecvFromInfo = function() {}; - - -/** @type {number} */ -chrome.socket.RecvFromInfo.prototype.resultCode; - - -/** @type {!ArrayBuffer} */ -chrome.socket.RecvFromInfo.prototype.data; - - -/** @type {string} */ -chrome.socket.RecvFromInfo.prototype.address; - - -/** @type {number} */ -chrome.socket.RecvFromInfo.prototype.port; - - - -/** - * @constructor - */ -chrome.socket.AcceptInfo = function() {}; - - -/** @type {number} */ -chrome.socket.AcceptInfo.prototype.resultCode; - - -/** @type {(number|undefined)} */ -chrome.socket.AcceptInfo.prototype.socketId; - - - -/** - * @constructor - */ -chrome.socket.SocketInfo = function() {}; - - -/** @type {string} */ -chrome.socket.SocketInfo.prototype.socketType; - - -/** @type {boolean} */ -chrome.socket.SocketInfo.prototype.connected; - - -/** @type {(string|undefined)} */ -chrome.socket.SocketInfo.prototype.peerAddress; - - -/** @type {(number|undefined)} */ -chrome.socket.SocketInfo.prototype.peerPort; - - -/** @type {(string|undefined)} */ -chrome.socket.SocketInfo.prototype.localAddress; - - -/** @type {(number|undefined)} */ -chrome.socket.SocketInfo.prototype.localPort; - - - -/** - * @constructor - */ -chrome.socket.NetworkAdapterInfo = function() {}; - - -/** @type {string} */ -chrome.socket.NetworkAdapterInfo.prototype.name; - - -/** @type {string} */ -chrome.socket.NetworkAdapterInfo.prototype.address; - - -/** - * @param {string} type The type of socket to create. Must be 'tcp' or 'udp'. - * @param {(Object|function(!chrome.socket.CreateInfo))} optionsOrCallback The - * socket options or callback. - * @param {function(!chrome.socket.CreateInfo)=} opt_callback Called when the - * socket has been created. - * @return {undefined} - */ -chrome.socket.create = function(type, optionsOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId The id of the socket to destroy. - * @return {undefined} - */ -chrome.socket.destroy = function(socketId) {}; - - -/** - * @param {number} socketId The id of the socket. - * @param {string} hostname The hostname or IP address of the remote machine. - * @param {number} port The port of the remote machine. - * @param {function(number)} callback Called when the connection attempt is - * complete. - * @return {undefined} - */ -chrome.socket.connect = function(socketId, hostname, port, callback) {}; - - -/** - * @param {number} socketId The id of the socket. - * @param {string} address The address of the local machine. - * @param {number} port The port of the local machine. - * @param {function(number)} callback Called when the bind attempt is complete. - * @return {undefined} - */ -chrome.socket.bind = function(socketId, address, port, callback) {}; - - -/** - * @param {number} socketId The id of the socket to disconnect. - * @return {undefined} - */ -chrome.socket.disconnect = function(socketId) {}; - - -/** - * @param {number} socketId The id of the socket to read from. - * @param {(number|function(!chrome.socket.ReadInfo))} bufferSizeOrCallback The - * read buffer size or the callback. - * @param {function(!chrome.socket.ReadInfo)=} opt_callback Called with data - * that was available to be read without blocking. - * @return {undefined} - */ -chrome.socket.read = function(socketId, bufferSizeOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId The id of the socket to write to. - * @param {!ArrayBuffer} data The data to write. - * @param {function(!chrome.socket.WriteInfo)} callback Called when the write - * operation completes without blocking or an error occurs. - * @return {undefined} - */ -chrome.socket.write = function(socketId, data, callback) {}; - - -/** - * @param {number} socketId The id of the socket to read from. - * @param {(number|function(!chrome.socket.RecvFromInfo))} bufferSizeOrCallback - * The read buffer size or the callback. - * @param {function(!chrome.socket.RecvFromInfo)=} opt_callback Called with data - * that was available to be read without blocking. - * @return {undefined} - */ -chrome.socket.recvFrom = function( - socketId, bufferSizeOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId The id of the socket to write to. - * @param {!ArrayBuffer} data The data to write. - * @param {string} address The address of the remote machine. - * @param {number} port The port of the remote machine. - * @param {function(!chrome.socket.WriteInfo)} callback Called when the write - * operation completes without blocking or an error occurs. - * @return {undefined} - */ -chrome.socket.sendTo = function(socketId, data, address, port, callback) {}; - - -/** - * @param {number} socketId The id of the socket to listen on. - * @param {string} address The address of the local machine to listen on. Use - * '0' to listen on all addresses. - * @param {number} port The port of the local machine. - * @param {(number|function(number))} backlogOrCallback The length of the - * socket's listen queue or the callback. - * @param {function(number)=} opt_callback Called when the listen operation - * completes. - * @return {undefined} - */ -chrome.socket.listen = function( - socketId, address, port, backlogOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId The id of the socket to accept a connection on. - * @param {function(!chrome.socket.AcceptInfo)} callback Called when a new - * socket is accepted. - * @return {undefined} - */ -chrome.socket.accept = function(socketId, callback) {}; - - -/** - * @param {number} socketId The id of the socket to listen on. - * @param {boolean} enable If true, enable keep-alive functionality. - * @param {(number|function(boolean))} delayOrCallback The delay in seconds - * between the last packet received and the first keepalive probe (default - * is 0) or the callback - * @param {function(boolean)=} opt_callback Called when the setKeepAlive attempt - * is complete. - * @return {undefined} - */ -chrome.socket.setKeepAlive = function( - socketId, enable, delayOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId The id of the socket to listen on. - * @param {boolean} noDelay If true, disables Nagle's algorithm. - * @param {function(boolean)} callback Called when the setNoDelay attempt is - * complete. - * @return {undefined} - */ -chrome.socket.setNoDelay = function(socketId, noDelay, callback) {}; - - -/** - * @param {number} socketId The id of the socket. - * @param {function(!chrome.socket.SocketInfo)} callback Called when the state - * is available. - * @return {undefined} - */ -chrome.socket.getInfo = function(socketId, callback) {}; - - -/** - * @param {function(!Array)} callback Called - * when local adapter information is available. - * @return {undefined} - */ -chrome.socket.getNetworkList = function(callback) {}; - - -/** - * @param {number} socketId The id of the socket. - * @param {string} address The group address to join. Domain names are not - * supported. - * @param {function(number)} callback Called when the join operation is done. - * @return {undefined} - */ -chrome.socket.joinGroup = function(socketId, address, callback) {}; - - -/** - * @param {number} socketId The id of the socket. - * @param {string} address The group address to leave. Domain names are not - * supported. - * @param {function(number)} callback Called when the leave operation is done. - * @return {undefined} - */ -chrome.socket.leaveGroup = function(socketId, address, callback) {}; - - -/** - * @param {number} socketId The id of the socket. - * @param {number} ttl The time-to-live value. - * @param {function(number)} callback Called when the configuration operation is - * done. - * @return {undefined} - */ -chrome.socket.setMulticastTimeToLive = function(socketId, ttl, callback) {}; - - -/** - * @param {number} socketId The id of the socket. - * @param {boolean} enabled True to enable loopback mode. - * @param {function(number)} callback Called when the configuration operation is - * done. - * @return {undefined} - */ -chrome.socket.setMulticastLoopbackMode = function( - socketId, enabled, callback) {}; - - -/** - * @param {number} socketId The id of the socket. - * @param {function(!Array)} callback Called with an array of string - * groups. - * @return {undefined} - */ -chrome.socket.getJoinedGroups = function(socketId, callback) {}; - - -/** - * @const - */ -chrome.sockets = {}; - - -/** - * @const - * @see https://developer.chrome.com/apps/sockets_tcp - */ -chrome.sockets.tcp = {}; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/sockets_tcp#type-SocketInfo - */ -chrome.sockets.tcp.SocketInfo = function() {}; - - -/** @type {number} */ -chrome.sockets.tcp.SocketInfo.prototype.socketId; - - -/** @type {boolean} */ -chrome.sockets.tcp.SocketInfo.prototype.persistent; - - -/** @type {string|undefined} */ -chrome.sockets.tcp.SocketInfo.prototype.name; - - -/** @type {number|undefined} */ -chrome.sockets.tcp.SocketInfo.prototype.bufferSize; - - -/** @type {boolean} */ -chrome.sockets.tcp.SocketInfo.prototype.paused; - - -/** @type {boolean} */ -chrome.sockets.tcp.SocketInfo.prototype.connected; - - -/** @type {string|undefined} */ -chrome.sockets.tcp.SocketInfo.prototype.localAddress; - - -/** @type {number|undefined} */ -chrome.sockets.tcp.SocketInfo.prototype.localPort; - - -/** @type {string|undefined} */ -chrome.sockets.tcp.SocketInfo.prototype.peerAddress; - - -/** @type {number|undefined} */ -chrome.sockets.tcp.SocketInfo.prototype.peerPort; - - -/** - * @typedef {?{ - * persistent: (boolean|undefined), - * name: (string|undefined), - * bufferSize: (number|undefined) - * }} - * @see https://developer.chrome.com/apps/sockets_tcp#type-SocketProperties - */ -chrome.sockets.tcp.SocketProperties; - - -/** - * @typedef {?{ - * min: (string|undefined), - * max: (string|undefined) - * }} - * @see https://developer.chrome.com/apps/sockets_tcp#method-secure - */ -chrome.sockets.tcp.SecurePropertiesTlsVersion; - - -/** - * @typedef {?{ - * tlsVersion: (chrome.sockets.tcp.SecurePropertiesTlsVersion|undefined) - * }} - * @see https://developer.chrome.com/apps/sockets_tcp#method-secure - */ -chrome.sockets.tcp.SecureProperties; - - -/** - * @param {!chrome.sockets.tcp.SocketProperties| - * function(!Object)} propertiesOrCallback - * @param {function(!Object)=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-create - * @return {undefined} - */ -chrome.sockets.tcp.create = function(propertiesOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {!chrome.sockets.tcp.SocketProperties} properties - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-update - * @return {undefined} - */ -chrome.sockets.tcp.update = function(socketId, properties, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {boolean} paused - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-setPaused - * @return {undefined} - */ -chrome.sockets.tcp.setPaused = function(socketId, paused, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {boolean} enable - * @param {(number|function(number))} delayOrCallback - * @param {function(number)=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-setKeepAlive - * @return {undefined} - */ -chrome.sockets.tcp.setKeepAlive = function( - socketId, enable, delayOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {boolean} noDelay - * @param {function(number)} callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-setNoDelay - * @return {undefined} - */ -chrome.sockets.tcp.setNoDelay = function(socketId, noDelay, callback) {}; - - -/** - * @param {number} socketId - * @param {string} peerAddress - * @param {number} peerPort - * @param {function(number)} callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-connect - * @return {undefined} - */ -chrome.sockets.tcp.connect = function( - socketId, peerAddress, peerPort, callback) {}; - - -/** - * @param {number} socketId The id of the socket to disconnect. - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-disconnect - * @return {undefined} - */ -chrome.sockets.tcp.disconnect = function(socketId, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {!chrome.sockets.tcp.SecureProperties|function(number)} - * optionsOrCallback - * @param {function(number)=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-secure - * @return {undefined} - */ -chrome.sockets.tcp.secure = function( - socketId, optionsOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {!ArrayBuffer} data - * @param {function(!Object)} callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-send - * @return {undefined} - */ -chrome.sockets.tcp.send = function(socketId, data, callback) {}; - - -/** - * @param {number} socketId - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-close - * @return {undefined} - */ -chrome.sockets.tcp.close = function(socketId, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {function(!chrome.sockets.tcp.SocketInfo)} callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-getInfo - * @return {undefined} - */ -chrome.sockets.tcp.getInfo = function(socketId, callback) {}; - - -/** - * @param {function(!Array)} callback - * @see https://developer.chrome.com/apps/sockets_tcp#method-getSockets - * @return {undefined} - */ -chrome.sockets.tcp.getSockets = function(callback) {}; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/sockets_tcp#event-onReceive - */ -chrome.sockets.tcp.ReceiveEventData = function() {}; - - -/** @type {number} */ -chrome.sockets.tcp.ReceiveEventData.prototype.socketId; - - -/** @type {!ArrayBuffer} */ -chrome.sockets.tcp.ReceiveEventData.prototype.data; - - - -/** - * Event whose listeners take a ReceiveEventData parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.sockets.tcp.ReceiveEvent = function() {}; - - -/** @type {!chrome.sockets.tcp.ReceiveEvent} */ -chrome.sockets.tcp.onReceive; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/sockets_tcp#event-onReceiveError - */ -chrome.sockets.tcp.ReceiveErrorEventData = function() {}; - - -/** @type {number} */ -chrome.sockets.tcp.ReceiveErrorEventData.prototype.socketId; - - -/** @type {number} */ -chrome.sockets.tcp.ReceiveErrorEventData.prototype.resultCode; - - - -/** - * Event whose listeners take a ReceiveErrorEventData parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.sockets.tcp.ReceiveErrorEvent = function() {}; - - -/** @type {!chrome.sockets.tcp.ReceiveErrorEvent} */ -chrome.sockets.tcp.onReceiveError; - - -/** - * @const - * @see https://developer.chrome.com/apps/sockets_tcpServer - */ -chrome.sockets.tcpServer = {}; - - -/** - * @typedef {?{ - * persistent: (boolean|undefined), - * name: (string|undefined), - * }} - * @see https://developer.chrome.com/apps/sockets_tcpServer#type-SocketProperties - */ -chrome.sockets.tcpServer.SocketProperties; - - -/** - * @constructor - * @see https://developer.chrome.com/apps/sockets_tcpServer#type-SocketInfo - */ -chrome.sockets.tcpServer.SocketInfo = function() {}; - - -/** @type {number} */ -chrome.sockets.tcpServer.SocketInfo.prototype.socketId; - - -/** @type {boolean} */ -chrome.sockets.tcpServer.SocketInfo.prototype.persistent; - - -/** @type {string|undefined} */ -chrome.sockets.tcpServer.SocketInfo.prototype.name; - - -/** @type {boolean} */ -chrome.sockets.tcpServer.SocketInfo.prototype.paused; - - -/** @type {string|undefined} */ -chrome.sockets.tcpServer.SocketInfo.prototype.localAddress; - - -/** @type {number|undefined} */ -chrome.sockets.tcpServer.SocketInfo.prototype.localPort; - - -/** - * @param { - * (!chrome.sockets.tcpServer.SocketProperties|function(!Object)) - * } propertiesOrCallback - * @param {function(!Object)=} opt_callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_tcpServer#method-create - */ -chrome.sockets.tcpServer.create = function( - propertiesOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {!chrome.sockets.tcpServer.SocketProperties} properties - * @param {function(): void=} opt_callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_tcpServer#method-update - */ -chrome.sockets.tcpServer.update = function( - socketId, properties, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {boolean} paused - * @param {function(): void=} opt_callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_tcpServer#method-setPaused - */ -chrome.sockets.tcpServer.setPaused = function( - socketId, paused, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {string} address - * @param {number} port - * @param {number|function(number)} backlogOrCallback - * @param {function(number)=} opt_callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_tcpServer#method-listen - */ -chrome.sockets.tcpServer.listen = function( - socketId, address, port, backlogOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId The id of the socket to disconnect. - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcpServer#method-disconnect - * @return {undefined} - */ -chrome.sockets.tcpServer.disconnect = function(socketId, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {function()=} opt_callback - * @see https://developer.chrome.com/apps/sockets_tcpServer#method-close - * @return {undefined} - */ -chrome.sockets.tcpServer.close = function(socketId, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {function(!chrome.sockets.tcpServer.SocketInfo)} callback - * @see https://developer.chrome.com/apps/sockets_tcpServer#method-getInfo - * @return {undefined} - */ -chrome.sockets.tcpServer.getInfo = function(socketId, callback) {}; - - -/** - * @param {function(!Array)} callback - * @see https://developer.chrome.com/apps/sockets_tcpServerp#method-getSockets - * @return {undefined} - */ -chrome.sockets.tcpServer.getSockets = function(callback) {}; - - -/** - * @constructor - * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAccept - */ -chrome.sockets.tcpServer.AcceptEventData = function() {}; - - -/** @type {number} */ -chrome.sockets.tcpServer.AcceptEventData.prototype.socketId; - - -/** @type {number} */ -chrome.sockets.tcpServer.AcceptEventData.prototype.clientSocketId; - - -/** - * Event whose listeners take a AcceptEventData parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.sockets.tcpServer.AcceptEvent = function() {}; - - -/** @type {!chrome.sockets.tcpServer.AcceptEvent} */ -chrome.sockets.tcpServer.onAccept; - - -/** - * @constructor - * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAcceptError - */ -chrome.sockets.tcpServer.AcceptErrorEventData = function() {}; - - -/** @type {number} */ -chrome.sockets.tcpServer.AcceptErrorEventData.prototype.socketId; - - -/** @type {number} */ -chrome.sockets.tcpServer.AcceptErrorEventData.prototype.resultCode; - - -/** - * Event whose listeners take a AcceptErrorEventData parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.sockets.tcpServer.AcceptErrorEvent = function() {}; - - -/** @type {!chrome.sockets.tcpServer.AcceptErrorEvent} */ -chrome.sockets.tcpServer.onAcceptError; - - -/** - * @see https://developer.chrome.com/apps/sockets_udp - * @const - */ -chrome.sockets.udp = {}; - - -/** - * @typedef {?{ - * persistent: (boolean|undefined), - * name: (string|undefined), - * bufferSize: (number|undefined) - * }} - * @see https://developer.chrome.com/apps/sockets_udp#type-SocketProperties - */ -chrome.sockets.udp.SocketProperties; - - -/** - * @constructor - * @see https://developer.chrome.com/apps/sockets_udp#type-SocketInfo - */ -chrome.sockets.udp.SocketInfo = function() {}; - - -/** @type {number} */ -chrome.sockets.udp.SocketInfo.prototype.socketId; - - -/** @type {boolean} */ -chrome.sockets.udp.SocketInfo.prototype.persistent; - - -/** @type {string|undefined} */ -chrome.sockets.udp.SocketInfo.prototype.name; - - -/** @type {number|undefined} */ -chrome.sockets.udp.SocketInfo.prototype.bufferSize; - - -/** @type {boolean} */ -chrome.sockets.udp.SocketInfo.prototype.paused; - - -/** @type {string|undefined} */ -chrome.sockets.udp.SocketInfo.prototype.localAddress; - - -/** @type {number|undefined} */ -chrome.sockets.udp.SocketInfo.prototype.localPort; - - -/** - * @param { - * (!chrome.sockets.udp.SocketProperties|function(!Object)) - * } propertiesOrCallback - * @param {function(!Object)=} opt_callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-create - */ -chrome.sockets.udp.create = function(propertiesOrCallback, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {!chrome.sockets.udp.SocketProperties} properties - * @param {function(): void=} opt_callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-update - */ -chrome.sockets.udp.update = function(socketId, properties, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {boolean} paused - * @param {function(): void=} opt_callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-setPaused - */ -chrome.sockets.udp.setPaused = function(socketId, paused, opt_callback) {}; - - -/** - * @param {number} socketId - * @param {string} address - * @param {number} port - * @param {function(number): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-bind - */ -chrome.sockets.udp.bind = function(socketId, address, port, callback) {}; - - -/** - * @param {number} socketId - * @param {!ArrayBuffer} data - * @param {string} address - * @param {number} port - * @param {function(!Object): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-send - */ -chrome.sockets.udp.send = function(socketId, data, address, port, callback) {}; - - -/** - * @param {number} socketId - * @param {function()} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-close - */ -chrome.sockets.udp.close = function(socketId, callback) {}; - - -/** - * @param {number} socketId - * @param {function(!chrome.sockets.udp.SocketInfo): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-getInfo - */ -chrome.sockets.udp.getInfo = function(socketId, callback) {}; - - -/** - * @param {function(!Array): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-getSockets - */ -chrome.sockets.udp.getSockets = function(callback) {}; - - -/** - * @param {number} socketId - * @param {string} address - * @param {function(number): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-joinGroup - */ -chrome.sockets.udp.joinGroup = function(socketId, address, callback) {}; - - -/** - * @param {number} socketId - * @param {string} address - * @param {function(number): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-leaveGroup - */ -chrome.sockets.udp.leaveGroup = function(socketId, address, callback) {}; - - -/** - * @param {number} socketId - * @param {number} ttl - * @param {function(number): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-setMulticastTimeToLive - */ -chrome.sockets.udp.setMulticastTimeToLive = function( - socketId, ttl, callback) {}; - - -/** - * @param {number} socketId - * @param {boolean} enabled - * @param {function(number): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-setMulticastLoopbackMode - */ -chrome.sockets.udp.setMulticastLoopbackMode = function( - socketId, enabled, callback) {}; - - -/** - * @param {number} socketId - * @param {function(!Array): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-getJoinedGroups - */ -chrome.sockets.udp.getJoinedGroups = function(socketId, callback) {}; - - -/** - * @param {number} socketId - * @param {boolean} enabled - * @param {function(number): void} callback - * @return {undefined} - * @see https://developer.chrome.com/apps/sockets_udp#method-send - */ -chrome.sockets.udp.setBroadcast = function(socketId, enabled, callback) {}; - - -/** - * @type {!ChromeObjectEvent} - * @see https://developer.chrome.com/apps/sockets_udp#event-onReceive - */ -chrome.sockets.udp.onReceive; - - -/** - * @type {!ChromeObjectEvent} - * @see https://developer.chrome.com/apps/sockets_udp#event-onReceiveError - */ -chrome.sockets.udp.onReceiveError; - - -/** - * @const - * @see https://developer.chrome.com/extensions/storage.html - */ -chrome.storage = {}; - - -/** @type {!StorageArea} */ -chrome.storage.sync; - - -/** @type {!StorageArea} */ -chrome.storage.local; - - -/** @type {!StorageArea} */ -chrome.storage.managed; - - -/** @type {!StorageChangeEvent} */ -chrome.storage.onChanged; - - -/** @const */ -chrome.system = {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/system_cpu.html - */ -chrome.system.cpu = {}; - - -/** - * @typedef {?{ - * user: number, - * kernel: number, - * idle: number, - * total: number, - * }} - */ -chrome.system.cpu.CpuTime; - - -/** - * @typedef {?{ - * usage: !chrome.system.cpu.CpuTime, - * }} - */ -chrome.system.cpu.ProcessorInfo; - - -/** - * @typedef {?{ - * numOfProcessors: number, - * archName: string, - * modelName: string, - * features: !Array, - * processors: !Array, - * temperatures: !Array, - * }} - */ -chrome.system.cpu.CpuInfo; - - -/** - * @param {function(!chrome.system.cpu.CpuInfo)} callback - * @return {undefined} - */ -chrome.system.cpu.getInfo = function(callback) {}; - - -/** - * @const - * @see http://developer.chrome.com/apps/system_display.html - */ -chrome.system.display = {}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/system.display#type-MirrorMode - */ -chrome.system.display.MirrorMode = { - OFF: '', - NORMAL: '', - MIXED: '', -}; - - -/** - * @typedef {!{ - * left: number, - * top: number, - * width: number, - * height: number - * }} - * @see https://developer.chrome.com/extensions/system.display#type-Bounds - */ -chrome.system.display.Bounds; - - -/** - * @typedef {!{ - * left: number, - * top: number, - * right: number, - * bottom: number - * }} - * @see https://developer.chrome.com/extensions/system.display#type-Insets - */ -chrome.system.display.Insets; - - -/** - * @typedef {!{ - * x: number, - * y: number - * }} - * @see https://developer.chrome.com/extensions/system.display#type-Point - */ -chrome.system.display.Point; - - -/** - * @typedef {!{ - * displayPoint: !chrome.system.display.Point, - * touchPoint: !chrome.system.display.Point - * }} - * @see https://developer.chrome.com/extensions/system.display#type-TouchCalibrationPair - */ -chrome.system.display.TouchCalibrationPair; - - -/** - * @typedef {!{ - * pair1: !chrome.system.display.TouchCalibrationPair, - * pair2: !chrome.system.display.TouchCalibrationPair, - * pair3: !chrome.system.display.TouchCalibrationPair, - * pair4: !chrome.system.display.TouchCalibrationPair - * }} - * @see https://developer.chrome.com/extensions/system.display#type-TouchCalibrationPairQuad - */ -chrome.system.display.TouchCalibrationPairQuad; - - -/** - * @typedef {!{ - * width: number, - * height: number, - * widthInNativePixels: number, - * heightInNativePixels: number, - * uiScale: number, - * deviceScaleFactor: number, - * isNative: boolean, - * isSelected: boolean - * }} - * @see https://developer.chrome.com/extensions/system.display#type-DisplayMode - */ -chrome.system.display.DisplayMode; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/system.display#type-LayoutPosition - */ -chrome.system.display.LayoutPosition = { - TOP: '', - RIGHT: '', - BOTTOM: '', - LEFT: '', -}; - - -/** - * @typedef {!{ - * id: string, - * parentId: string, - * position: (!chrome.system.display.LayoutPosition|string), - * offset: number - * }} - * @see https://developer.chrome.com/extensions/system.display#type-DisplayLayout - */ -chrome.system.display.DisplayLayout; - - -/** - * @typedef {!{ - * isUnified: (boolean|undefined), - * mirroringSourceId: (string|undefined), - * mirroringDestinationIds: (!Array|undefined), - * isPrimary: (boolean|undefined), - * overscan: (!chrome.system.display.Insets|undefined), - * rotation: (number|undefined), - * boundsOriginX: (number|undefined), - * boundsOriginY: (number|undefined), - * displayMode: (!chrome.system.display.DisplayMode|undefined), - * availableDisplayZoomFactors: (!Array|undefined), - * displayZoomFactor: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/system.display#type-DisplayProperties - */ -chrome.system.display.DisplayProperties; - - -/** - * @typedef {!{ - * singleUnified: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/system.display#type-GetInfoFlags - */ -chrome.system.display.GetInfoFlags; - - -/** - * @typedef {!{ - * mode: (!chrome.system.display.MirrorMode|string), - * mirroringSourceId: (string|undefined), - * mirroringDestinationIds: (!Array|undefined), - * }} - * @see https://developer.chrome.com/extensions/system.display#type-MirrorModeInfo - */ -chrome.system.display.MirrorModeInfo; - - -/** - * @typedef {!{ - * manufacturerId: string, - * productId: string, - * yearOfManufacture: number, - * }} - */ -chrome.system.display.Edid; - - -/** - * An undocumented type that defines the objects passed to getInfo()'s callback. - * @constructor - */ -chrome.system.display.DisplayUnitInfo = function() {}; - - -/** @type {string} */ -chrome.system.display.DisplayUnitInfo.prototype.id; - - -/** @type {string} */ -chrome.system.display.DisplayUnitInfo.prototype.name; - - -/** @type {!chrome.system.display.Edid|undefined} */ -chrome.system.display.DisplayUnitInfo.prototype.edid; - - -/** @type {string} */ -chrome.system.display.DisplayUnitInfo.prototype.mirroringSourceId; - - -/** @type {!Array} */ -chrome.system.display.DisplayUnitInfo.prototype.mirroringDestinationIds; - - -/** @type {boolean} */ -chrome.system.display.DisplayUnitInfo.prototype.isPrimary; - - -/** @type {boolean} */ -chrome.system.display.DisplayUnitInfo.prototype.isInternal; - - -/** @type {boolean} */ -chrome.system.display.DisplayUnitInfo.prototype.isEnabled; - - -/** @type {number} */ -chrome.system.display.DisplayUnitInfo.prototype.dpiX; - - -/** @type {number} */ -chrome.system.display.DisplayUnitInfo.prototype.dpiY; - - -/** @type {number} */ -chrome.system.display.DisplayUnitInfo.prototype.rotation; - - -/** @type {!chrome.system.display.Bounds} */ -chrome.system.display.DisplayUnitInfo.prototype.bounds; - - -/** @type {!chrome.system.display.Insets} */ -chrome.system.display.DisplayUnitInfo.prototype.overscan; - - -/** @type {!chrome.system.display.Bounds} */ -chrome.system.display.DisplayUnitInfo.prototype.workArea; - - -/** @type {!Array} */ -chrome.system.display.DisplayUnitInfo.prototype.modes; - - -/** @type {boolean} */ -chrome.system.display.DisplayUnitInfo.prototype.hasTouchSupport; - - -/** @type {!Array} */ -chrome.system.display.DisplayUnitInfo.prototype.availableDisplayZoomFactors; - - -/** @type {number} */ -chrome.system.display.DisplayUnitInfo.prototype.displayZoomFactor; - - -/** - * @param {!chrome.system.display.GetInfoFlags| - * function(!Array):void} - * flags Options affecting how the information is returned. - * @param {function(!Array):void=} - * callback The callback to invoke with the results. - * @return {undefined} - * @see https://developer.chrome.com/extensions/system.display#method-getInfo - */ -chrome.system.display.getInfo = function(flags, callback) {}; - - -/** - * @param {function(!Array):void} callback - * The callback to invoke with the results. - * @see https://developer.chrome.com/extensions/system.display#method-getDisplayLayout - */ -chrome.system.display.getDisplayLayout = function(callback) {}; - - -/** - * @param {string} id The display's unique identifier. - * @param {!chrome.system.display.DisplayProperties} info The information about - * display properties that should be changed. A property will be changed - * only if a new value for it is specified in info. - * @param {function():void=} callback Empty function called when the function - * finishes. To find out whether the function succeeded, runtime.lastError - * should be queried. - * @see https://developer.chrome.com/extensions/system.display#method-setDisplayProperties - */ -chrome.system.display.setDisplayProperties = function(id, info, callback) {}; - - -/** - * @param {!Array} layouts The layout - * information, required for all displays except the primary display. - * @param {function():void=} callback Empty function called when the function - * finishes. To find out whether the function succeeded, runtime.lastError - * should be queried. - * @see https://developer.chrome.com/extensions/system.display#method-setDisplayLayout - */ -chrome.system.display.setDisplayLayout = function(layouts, callback) {}; - - -/** - * @param {!chrome.system.display.MirrorModeInfo} info The information of the - * mirror mode that should be applied to the display mode. - * @param {function():void=} callback Empty function called when the function - * finishes. To find out whether the function succeeded, - * $(ref:runtime.lastError) should be queried. - * @see https://developer.chrome.com/extensions/system.display#method-setMirrorMode - */ -chrome.system.display.setMirrorMode = function(info, callback) {}; - - -/** - * @param {boolean} enabled True if unified desktop should be enabled. - * @see https://developer.chrome.com/extensions/system.display#method-enableUnifiedDesktop - */ -chrome.system.display.enableUnifiedDesktop = function(enabled) {}; - - -/** - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-overscanCalibrationStart - */ -chrome.system.display.overscanCalibrationStart = function(id) {}; - - -/** - * @param {string} id The display's unique identifier. - * @param {!chrome.system.display.Insets} delta The amount to change the - * overscan insets. - * @see https://developer.chrome.com/extensions/system.display#method-overscanCalibrationAdjust - */ -chrome.system.display.overscanCalibrationAdjust = function(id, delta) {}; - - -/** - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-overscanCalibrationReset - */ -chrome.system.display.overscanCalibrationReset = function(id) {}; - - -/** - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-overscanCalibrationComplete - */ -chrome.system.display.overscanCalibrationComplete = function(id) {}; - - -/** - * @param {string} id The display's unique identifier. - * @param {function(boolean):void=} callback Optional callback to inform the - * caller that the touch calibration has ended. The argument of the callback - * informs if the calibration was a success or not. - * @see https://developer.chrome.com/extensions/system.display#method-showNativeTouchCalibration - */ -chrome.system.display.showNativeTouchCalibration = function(id, callback) {}; - - -/** - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-startCustomTouchCalibration - */ -chrome.system.display.startCustomTouchCalibration = function(id) {}; - - -/** - * @param {!chrome.system.display.TouchCalibrationPairQuad} pairs The pairs of - * point used to calibrate the display. - * @param {!chrome.system.display.Bounds} bounds Bounds of the display when the - * touch calibration was performed. |bounds.left| and |bounds.top| values - * are ignored. - * @see https://developer.chrome.com/extensions/system.display#method-completeCustomTouchCalibration - */ -chrome.system.display.completeCustomTouchCalibration = function( - pairs, bounds) {}; - - -/** - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-clearTouchCalibration - */ -chrome.system.display.clearTouchCalibration = function(id) {}; - - -/** - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/system.display#event-onDisplayChanged - */ -chrome.system.display.onDisplayChanged; - -/** - * @const - * @see https://developer.chrome.com/extensions/system_memory - */ -chrome.system.memory = {}; - -/** - * Get physical memory information. - * @param {function(!chrome.system.memory.MemoryInfo)} callback - * @return {undefined} - */ -chrome.system.memory.getInfo = function(callback) {}; - -/** - * @constructor - */ -chrome.system.memory.MemoryInfo = function() {}; - - -/** @type {number} */ -chrome.system.memory.MemoryInfo.prototype.capacity; - - -/** @type {number} */ -chrome.system.memory.MemoryInfo.prototype.availableCapacity; - -/** - * @const - * @see http://developer.chrome.com/apps/system_network.html - */ -chrome.system.network = {}; - -/** - * @param {function(!Array)} callback - * @return {undefined} - */ -chrome.system.network.getNetworkInterfaces = function(callback) {}; - -/** - * @interface - */ -chrome.system.network.NetworkInterface = function() {}; - -/** - * @const {string} The underlying name of the adapter. On *nix, this will - * typically be "eth0", "wlan0", etc. - */ -chrome.system.network.NetworkInterface.prototype.name; - -/** @const {string} The available IPv4/6 address. */ -chrome.system.network.NetworkInterface.prototype.address; - -/** @const {number} The prefix length */ -chrome.system.network.NetworkInterface.prototype.prefixLength; - - -/** - * @const - */ -chrome.types = {}; - - -/** - * @typedef {?{ - * format: (string|undefined), - * quality: (number|undefined) - * }} - */ -chrome.types.ImageDetails; - - - -/** - * @const - * @see https://developer.chrome.com/extensions/types.html - */ -chrome.chromeSetting = {}; - - -/** @type {!ChromeEvent} */ -chrome.chromeSetting.onChange; - - -/** - * @const - * @see https://developer.chrome.com/extensions/webNavigation.html - */ -chrome.webNavigation = {}; - - -/** - * @param {Object} details Object with a 'tabId' (number) key. - * @param {function(!Array>)} callback - * Callback function. - * @return {undefined} - */ -chrome.webNavigation.getAllFrames = function(details, callback) {}; - - -/** - * @param {Object} details Object with 'tabId' (number) and 'frameId' (number) - * keys. - * @param {function(Object)} callback - * Callback function. - * @return {undefined} - */ -chrome.webNavigation.getFrame = function(details, callback) {}; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onBeforeNavigate; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onCommitted; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onDOMContentLoaded; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onCompleted; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onErrorOccurred; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onCreatedNavigationTarget; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onReferenceFragmentUpdated; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onTabReplaced; - - -/** @type {!ChromeEvent} */ -chrome.webNavigation.onHistoryStateUpdated; - - -/** - * Base event type for WebRequest-releated events. - * - * The `addListener()` methods for these take more than one argument, so they - * cannot just extend `ChromeBaseEvent`. - * @interface - * @extends {ChromeBaseEventNoListeners} - * @template LISTENER - */ -function WebRequestBaseEvent() {} - - -/** - * @param {LISTENER} listener Listener function. - * @param {!RequestFilter} filter A set of filters that restrict - * the events that will be sent to this listener. - * @param {!Array=} opt_extraInfoSpec Array of extra information - * that should be passed to the listener function. - * @return {undefined} - */ -WebRequestBaseEvent.prototype.addListener = function( - listener, filter, opt_extraInfoSpec) {}; - - -/** - * @param {LISTENER} listener Listener function. - * @return {undefined} - */ -WebRequestBaseEvent.prototype.removeListener = function(listener) {}; - - -/** - * @param {LISTENER} listener Listener function. - * @return {boolean} - */ -WebRequestBaseEvent.prototype.hasListener = function(listener) {}; - - -/** - * @return {boolean} - */ -WebRequestBaseEvent.prototype.hasListeners = function() {}; - - -/** - * Most event listeners for WebRequest take extra arguments. - * @see https://developer.chrome.com/extensions/webRequest - * @interface - * @extends {WebRequestBaseEvent} - */ -function WebRequestEvent() {} - - -/** - * Some event listeners can be optionally synchronous. - * @see https://developer.chrome.com/extensions/webRequest - * @interface - * @extends {WebRequestBaseEvent} - */ -function WebRequestOptionallySynchronousEvent() {} - - -/** - * The onAuthRequired event listener can be optionally synchronous, and can also - * optionally take a callback. - * @see https://developer.chrome.com/extensions/webRequest - * @interface - * @extends {WebRequestBaseEvent< - * function( - * !Object, - * function(!BlockingResponse)=): (undefined|!BlockingResponse)>} - */ -function WebRequestOnAuthRequiredEvent() {} - - -/** - * The onErrorOccurred event takes one fewer parameter than the others. - * - * The `addListener()` methods for these take more than one argument, so they - * cannot just extend `ChromeBaseEvent`. - * @see https://developer.chrome.com/extensions/webRequest - * @interface - * @extends {ChromeBaseEventNoListeners} - */ -function WebRequestOnErrorOccurredEvent() {} - - -/** - * @param {function(!Object): void} listener Listener function. - * @param {!RequestFilter} filter A set of filters that restrict - * the events that will be sent to this listener. - * @return {undefined} - */ -WebRequestOnErrorOccurredEvent.prototype.addListener = function( - listener, filter) {}; - - -/** - * @param {function(!Object): void} listener Listener function. - * @return {undefined} - */ -WebRequestOnErrorOccurredEvent.prototype.removeListener = function(listener) {}; - - -/** - * @param {function(!Object): void} listener Listener function. - * @return {boolean} - */ -WebRequestOnErrorOccurredEvent.prototype.hasListener = function(listener) {}; - - -/** - * @return {boolean} - */ -WebRequestOnErrorOccurredEvent.prototype.hasListeners = function() {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/webRequest - */ -chrome.webRequest = {}; - - -/** - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -chrome.webRequest.handlerBehaviorChanged = function(opt_callback) {}; - - -/** @type {!WebRequestOnAuthRequiredEvent} */ -chrome.webRequest.onAuthRequired; - - -/** @type {!WebRequestEvent} */ -chrome.webRequest.onBeforeRedirect; - - -/** @type {!WebRequestOptionallySynchronousEvent} */ -chrome.webRequest.onBeforeRequest; - - -/** @type {!WebRequestOptionallySynchronousEvent} */ -chrome.webRequest.onBeforeSendHeaders; - - -/** @type {!WebRequestEvent} */ -chrome.webRequest.onCompleted; - - -/** @type {!WebRequestOnErrorOccurredEvent} */ -chrome.webRequest.onErrorOccurred; - - -/** @type {!WebRequestOptionallySynchronousEvent} */ -chrome.webRequest.onHeadersReceived; - - -/** @type {!WebRequestEvent} */ -chrome.webRequest.onResponseStarted; - - -/** @type {!WebRequestEvent} */ -chrome.webRequest.onSendHeaders; - - -// Classes - - - -/** - * @see https://developer.chrome.com/extensions/management.html - * @constructor - */ -function ExtensionInfo() {} - - -/** @type {string} */ -ExtensionInfo.prototype.id; - - -/** @type {string} */ -ExtensionInfo.prototype.name; - - -/** @type {string} */ -ExtensionInfo.prototype.shortName; - - -/** @type {string} */ -ExtensionInfo.prototype.description; - - -/** @type {string} */ -ExtensionInfo.prototype.version; - - -/** @type {boolean} */ -ExtensionInfo.prototype.mayDisable; - - -/** @type {boolean} */ -ExtensionInfo.prototype.enabled; - - -/** @type {string|undefined} */ -ExtensionInfo.prototype.disabledReason; - - -/** @type {boolean} */ -ExtensionInfo.prototype.isApp; - - -/** @type {string} */ -ExtensionInfo.prototype.type; - - -/** @type {string|undefined} */ -ExtensionInfo.prototype.appLaunchUrl; - - -/** @type {string|undefined} */ -ExtensionInfo.prototype.homepageUrl; - - -/** @type {string|undefined} */ -ExtensionInfo.prototype.updateUrl; - - -/** @type {boolean} */ -ExtensionInfo.prototype.offlineEnabled; - - -/** @type {string} */ -ExtensionInfo.prototype.optionsUrl; - - -/** @type {!Array|undefined} */ -ExtensionInfo.prototype.icons; - - -/** @type {!Array} */ -ExtensionInfo.prototype.permissions; - - -/** @type {!Array} */ -ExtensionInfo.prototype.hostPermissions; - - -/** @type {string} */ -ExtensionInfo.prototype.installType; - - -/** @type {string|undefined} */ -ExtensionInfo.prototype.launchType; - - -/** @type {!Array|undefined} */ -ExtensionInfo.prototype.availableLaunchTypes; - - - -/** - * @see https://developer.chrome.com/extensions/management.html - * @constructor - */ -function IconInfo() {} - - -/** @type {number} */ -IconInfo.prototype.size; - - -/** @type {string} */ -IconInfo.prototype.url; - - - -/** - * @see https://developer.chrome.com/extensions/windows.html - * @constructor - */ -function ChromeWindow() {} - - -/** @type {number} */ -ChromeWindow.prototype.id; - - -/** @type {boolean} */ -ChromeWindow.prototype.focused; - - -/** @type {number} */ -ChromeWindow.prototype.top; - - -/** @type {number} */ -ChromeWindow.prototype.left; - - -/** @type {number} */ -ChromeWindow.prototype.width; - - -/** @type {number} */ -ChromeWindow.prototype.height; - - -/** @type {Array} */ -ChromeWindow.prototype.tabs; - - -/** @type {boolean} */ -ChromeWindow.prototype.incognito; - - -/** @type {string} */ -ChromeWindow.prototype.type; - - -/** @type {string} */ -ChromeWindow.prototype.state; - - -/** @type {boolean} */ -ChromeWindow.prototype.alwaysOnTop; - - -/** - * @see http://developer.chrome.com/extensions/pushMessaging.html - * @const - */ -chrome.pushMessaging = {}; - - -/** - * @type {!chrome.pushMessaging.PushMessageEvent} - */ -chrome.pushMessaging.onMessage; - - -/** - * @param {boolean|function(!chrome.pushMessaging.ChannelIdResult)} - * interactiveOrCallback Either a flag(optional), if set to true, user will - * be asked to log in if they are not already logged in, or, when he flag is - * not given, the callback. - * @param {function(!chrome.pushMessaging.ChannelIdResult)=} opt_callback - * Callback. - * @return {undefined} - */ -chrome.pushMessaging.getChannelId = function( - interactiveOrCallback, opt_callback) {}; - - - -/** - * Event whose listeners take a chrome.pushMessaging.Message parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.pushMessaging.PushMessageEvent = function() {}; - - -/** - * @see https://developer.chrome.com/extensions/bookmarks.html#type-BookmarkTreeNode - * @constructor - */ -function BookmarkTreeNode() {} - - -/** @type {string} */ -BookmarkTreeNode.prototype.id; - - -/** @type {string|undefined} */ -BookmarkTreeNode.prototype.parentId; - - -/** @type {number|undefined} */ -BookmarkTreeNode.prototype.index; - - -/** @type {string|undefined} */ -BookmarkTreeNode.prototype.url; - - -/** @type {string} */ -BookmarkTreeNode.prototype.title; - - -/** @type {number|undefined} */ -BookmarkTreeNode.prototype.dateAdded; - - -/** @type {number|undefined} */ -BookmarkTreeNode.prototype.dateGroupModified; - - -/** @type {string|undefined} */ -BookmarkTreeNode.prototype.unmodifiable; - - -/** @type {!Array|undefined} */ -BookmarkTreeNode.prototype.children; - - - -/** - * @see https://developer.chrome.com/extensions/dev/cookies.html#type-Cookie - * @constructor - */ -function Cookie() {} - - -/** @type {string} */ -Cookie.prototype.name; - - -/** @type {string} */ -Cookie.prototype.value; - - -/** @type {string} */ -Cookie.prototype.domain; - - -/** @type {boolean} */ -Cookie.prototype.hostOnly; - - -/** @type {string} */ -Cookie.prototype.path; - - -/** @type {boolean} */ -Cookie.prototype.secure; - - -/** @type {boolean} */ -Cookie.prototype.httpOnly; - - -/** @type {boolean} */ -Cookie.prototype.session; - - -/** @type {number} */ -Cookie.prototype.expirationDate; - - -/** @type {string} */ -Cookie.prototype.storeId; - - - -/** - * @see https://developer.chrome.com/extensions/dev/cookies.html#type-CookieStore - * @constructor - */ -function CookieStore() {} - - -/** @type {string} */ -CookieStore.prototype.id; - - -/** @type {Array} */ -CookieStore.prototype.tabIds; - - - -/** - * @see https://developer.chrome.com/docs/extensions/reference/contextMenus/#type-OnClickData - * @constructor - */ -function OnClickData() {} - - -/** @type {number|string} */ -OnClickData.prototype.menuItemId; - - -/** @type {number|string} */ -OnClickData.prototype.parentMenuItemId; - - -/** @type {string} */ -OnClickData.prototype.mediaType; - - -/** @type {string} */ -OnClickData.prototype.linkUrl; - - -/** @type {string} */ -OnClickData.prototype.srcUrl; - - -/** @type {string} */ -OnClickData.prototype.pageUrl; - - -/** @type {string} */ -OnClickData.prototype.frameUrl; - - -/** @type {number} */ -OnClickData.prototype.frameId; - - -/** @type {string} */ -OnClickData.prototype.selectionText; - - -/** @type {boolean} */ -OnClickData.prototype.editable; - - -/** @type {boolean} */ -OnClickData.prototype.wasChecked; - - -/** @type {boolean} */ -OnClickData.prototype.checked; - - - -/** - * @see https://developer.chrome.com/extensions/debugger.html#type-Debuggee - * @constructor - */ -function Debuggee() {} - - -/** @type {number} */ -Debuggee.prototype.tabId; - - -/** - * @see https://developer.chrome.com/extensions/contentSettings.html#type-ResourceIdentifier - * @constructor - */ -function ResourceIdentifier() {} - - -/** @type {string} */ -ResourceIdentifier.prototype.id; - - -/** @type {string} */ -ResourceIdentifier.prototype.description; - - - -/** - * @see https://developer.chrome.com/extensions/contentSettings.html#type-ContentSetting - * @constructor - */ -function ContentSetting() {} - - -/** - * @param {!Object} details Settings details. - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -ContentSetting.prototype.clear = function(details, opt_callback) {}; - - -/** - * @param {!Object} details - * Settings details. - * @param {function({setting: *}): void} callback Callback function. - * @return {undefined} - */ -ContentSetting.prototype.get = function(details, callback) {}; - - -/** - * @param {function(): void} callback Callback function. - * @return {undefined} - */ -ContentSetting.prototype.getResourceIdentifiers = function(callback) {}; - - -/** - * @param {!Object} details - * Settings details. - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -ContentSetting.prototype.set = function(details, opt_callback) {}; - - - -/** - * @see https://developer.chrome.com/extensions/history.html#type-HistoryItem - * @constructor - */ -function HistoryItem() {} - - -/** @type {string} */ -HistoryItem.prototype.id; - - -/** @type {string} */ -HistoryItem.prototype.url; - - -/** @type {string} */ -HistoryItem.prototype.title; - - -/** @type {number} */ -HistoryItem.prototype.lastVisitTime; - - -/** @type {number} */ -HistoryItem.prototype.visitCount; - - -/** @type {number} */ -HistoryItem.prototype.typedCount; - - - -/** - * @see https://developer.chrome.com/extensions/history.html#type-VisitItem - * @constructor - */ -function VisitItem() {} - - -/** @type {string} */ -VisitItem.prototype.id; - - -/** @type {string} */ -VisitItem.prototype.visitId; - - -/** @type {number} */ -VisitItem.prototype.visitTime; - - -/** @type {string} */ -VisitItem.prototype.referringVisitId; - - -/** @type {string} */ -VisitItem.prototype.transition; - - - -/** - * @see https://developer.chrome.com/extensions/fileBrowserHandler.html#type-FileHandlerExecuteEventDetails - * @constructor - */ -function FileHandlerExecuteEventDetails() {} - - -/** @type {!Array} */ -FileHandlerExecuteEventDetails.prototype.entries; - - -/** @type {number|undefined} */ -FileHandlerExecuteEventDetails.prototype.tab_id; - - - -/** - * @see https://developer.chrome.com/extensions/input.ime.html#type-KeyboardEvent - * @constructor - */ -function ChromeKeyboardEvent() {} - - -/** @type {string} */ -ChromeKeyboardEvent.prototype.type; - - -/** @type {string} */ -ChromeKeyboardEvent.prototype.requestId; - - -/** @type {string|undefined} */ -ChromeKeyboardEvent.prototype.extensionId; - - -/** @type {string} */ -ChromeKeyboardEvent.prototype.key; - - -/** @type {string} */ -ChromeKeyboardEvent.prototype.code; - - -/** @type {number|undefined} */ -ChromeKeyboardEvent.prototype.keyCode; - - -/** @type {boolean|undefined} */ -ChromeKeyboardEvent.prototype.altKey; - - -/** @type {boolean|undefined} */ -ChromeKeyboardEvent.prototype.altgrKey; - - -/** @type {boolean|undefined} */ -ChromeKeyboardEvent.prototype.ctrlKey; - - -/** @type {boolean|undefined} */ -ChromeKeyboardEvent.prototype.shiftKey; - - -/** @type {boolean|undefined} */ -ChromeKeyboardEvent.prototype.capsLock; - - - -/** - * @see https://developer.chrome.com/extensions/input.ime.html#type-InputContext - * @constructor - */ -chrome.input.ime.InputContext = function() {}; - - -/** @type {number} */ -chrome.input.ime.InputContext.prototype.contextID; - - -/** @type {string} */ -chrome.input.ime.InputContext.prototype.type; - - -/** @type {boolean} */ -chrome.input.ime.InputContext.prototype.autoCorrect; - - -/** @type {boolean} */ -chrome.input.ime.InputContext.prototype.autoComplete; - - -/** @type {string} */ -chrome.input.ime.InputContext.prototype.autoCapitalize; - - -/** @type {boolean} */ -chrome.input.ime.InputContext.prototype.spellCheck; - - -/** @type {boolean} */ -chrome.input.ime.InputContext.prototype.shouldDoLearning; - - -/** - * @see https://developer.chrome.com/extensions/proxy.html#type-ProxyServer - * @constructor - */ -function ProxyServer() {} - - -/** @type {string} */ -ProxyServer.prototype.scheme; - - -/** @type {string} */ -ProxyServer.prototype.host; - - -/** @type {number} */ -ProxyServer.prototype.port; - - - -/** - * @see https://developer.chrome.com/extensions/proxy.html#type-ProxyRules - * @constructor - */ -function ProxyRules() {} - - -/** @type {ProxyServer} */ -ProxyRules.prototype.singleProxy; - - -/** @type {ProxyServer} */ -ProxyRules.prototype.proxyForHttp; - - -/** @type {ProxyServer} */ -ProxyRules.prototype.proxyForHttps; - - -/** @type {ProxyServer} */ -ProxyRules.prototype.proxyForFtp; - - -/** @type {ProxyServer} */ -ProxyRules.prototype.fallbackProxy; - - -/** @type {!Array} */ -ProxyRules.prototype.bypassList; - - - -/** - * @see https://developer.chrome.com/extensions/proxy.html#type-PacScript - * @constructor - */ -function PacScript() {} - - -/** @type {string} */ -PacScript.prototype.url; - - -/** @type {string} */ -PacScript.prototype.data; - - -/** @type {boolean} */ -PacScript.prototype.mandatory; - - - -/** - * @see https://developer.chrome.com/extensions/proxy.html#type-ProxyConfig - * @constructor - */ -function ProxyConfig() {} - - -/** @type {ProxyRules} */ -ProxyConfig.prototype.rules; - - -/** @type {PacScript} */ -ProxyConfig.prototype.pacScript; - - -/** @type {string} */ -ProxyConfig.prototype.mode; - - - -/** - * The event listener for Storage receives an Object mapping each - * key that changed to its corresponding StorageChange for that item. - * - * Listener will receive an object that maps each key to its StorageChange, - * and the namespace ("sync" or "local") of the storage area the changes - * are for. - * @see https://developer.chrome.com/extensions/storage#event-onChanged - * @interface - * @extends {ChromeBaseEvent, string)>} - */ -function StorageChangeEvent() {} - - -/** - * The event listener for StorageArea receives an Object mapping each - * key that changed to its corresponding StorageChange for that item. - * - * Listener will receive an object that maps each key to its StorageChange. - * @see https://developer.chrome.com/extensions/storage#type-StorageArea - * @interface - * @extends {ChromeBaseEvent)>} - */ -function StorageAreaChangeEvent() {} - - -/** - * @see https://developer.chrome.com/extensions/storage.html#type-StorageChange - * @constructor - */ -function StorageChange() {} - - -/** @type {?} */ -StorageChange.prototype.oldValue; - - -/** @type {?} */ -StorageChange.prototype.newValue; - - - -/** - * @see https://developer.chrome.com/extensions/storage.html#type-StorageArea - * @constructor - */ -function StorageArea() {} - - -/** - * @param {(string|!Array|!Object|null|function(!Object))=} - * keysOrCallback - * A single key to get, list of keys to get, or a dictionary - * specifying default values (see description of the - * object). An empty list or object will return an empty - * result object. Pass in null to get the entire contents of storage. - * @param {function(!Object)=} opt_callback Callback with storage items, or null - * on failure. - * @return {undefined} - */ -StorageArea.prototype.get = function(keysOrCallback, opt_callback) {}; - - -/** - * @param {(string|!Array|null|function(!Object))=} keysOrCallback - * A single key or list of keys to get the total usage for. An empty list - * will return 0. Pass in null to get the total usage of all of storage. - * @param {function(number)=} opt_callback - * Callback with the amount of space being used by storage. - * @return {undefined} - */ -StorageArea.prototype.getBytesInUse = function(keysOrCallback, opt_callback) {}; - - -/** - * @param {!Object} items - * Object specifying items to augment storage - * with. Values that cannot be serialized (functions, etc) will be ignored. - * @param {function()=} opt_callback Callback. - * @return {undefined} - */ -StorageArea.prototype.set = function(items, opt_callback) {}; - - -/** - * @param {(string|!Array)} keys - * A single key or a list of keys for items to remove. - * @param {function()=} opt_callback Callback. - * @return {undefined} - */ -StorageArea.prototype.remove = function(keys, opt_callback) {}; - - -/** - * Removes all items from storage. - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -StorageArea.prototype.clear = function(opt_callback) {}; - - -/** - * Fired when one or more items change. - * @type {!StorageAreaChangeEvent} - */ -StorageArea.prototype.onChanged; - - -/** - * @see https://developer.chrome.com/extensions/types.html#type-ChromeSetting - * @constructor - */ -function ChromeSetting() {} - - -/** - * @param {Object} details Object with a 'scope' (string) key. - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -ChromeSetting.prototype.clear = function(details, opt_callback) {}; - - -/** - * @param {Object} details Object with an 'incognito' (boolean) key. - * @param {function(Object): void} callback Callback function. - * @return {undefined} - */ -ChromeSetting.prototype.get = function(details, callback) {}; - - -/** - * @param {Object} details Object with a 'value' (*) key and an optional - * 'scope' (string) key. - * @param {function(): void=} opt_callback Callback function. - * @return {undefined} - */ -ChromeSetting.prototype.set = function(details, opt_callback) {}; - - -/** @type {!ChromeObjectEvent} */ -ChromeSetting.prototype.onChange; - - - -/** - * @see https://developer.chrome.com/extensions/webRequest#type-RequestFilter - * @typedef {?{ - * urls: !Array, - * types: (!Array|undefined), - * tabId: (number|undefined), - * windowId: (number|undefined), - * }} - */ -var RequestFilter; - - - -/** - * @see https://developer.chrome.com/extensions/webRequest#type-HttpHeaders - * @typedef {?{ - * name: string, - * value: (string|undefined), - * binaryValue: (!Array|undefined), - * }} - */ -var HttpHeader; - - - -/** - * @see https://developer.chrome.com/extensions/webRequest#type-HttpHeaders - * @typedef {?Array} - */ -chrome.webRequest.HttpHeaders; - - - -/** - * @see https://developer.chrome.com/extensions/webRequest#type-BlockingResponse - * @typedef {?{ - * cancel: (boolean|undefined), - * redirectUrl: (string|undefined), - * requestHeaders: (!chrome.webRequest.HttpHeaders|undefined), - * responseHeaders: (!chrome.webRequest.HttpHeaders|undefined), - * authCredentials: (!{username: string, password: string}|undefined), - * }} - */ -var BlockingResponse; - - - -/** - * @see http://developer.chrome.com/extensions/pushMessaging.html#type-Message - * @constructor - */ -chrome.pushMessaging.Message = function() {}; - - -/** - * @type {number} - */ -chrome.pushMessaging.Message.prototype.subchannelId; - - -/** - * @type {string} - */ -chrome.pushMessaging.Message.prototype.payload; - - - -/** - * @see http://developer.chrome.com/extensions/pushMessaging.html#type-ChannelIdResult - * @constructor - */ -chrome.pushMessaging.ChannelIdResult = function() {}; - - -/** - * @type {string} - */ -chrome.pushMessaging.ChannelIdResult.prototype.channelId; - - -/** - * The `chrome.fileSystem` API makes use of the Entry and FileEntry types - * defined in {@code javascript/externs/fileapi.js}. - * @const - * @see http://developer.chrome.com/apps/fileSystem.html - */ -chrome.fileSystem = {}; - - -/** - * @param {!Entry} entry The entry to get the display path for. The entry can - * originally be obtained through - * `chrome.fileSystem.chooseEntry` or - * `chrome.fileSystem.restoreEntry`. - * @param {function(string)} callback A success callback. - * @see http://developer.chrome.com/apps/fileSystem.html#method-getDisplayPath - * @return {undefined} - */ -chrome.fileSystem.getDisplayPath = function(entry, callback) {}; - - -/** - * @param {!Entry} entry The entry to get a writable entry for. - * @param {function(!Entry)} callback A success callback. - * @see http://developer.chrome.com/apps/fileSystem.html#method-getWritableEntry - * @return {undefined} - */ -chrome.fileSystem.getWritableEntry = function(entry, callback) {}; - - -/** - * @param {!Entry} entry The entry to query writability. - * @param {function(boolean)} callback A success callback. - * @see http://developer.chrome.com/apps/fileSystem.html#method-isWritableEntry - * @return {undefined} - */ -chrome.fileSystem.isWritableEntry = function(entry, callback) {}; - - -/** - * @typedef {{ - * description: (string|undefined), - * mimeTypes: (!Array|undefined), - * extensions: (!Array|undefined) - * }} - * @see http://developer.chrome.com/apps/fileSystem.html#method-chooseEntry - */ -chrome.fileSystem.AcceptsOption; - - -/** - * @typedef {{ - * type: (string|undefined), - * suggestedName: (string|undefined), - * accepts: (!Array|undefined), - * acceptsAllTypes: (boolean|undefined), - * acceptsMultiple: (boolean|undefined) - * }} - * @see http://developer.chrome.com/apps/fileSystem.html#method-chooseEntry - */ -chrome.fileSystem.ChooseEntryOptions; - - -/** - * @typedef {?{ - * volumeId: string, - * writable: (boolean|undefined) - * }} - * @see http://developer.chrome.com/apps/fileSystem.html#method-requestFileSystem - */ -chrome.fileSystem.RequestFileSystemOptions; - - -/** - * @see http://developer.chrome.com/apps/fileSystem.html#method-getVolumeList - * @constructor - */ -chrome.fileSystem.Volume = function() {}; - - -/** @type {string} */ -chrome.fileSystem.Volume.prototype.volumeId; - - -/** @type {boolean} */ -chrome.fileSystem.Volume.prototype.writable; - - -/** - * @param {!chrome.fileSystem.ChooseEntryOptions| - * function(Entry=, !Array=)} optionsOrCallback The - * options for the file prompt or the callback. - * @param {function(Entry=, !Array=)=} opt_callback A success - * callback, if arg1 is options. - * @see http://developer.chrome.com/apps/fileSystem.html#method-chooseEntry - * @return {undefined} - */ -chrome.fileSystem.chooseEntry = function(optionsOrCallback, opt_callback) {}; - - -/** - * @param {string} id The ID of the file entry to restore. - * @param {function(!Entry)} callback A success callback. - * @see http://developer.chrome.com/apps/fileSystem.html#method-restoreEntry - * @return {undefined} - */ -chrome.fileSystem.restoreEntry = function(id, callback) {}; - - -/** - * @param {string} id The ID of the file entry to query restorability. - * @param {function(boolean)} callback A success callback. - * @see http://developer.chrome.com/apps/fileSystem.html#method-isRestorable - * @return {undefined} - */ -chrome.fileSystem.isRestorable = function(id, callback) {}; - - -/** - * @param {!Entry} entry The entry to regain access to. - * @return {string} The ID that can be passed to restoreEntry to regain access - * to the given file entry. - * @see http://developer.chrome.com/apps/fileSystem.html#method-retainEntry - */ -chrome.fileSystem.retainEntry = function(entry) {}; - - -/** - * @param {!chrome.fileSystem.RequestFileSystemOptions} options Options for the - * request. - * @param {function(!FileSystem=)} callback A completion callback with the file - * system in case of a success. Otherwise the error is passed as - * chrome.runtime.lastError. - * @see http://developer.chrome.com/apps/fileSystem.html#method-requestFileSystem - * @return {undefined} - */ -chrome.fileSystem.requestFileSystem = function(options, callback) {}; - - -/** - * @param {function(!Array=)} callback A completion - * callback with the file system list in case of a success. Otherwise the - * error is passed as chrome.runtime.lastError. - * @see http://developer.chrome.com/apps/fileSystem.html#method-getVolumeList - * @return {undefined} - */ -chrome.fileSystem.getVolumeList = function(callback) {}; - - -/** - * @const - * @see https://developer.chrome.com/apps/syncFileSystem - */ -chrome.syncFileSystem = {}; - - -/** - * Returns a syncable filesystem backed by Google Drive. The returned - * DOMFileSystem instance can be operated on in the same way as - * the Temporary and Persistent file systems (see - * http://www.w3.org/TR/file-system-api/), except that the filesystem - * object returned for Sync FileSystem does NOT support directory - * operations (yet). You can get a list of file entries by reading - * the root directory (by creating a new DirectoryReader), - * but cannot create a new directory in it. - * - *

Calling this multiple times from the same app will return the same - * handle to the same file system. - * - *

Note this call can fail. For example, if the user is not signed in - * to Chrome or if there is no network operation. To handle these errors - * it is important chrome.runtime.lastError is checked in the callback. - * - * @param {function(!FileSystem)} callback A callback type for - * requestFileSystem. - * @see https://developer.chrome.com/apps/syncFileSystem#method-requestFileSystem - * @return {undefined} - */ -chrome.syncFileSystem.requestFileSystem = function(callback) {}; - - -/** - * Sets the default conflict resolution policy for the 'syncable' file - * storage for the app. By default it is set to 'last_write_win'. - * When conflict resolution policy is set to 'last_write_win' conflicts - * for existing files are automatically resolved next time the file is updated. - * `callback` can be optionally given to know if the request has - * succeeded or not. - * - * @param {string} policy Any of 'last_write_win' or 'manual' - * @param {function()=} opt_callback - * - * @see https://developer.chrome.com/apps/syncFileSystem#method-setConflictResolutionPolicy - * @return {undefined} - */ -chrome.syncFileSystem.setConflictResolutionPolicy = function( - policy, opt_callback) {}; - - -/** - * Gets the current conflict resolution policy. - * - * @param {function(string)} callback Accepting any of 'last_write_win' - * or 'manual'. - * @see https://developer.chrome.com/apps/syncFileSystem#method-getConflictResolutionPolicy - * @return {undefined} - */ -chrome.syncFileSystem.getConflictResolutionPolicy = function(callback) {}; - - -/** - * Returns the current usage and quota in bytes for the 'syncable' file - * storage for the app. - * - * @param {!FileSystem} fileSystem - * @param {function(!Object)} callback Taking an object substantially similar - * to {@code {'usageBytes': number, quotaBytes: number}}. - * @see https://developer.chrome.com/apps/syncFileSystem#method-getUsageAndQuota - * @return {undefined} - */ -chrome.syncFileSystem.getUsageAndQuota = function(fileSystem, callback) {}; - - -/** - * Returns the FileStatus for the given fileEntry. The status value can be - * 'synced', 'pending' or 'conflicting'. Note that 'conflicting' state only - * happens when the service's conflict resolution policy is set to 'manual'. - * - * @param {!Entry} fileEntry - * @param {function(string)} callback Called with any of 'synced', 'pending' - * or 'conflicting'. - * - * @see https://developer.chrome.com/apps/syncFileSystem#method-getFileStatus - * @return {undefined} - */ -chrome.syncFileSystem.getFileStatus = function(fileEntry, callback) {}; - - -/** - * Returns each FileStatus for the given fileEntry array. Typically called - * with the result from dirReader.readEntries(). - * - * @param {!Array} fileEntries - * @param {function(!Array)} callback Each object will look like: - * {@code {'fileEntry': Entry, 'status': string, 'error': string?}}. - * - * @see https://developer.chrome.com/apps/syncFileSystem#method-getFileStatuses - * @return {undefined} - */ -chrome.syncFileSystem.getFileStatuses = function(fileEntries, callback) {}; - - -/** - * Since Chrome 31. - * - *

Returns the current sync backend status. - * - * @param {function(string)} callback Arg is any of 'initializing', 'running', - * 'authentication_required', 'temporary_unavailable', or 'disabled'. - * - * @see https://developer.chrome.com/apps/syncFileSystem#method-getServiceStatus - * @return {undefined} - */ -chrome.syncFileSystem.getServiceStatus = function(callback) {}; - - -/** - * Fired when an error or other status change has happened in the sync - * backend (for example, when the sync is temporarily disabled due - * to network or authentication error). - * - * @type {!ChromeObjectEvent} - * - * @see https://developer.chrome.com/apps/syncFileSystem#event-onServiceStatusChanged - */ -chrome.syncFileSystem.onServiceStatusChanged; - - -/** - * Fired when a file has been updated by the background sync service. - * - * @type {!ChromeObjectEvent} - * - * @see https://developer.chrome.com/apps/syncFileSystem#event-onFileStatusChanged - */ -chrome.syncFileSystem.onFileStatusChanged; - - -/** - * @const - * @see http://developer.chrome.com/extensions/alarms.html - */ -chrome.alarms = {}; - - -/** - * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event - * is fired. If there is another alarm with the same name (or no name if none is - * specified), it will be cancelled and replaced by this alarm. - * @param {string|!chrome.alarms.AlarmCreateInfo} nameOrAlarmCreateInfo Either - * the name to identify this alarm or the info used to create the alarm. If - * no name is passed, the empty string is used to identify the alarm. - * @param {!chrome.alarms.AlarmCreateInfo=} opt_alarmInfo If a name was passed - * as arg1, the info used to create the alarm. - * @see http://developer.chrome.com/extensions/alarms.html#method-create - * @return {undefined} - */ -chrome.alarms.create = function(nameOrAlarmCreateInfo, opt_alarmInfo) {}; - - -/** - * Retrieves details about the specified alarm. - * @param {string|function(!chrome.alarms.Alarm)} nameOrCallback The name - * of the alarm to get or the callback to invoke with the alarm. If no name - * is passed, the empty string is used to get the alarm. - * @param {function(!chrome.alarms.Alarm)=} opt_callback If a name was passed - * as arg1, the callback to invoke with the alarm. - * @see http://developer.chrome.com/extensions/alarms.html#method-get - * @return {undefined} - */ -chrome.alarms.get = function(nameOrCallback, opt_callback) {}; - - -/** - * Gets an array of all the alarms. - * @param {function(!Array)} callback - * @see http://developer.chrome.com/extensions/alarms.html#method-getAll - * @return {undefined} - */ -chrome.alarms.getAll = function(callback) {}; - - -/** - * Clears the alarm with the given name. - * @param {string=} opt_name - * @param {function(boolean)=} opt_callback A callback that will be called with - * a boolean for whether the alarm was cleared. - * @see http://developer.chrome.com/extensions/alarms.html#method-clear - * @return {undefined} - */ -chrome.alarms.clear = function(opt_name, opt_callback) {}; - - -/** - * Clears all alarms. - * @param {function(boolean)=} opt_callback A callback that will be called with - * a boolean for whether the alarms were cleared. - * @see http://developer.chrome.com/extensions/alarms.html#method-clearAll - * @return {undefined} - */ -chrome.alarms.clearAll = function(opt_callback) {}; - - -/** - * Fired when an alarm has elapsed. Useful for event pages. - * @type {!chrome.alarms.AlarmEvent} - * @see http://developer.chrome.com/extensions/alarms.html#event-onAlarm - */ -chrome.alarms.onAlarm; - - - -/** - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.alarms.AlarmEvent = function() {}; - - -/** - * @interface - * @see http://developer.chrome.com/extensions/alarms.html#type-Alarm - */ -chrome.alarms.Alarm = function() {}; - - -/** - * Name of this alarm. - * @type {string} - */ -chrome.alarms.Alarm.prototype.name; - - -/** - * Time at which this alarm was scheduled to fire, in milliseconds past the - * epoch (e.g. Date.now() + n). For performance reasons, the alarm may have been - * delayed an arbitrary amount beyond this. - * @type {number} - */ -chrome.alarms.Alarm.prototype.scheduledTime; - - -/** - * If not null, the alarm is a repeating alarm and will fire again in - * periodInMinutes minutes. - * @type {?number} - */ -chrome.alarms.Alarm.prototype.periodInMinutes; - - -/** - * @typedef {{ - * when: (number|undefined), - * delayInMinutes: (number|undefined), - * periodInMinutes: (number|undefined) - * }} - * @see http://developer.chrome.com/extensions/alarms.html#method-create - */ -chrome.alarms.AlarmCreateInfo; - - -/** - * @see https://developer.chrome.com/apps/hid - * @const - */ -chrome.hid = {}; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/hid#type-DeviceFilter - */ -chrome.hid.DeviceFilter = function() {}; - - -/** - * Device vendor ID. - * @type {number|undefined} - */ -chrome.hid.DeviceFilter.prototype.vendorId; - - -/** - * Device product ID, only checked if the vendor ID matches. - * @type {number|undefined} - */ -chrome.hid.DeviceFilter.prototype.productId; - - -/** - * HID usage page identifier. - * @type {number|undefined} - */ -chrome.hid.DeviceFilter.prototype.usagePage; - - -/** - * HID usage identifier, checked only if the HID usage page matches. - * @type {number|undefined} - */ -chrome.hid.DeviceFilter.prototype.usage; - - -/** - * @typedef {?{ - * vendorId: (number|undefined), - * productId: (number|undefined), - * filters: (!Array|undefined) - * }} - * Deprecated since Chrome 39: vendorId, productId - * Since Chrome 39: filters - * @see https://developer.chrome.com/apps/hid#method-getDevices - */ -chrome.hid.HidGetDevicesOptions; - - -/** - * @typedef {?{ - * multiple: (boolean|undefined), - * filters: (!Array|undefined) - * }} - * @see https://developer.chrome.com/apps/hid#method-getUserSelectedDevices - */ -chrome.hid.HidGetUserSelectedDevicesOptions; - - -/** - * @typedef {?{ - * usagePage: number, - * usage: number, - * reportIds: !Array - * }} - * @see https://developer.chrome.com/apps/hid#method-getDevices - */ -chrome.hid.HidDeviceUsage; - - - -/** - * @constructor - * @see https://developer.chrome.com/apps/hid#type-HidDeviceInfo - */ -chrome.hid.HidDeviceInfo = function() {}; - - -/** - * Opaque device ID. - * @type {number} - */ -chrome.hid.HidDeviceInfo.prototype.deviceId; - - -/** - * Vendor ID. - * @type {number} - */ -chrome.hid.HidDeviceInfo.prototype.vendorId; - - -/** - * Product ID. - * @type {number} - */ -chrome.hid.HidDeviceInfo.prototype.productId; - - -/** - * The product name read from the device, if available. - * Since Chrome 46. - * @type {string} - */ -chrome.hid.HidDeviceInfo.prototype.productName; - - -/** - * The serial number read from the device, if available. - * Since Chrome 46. - * @type {string} - */ -chrome.hid.HidDeviceInfo.prototype.serialNumber; - - -/** - * Top-level collections from this device's report descriptors. - * @type {!Array} - */ -chrome.hid.HidDeviceInfo.prototype.collections; - - -/** - * Top-level collection's maximum input report size. - * @type {number} - */ -chrome.hid.HidDeviceInfo.prototype.maxInputReportSize; - - -/** - * Top-level collection's maximum output report size. - * @type {number} - */ -chrome.hid.HidDeviceInfo.prototype.maxOutputReportSize; - - -/** - * Top-level collection's maximum feature report size. - * @type {number} - */ -chrome.hid.HidDeviceInfo.prototype.maxFeatureReportSize; - - -/** - * Raw device report descriptor (not available on Windows). - * Since Chrome 42. - * @type {!ArrayBuffer} - */ -chrome.hid.HidDeviceInfo.prototype.reportDescriptor; - - -/** - * @typedef {?{ - * connectionId: number - * }} - * @see https://developer.chrome.com/apps/hid#method-connect - */ -chrome.hid.HidConnectInfo; - - -/** - * @see https://developer.chrome.com/apps/hid#method-getDevices - * Enumerates all the connected HID devices specified by the - * vendorId/productId/interfaceId tuple. - * @param {!chrome.hid.HidGetDevicesOptions} options The properties to search - * for on target devices. - * @param {function(!Array)} callback Invoked with a - * list of |HidDeviceInfo|s on complete. - * @return {undefined} - */ -chrome.hid.getDevices = function(options, callback) {}; - - -/** - * @see https://developer.chrome.com/apps/hid#method-getUserSelectedDevices - * Presents a device picker to the user and returns HidDeviceInfo objects for - * the devices selected. If the user cancels the picker devices will be empty. A - * user gesture is required for the dialog to display. Without a user gesture, - * the callback will run as though the user cancelled. If multiple filters are - * provided devices matching any filter will be displayed. - * @param {!chrome.hid.HidGetUserSelectedDevicesOptions} options - * @param {function(!Array)} callback Invoked with a - * list of |HidDeviceInfo|s on complete. - * @return {undefined} - */ -chrome.hid.getUserSelectedDevices = function(options, callback) {}; - - -/** - * @see https://developer.chrome.com/apps/hid#method-connect - * Opens a connection to a HID device for communication. - * @param {number} deviceId The ID of the device to open. - * @param {function(!Object=)} callback Invoked with an |HidConnectInfo| if the - * connection succeeds, or undefined if it fails. - * @return {undefined} - */ -chrome.hid.connect = function(deviceId, callback) {}; - - -/** - * @see https://developer.chrome.com/apps/hid#method-disconnect - * Disconnects from a device. - * @param {number} connectionId The connection to close. - * @param {function()=} opt_callback The callback to invoke once the connection - * is closed. - * @return {undefined} - */ -chrome.hid.disconnect = function(connectionId, opt_callback) {}; - - -/** - * @see https://developer.chrome.com/apps/hid#method-receive - * Receives an input report from an HID device. - * @param {number} connectionId The connection from which to receive the report. - * @param {function(number, !ArrayBuffer)} callback The callback to invoke with - * the received report. - * @return {undefined} - */ -chrome.hid.receive = function(connectionId, callback) {}; - - -/** - * @see https://developer.chrome.com/apps/hid#method-send - * Sends an output report to an HID device. - * @param {number} connectionId The connection to which to send the report. - * @param {number} reportId The report ID to use, or 0 if none. - * @param {!ArrayBuffer} data The report data. - * @param {function()} callback The callback to invoke once the write is - * finished. - * @return {undefined} - */ -chrome.hid.send = function(connectionId, reportId, data, callback) {}; - - -/** - * @see https://developer.chrome.com/apps/hid#method-receiveFeatureReport - * Receives a feature report from the device. - * @param {number} connectionId The connection from which to read the feature - * report. - * @param {number} reportId The report ID to use, or 0 if none. - * @param {number} size The size of the feature report to receive. - * @param {function(!ArrayBuffer)} callback The callback to invoke with the - * received report. - * @return {undefined} - */ -chrome.hid.receiveFeatureReport = function( - connectionId, reportId, size, callback) {}; - - -/** - * @see https://developer.chrome.com/apps/hid#method-sendFeatureReport - * Sends a feature report to the device. - * @param {number} connectionId The connection to which to send the feature - * report. - * @param {number} reportId The report ID to use, or 0 if none. - * @param {!ArrayBuffer} data The report data. - * @param {function()} callback The callback to invoke once the write is - * finished. - * @return {undefined} - */ -chrome.hid.sendFeatureReport = function( - connectionId, reportId, data, callback) {}; - - - -/** - * Event whose listeners take an HidDeviceInfo parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.hid.DeviceAddedEvent = function() {}; - - -/** - * @type {!chrome.hid.DeviceAddedEvent} - * @see https://developer.chrome.com/apps/hid#event-onDeviceAdded - */ -chrome.hid.onDeviceAdded; - - -/** - * @type {!ChromeNumberEvent} - * @see https://developer.chrome.com/apps/hid#event-onDeviceRemoved - */ -chrome.hid.onDeviceRemoved; - - -/** - * @see http://developer.chrome.com/extensions/notifications.html - * @const - */ -chrome.notifications = {}; - - -/** - * @typedef {{ - * title: string, - * iconUrl: (string|undefined) - * }} - * @see http://developer.chrome.com/extensions/notifications.html#type-NotificationOptions - */ -chrome.notifications.NotificationButton; - - -/** - * @typedef {{ - * title: string, - * message: string - * }} - * @see http://developer.chrome.com/extensions/notifications.html#type-NotificationOptions - */ -chrome.notifications.NotificationItem; - - -/** - * @typedef {{ - * type: (string|undefined), - * iconUrl: (string|undefined), - * appIconMaskUrl: (string|undefined), - * title: (string|undefined), - * message: (string|undefined), - * contextMessage: (string|undefined), - * priority: (number|undefined), - * eventTime: (number|undefined), - * buttons: (!Array|undefined), - * imageUrl: (string|undefined), - * items: (!Array|undefined), - * progress: (number|undefined), - * isClickable: (boolean|undefined), - * requireInteraction: (boolean|undefined), - * silent: (boolean|undefined) - * }} - * @see http://developer.chrome.com/extensions/notifications.html#type-NotificationOptions - */ -chrome.notifications.NotificationOptions; - - -/** - * @typedef {function(boolean): void} - * @see http://developer.chrome.com/extensions/notifications.html#method-update - * @see http://developer.chrome.com/extensions/notifications.html#method-clear - */ -chrome.notifications.BooleanCallback; - - -/** - * @typedef {function(!Object): void} - * @see http://developer.chrome.com/extensions/notifications.html#method-getAll - */ -chrome.notifications.ObjectCallback; - - -/** - * @typedef {function(string, boolean): void} - * @see http://developer.chrome.com/extensions/notifications.html#event-onClosed - */ -chrome.notifications.ClosedCallback; - - -/** - * @typedef {function(string, number): void} - * @see http://developer.chrome.com/extensions/notifications.html#event-onButtonClicked - */ -chrome.notifications.ButtonCallback; - - -/** - * @param {string|!chrome.notifications.NotificationOptions} - * notificationIdOrOptions - * @param {(!chrome.notifications.NotificationOptions|function(string): void)=} - * opt_optionsOrCallback - * @param {(function(string): void)=} opt_callback - * @see http://developer.chrome.com/extensions/notifications.html#method-create - * @return {undefined} - */ -chrome.notifications.create = function( - notificationIdOrOptions, opt_optionsOrCallback, opt_callback) {}; - - -/** - * @param {string} notificationId - * @param {!chrome.notifications.NotificationOptions} options - * @param {chrome.notifications.BooleanCallback=} opt_callback - * @see http://developer.chrome.com/extensions/notifications.html#method-update - * @return {undefined} - */ -chrome.notifications.update = function( - notificationId, options, opt_callback) {}; - - -/** - * @param {string} notificationId - * @param {!chrome.notifications.BooleanCallback=} opt_callback - * @see http://developer.chrome.com/extensions/notifications.html#method-clear - * @return {undefined} - */ -chrome.notifications.clear = function(notificationId, opt_callback) {}; - - -/** - * @see http://developer.chrome.com/extensions/notifications.html#method-getAll - * @param {!chrome.notifications.ObjectCallback} callback - * @return {undefined} - */ -chrome.notifications.getAll = function(callback) {}; - - -/** - * @see http://developer.chrome.com/extensions/notifications.html#method-getPermissionLevel - * @param {function(string): void} callback takes 'granted' or 'denied' - * @return {undefined} - */ -chrome.notifications.getPermissionLevel = function(callback) {}; - - -/** - * @type {!chrome.notifications.ClosedEvent} - * @see http://developer.chrome.com/extensions/notifications.html#event-onClosed - */ -chrome.notifications.onClosed; - - -/** - * The user clicked a non-button area of the notification. Callback receives a - * notificationId. - * @type {!ChromeStringEvent} - * @see http://developer.chrome.com/extensions/notifications.html#event-onClicked - */ -chrome.notifications.onClicked; - - -/** - * @type {!chrome.notifications.ButtonClickedEvent} - * @see http://developer.chrome.com/extensions/notifications.html#event-onButtonClicked - */ -chrome.notifications.onButtonClicked; - - -/** - * Indicates permission level change. Callback should expect 'granted' or - * 'denied'. - * @type {!ChromeStringEvent} - * @see http://developer.chrome.com/extensions/notifications.html#event-onPermissionLevelChanged - */ -chrome.notifications.onPermissionLevelChanged; - - -/** - * @type {!ChromeEvent} - * @see http://developer.chrome.com/extensions/notifications.html#event-onShowSettings - */ -chrome.notifications.onShowSettings; - - - -/** - * @interface - * @extends {ChromeBaseEvent} - * @see http://developer.chrome.com/extensions/notifications.html#event-onClosed - */ -chrome.notifications.ClosedEvent = function() {}; - - -/** - * @interface - * @extends {ChromeBaseEvent} - * @see http://developer.chrome.com/extensions/notifications.html#event-onButtonClicked - */ -chrome.notifications.ButtonClickedEvent = function() {}; - - -/** - * @const - * @see http://developer.chrome.com/apps/system_storage.html - */ -chrome.system.storage = {}; - - - -/** @constructor */ -chrome.system.storage.StorageUnitInfo = function() {}; - - -/** @type {string} */ -chrome.system.storage.StorageUnitInfo.prototype.id; - - -/** @type {string} */ -chrome.system.storage.StorageUnitInfo.prototype.name; - - -/** @type {string} Any of 'fixed', 'removable', or 'unknown' */ -chrome.system.storage.StorageUnitInfo.prototype.type; - - -/** @type {number} */ -chrome.system.storage.StorageUnitInfo.prototype.capacity; - - - -/** - * Event whose listeners take a StorageUnitInfoEvent parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.system.storage.StorageUnitInfoEvent = function() {}; - - -/** @type {chrome.system.storage.StorageUnitInfoEvent} */ -chrome.system.storage.onAttached; - - -/** @type {!ChromeStringEvent} */ -chrome.system.storage.onDetached; - - -/** - * Gets the storage information from the system. - * @param {function(!Array)} callback - * @return {undefined} - */ -chrome.system.storage.getInfo = function(callback) {}; - - -/** - * Ejects a removable storage device. - * @param {string} id The transient device ID from StorageUnitInfo. - * @param {function(string)} callback Callback function where the value - * is any of: "success", "in_use", "no_such_device", "failure" - * @return {undefined} - */ -chrome.system.storage.ejectDevice = function(id, callback) {}; - - -/** - * Gets the available capacity of a specified storage device. - * @param {string} id The transient device ID from StorageUnitInfo. - * @param {function(Object)} callback A callback function that - * accepts an object with `id` and `availableCapacity` fields. - * @return {undefined} - */ -chrome.system.storage.getAvailableCapacity = function(id, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html - * @const - */ -chrome.usb = {}; - - - -/** @constructor */ -chrome.usb.Device = function Device() {}; - - -/** @type {number} */ -chrome.usb.Device.prototype.device; - - -/** @type {number} */ -chrome.usb.Device.prototype.vendorId; - - -/** @type {number} */ -chrome.usb.Device.prototype.productId; - - -/** @type {number} */ -chrome.usb.Device.prototype.version; - - -/** - * The product name read from the device, if available. - * Since Chrome 46. - * @type {string} - */ -chrome.usb.Device.prototype.productName; - -/** - * The manufacturer name read from the device, if available. - * Since Chrome 46. - * @type {string} - */ -chrome.usb.Device.prototype.manufacturerName; - -/** - * The serial number read from the device, if available. - * Since Chrome 46. - * @type {string} - */ -chrome.usb.Device.prototype.serialNumber; - - - -/** @constructor */ -chrome.usb.ConnectionHandle = function ConnectionHandle() {}; - - -/** @type {number} */ -chrome.usb.ConnectionHandle.prototype.handle; - - -/** @type {number} */ -chrome.usb.ConnectionHandle.prototype.vendorId; - - -/** @type {number} */ -chrome.usb.ConnectionHandle.prototype.productId; - - -/** - * @typedef {?{ - * direction: string, - * endpoint: number, - * length: (number|undefined), - * data: (!ArrayBuffer|undefined), - * timeout: (number|undefined) - * }} - */ -chrome.usb.GenericTransferInfo; - - -/** - * @typedef {?{ - * direction: string, - * recipient: string, - * requestType: string, - * request: number, - * value: number, - * index: number, - * length: (number|undefined), - * data: (!ArrayBuffer|undefined), - * timeout: (number|undefined) - * }} - */ -chrome.usb.ControlTransferInfo; - - - -/** @constructor */ -chrome.usb.TransferResultInfo = function() {}; - - -/** @type {number|undefined} */ -chrome.usb.TransferResultInfo.prototype.resultCode; - - -/** @type {!ArrayBuffer|undefined} */ -chrome.usb.TransferResultInfo.prototype.data; - - -/** - * @typedef {?{ - * vendorId: number, - * productId: number, - * interfaceId: (number|undefined) - * }} - */ -chrome.usb.FindDevicesOptions; - - -/** - * @typedef {?{ - * vendorId: (number|undefined), - * productId: (number|undefined), - * interfaceClass: (number|undefined), - * interfaceSubclass: (number|undefined), - * interfaceProtocol: (number|undefined) - * }} - */ -chrome.usb.DeviceFilter; - - -/** - * @typedef {?{ - * vendorId: (number|undefined), - * productId: (number|undefined), - * filters: (!Array|undefined) - * }} - */ -chrome.usb.GetDevicesOptions; - - -/** - * @typedef {?{ - * multiple: (boolean|undefined), - * filters: (!Array|undefined) - * }} - */ -chrome.usb.GetUserSelectedDevicesOptions; - - -/** - * @typedef {?{ - * transferInfo: !chrome.usb.GenericTransferInfo, - * packets: number, - * packetLength: number - * }} - */ -chrome.usb.IsochronousTransferInfo; - - - -/** @constructor */ -chrome.usb.EndpointDescriptor = function() {}; - - -/** @type {number} */ -chrome.usb.EndpointDescriptor.prototype.address; - -/** @type {string} */ -chrome.usb.EndpointDescriptor.prototype.type; - - -/** @type {string} */ -chrome.usb.EndpointDescriptor.prototype.direction; - - -/** @type {number} */ -chrome.usb.EndpointDescriptor.prototype.maximumPacketSize; - - -/** @type {(string|undefined)} */ -chrome.usb.EndpointDescriptor.prototype.synchronization; - - -/** @type {(string|undefined)} */ -chrome.usb.EndpointDescriptor.prototype.usage; - - -/** @type {(number|undefined)} */ -chrome.usb.EndpointDescriptor.prototype.pollingInterval; - - -/** @type {!ArrayBuffer} */ -chrome.usb.EndpointDescriptor.prototype.extra_data; - - - -/** @constructor */ -chrome.usb.InterfaceDescriptor = function() {}; - - -/** @type {number} */ -chrome.usb.InterfaceDescriptor.prototype.interfaceNumber; - - -/** @type {number} */ -chrome.usb.InterfaceDescriptor.prototype.alternateSetting; - - -/** @type {number} */ -chrome.usb.InterfaceDescriptor.prototype.interfaceClass; - - -/** @type {number} */ -chrome.usb.InterfaceDescriptor.prototype.interfaceSubclass; - - -/** @type {number} */ -chrome.usb.InterfaceDescriptor.prototype.interfaceProtocol; - - -/** @type {(string|undefined)} */ -chrome.usb.InterfaceDescriptor.prototype.description; - - -/** @type {!Array.} */ -chrome.usb.InterfaceDescriptor.prototype.endpoints; - - -/** @type {!ArrayBuffer} */ -chrome.usb.InterfaceDescriptor.prototype.extra_data; - - - -/** @constructor */ -chrome.usb.ConfigDescriptor = function() {}; - - -/** @type {boolean} */ -chrome.usb.ConfigDescriptor.prototype.active; - - -/** @type {number} */ -chrome.usb.ConfigDescriptor.prototype.configurationValue; - - -/** @type {string|undefined} */ -chrome.usb.ConfigDescriptor.prototype.description; - - -/** @type {boolean} */ -chrome.usb.ConfigDescriptor.prototype.selfPowered; - - -/** @type {boolean} */ -chrome.usb.ConfigDescriptor.prototype.remoteWakeup; - - -/** @type {number} */ -chrome.usb.ConfigDescriptor.prototype.maxPower; - - -/** @type {!Array} */ -chrome.usb.ConfigDescriptor.prototype.interfaces; - - -/** @type {!ArrayBuffer} */ -chrome.usb.ConfigDescriptor.prototype.extra_data; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-getDevices - * @param {!chrome.usb.GetDevicesOptions} options The properties to - * search for on target devices. - * @param {function(!Array)} callback Invoked with a list - * of |Device|s on complete. - * @return {undefined} - */ -chrome.usb.getDevices = function(options, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-getUserSelectedDevices - * @param {!chrome.usb.GetUserSelectedDevicesOptions} options Configuration of - * the device picker dialog box. - * @param {function(!Array)} callback Invoked with a list - * of |Device|s on complete. - * @return {undefined} - */ -chrome.usb.getUserSelectedDevices = function(options, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-getConfigurations - * @param {!chrome.usb.Device} device The device to fetch descriptors from. - * @param {function(!Array)} callback Invoked with - * the full set of device configuration descriptors. - * @return {undefined} - */ -chrome.usb.getConfigurations = function(device, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-requestAccess - * @param {!chrome.usb.Device} device The device to request access to. - * @param {number} interfaceId - * @param {function(boolean)} callback - * @return {undefined} - */ -chrome.usb.requestAccess = function(device, interfaceId, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-openDevice - * @param {!chrome.usb.Device} device The device to open. - * @param {function(!chrome.usb.ConnectionHandle)} callback Invoked with the - * created ConnectionHandle on complete. - * @return {undefined} - */ -chrome.usb.openDevice = function(device, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-findDevices - * @param {!chrome.usb.FindDevicesOptions} options The properties to search for - * on target devices. - * @param {function(!Array)} callback Invoked - * with the opened ConnectionHandle on complete. - * @return {undefined} - */ -chrome.usb.findDevices = function(options, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-closeDevice - * @param {!chrome.usb.ConnectionHandle} handle The connection handle to close. - * @param {function()=} opt_callback The callback to invoke once the device is - * closed. - * @return {undefined} - */ -chrome.usb.closeDevice = function(handle, opt_callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-setConfiguration - * @param {!chrome.usb.ConnectionHandle} handle The connection handle for which - * to select a device configuration. - * @param {number} configurationValue The configuration to select. - * @param {function()} callback The callback to invoke on complete. - * @return {undefined} - */ -chrome.usb.setConfiguration = function(handle, configurationValue, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-getConfiguration - * @param {!chrome.usb.ConnectionHandle} handle The connection handle for which - * to get the current device configuration descriptor. - * @param {function(!chrome.usb.ConfigDescriptor)} callback The callback to - * invoke on complete. - * @return {undefined} - */ -chrome.usb.getConfiguration = function(handle, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-listInterfaces - * @param {!chrome.usb.ConnectionHandle} handle The device from which the - * interfaces should be listed. - * @param {function(!Array)} callback The - * callback to invoke when the interfaces are enumerated. - * @return {undefined} - */ -chrome.usb.listInterfaces = function(handle, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-claimInterface - * @param {!chrome.usb.ConnectionHandle} handle The device on which the - * interface is to be claimed. - * @param {number} interfaceNumber - * @param {function()} callback The callback to invoke once the interface is - * claimed. - * @return {undefined} - */ -chrome.usb.claimInterface = function(handle, interfaceNumber, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-releaseInterface - * @param {!chrome.usb.ConnectionHandle} handle The device on which the - * interface is to be released. - * @param {number} interfaceNumber - * @param {function()} callback The callback to invoke once the interface is - * released. - * @return {undefined} - */ -chrome.usb.releaseInterface = function(handle, interfaceNumber, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-setInterfaceAlternateSetting - * @param {!chrome.usb.ConnectionHandle} handle The device on which the - * interface settings are to be set. - * @param {number} interfaceNumber - * @param {number} alternateSetting The alternate setting to set. - * @param {function()} callback The callback to invoke once the interface - * setting is set. - * @return {undefined} - */ -chrome.usb.setInterfaceAlternateSetting = function( - handle, interfaceNumber, alternateSetting, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-controlTransfer - * @param {!chrome.usb.ConnectionHandle} handle A connection handle to make the - * transfer on. - * @param {!chrome.usb.ControlTransferInfo} transferInfo The parameters to the - * transfer. - * @param {function(!chrome.usb.TransferResultInfo)} callback Invoked once the - * transfer has completed. - * @return {undefined} - */ -chrome.usb.controlTransfer = function(handle, transferInfo, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-bulkTransfer - * @param {!chrome.usb.ConnectionHandle} handle A connection handle to make - * the transfer on. - * @param {!chrome.usb.GenericTransferInfo} transferInfo The parameters to the - * transfer. See GenericTransferInfo. - * @param {function(!chrome.usb.TransferResultInfo)} callback Invoked once the - * transfer has completed. - * @return {undefined} - */ -chrome.usb.bulkTransfer = function(handle, transferInfo, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-interruptTransfer - * @param {!chrome.usb.ConnectionHandle} handle A connection handle to make the - * transfer on. - * @param {!chrome.usb.GenericTransferInfo} transferInfo The parameters to the - * transfer. See GenericTransferInfo. - * @param {function(!chrome.usb.TransferResultInfo)} callback Invoked once the - * transfer has completed. - * @return {undefined} - */ -chrome.usb.interruptTransfer = function(handle, transferInfo, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-isochronousTransfer - * @param {!chrome.usb.ConnectionHandle} handle A connection handle to make the - * transfer on. - * @param {!chrome.usb.IsochronousTransferInfo} transferInfo The parameters to - * the transfer. - * @param {function(!chrome.usb.TransferResultInfo)} callback Invoked once the - * transfer has been completed. - * @return {undefined} - */ -chrome.usb.isochronousTransfer = function(handle, transferInfo, callback) {}; - - -/** - * @see http://developer.chrome.com/apps/usb.html#method-resetDevice - * @param {!chrome.usb.ConnectionHandle} handle A connection handle to reset. - * @param {function(boolean)} callback Invoked once the device is reset with a - * boolean indicating whether the reset completed successfully. - * @return {undefined} - */ -chrome.usb.resetDevice = function(handle, callback) {}; - - - -/** - * Event whose listeners take an chrome.usb.Device parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.usb.DeviceEvent = function() {}; - - -/** - * @type {!chrome.usb.DeviceEvent} - * @see https://developer.chrome.com/apps/usb#event-onDeviceAdded - */ -chrome.usb.onDeviceAdded; - - -/** - * @type {!chrome.usb.DeviceEvent} - * @see https://developer.chrome.com/apps/usb#event-onDeviceRemoved - */ -chrome.usb.onDeviceRemoved; - - -/** - * @see https://developer.chrome.com/apps/serial - * @const - */ -chrome.serial = {}; - - - -/** - * @typedef {?{ - * persistent: (boolean|undefined), - * name: (string|undefined), - * bufferSize: (number|undefined), - * bitrate: (number|undefined), - * dataBits: (string|undefined), - * parityBit: (string|undefined), - * stopBits: (string|undefined), - * ctsFlowControl: (boolean|undefined), - * receiveTimeout: (number|undefined), - * sendTimeout: (number|undefined) - * }} - * @see https://developer.chrome.com/apps/serial#type-ConnectionOptions - */ -chrome.serial.ConnectionOptions; - - -/** - * @typedef {?{ - * connectionId: number, - * paused: boolean, - * persistent: boolean, - * name: string, - * bufferSize: number, - * receiveTimeout: number, - * sendTimeout: number, - * bitrate: (number|undefined), - * dataBits: (string|undefined), - * parityBit: (string|undefined), - * stopBits: (string|undefined), - * ctsFlowControl: (boolean|undefined) - * }} - * @see https://developer.chrome.com/apps/serial#type-ConnectionInfo - */ -chrome.serial.ConnectionInfo; - - -/** - * Returns information about available serial devices on the system. The - * list is regenerated each time this method is called. - * @param {function(!Array)} callback Invoked with a - * list of ports on complete. - * @see https://developer.chrome.com/apps/serial#method-getDevices - * @return {undefined} - */ -chrome.serial.getDevices = function(callback) {}; - - -/** - * Connects to a given serial port. - * @param {string} path The system path of the serial port to open. - * @param {!chrome.serial.ConnectionOptions| - * function(!chrome.serial.ConnectionInfo)} optionsOrCallback - * Port configuration options, or the callback invoked with the created - * ConnectionInfo on complete. - * @param {function(!chrome.serial.ConnectionInfo)=} opt_callback Invoked with - * the created ConnectionInfo on complete. - * @see https://developer.chrome.com/apps/serial#method-connect - * @return {undefined} - */ -chrome.serial.connect = function(path, optionsOrCallback, opt_callback) {}; - - -/** - * Update the option settings on an open serial port connection. - * @param {number} connectionId The id of the opened connection. - * @param {!chrome.serial.ConnectionOptions} options Port configuration - * options. - * @param {function(boolean)} callback Called when the configuration has - * completed. - * @see https://developer.chrome.com/apps/serial#method-update - * @return {undefined} - */ -chrome.serial.update = function(connectionId, options, callback) {}; - - -/** - * Disconnects from a serial port. - * @param {number} connectionId The id of the opened connection. - * @param {function(boolean)} callback Called when the connection - * has been closed. - * @see https://developer.chrome.com/apps/serial#method-disconnect - * @return {undefined} - */ -chrome.serial.disconnect = function(connectionId, callback) {}; - - -/** - * Pauses or unpauses an open connection. - * @param {number} connectionId The id of the opened connection. - * @param {boolean} paused Flag to indicate whether to pause or unpause. - * @param {function()} callback Called when the configuration has completed. - * @see https://developer.chrome.com/apps/serial#method-setPaused - * @return {undefined} - */ -chrome.serial.setPaused = function(connectionId, paused, callback) {}; - - -/** - * Retrieves the state of a given connection. - * @param {number} connectionId The id of the opened connection. - * @param {function(!chrome.serial.ConnectionInfo)} callback - * Called with connection state information when available. - * @see https://developer.chrome.com/apps/serial#method-getInfo - * @return {undefined} - */ -chrome.serial.getInfo = function(connectionId, callback) {}; - - -/** - * Retrieves the list of currently opened serial port connections owned by - * the application. - * @param {function(!Array)} callback - * Called with the list of |ConnectionInfo|s when available. - * @see https://developer.chrome.com/apps/serial#method-getConnections - * @return {undefined} - */ -chrome.serial.getConnections = function(callback) {}; - - -/** - * Writes data to the given connection. - * @param {number} connectionId The id of the opened connection. - * @param {!ArrayBuffer} data The data to send. - * @param {function(!Object)} callback Called when the operation has - * completed. - * @see https://developer.chrome.com/apps/serial#method-send - * @return {undefined} - */ -chrome.serial.send = function(connectionId, data, callback) {}; - - -/** - * Flushes all bytes in the given connection's input and output buffers. - * @param {number} connectionId The id of the opened connection. - * @param {function(boolean)} callback - * @see https://developer.chrome.com/apps/serial#method-flush - * @return {undefined} - */ -chrome.serial.flush = function(connectionId, callback) {}; - - - -/** - * Retrieves the state of control signals on a given connection. - * @param {number} connectionId The id of the opened connection. - * @param {function(!Object)} callback - * @see https://developer.chrome.com/apps/serial#method-getControlSignals - * @return {undefined} - */ -chrome.serial.getControlSignals = function(connectionId, callback) {}; - - -/** - * @typedef {?{ - * dtr: (boolean|undefined), - * rts: (boolean|undefined) - * }} - */ -chrome.serial.ControlSignals; - - -/** - * Sets the state of control signals on a given connection. - * @param {number} connectionId The id of the opened connection. - * @param {!chrome.serial.ControlSignals} signals - * The set of signal changes to send to the device. - * @param {function(boolean)} callback Called once the control signals - * have been set. - * @see https://developer.chrome.com/apps/serial#method-setControlSignals - * @return {undefined} - */ -chrome.serial.setControlSignals = function(connectionId, signals, callback) {}; - - -/** - * Event raised when data has been read from the connection. - * @type {!ChromeObjectEvent} - * @see https://developer.chrome.com/apps/serial#event-onReceive - */ -chrome.serial.onReceive; - - -/** - * Event raised when an error occurred while the runtime was waiting for - * data on the serial port. Once this event is raised, the connection may - * be set to paused. A "timeout" error does not pause the connection. - * @type {!ChromeObjectEvent} - * @see https://developer.chrome.com/apps/serial#event-onReceiveError - */ -chrome.serial.onReceiveError; - - - -//////////////////////////////////////////////////////////////////////////////// -/////////////////////////// Chrome Private APIs //////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - - -/** - * @const - */ -chrome.musicManagerPrivate = {}; - - -/** - * @param {function(string): void} callback - * @return {undefined} - */ -chrome.musicManagerPrivate.getDeviceId = function(callback) {}; - - -/** - * @const - */ -chrome.mediaGalleriesPrivate = {}; - - -/** - * @typedef {function({deviceId: string, deviceName: string}): void} - */ -chrome.mediaGalleriesPrivate.DeviceCallback; - - -/** - * @typedef {function({galleryId: string}): void} - */ -chrome.mediaGalleriesPrivate.GalleryChangeCallback; - - -/** - * @typedef {function({galleryId: string, success: boolean}): void} - */ -chrome.mediaGalleriesPrivate.AddGalleryWatchCallback; - - -/** - * @param {string} galleryId - * @param {!chrome.mediaGalleriesPrivate.AddGalleryWatchCallback} callback - * @return {undefined} - */ -chrome.mediaGalleriesPrivate.addGalleryWatch = function(galleryId, callback) {}; - - -/** - * @type {!chrome.mediaGalleriesPrivate.DeviceEvent} - * @deprecated Use {chrome.system.storage.onAttach}. - */ -chrome.mediaGalleriesPrivate.onDeviceAttached; - - -/** - * @type {!chrome.mediaGalleriesPrivate.DeviceEvent} - * @deprecated Use {chrome.system.storage.onDetach}. - */ -chrome.mediaGalleriesPrivate.onDeviceDetached; - - -/** - * @type {!chrome.mediaGalleriesPrivate.GalleryChangeEvent} - */ -chrome.mediaGalleriesPrivate.onGalleryChanged; - - - -/** - * @interface - * @extends {ChromeBaseEvent} - * @deprecated Use {chrome.system.storage.DeviceEvent}. - */ -chrome.mediaGalleriesPrivate.DeviceEvent = function() {}; - - -/** - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.mediaGalleriesPrivate.GalleryChangeEvent = function() {}; - - -/** - * safeBrowsingPrivate is a Private API for observing events and retrieving a - * referrer chain. - * @see https://cs.chromium.org/chromium/src/chrome/common/extensions/api/safe_browsing_private.idl - */ -chrome.safeBrowsingPrivate = {}; - -/** - * @enum {string} - */ -chrome.safeBrowsingPrivate.URLType = { - EVENT_URL: '', - LANDING_PAGE: '', - LANDING_REFERRER: '', - CLIENT_REDIRECT: '', - RECENT_NAVIGATION: '', - REFERRER: '', -}; - -/** - * @enum {string} - */ -chrome.safeBrowsingPrivate.NavigationInitiation = { - BROWSER_INITIATED: '', - RENDERER_INITIATED_WITHOUT_USER_GESTURE: '', - RENDERER_INITIATED_WITH_USER_GESTURE: '', -}; - -/** - * @typedef {{ - * url: string, - * userName: string, - * isPhishingUrl: boolean - * }} - */ -chrome.safeBrowsingPrivate.PolicySpecifiedPasswordReuse; - -/** - * @typedef {{ - * url: string, - * fileName: string, - * downloadDigestSha256: string, - * userName: string - * }} - */ -chrome.safeBrowsingPrivate.DangerousDownloadInfo; - -/** - * @typedef {{ - * url: string, - * reason: string, - * netErrorCode: (string|undefined), - * userName: string - * }} - */ -chrome.safeBrowsingPrivate.InterstitialInfo; - -/** - * @typedef {{ - * url: (string|undefined) - * }} - */ -chrome.safeBrowsingPrivate.ServerRedirect; - -/** - * @typedef {{ - * url: string, - * mainFrameUrl: (string|undefined), - * urlType: !chrome.safeBrowsingPrivate.URLType, - * ipAddresses: (!Array|undefined), - * referrerUrl: (string|undefined), - * referrerMainFrameUrl: (string|undefined), - * isRetargeting: (boolean|undefined), - * navigationTimeMs: (number|undefined), - * serverRedirectChain: - * (!Array|undefined), - * navigationInitiation: - * (!chrome.safeBrowsingPrivate.NavigationInitiation|undefined), - * maybeLaunchedByExternalApp: (boolean|undefined) - * }} - */ -chrome.safeBrowsingPrivate.ReferrerChainEntry; - -/** - * Gets referrer chain for the specified tab. - * @param {number} tabId Id of the tab from which to retrieve the referrer. - * @param {function(!Array):void} - * callback Called with the list of referrer chain entries. - */ -chrome.safeBrowsingPrivate.getReferrerChain = function(tabId, callback) {}; - -/** - * Fired when Chrome detects a reuse of a policy specified password. - * @type {!ChromeObjectEvent} - */ -chrome.safeBrowsingPrivate.onPolicySpecifiedPasswordReuseDetected; - -/** - * Fired when the user changed their policy specified password. - * @type {!ChromeStringEvent} - */ -chrome.safeBrowsingPrivate.onPolicySpecifiedPasswordChanged; - -/** - * Fired when the user opened a dangerous download. - * @type {!ChromeObjectEvent} - */ -chrome.safeBrowsingPrivate.onDangerousDownloadOpened; - -/** - * Fired when a security interstitial is shown to the user. - * @type {!ChromeObjectEvent} - */ -chrome.safeBrowsingPrivate.onSecurityInterstitialShown; - -/** - * Fired when the user clicked-through a security interstitial. - * @type {!ChromeObjectEvent} - */ -chrome.safeBrowsingPrivate.onSecurityInterstitialProceeded; - -/** - * WARNING(2014/08/14): This API is still under active initial development and - * unstable. The types are not well defined or documented, and this API - * definition here should not be used as an example for other APIs added to this - * file. Please contact mednik@ for questions on and maintenance for this API. - * @const - * @see http://goo.gl/afV8wB - */ -chrome.mdns = {}; - - -/** - * Data type sent to the event handler of chrome.mdns.onServiceList. - * @constructor - */ -chrome.mdns.MdnsService = function() {}; - - -/** @type {string} */ -chrome.mdns.MdnsService.prototype.serviceName; - - -/** @type {string} */ -chrome.mdns.MdnsService.prototype.serviceHostPort; - - -/** @type {string} */ -chrome.mdns.MdnsService.prototype.ipAddress; - - -/** @type {!Array} */ -chrome.mdns.MdnsService.prototype.serviceData; - - -/** - * Event whose listeners take an array of MdnsService parameter. - * - * The `addListener()` methods for these take more than one argument, so they - * cannot just extend `ChromeBaseEvent`. - * @interface - * @extends {ChromeBaseEventNoListeners} - */ -chrome.mdns.ServiceListEvent = function() {}; - - -/** - * @param {function(!Array): void} callback - * @param {!Object=} opt_filter - * @return {undefined} - */ -chrome.mdns.ServiceListEvent.prototype.addListener = function( - callback, opt_filter) {}; - - -/** - * @param {function(!Array): void} callback - * @return {undefined} - */ -chrome.mdns.ServiceListEvent.prototype.removeListener = function(callback) {}; - - -/** - * @param {function(!Array): void} callback - * @return {boolean} - */ -chrome.mdns.ServiceListEvent.prototype.hasListener = function(callback) {}; - - -/** @return {boolean} */ -chrome.mdns.ServiceListEvent.prototype.hasListeners = function() {}; - - -/** @type {!chrome.mdns.ServiceListEvent} */ -chrome.mdns.onServiceList; - - -/** - * @param {function()} callback - * @return {undefined} - */ -chrome.mdns.forceDiscovery = function(callback) {}; - - -/** - * @const - * @see http://goo.gl/79p5h5 - */ -chrome.gcdPrivate = {}; - - -/** - * Represents a GCD device discovered locally or registered to a given user. - * deviceId: Opaque device identifier to be passed to API. - * setupType: How this device was discovered. - * cloudId: Cloud identifier string. - * deviceName: Device human readable name. - * deviceType: Device type (camera, printer, etc). - * deviceDescription: Device human readable description. - * @typedef {?{ - * deviceId: string, - * setupType: string, - * cloudId: (string|undefined), - * deviceType: string, - * deviceName: string, - * deviceDescription: string - * }} - */ -chrome.gcdPrivate.Device; - - -/** - * Returns the list of cloud devices visible locally or available in the - * cloud for user account. - * @param {function(!Array): void} callback - * @return {undefined} - */ -chrome.gcdPrivate.getCloudDeviceList = function(callback) {}; - - -/** - * Queries network for local devices. Triggers onDeviceStateChanged and - * onDeviceRemoved events. Call this function *only* after registering for - * onDeviceStateChanged and onDeviceRemoved events, or it will do nothing. - * @return {undefined} - */ -chrome.gcdPrivate.queryForNewLocalDevices = function() {}; - - -/** - * Cache the WiFi password in the browser process for use during - * provisioning. This is done to allow the gathering of the wifi password to - * not be done while connected to the device's network. Callback is called - * with true if wifi password was cached and false if it was unavailable. - * @param {string} ssid - * @param {function(boolean): void} callback - * @return {undefined} - */ -chrome.gcdPrivate.prefetchWifiPassword = function(ssid, callback) {}; - - -/** - * Returns local device information. - * @param {string} serviceName The mDNS service name of the device. - * @param {function(string, !Object): void} - * callback Called when when the device info is available or on error. - * |status|: The status of the operation (success or type of error). - * |deviceInfo|: Content of /privet/info response. - * https://developers.google.com/cloud-devices/v1/reference/local-api/info - * @return {undefined} - */ -chrome.gcdPrivate.getDeviceInfo = function(serviceName, callback) {}; - - -/** - * Create new pairing session. - * @param {string} serviceName The mDNS service name of the device. - * @param {function(number, string, !Array): void} - * callback Called when the session is established or on error. 1st param, - * |sessionId|, is the session ID (identifies the session for future calls). - * 2nd param, |status|, is the status (success or type of error). 3rd param, - * |pairingTypes|, is a list of pairing types supported by this device. - * @return {undefined} - */ -chrome.gcdPrivate.createSession = function(serviceName, callback) {}; - - -/** - * Start pairing with the selected method. - * @param {number} sessionId - * @param {string} pairingType - * @param {function(string): void} callback - * @return {undefined} - */ -chrome.gcdPrivate.startPairing = function(sessionId, pairingType, callback) {}; - - -/** - * Confirm pairing code. - * @param {number} sessionId - * @param {string} code - * @param {function(string): void} callback - * @return {undefined} - */ -chrome.gcdPrivate.confirmCode = function(sessionId, code, callback) {}; - - -/** - * Send an encrypted message to the device. If the message is a setup message - * with a wifi ssid specified but no password, the password cached from - * prefetchWifiPassword() will be used and the call will fail if it's not - * available. For open networks use an empty string as the password. - * @param {number} sessionId - * @param {string} api The API path. - * @param {!Object} input The input message to be sent over the encrypted - * channel. - * @param {function(string, ?Object): void} callback - * @return {undefined} - */ -chrome.gcdPrivate.sendMessage = function(sessionId, api, input, callback) {}; - - -/** - * Terminate the session with the device. - * @param {number} sessionId - * @return {undefined} - */ -chrome.gcdPrivate.terminateSession = function(sessionId) {}; - - -/** - * Returns command definitions. - * @param {string} deviceId The device to get command definitions for. - * @param {function(!Object): void} callback The result callback. - * @return {undefined} - */ -chrome.gcdPrivate.getCommandDefinitions = function(deviceId, callback) {}; - - -/** - * Creates and sends a new command. - * @param {string} deviceId The device to send the command to. - * @param {number} expireInMs The number of milliseconds since now before the - * command expires. An expired command should not be executed by the device. - * Acceptable values are 10 sec (10000 ms) to 30 days (2592000000 ms), - * inclusive. All values outside that range will be replaced by 30 days. - * @param {!Object} command Described at - * https://developers.google.com/cloud-devices/v1/reference/commands. - * @param {function(!Object): void} callback The result callback. - * @return {undefined} - */ -chrome.gcdPrivate.insertCommand = function( - deviceId, expireInMs, command, callback) {}; - - -/** - * Returns a particular command. - * @param {string} commandId Unique command ID. - * @param {function(!Object): void} callback The result callback. - * @return {undefined} - */ -chrome.gcdPrivate.getCommand = function(commandId, callback) {}; - - -/** - * Cancels a command. - * @param {string} commandId Unique command ID. - * @param {function(!Object): void} callback The result callback. - * @return {undefined} - */ -chrome.gcdPrivate.cancelCommand = function(commandId, callback) {}; - - -/** - * Lists all commands in order of creation. - * @param {string} deviceId The device to send the command to. - * @param {string} byUser List all the commands issued by the user. Special - * value 'me' can be used to list by the current user. - * @param {string} state Command state. - * @param {function(!Array): void} callback The result callback. - * @return {undefined} - */ -chrome.gcdPrivate.getCommandsList = function( - deviceId, byUser, state, callback) {}; - - - -/** - * Event whose listeners take a chrome.gcdPrivate.Device. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.gcdPrivate.DeviceEvent = function() {}; - - -/** - * Fires when a device's state changes. When a listener is first added, this - * event fires for all known devices on the network. Afterwards, it will fire - * with device status updates. - * @type {!chrome.gcdPrivate.DeviceEvent} - */ -chrome.gcdPrivate.onDeviceStateChanged; - - -/** - * Fires when a given device disappears. - * |deviceId| The device that has disappeared. - * @type {!ChromeStringEvent} - */ -chrome.gcdPrivate.onDeviceRemoved; - - -/** - * @const - * @see https://cs.chromium.org/chromium/src/extensions/common/api/bluetooth_private.idl - */ -chrome.bluetoothPrivate = {}; - - - -/** @constructor */ -chrome.bluetoothPrivate.PairingEvent = function() {}; - - -/** @type {string} */ -chrome.bluetoothPrivate.PairingEvent.prototype.pairing; - - -/** @type {!chrome.bluetooth.Device} */ -chrome.bluetoothPrivate.PairingEvent.prototype.device; - - -/** @type {string|undefined} */ -chrome.bluetoothPrivate.PairingEvent.prototype.pincode; - - -/** @type {number|undefined} */ -chrome.bluetoothPrivate.PairingEvent.prototype.passkey; - - -/** @type {number|undefined} */ -chrome.bluetoothPrivate.PairingEvent.prototype.enteredKey; - - -/** - * @typedef {{ - * name: (string|undefined), - * powered: (boolean|undefined), - * discoverable: (boolean|undefined) - * }} - */ -chrome.bluetoothPrivate.NewAdapterState; - - -/** - * @typedef {{ - * device: !chrome.bluetooth.Device, - * response: (string|undefined), - * pincode: (string|undefined), - * passkey: (number|undefined), - * enteredKey: (number|undefined) - * }} - */ -chrome.bluetoothPrivate.SetPairingResponseOptions; - - -/** - * @param {!chrome.bluetoothPrivate.NewAdapterState} adapterState - * @param {function()} callback - * @return {undefined} - */ -chrome.bluetoothPrivate.setAdapterState = function(adapterState, callback) {}; - - -/** - * @param {!chrome.bluetoothPrivate.SetPairingResponseOptions} options - * @param {function()} callback - * @return {undefined} - */ -chrome.bluetoothPrivate.setPairingResponse = function(options, callback) {}; - - -/** - * @param {string} deviceAddress - * @param {function():void=} callback - */ -chrome.bluetoothPrivate.disconnectAll = function(deviceAddress, callback) {}; - - -/** - * @param {string} deviceAddress - * @param {function():void=} callback - * @return {undefined} - */ -chrome.bluetoothPrivate.forgetDevice = function(deviceAddress, callback) {}; - - -/** - * @typedef {{ - * transport: (!chrome.bluetoothPrivate.TransportType|undefined), - * uuids: ((string|!Array)|undefined), - * rssi: (number|undefined), - * pathloss: (number|undefined) - * }} - */ -chrome.bluetoothPrivate.DiscoveryFilter; - - -/** - * Set or clear discovery filter. - * @param {!chrome.bluetoothPrivate.DiscoveryFilter} discoveryFilter - * @param {function():void=} callback - */ -chrome.bluetoothPrivate.setDiscoveryFilter = function( - discoveryFilter, callback) {}; - - -/** - * Event whose listeners take a PairingEvent parameter. - * @interface - * @extends {ChromeBaseEvent} - */ -chrome.bluetoothPrivate.PairingEventEvent = function() {}; - - -/** @type {!chrome.bluetoothPrivate.PairingEventEvent} */ -chrome.bluetoothPrivate.onPairing; - - -/** - * @param {string} deviceAddress - * @param {function(): void=} callback - */ -chrome.bluetoothPrivate.pair = function(deviceAddress, callback) {}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/bluetoothPrivate#type-PairingResponse - */ -chrome.bluetoothPrivate.PairingResponse = { - CONFIRM: '', - REJECT: '', - CANCEL: '', -}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/bluetoothPrivate#type-PairingEventType - */ -chrome.bluetoothPrivate.PairingEventType = { - REQUEST_PINCODE: '', - DISPLAY_PINCODE: '', - REQUEST_PASSKEY: '', - DISPLAY_PASSKEY: '', - KEYS_ENTERED: '', - CONFIRM_PASSKEY: '', - REQUEST_AUTHORIZATION: '', - COMPLETE: '', -}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/bluetoothPrivate#type-ConnectResultType - */ -chrome.bluetoothPrivate.ConnectResultType = { - ALREADY_CONNECTED: '', - ATTRIBUTE_LENGTH_INVALID: '', - AUTH_CANCELED: '', - AUTH_FAILED: '', - AUTH_REJECTED: '', - AUTH_TIMEOUT: '', - CONNECTION_CONGESTED: '', - FAILED: '', - IN_PROGRESS: '', - INSUFFICIENT_ENCRYPTION: '', - OFFSET_INVALID: '', - READ_NOT_PERMITTED: '', - REQUEST_NOT_SUPPORTED: '', - SUCCESS: '', - UNKNOWN_ERROR: '', - UNSUPPORTED_DEVICE: '', - WRITE_NOT_PERMITTED: '', -}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/bluetoothPrivate#type-TransportType - */ -chrome.bluetoothPrivate.TransportType = { - LE: '', - BREDR: '', - DUAL: '', -}; - - -/** - * Connects to the given device. This will only throw an error if the device - * address is invalid or the device is already connected. Otherwise this will - * succeed and invoke |callback| with ConnectResultType. - * @param {string} deviceAddress - * @param {function(!chrome.bluetoothPrivate.ConnectResultType):void=} callback - */ -chrome.bluetoothPrivate.connect = function(deviceAddress, callback) {}; - - -/** - * @const - * @see http://goo.gl/XmVdHm - */ -chrome.inlineInstallPrivate = {}; - - -/** - * Installs the given app ID. - * @param {string} id - * @param {function(string, string): void=} opt_callback Response callback that - * returns two string: (1) an error string (or empty string on success) and - * (2) an error code in case of error - * @return {undefined} - */ -chrome.inlineInstallPrivate.install = function(id, opt_callback) {}; - - -/** - * @const - * @see https://goo.gl/7dvJFW - */ -chrome.wallpaper = {}; - - -/** - * @enum {string} - * @see https://goo.gl/7dvJFW#type-WallpaperLayout - */ -chrome.wallpaper.WallpaperLayout = { - STRETCH: '', - CENTER: '', - CENTER_CROPPED: '', -}; - - -/** - * Sets wallpaper to the image at url or wallpaperData with the specified - * layout. - * @param {{ - * data: (ArrayBuffer|undefined), - * url: (string|undefined), - * layout: (chrome.wallpaper.WallpaperLayout|string), - * filename: string, - * thumbnail: (boolean|undefined) - * }} details - * @param {function(ArrayBuffer=)} callback - * @return {undefined} - * @see https://goo.gl/7dvJFW#method-setWallpaper - */ -chrome.wallpaper.setWallpaper = function(details, callback) {}; - - -/** - * @const - * @see https://developer.chrome.com/extensions/downloads - */ -chrome.downloads = {}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/downloads#type-FilenameConflictAction - */ -chrome.downloads.FilenameConflictAction = { - UNIQUIFY: '', - OVERWRITE: '', - PROMPT: '' -}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/downloads#type-InterruptReason - */ -chrome.downloads.InterruptReason = { - FILE_FAILED: '', - FILE_ACCESS_DENIED: '', - FILE_NO_SPACE: '', - FILE_NAME_TOO_LONG: '', - FILE_TOO_LARGE: '', - FILE_VIRUS_INFECTED: '', - FILE_TRANSIENT_ERROR: '', - FILE_BLOCKED: '', - FILE_SECURITY_CHECK_FAILED: '', - FILE_TOO_SHORT: '', - FILE_HASH_MISMATCH: '', - NETWORK_FAILED: '', - NETWORK_TIMEOUT: '', - NETWORK_DISCONNECTED: '', - NETWORK_SERVER_DOWN: '', - NETWORK_INVALID_REQUEST: '', - SERVER_FAILED: '', - SERVER_NO_RANGE: '', - SERVER_BAD_CONTENT: '', - SERVER_UNAUTHORIZED: '', - SERVER_CERT_PROBLEM: '', - SERVER_FORBIDDEN: '', - SERVER_UNREACHABLE: '', - USER_CANCELED: '', - USER_SHUTDOWN: '', - CRASH: '', -}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/downloads#type-DangerType - */ -chrome.downloads.DangerType = { - FILE: '', - URL: '', - CONTENT: '', - UNCOMMON: '', - HOST: '', - UNWANTED: '', - SAFE: '', - ACCEPTED: '' -}; - - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/downloads#type-State - */ -chrome.downloads.State = { - IN_PROGRESS: '', - INTERRUPTED: '', - COMPLETE: '', -}; - - -/** - * @constructor - * @see https://developer.chrome.com/extensions/downloads#type-DownloadItem - */ -chrome.downloads.DownloadItem = function() {}; - - -/** @type {number} */ -chrome.downloads.DownloadItem.prototype.id; - - -/** @type {string} */ -chrome.downloads.DownloadItem.prototype.url; - - -/** @type {string} */ -chrome.downloads.DownloadItem.prototype.finalUrl; - - -/** @type {string} */ -chrome.downloads.DownloadItem.prototype.referrer; - - -/** @type {string} */ -chrome.downloads.DownloadItem.prototype.filename; - - -/** @type {boolean} */ -chrome.downloads.DownloadItem.prototype.incognito; - - -/** @type {!chrome.downloads.DangerType|string} */ -chrome.downloads.DownloadItem.prototype.danger; - - -/** @type {string} */ -chrome.downloads.DownloadItem.prototype.mime; - - -/** @type {string} */ -chrome.downloads.DownloadItem.prototype.startTime; - - -/** @type {?string} */ -chrome.downloads.DownloadItem.prototype.endTime; - - -/** @type {?string} */ -chrome.downloads.DownloadItem.prototype.estimatedEndTime; - - -/** @type {!chrome.downloads.State|string} */ -chrome.downloads.DownloadItem.prototype.state; - - -/** @type {boolean} */ -chrome.downloads.DownloadItem.prototype.paused; - - -/** @type {boolean} */ -chrome.downloads.DownloadItem.prototype.canResume; - - -/** @type {!chrome.downloads.InterruptReason|string|undefined} */ -chrome.downloads.DownloadItem.prototype.error; - - -/** @type {number} */ -chrome.downloads.DownloadItem.prototype.bytesReceived; - - -/** @type {number} */ -chrome.downloads.DownloadItem.prototype.totalBytes; - - -/** @type {number} */ -chrome.downloads.DownloadItem.prototype.fileSize; - - -/** @type {boolean} */ -chrome.downloads.DownloadItem.prototype.exists; - - -/** @type {?string} */ -chrome.downloads.DownloadItem.prototype.byExtensionId; - - -/** @type {?string} */ -chrome.downloads.DownloadItem.prototype.byExtensionName; - - -/** - * @constructor - * @see https://developer.chrome.com/extensions/downloads#type-StringDelta - */ -chrome.downloads.StringDelta = function() {}; - - -/** @type {?string} */ -chrome.downloads.StringDelta.prototype.previous; - - -/** @type {?string} */ -chrome.downloads.StringDelta.prototype.current; - - -/** - * @constructor - * @see https://developer.chrome.com/extensions/downloads#type-DoubleDelta - */ -chrome.downloads.DoubleDelta = function() {}; - - -/** @type {?number} */ -chrome.downloads.DoubleDelta.prototype.previous; - - -/** @type {?number} */ -chrome.downloads.DoubleDelta.prototype.current; - - -/** - * @constructor - * @see https://developer.chrome.com/extensions/downloads#type-BooleanDelta - */ -chrome.downloads.BooleanDelta = function() {}; - - -/** @type {?boolean} */ -chrome.downloads.BooleanDelta.prototype.previous; - - -/** @type {?boolean} */ -chrome.downloads.BooleanDelta.prototype.current; - - -/** - * @param {{ - * url: string, - * filename: (string|undefined), - * conflictAction: - * (!chrome.downloads.FilenameConflictAction|string|undefined), - * saveAs: (boolean|undefined), - * method: (string|undefined), - * headers: (!Array<{name:string, value:string}>|undefined), - * body: (string|undefined) - * }} details - * @param {function(number)=} opt_callback - * @see https://developer.chrome.com/extensions/downloads#method-download - */ -chrome.downloads.download = function(details, opt_callback) {}; - - -/** - * @typedef {?{ - * query: (!Array|undefined), - * startedBefore: (string|undefined), - * startedAfter: (string|undefined), - * endedBefore: (string|undefined), - * endedAfter: (string|undefined), - * totalBytesGreater: (number|undefined), - * totalBytesLess: (number|undefined), - * filenameRegex: (string|undefined), - * urlRegex: (string|undefined), - * finalUrlRegex: (string|undefined), - * limit: (number|undefined), - * orderedBy: (!Array|undefined), - * id: (number|undefined), - * url: (string|undefined), - * finalUrl: (string|undefined), - * filename: (string|undefined), - * danger: (!chrome.downloads.DangerType|string|undefined), - * mime: (string|undefined), - * startTime: (string|undefined), - * endTime: (string|undefined), - * state: (!chrome.downloads.State|string|undefined), - * paused: (boolean|undefined), - * error: (!chrome.downloads.InterruptReason|string|undefined), - * bytesReceived: (number|undefined), - * totalBytes: (number|undefined), - * fileSize: (number|undefined), - * exists: (boolean|undefined) - * }} - */ -chrome.downloads.Query; - - -/** - * @param {!chrome.downloads.Query} query - * @param {function(!Array)} callback - * @see https://developer.chrome.com/extensions/downloads#method-search - */ -chrome.downloads.search = function(query, callback) {}; - - -/** - * @param {number} id - * @param {function()=} opt_callback - * - * @see https://developer.chrome.com/extensions/downloads#method-pause - */ -chrome.downloads.pause = function(id, opt_callback) {}; - - -/** - * @param {number} id - * @param {function()=} opt_callback - * - * @see https://developer.chrome.com/extensions/downloads#method-resume - */ -chrome.downloads.resume = function(id, opt_callback) {}; - - -/** - * @param {number} id - * @param {function()=} opt_callback - * - * @see https://developer.chrome.com/extensions/downloads#method-cancel - */ -chrome.downloads.cancel = function(id, opt_callback) {}; - - -/** - * @param {number} id - * @param {{size:(number|undefined)}|function(string)} optionsOrCallback - * @param {function(string)=} opt_callback - * - * @see https://developer.chrome.com/extensions/downloads#method-getFileIcon - */ -chrome.downloads.getFileIcon = function(id, optionsOrCallback, opt_callback) {}; - - -/** - * @param {number} id - * @see https://developer.chrome.com/extensions/downloads#method-open - */ -chrome.downloads.open = function(id) {}; - - -/** - * @param {number} id - * @see https://developer.chrome.com/extensions/downloads#method-show - */ -chrome.downloads.show = function(id) {}; - - -/** - * @see https://developer.chrome.com/extensions/downloads#method-showDefaultFolder - */ -chrome.downloads.showDefaultFolder = function() {}; - - -/** - * @param {!chrome.downloads.Query} query - * @param {function(!Array)} callback - * @see https://developer.chrome.com/extensions/downloads#method-erase - */ -chrome.downloads.erase = function(query, callback) {}; - - -/** - * @param {number} id - * @param {function()=} opt_callback - * - * @see https://developer.chrome.com/extensions/downloads#method-removeFile - */ -chrome.downloads.removeFile = function(id, opt_callback) {}; - - -/** - * @param {number} id - * @param {function()=} opt_callback - * - * @see https://developer.chrome.com/extensions/downloads#method-acceptDanger - */ -chrome.downloads.acceptDanger = function(id, opt_callback) {}; - - -/** - * @param {number} id - * - * @see https://developer.chrome.com/extensions/downloads#method-drag - */ -chrome.downloads.drag = function(id) {}; - - -/** - * @param {boolean} enabled - * - * @see https://developer.chrome.com/extensions/downloads#method-setShelfEnabled - */ -chrome.downloads.setShelfEnabled = function(enabled) {}; - - -/** - * @interface - * @extends {ChromeBaseEvent} - * @see https://developer.chrome.com/extensions/downloads#event-onCreated - */ -chrome.downloads.CreatedEvent = function() {}; - - -/** - * @type {!chrome.downloads.CreatedEvent} - * https://developer.chrome.com/extensions/downloads#event-onCreated - */ -chrome.downloads.onCreated; - - -/** - * @type {!ChromeNumberEvent} - * https://developer.chrome.com/extensions/downloads#event-onErased - */ -chrome.downloads.onErased; - - -/** - * @type {!ChromeObjectEvent} - * https://developer.chrome.com/extensions/downloads#event-onChanged - */ -chrome.downloads.onChanged; - - -/** - * @typedef {?{ - * filename: string, - * conflictAction: (!chrome.downloads.FilenameConflictAction|undefined) - * }} - * @see https://developer.chrome.com/extensions/downloads#event-onDeterminingFilename - */ -chrome.downloads.FilenameSuggestion; - - -/** - * @interface - * @extends {ChromeBaseEvent< - * function( - * !chrome.downloads.DownloadItem, - * function(!chrome.downloads.FilenameSuggestion=))>} - * @see https://developer.chrome.com/extensions/downloads#event-onDeterminingFilename - */ -chrome.downloads.DeterminingFilenameEvent = function() {}; - - -/** - * @type {!chrome.downloads.DeterminingFilenameEvent} - * https://developer.chrome.com/extensions/downloads#event-onDeterminingFilename - */ -chrome.downloads.onDeterminingFilename; - - -/** - * @const - * @see https://developer.chrome.com/extensions/declarativeContent - */ -chrome.declarativeContent = {}; - - -/** - * @typedef {!{ - * pageUrl: (!UrlFilter|undefined), - * css: (!Array|undefined), - * isBookmarked: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/declarativeContent#type-PageStateMatcher - */ -chrome.declarativeContent.PageStateMatcherLiteral; - - -/** - * @constructor - * @param {!chrome.declarativeContent.PageStateMatcherLiteral=} literalValue - * @see https://developer.chrome.com/extensions/declarativeContent#type-PageStateMatcher - */ -chrome.declarativeContent.PageStateMatcher = function(literalValue) {}; - - -/** - * @constructor - * @see https://developer.chrome.com/extensions/declarativeContent#type-ShowPageAction - */ -chrome.declarativeContent.ShowPageAction = function() {}; - - -/** - * @typedef {!{ - * imageData: (!ImageData|!Object|undefined) - * }} - * @see https://developer.chrome.com/extensions/declarativeContent#type-SetIcon - */ -chrome.declarativeContent.SetIconLiteral; - - -/** - * @constructor - * @param {!chrome.declarativeContent.SetIconLiteral} literalValue - * @see https://developer.chrome.com/extensions/declarativeContent#type-SetIcon - */ -chrome.declarativeContent.SetIcon = function(literalValue) {}; - - -/** - * @typedef {!{ - * css: (!Array|undefined), - * js: (!Array|undefined), - * allFrames: (boolean|undefined), - * matchAboutBlank: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/declarativeContent#type-RequestContentScript - */ -chrome.declarativeContent.RequestContentScriptLiteral; - - -/** - * @constructor - * @param {!chrome.declarativeContent.RequestContentScriptLiteral=} literalValue - * @see https://developer.chrome.com/extensions/declarativeContent#type-RequestContentScript - */ -chrome.declarativeContent.RequestContentScript = function(literalValue) {}; - - -/** - * @type {!ChromeVoidEvent} - * @see https://developer.chrome.com/extensions/declarativeContent#event-onPageChanged - */ -chrome.declarativeContent.onPageChanged; - -/** - * @see https://developer.chrome.com/extensions/instanceID - * @const - */ -chrome.instanceID = {}; - -/** - * @param {function(string)} callback - * @see https://developer.chrome.com/extensions/instanceID#method-getID - */ -chrome.instanceID.getID = function(callback) {}; - -/** - * @param {function(number)} callback - * @see https://developer.chrome.com/extensions/instanceID#method-getCreationTime - */ -chrome.instanceID.getCreationTime = function(callback) {}; - -/** - * @typedef {{ - * authorizedEntity: string, - * scope: string, - * options: (!Object|undefined) - * }} - */ -chrome.instanceID.GetTokenParams; - -/** - * @param {!chrome.instanceID.GetTokenParams} getTokenParams - * @param {function(string)} callback - * @see https://developer.chrome.com/extensions/instanceID#method-getToken - */ -chrome.instanceID.getToken = function(getTokenParams, callback) {}; - -/** - * @typedef {{ - * authorizedEntity: string, - * scope: string, - * }} - */ -chrome.instanceID.DeleteTokenParams; - -/** - * @param {!chrome.instanceID.DeleteTokenParams} deleteTokenParams - * @param {function()} callback - * @see https://developer.chrome.com/extensions/instanceID#method-deleteToken - */ -chrome.instanceID.deleteToken = function(deleteTokenParams, callback) {}; - -/** - * @param {function()} callback - * @see https://developer.chrome.com/extensions/instanceID#method-deleteID - */ -chrome.instanceID.deleteID = function(callback) {}; - -/** - * @const - * @see https://developer.chrome.com/extensions/instanceID#event-onTokenRefresh - */ -chrome.instanceID.onTokenRefresh = {}; - -/** - * @param {function()} callback - * @see https://developer.chrome.com/extensions/instanceID#event-onTokenRefresh - */ -chrome.instanceID.onTokenRefresh.addListener = function(callback) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/chrome_send.js chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome_send.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/chrome_send.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/chrome_send.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Externs for global |chrome| object. These methods are defined - * in WebUIExtension::Install. - * @externs - */ - -/** - * @param {string} msg - * @param {Array=} opt_args - */ -chrome.send = function(msg, opt_args) {}; - -/** - * @param {string} name The name of the variable set with SetWebUIProperty() - * @return {string} JSON variable value - */ -chrome.getVariableValue = function(name) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/chromeos_info_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/chromeos_info_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/chromeos_info_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/chromeos_info_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,157 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.chromeosInfoPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: chromeosInfoPrivate - * @externs - */ - -/** @const */ -chrome.chromeosInfoPrivate = {}; - -/** - * @enum {string} - */ -chrome.chromeosInfoPrivate.PropertyName = { - TIMEZONE: 'timezone', - A11Y_LARGE_CURSOR_ENABLED: 'a11yLargeCursorEnabled', - A11Y_STICKY_KEYS_ENABLED: 'a11yStickyKeysEnabled', - A11Y_SPOKEN_FEEDBACK_ENABLED: 'a11ySpokenFeedbackEnabled', - A11Y_HIGH_CONTRAST_ENABLED: 'a11yHighContrastEnabled', - A11Y_SCREEN_MAGNIFIER_ENABLED: 'a11yScreenMagnifierEnabled', - A11Y_AUTO_CLICK_ENABLED: 'a11yAutoClickEnabled', - A11Y_VIRTUAL_KEYBOARD_ENABLED: 'a11yVirtualKeyboardEnabled', - A11Y_CARET_HIGHLIGHT_ENABLED: 'a11yCaretHighlightEnabled', - A11Y_CURSOR_HIGHLIGHT_ENABLED: 'a11yCursorHighlightEnabled', - A11Y_FOCUS_HIGHLIGHT_ENABLED: 'a11yFocusHighlightEnabled', - A11Y_SELECT_TO_SPEAK_ENABLED: 'a11ySelectToSpeakEnabled', - A11Y_SWITCH_ACCESS_ENABLED: 'a11ySwitchAccessEnabled', - A11Y_CURSOR_COLOR_ENABLED: 'a11yCursorColorEnabled', - A11Y_DOCKED_MAGNIFIER_ENABLED: 'a11yDockedMagnifierEnabled', - SEND_FUNCTION_KEYS: 'sendFunctionKeys', -}; - -/** - * @enum {string} - */ -chrome.chromeosInfoPrivate.SessionType = { - NORMAL: 'normal', - KIOSK: 'kiosk', - PUBLIC_SESSION: 'public session', -}; - -/** - * @enum {string} - */ -chrome.chromeosInfoPrivate.PlayStoreStatus = { - NOT_AVAILABLE: 'not available', - AVAILABLE: 'available', - ENABLED: 'enabled', -}; - -/** - * @enum {string} - */ -chrome.chromeosInfoPrivate.ManagedDeviceStatus = { - MANAGED: 'managed', - NOT_MANAGED: 'not managed', -}; - -/** - * @enum {string} - */ -chrome.chromeosInfoPrivate.DeviceType = { - CHROMEBASE: 'chromebase', - CHROMEBIT: 'chromebit', - CHROMEBOOK: 'chromebook', - CHROMEBOX: 'chromebox', - CHROMEDEVICE: 'chromedevice', -}; - -/** - * @enum {string} - */ -chrome.chromeosInfoPrivate.StylusStatus = { - UNSUPPORTED: 'unsupported', - SUPPORTED: 'supported', - SEEN: 'seen', -}; - -/** - * @enum {string} - */ -chrome.chromeosInfoPrivate.AssistantStatus = { - UNSUPPORTED: 'unsupported', - SUPPORTED: 'supported', -}; - -/** - * Fetches customization values for the given property names. See property names - * in the declaration of the returned dictionary. - * @param {!Array} propertyNames Chrome OS Property names - * @param {function({ - * board: (string|undefined), - * customizationId: (string|undefined), - * homeProvider: (string|undefined), - * hwid: (string|undefined), - * deviceRequisition: (string|undefined), - * isMeetDevice: (boolean|undefined), - * initialLocale: (string|undefined), - * isOwner: (boolean|undefined), - * sessionType: (!chrome.chromeosInfoPrivate.SessionType|undefined), - * playStoreStatus: (!chrome.chromeosInfoPrivate.PlayStoreStatus|undefined), - * managedDeviceStatus: (!chrome.chromeosInfoPrivate.ManagedDeviceStatus|undefined), - * deviceType: (!chrome.chromeosInfoPrivate.DeviceType|undefined), - * stylusStatus: (!chrome.chromeosInfoPrivate.StylusStatus|undefined), - * assistantStatus: (!chrome.chromeosInfoPrivate.AssistantStatus|undefined), - * clientId: (string|undefined), - * timezone: (string|undefined), - * a11yLargeCursorEnabled: (boolean|undefined), - * a11yStickyKeysEnabled: (boolean|undefined), - * a11ySpokenFeedbackEnabled: (boolean|undefined), - * a11yHighContrastEnabled: (boolean|undefined), - * a11yScreenMagnifierEnabled: (boolean|undefined), - * a11yAutoClickEnabled: (boolean|undefined), - * a11yVirtualKeyboardEnabled: (boolean|undefined), - * a11yCaretHighlightEnabled: (boolean|undefined), - * a11yCursorHighlightEnabled: (boolean|undefined), - * a11yFocusHighlightEnabled: (boolean|undefined), - * a11ySelectToSpeakEnabled: (boolean|undefined), - * a11ySwitchAccessEnabled: (boolean|undefined), - * a11yCursorColorEnabled: (boolean|undefined), - * a11yDockedMagnifierEnabled: (boolean|undefined), - * sendFunctionKeys: (boolean|undefined), - * supportedTimezones: (!Array>|undefined) - * }): void} callback - */ -chrome.chromeosInfoPrivate.get = function(propertyNames, callback) {}; - -/** - * Sets values for the given system property. - * @param {!chrome.chromeosInfoPrivate.PropertyName} propertyName Chrome OS - * system property name - * @param {*} propertyValue Chrome OS system property value - */ -chrome.chromeosInfoPrivate.set = function(propertyName, propertyValue) {}; - -/** - * Called to request tablet mode enabled status from the Chrome OS system. - * @param {function(boolean): void} callback Returns tablet mode enabled status - * as a boolean. - */ -chrome.chromeosInfoPrivate.isTabletModeEnabled = function(callback) {}; - -/** - * Called to request status of lacros browser enabled for primary user. - * @param {function(boolean): void} callback Returns true if called from within - * the Lacros context. - */ -chrome.chromeosInfoPrivate.isRunningOnLacros = function(callback) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/clipboard.js chromium-132.0.6834.159/third_party/closure_compiler/externs/clipboard.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/clipboard.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/clipboard.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.clipboard.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: clipboard - * @externs - */ - -/** @const */ -chrome.clipboard = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/clipboard#type-ImageType - */ -chrome.clipboard.ImageType = { - PNG: 'png', - JPEG: 'jpeg', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/clipboard#type-DataItemType - */ -chrome.clipboard.DataItemType = { - TEXT_PLAIN: 'textPlain', - TEXT_HTML: 'textHtml', -}; - -/** - * @typedef {{ - * type: !chrome.clipboard.DataItemType, - * data: string - * }} - * @see https://developer.chrome.com/extensions/clipboard#type-AdditionalDataItem - */ -chrome.clipboard.AdditionalDataItem; - -/** - * Sets image data to clipboard. - * @param {ArrayBuffer} imageData The encoded image data. - * @param {!chrome.clipboard.ImageType} type The type of image being passed. - * @param {!Array=} additionalItems - * Additional data items for describing image data. The callback is called - * with chrome.runtime.lastError set to error code if there is - * an error. Requires clipboard and clipboardWrite permissions. - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/clipboard#method-setImageData - */ -chrome.clipboard.setImageData = function(imageData, type, additionalItems, callback) {}; - -/** - * Fired when clipboard data changes. Requires clipboard and clipboardRead - * permissions for adding listener to chrome.clipboard.onClipboardDataChanged - * event. After this event fires, the clipboard data is available by calling - * document.execCommand('paste'). - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/clipboard#event-onClipboardDataChanged - */ -chrome.clipboard.onClipboardDataChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/command_line_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/command_line_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/command_line_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/command_line_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// 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. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.commandLinePrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: commandLinePrivate - * @externs - */ - -/** @const */ -chrome.commandLinePrivate = {}; - -/** - * Returns whether a switch is specified on the command line when launching - * Chrome. - * @param {string} name The name of a command line switch, without leading "--", - * such as "enable-experimental-extension-apis". - * @param {function(boolean): void} callback - */ -chrome.commandLinePrivate.hasSwitch = function(name, callback) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/crash_report_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/crash_report_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/crash_report_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/crash_report_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -// 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. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.crashReportPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: crashReportPrivate - * @externs - */ - -/** @const */ -chrome.crashReportPrivate = {}; - -/** - * @typedef {{ - * message: string, - * url: string, - * product: (string|undefined), - * version: (string|undefined), - * lineNumber: (number|undefined), - * columnNumber: (number|undefined), - * debugId: (string|undefined), - * stackTrace: (string|undefined) - * }} - */ -chrome.crashReportPrivate.ErrorInfo; - -/** - * Report and upload an error to Crash. - * @param {!chrome.crashReportPrivate.ErrorInfo} info Information about the - * error. - * @param {function(): void} callback Called when the error has been uploaded. - */ -chrome.crashReportPrivate.reportError = function(info, callback) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/events.js chromium-132.0.6834.159/third_party/closure_compiler/externs/events.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/events.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/events.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.events.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: events - * @externs - */ - -/** @const */ -chrome.events = {}; - -/** - * Description of a declarative rule for handling events. - * @typedef {{ - * id: (string|undefined), - * tags: (!Array|undefined), - * conditions: !Array<*>, - * actions: !Array<*>, - * priority: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/events#type-Rule - */ -chrome.events.Rule; - -/** - * An object which allows the addition and removal of listeners for a Chrome - * event. - * @typedef {Object} - * @see https://developer.chrome.com/extensions/events#type-Event - */ -chrome.events.Event; - -/** - * Filters URLs for various criteria. See event - * filtering. All criteria are case sensitive. - * @typedef {{ - * hostContains: (string|undefined), - * hostEquals: (string|undefined), - * hostPrefix: (string|undefined), - * hostSuffix: (string|undefined), - * pathContains: (string|undefined), - * pathEquals: (string|undefined), - * pathPrefix: (string|undefined), - * pathSuffix: (string|undefined), - * queryContains: (string|undefined), - * queryEquals: (string|undefined), - * queryPrefix: (string|undefined), - * querySuffix: (string|undefined), - * urlContains: (string|undefined), - * urlEquals: (string|undefined), - * urlMatches: (string|undefined), - * originAndPathMatches: (string|undefined), - * urlPrefix: (string|undefined), - * urlSuffix: (string|undefined), - * schemes: (!Array|undefined), - * ports: (!Array<(number|!Array)>|undefined), - * cidrBlocks: (!Array|undefined) - * }} - * @see https://developer.chrome.com/extensions/events#type-UrlFilter - */ -chrome.events.UrlFilter; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/extension_types.js chromium-132.0.6834.159/third_party/closure_compiler/externs/extension_types.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/extension_types.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/extension_types.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.extensionTypes.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: extensionTypes - * @externs - */ - -/** @const */ -chrome.extensionTypes = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/extensionTypes#type-ImageFormat - */ -chrome.extensionTypes.ImageFormat = { - JPEG: 'jpeg', - PNG: 'png', -}; - -/** - * Details about the format and quality of an image. - * @typedef {{ - * format: (!chrome.extensionTypes.ImageFormat|undefined), - * quality: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/extensionTypes#type-ImageDetails - */ -chrome.extensionTypes.ImageDetails; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/extensionTypes#type-RunAt - */ -chrome.extensionTypes.RunAt = { - DOCUMENT_START: 'document_start', - DOCUMENT_END: 'document_end', - DOCUMENT_IDLE: 'document_idle', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/extensionTypes#type-CSSOrigin - */ -chrome.extensionTypes.CSSOrigin = { - AUTHOR: 'author', - USER: 'user', -}; - -/** - * Details of the script or CSS to inject. Either the code or the file property - * must be set, but both may not be set at the same time. - * @typedef {{ - * code: (string|undefined), - * file: (string|undefined), - * allFrames: (boolean|undefined), - * frameId: (number|undefined), - * matchAboutBlank: (boolean|undefined), - * runAt: (!chrome.extensionTypes.RunAt|undefined), - * cssOrigin: (!chrome.extensionTypes.CSSOrigin|undefined) - * }} - * @see https://developer.chrome.com/extensions/extensionTypes#type-InjectDetails - */ -chrome.extensionTypes.InjectDetails; - -/** - * Details of the CSS to remove. Either the code or the file property must be - * set, but both may not be set at the same time. - * @typedef {{ - * code: (string|undefined), - * file: (string|undefined), - * allFrames: (boolean|undefined), - * frameId: (number|undefined), - * matchAboutBlank: (boolean|undefined), - * cssOrigin: (!chrome.extensionTypes.CSSOrigin|undefined) - * }} - * @see https://developer.chrome.com/extensions/extensionTypes#type-DeleteInjectionDetails - */ -chrome.extensionTypes.DeleteInjectionDetails; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/extensionTypes#type-FrameType - */ -chrome.extensionTypes.FrameType = { - OUTERMOST_FRAME: 'outermost_frame', - FENCED_FRAME: 'fenced_frame', - SUB_FRAME: 'sub_frame', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/extensionTypes#type-DocumentLifecycle - */ -chrome.extensionTypes.DocumentLifecycle = { - PRERENDER: 'prerender', - ACTIVE: 'active', - CACHED: 'cached', - PENDING_DELETION: 'pending_deletion', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/extensionTypes#type-ExecutionWorld - */ -chrome.extensionTypes.ExecutionWorld = { - ISOLATED: 'ISOLATED', - MAIN: 'MAIN', - USER_SCRIPT: 'USER_SCRIPT', -}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/file_system_provider.js chromium-132.0.6834.159/third_party/closure_compiler/externs/file_system_provider.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/file_system_provider.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/file_system_provider.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,670 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.fileSystemProvider.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: fileSystemProvider - * @externs - */ - -/** @const */ -chrome.fileSystemProvider = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-ProviderError - */ -chrome.fileSystemProvider.ProviderError = { - OK: 'OK', - FAILED: 'FAILED', - IN_USE: 'IN_USE', - EXISTS: 'EXISTS', - NOT_FOUND: 'NOT_FOUND', - ACCESS_DENIED: 'ACCESS_DENIED', - TOO_MANY_OPENED: 'TOO_MANY_OPENED', - NO_MEMORY: 'NO_MEMORY', - NO_SPACE: 'NO_SPACE', - NOT_A_DIRECTORY: 'NOT_A_DIRECTORY', - INVALID_OPERATION: 'INVALID_OPERATION', - SECURITY: 'SECURITY', - ABORT: 'ABORT', - NOT_A_FILE: 'NOT_A_FILE', - NOT_EMPTY: 'NOT_EMPTY', - INVALID_URL: 'INVALID_URL', - IO: 'IO', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-OpenFileMode - */ -chrome.fileSystemProvider.OpenFileMode = { - READ: 'READ', - WRITE: 'WRITE', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-ChangeType - */ -chrome.fileSystemProvider.ChangeType = { - CHANGED: 'CHANGED', - DELETED: 'DELETED', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-CommonActionId - */ -chrome.fileSystemProvider.CommonActionId = { - SAVE_FOR_OFFLINE: 'SAVE_FOR_OFFLINE', - OFFLINE_NOT_NECESSARY: 'OFFLINE_NOT_NECESSARY', - SHARE: 'SHARE', -}; - -/** - * @typedef {{ - * providerName: string, - * id: string - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-CloudIdentifier - */ -chrome.fileSystemProvider.CloudIdentifier; - -/** - * @typedef {{ - * versionTag: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-CloudFileInfo - */ -chrome.fileSystemProvider.CloudFileInfo; - -/** - * @typedef {{ - * isDirectory: (boolean|undefined), - * name: (string|undefined), - * size: (number|undefined), - * modificationTime: (Date|undefined), - * mimeType: (string|undefined), - * thumbnail: (string|undefined), - * cloudIdentifier: (!chrome.fileSystemProvider.CloudIdentifier|undefined), - * cloudFileInfo: (!chrome.fileSystemProvider.CloudFileInfo|undefined) - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-EntryMetadata - */ -chrome.fileSystemProvider.EntryMetadata; - -/** - * @typedef {{ - * entryPath: string, - * recursive: boolean, - * lastTag: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-Watcher - */ -chrome.fileSystemProvider.Watcher; - -/** - * @typedef {{ - * openRequestId: number, - * filePath: string, - * mode: !chrome.fileSystemProvider.OpenFileMode - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-OpenedFile - */ -chrome.fileSystemProvider.OpenedFile; - -/** - * @typedef {{ - * fileSystemId: string, - * displayName: string, - * writable: boolean, - * openedFilesLimit: number, - * openedFiles: !Array, - * supportsNotifyTag: (boolean|undefined), - * watchers: !Array - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-FileSystemInfo - */ -chrome.fileSystemProvider.FileSystemInfo; - -/** - * @typedef {{ - * fileSystemId: string, - * displayName: string, - * writable: (boolean|undefined), - * openedFilesLimit: (number|undefined), - * supportsNotifyTag: (boolean|undefined), - * persistent: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-MountOptions - */ -chrome.fileSystemProvider.MountOptions; - -/** - * @typedef {{ - * fileSystemId: string - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-UnmountOptions - */ -chrome.fileSystemProvider.UnmountOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-UnmountRequestedOptions - */ -chrome.fileSystemProvider.UnmountRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * entryPath: string, - * isDirectory: boolean, - * name: boolean, - * size: boolean, - * modificationTime: boolean, - * mimeType: boolean, - * thumbnail: boolean, - * cloudIdentifier: boolean, - * cloudFileInfo: boolean - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-GetMetadataRequestedOptions - */ -chrome.fileSystemProvider.GetMetadataRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * entryPaths: !Array - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-GetActionsRequestedOptions - */ -chrome.fileSystemProvider.GetActionsRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * directoryPath: string, - * isDirectory: boolean, - * name: boolean, - * size: boolean, - * modificationTime: boolean, - * mimeType: boolean, - * thumbnail: boolean - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-ReadDirectoryRequestedOptions - */ -chrome.fileSystemProvider.ReadDirectoryRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * filePath: string, - * mode: !chrome.fileSystemProvider.OpenFileMode - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-OpenFileRequestedOptions - */ -chrome.fileSystemProvider.OpenFileRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * openRequestId: number - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-CloseFileRequestedOptions - */ -chrome.fileSystemProvider.CloseFileRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * openRequestId: number, - * offset: number, - * length: number - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-ReadFileRequestedOptions - */ -chrome.fileSystemProvider.ReadFileRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * directoryPath: string, - * recursive: boolean - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-CreateDirectoryRequestedOptions - */ -chrome.fileSystemProvider.CreateDirectoryRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * entryPath: string, - * recursive: boolean - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-DeleteEntryRequestedOptions - */ -chrome.fileSystemProvider.DeleteEntryRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * filePath: string - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-CreateFileRequestedOptions - */ -chrome.fileSystemProvider.CreateFileRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * sourcePath: string, - * targetPath: string - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-CopyEntryRequestedOptions - */ -chrome.fileSystemProvider.CopyEntryRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * sourcePath: string, - * targetPath: string - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-MoveEntryRequestedOptions - */ -chrome.fileSystemProvider.MoveEntryRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * filePath: string, - * length: number - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-TruncateRequestedOptions - */ -chrome.fileSystemProvider.TruncateRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * openRequestId: number, - * offset: number, - * data: ArrayBuffer - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-WriteFileRequestedOptions - */ -chrome.fileSystemProvider.WriteFileRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * operationRequestId: number - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-AbortRequestedOptions - */ -chrome.fileSystemProvider.AbortRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * entryPath: string, - * recursive: boolean - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-AddWatcherRequestedOptions - */ -chrome.fileSystemProvider.AddWatcherRequestedOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * entryPath: string, - * recursive: boolean - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-RemoveWatcherRequestedOptions - */ -chrome.fileSystemProvider.RemoveWatcherRequestedOptions; - -/** - * @typedef {{ - * id: string, - * title: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-Action - */ -chrome.fileSystemProvider.Action; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number, - * entryPaths: !Array, - * actionId: string - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-ExecuteActionRequestedOptions - */ -chrome.fileSystemProvider.ExecuteActionRequestedOptions; - -/** - * @typedef {{ - * entryPath: string, - * changeType: !chrome.fileSystemProvider.ChangeType, - * cloudFileInfo: (!chrome.fileSystemProvider.CloudFileInfo|undefined) - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-Change - */ -chrome.fileSystemProvider.Change; - -/** - * @typedef {{ - * fileSystemId: string, - * observedPath: string, - * recursive: boolean, - * changeType: !chrome.fileSystemProvider.ChangeType, - * changes: (!Array|undefined), - * tag: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-NotifyOptions - */ -chrome.fileSystemProvider.NotifyOptions; - -/** - * @typedef {{ - * fileSystemId: string, - * requestId: number - * }} - * @see https://developer.chrome.com/extensions/fileSystemProvider#type-ConfigureRequestedOptions - */ -chrome.fileSystemProvider.ConfigureRequestedOptions; - -/** - *

Mounts a file system with the given fileSystemId and - * displayName. displayName will be shown in the left - * panel of the Files app. displayName can contain any characters - * including '/', but cannot be an empty string. displayName must - * be descriptive but doesn't have to be unique. The fileSystemId - * must not be an empty string.

Depending on the type of the file system - * being mounted, the source option must be set - * appropriately.

In case of an error, $(ref:runtime.lastError) will be - * set with a corresponding error code.

- * @param {!chrome.fileSystemProvider.MountOptions} options - * @param {function(): void=} callback A generic result callback to indicate - * success or failure. - * @see https://developer.chrome.com/extensions/fileSystemProvider#method-mount - */ -chrome.fileSystemProvider.mount = function(options, callback) {}; - -/** - *

Unmounts a file system with the given fileSystemId. It must - * be called after $(ref:onUnmountRequested) is invoked. Also, the providing - * extension can decide to perform unmounting if not requested (eg. in case of - * lost connection, or a file error).

In case of an error, - * $(ref:runtime.lastError) will be set with a corresponding error code.

- * @param {!chrome.fileSystemProvider.UnmountOptions} options - * @param {function(): void=} callback A generic result callback to indicate - * success or failure. - * @see https://developer.chrome.com/extensions/fileSystemProvider#method-unmount - */ -chrome.fileSystemProvider.unmount = function(options, callback) {}; - -/** - * Returns all file systems mounted by the extension. - * @param {function(!Array): void} - * callback Callback to receive the result of $(ref:getAll) function. - * @see https://developer.chrome.com/extensions/fileSystemProvider#method-getAll - */ -chrome.fileSystemProvider.getAll = function(callback) {}; - -/** - * Returns information about a file system with the passed - * fileSystemId. - * @param {string} fileSystemId - * @param {function(!chrome.fileSystemProvider.FileSystemInfo): void} callback - * Callback to receive the result of $(ref:get) function. - * @see https://developer.chrome.com/extensions/fileSystemProvider#method-get - */ -chrome.fileSystemProvider.get = function(fileSystemId, callback) {}; - -/** - *

Notifies about changes in the watched directory at - * observedPath in recursive mode. If the file system - * is mounted with supportsNotifyTag, then tag must be - * provided, and all changes since the last notification always reported, even - * if the system was shutdown. The last tag can be obtained with - * $(ref:getAll).

To use, the file_system_provider.notify - * manifest option must be set to true.

Value of tag can be - * any string which is unique per call, so it's possible to identify the last - * registered notification. Eg. if the providing extension starts after a - * reboot, and the last registered notification's tag is equal to "123", then it - * should call $(ref:notify) for all changes which happened since the change - * tagged as "123". It cannot be an empty string.

Not all providers are - * able to provide a tag, but if the file system has a changelog, then the tag - * can be eg. a change number, or a revision number.

Note that if a parent - * directory is removed, then all descendant entries are also removed, and if - * they are watched, then the API must be notified about the fact. Also, if a - * directory is renamed, then all descendant entries are in fact removed, as - * there is no entry under their original paths anymore.

In case of an - * error, $(ref:runtime.lastError) will be set will a corresponding error - * code.

- * @param {!chrome.fileSystemProvider.NotifyOptions} options - * @param {function(): void=} callback A generic result callback to indicate - * success or failure. - * @see https://developer.chrome.com/extensions/fileSystemProvider#method-notify - */ -chrome.fileSystemProvider.notify = function(options, callback) {}; - -/** - * Raised when unmounting for the file system with the fileSystemId - * identifier is requested. In the response, the $(ref:unmount) API method must - * be called together with successCallback. If unmounting is not - * possible (eg. due to a pending operation), then errorCallback - * must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onUnmountRequested - */ -chrome.fileSystemProvider.onUnmountRequested; - -/** - * Raised when metadata of a file or a directory at entryPath is - * requested. The metadata must be returned with the - * successCallback call. In case of an error, - * errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onGetMetadataRequested - */ -chrome.fileSystemProvider.onGetMetadataRequested; - -/** - * Raised when a list of actions for a set of files or directories at - * entryPaths is requested. All of the returned actions must be - * applicable to each entry. If there are no such actions, an empty array should - * be returned. The actions must be returned with the - * successCallback call. In case of an error, - * errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onGetActionsRequested - */ -chrome.fileSystemProvider.onGetActionsRequested; - -/** - * Raised when contents of a directory at directoryPath are - * requested. The results must be returned in chunks by calling the - * successCallback several times. In case of an error, - * errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onReadDirectoryRequested - */ -chrome.fileSystemProvider.onReadDirectoryRequested; - -/** - * Raised when opening a file at filePath is requested. If the file - * does not exist, then the operation must fail. Maximum number of files opened - * at once can be specified with MountOptions. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onOpenFileRequested - */ -chrome.fileSystemProvider.onOpenFileRequested; - -/** - * Raised when opening a file previously opened with openRequestId - * is requested to be closed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onCloseFileRequested - */ -chrome.fileSystemProvider.onCloseFileRequested; - -/** - * Raised when reading contents of a file opened previously with - * openRequestId is requested. The results must be returned in - * chunks by calling successCallback several times. In case of an - * error, errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onReadFileRequested - */ -chrome.fileSystemProvider.onReadFileRequested; - -/** - * Raised when creating a directory is requested. The operation must fail with - * the EXISTS error if the target directory already exists. If - * recursive is true, then all of the missing directories on the - * directory path must be created. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onCreateDirectoryRequested - */ -chrome.fileSystemProvider.onCreateDirectoryRequested; - -/** - * Raised when deleting an entry is requested. If recursive is - * true, and the entry is a directory, then all of the entries inside must be - * recursively deleted as well. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onDeleteEntryRequested - */ -chrome.fileSystemProvider.onDeleteEntryRequested; - -/** - * Raised when creating a file is requested. If the file already exists, then - * errorCallback must be called with the "EXISTS" - * error code. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onCreateFileRequested - */ -chrome.fileSystemProvider.onCreateFileRequested; - -/** - * Raised when copying an entry (recursively if a directory) is requested. If an - * error occurs, then errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onCopyEntryRequested - */ -chrome.fileSystemProvider.onCopyEntryRequested; - -/** - * Raised when moving an entry (recursively if a directory) is requested. If an - * error occurs, then errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onMoveEntryRequested - */ -chrome.fileSystemProvider.onMoveEntryRequested; - -/** - * Raised when truncating a file to a desired length is requested. If an error - * occurs, then errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onTruncateRequested - */ -chrome.fileSystemProvider.onTruncateRequested; - -/** - * Raised when writing contents to a file opened previously with - * openRequestId is requested. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onWriteFileRequested - */ -chrome.fileSystemProvider.onWriteFileRequested; - -/** - * Raised when aborting an operation with operationRequestId is - * requested. The operation executed with operationRequestId must - * be immediately stopped and successCallback of this abort request - * executed. If aborting fails, then errorCallback must be called. - * Note, that callbacks of the aborted operation must not be called, as they - * will be ignored. Despite calling errorCallback, the request may - * be forcibly aborted. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onAbortRequested - */ -chrome.fileSystemProvider.onAbortRequested; - -/** - * Raised when showing a configuration dialog for fileSystemId is - * requested. If it's handled, the - * file_system_provider.configurable manfiest option must be set to - * true. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onConfigureRequested - */ -chrome.fileSystemProvider.onConfigureRequested; - -/** - * Raised when showing a dialog for mounting a new file system is requested. If - * the extension/app is a file handler, then this event shouldn't be handled. - * Instead app.runtime.onLaunched should be handled in order to - * mount new file systems when a file is opened. For multiple mounts, the - * file_system_provider.multiple_mounts manifest option must be set - * to true. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onMountRequested - */ -chrome.fileSystemProvider.onMountRequested; - -/** - * Raised when setting a new directory watcher is requested. If an error occurs, - * then errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onAddWatcherRequested - */ -chrome.fileSystemProvider.onAddWatcherRequested; - -/** - * Raised when the watcher should be removed. If an error occurs, then - * errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onRemoveWatcherRequested - */ -chrome.fileSystemProvider.onRemoveWatcherRequested; - -/** - * Raised when executing an action for a set of files or directories is\ - * requested. After the action is completed, successCallback must - * be called. On error, errorCallback must be called. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/fileSystemProvider#event-onExecuteActionRequested - */ -chrome.fileSystemProvider.onExecuteActionRequested; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/image_loader_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/image_loader_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/image_loader_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/image_loader_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.imageLoaderPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: imageLoaderPrivate - * @externs - */ - -/** @const */ -chrome.imageLoaderPrivate = {}; - -/** - * For a file in DriveFS, retrieves its thumbnail. If |cropToSquare| is true, - * returns a thumbnail appropriate for file list or grid views; otherwise, - * returns a thumbnail appropriate for quickview. - * @param {string} url - * @param {boolean} cropToSquare - * @param {function(string): void} callback |thumbnailDataUrl| A data URL for - * the thumbnail; |thumbnailDataUrl| is empty if no thumbnail was available. - */ -chrome.imageLoaderPrivate.getDriveThumbnail = function(url, cropToSquare, callback) {}; - -/** - * For a local PDF file, retrieves its thumbnail with a given |width| and - * |height|. - * @param {string} url - * @param {number} width - * @param {number} height - * @param {function(string): void} callback |thumbnailDataUrl| A data URL for - * the thumbnail; |thumbnailDataUrl| is empty if no thumbnail was available. - */ -chrome.imageLoaderPrivate.getPdfThumbnail = function(url, width, height, callback) {}; - -/** - * Retrieves a thumbnail of an ARC DocumentsProvider file, closely matching the - * hinted size specified by |widthHint| and |heightHint|, but not necessarily - * the exact size. |callback| is called with thumbnail data encoded as a data - * URL. If the document does not support thumbnails, |callback| is called with - * an empty string. Note: The thumbnail data may originate from third-party - * application code, and is untrustworthy (Security). - * @param {string} url - * @param {number} widthHint - * @param {number} heightHint - * @param {function(string): void} callback |thumbnailDataUrl| A data URL for - * the thumbnail; |thumbnailDataUrl| is empty if no thumbnail was available. - */ -chrome.imageLoaderPrivate.getArcDocumentsProviderThumbnail = function(url, widthHint, heightHint, callback) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/input_method_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/input_method_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/input_method_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/input_method_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,460 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.inputMethodPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: inputMethodPrivate - * @externs - */ - -/** @const */ -chrome.inputMethodPrivate = {}; - -/** - * @enum {string} - */ -chrome.inputMethodPrivate.MenuItemStyle = { - CHECK: 'check', - RADIO: 'radio', - SEPARATOR: 'separator', -}; - -/** - * A menu item used by an input method to interact with the user from the - * language menu. - * @typedef {{ - * id: string, - * label: (string|undefined), - * style: (!chrome.inputMethodPrivate.MenuItemStyle|undefined), - * visible: (boolean|undefined), - * checked: (boolean|undefined), - * enabled: (boolean|undefined) - * }} - */ -chrome.inputMethodPrivate.MenuItem; - -/** - * @enum {string} - */ -chrome.inputMethodPrivate.UnderlineStyle = { - UNDERLINE: 'underline', - DOUBLE_UNDERLINE: 'doubleUnderline', - NO_UNDERLINE: 'noUnderline', -}; - -/** - * @enum {string} - */ -chrome.inputMethodPrivate.FocusReason = { - MOUSE: 'mouse', - TOUCH: 'touch', - PEN: 'pen', - OTHER: 'other', -}; - -/** - * @enum {string} - */ -chrome.inputMethodPrivate.InputModeType = { - NO_KEYBOARD: 'noKeyboard', - TEXT: 'text', - TEL: 'tel', - URL: 'url', - EMAIL: 'email', - NUMERIC: 'numeric', - DECIMAL: 'decimal', - SEARCH: 'search', -}; - -/** - * @enum {string} - */ -chrome.inputMethodPrivate.InputContextType = { - TEXT: 'text', - SEARCH: 'search', - TEL: 'tel', - URL: 'url', - EMAIL: 'email', - NUMBER: 'number', - PASSWORD: 'password', - NULL: 'null', -}; - -/** - * @enum {string} - */ -chrome.inputMethodPrivate.AutoCapitalizeType = { - OFF: 'off', - CHARACTERS: 'characters', - WORDS: 'words', - SENTENCES: 'sentences', -}; - -/** - * @enum {string} - */ -chrome.inputMethodPrivate.LanguagePackStatus = { - UNKNOWN: 'unknown', - NOT_INSTALLED: 'notInstalled', - IN_PROGRESS: 'inProgress', - INSTALLED: 'installed', - ERROR_OTHER: 'errorOther', - ERROR_NEEDS_REBOOT: 'errorNeedsReboot', -}; - -/** - * Object returned by callbacks when the status of language packs change. - * @typedef {{ - * engineIds: !Array, - * status: !chrome.inputMethodPrivate.LanguagePackStatus - * }} - */ -chrome.inputMethodPrivate.LanguagePackStatusChange; - -/** - * Describes an input Context - * @typedef {{ - * contextID: number, - * type: !chrome.inputMethodPrivate.InputContextType, - * mode: !chrome.inputMethodPrivate.InputModeType, - * autoCorrect: boolean, - * autoComplete: boolean, - * autoCapitalize: !chrome.inputMethodPrivate.AutoCapitalizeType, - * spellCheck: boolean, - * shouldDoLearning: boolean, - * focusReason: !chrome.inputMethodPrivate.FocusReason, - * appKey: (string|undefined) - * }} - */ -chrome.inputMethodPrivate.InputContext; - -/** - * User preference settings for a specific input method. Japanese input methods - * are not included because they are managed separately by Mozc module. - * @typedef {{ - * enableCompletion: (boolean|undefined), - * enableDoubleSpacePeriod: (boolean|undefined), - * enableGestureTyping: (boolean|undefined), - * enablePrediction: (boolean|undefined), - * enableSoundOnKeypress: (boolean|undefined), - * physicalKeyboardAutoCorrectionEnabledByDefault: (boolean|undefined), - * physicalKeyboardAutoCorrectionLevel: (number|undefined), - * physicalKeyboardEnableCapitalization: (boolean|undefined), - * physicalKeyboardEnableDiacriticsOnLongpress: (boolean|undefined), - * physicalKeyboardEnablePredictiveWriting: (boolean|undefined), - * virtualKeyboardAutoCorrectionLevel: (number|undefined), - * virtualKeyboardEnableCapitalization: (boolean|undefined), - * xkbLayout: (string|undefined), - * koreanEnableSyllableInput: (boolean|undefined), - * koreanKeyboardLayout: (string|undefined), - * koreanShowHangulCandidate: (boolean|undefined), - * pinyinChinesePunctuation: (boolean|undefined), - * pinyinDefaultChinese: (boolean|undefined), - * pinyinEnableFuzzy: (boolean|undefined), - * pinyinEnableLowerPaging: (boolean|undefined), - * pinyinEnableUpperPaging: (boolean|undefined), - * pinyinFullWidthCharacter: (boolean|undefined), - * pinyinFuzzyConfig: ({ - * an_ang: (boolean|undefined), - * c_ch: (boolean|undefined), - * en_eng: (boolean|undefined), - * f_h: (boolean|undefined), - * ian_iang: (boolean|undefined), - * in_ing: (boolean|undefined), - * k_g: (boolean|undefined), - * l_n: (boolean|undefined), - * r_l: (boolean|undefined), - * s_sh: (boolean|undefined), - * uan_uang: (boolean|undefined), - * z_zh: (boolean|undefined) - * }|undefined), - * zhuyinKeyboardLayout: (string|undefined), - * zhuyinPageSize: (number|undefined), - * zhuyinSelectKeys: (string|undefined), - * vietnameseVniAllowFlexibleDiacritics: (boolean|undefined), - * vietnameseVniNewStyleToneMarkPlacement: (boolean|undefined), - * vietnameseVniInsertDoubleHornOnUo: (boolean|undefined), - * vietnameseVniShowUnderline: (boolean|undefined), - * vietnameseTelexAllowFlexibleDiacritics: (boolean|undefined), - * vietnameseTelexNewStyleToneMarkPlacement: (boolean|undefined), - * vietnameseTelexInsertDoubleHornOnUo: (boolean|undefined), - * vietnameseTelexInsertUHornOnW: (boolean|undefined), - * vietnameseTelexShowUnderline: (boolean|undefined) - * }} - */ -chrome.inputMethodPrivate.InputMethodSettings; - -/** - * Gets configurations for input methods. - * @param {function({ - * isPhysicalKeyboardAutocorrectEnabled: boolean, - * isImeMenuActivated: boolean - * }): void} callback Callback which is called with the config object. - */ -chrome.inputMethodPrivate.getInputMethodConfig = function(callback) {}; - -/** - * Gets all enabled input methods, sorted in ascending order of their localized - * full display names, according to the lexicographical order defined by the - * current system locale aka. display language. - * @param {function(!Array<{ - * id: string, - * name: string, - * indicator: string - * }>): void} callback Callback which is called with the input method objects. - */ -chrome.inputMethodPrivate.getInputMethods = function(callback) {}; - -/** - * Gets the current input method. - * @param {function(string): void} callback Callback which is called with the - * current input method. - */ -chrome.inputMethodPrivate.getCurrentInputMethod = function(callback) {}; - -/** - * Sets the current input method. - * @param {string} inputMethodId The input method ID to be set as current input - * method. - * @param {function(): void=} callback Callback which is called once the current - * input method is set. If unsuccessful $(ref:runtime.lastError) is set. - */ -chrome.inputMethodPrivate.setCurrentInputMethod = function(inputMethodId, callback) {}; - -/** - * Switches to the last used input method. If no last used input method, this is - * a no-op. - * @param {function(): void=} callback Callback which is called once the input - * method is swapped (if applicable). If unsuccessful - * $(ref:runtime.lastError) is set. - */ -chrome.inputMethodPrivate.switchToLastUsedInputMethod = function(callback) {}; - -/** - * Fetches a list of all the words currently in the dictionary. - * @param {function(!Array): void} callback Callback which is called - * once the list of dictionary words are ready. - */ -chrome.inputMethodPrivate.fetchAllDictionaryWords = function(callback) {}; - -/** - * Adds a single word to be stored in the dictionary. - * @param {string} word A new word to add to the dictionary. - * @param {function(): void=} callback Callback which is called once the word is - * added. If unsuccessful $(ref:runtime.lastError) is set. - */ -chrome.inputMethodPrivate.addWordToDictionary = function(word, callback) {}; - -/** - * Sets the XKB layout for the given input method. - * @param {string} xkb_name The XKB layout name. - * @param {function(): void=} callback Callback which is called when the layout - * is set. - */ -chrome.inputMethodPrivate.setXkbLayout = function(xkb_name, callback) {}; - -/** - * Commits the text currently being composed without moving the selected text - * range. This is a no-op if the context is incorrect. - * @param {{ - * contextID: number - * }} parameters - * @param {function(): void=} callback Called when the operation completes. - */ -chrome.inputMethodPrivate.finishComposingText = function(parameters, callback) {}; - -/** - * Shows the input view window. If the input view window is already shown, this - * function will do nothing. - * @param {function(): void=} callback Called when the operation completes. - */ -chrome.inputMethodPrivate.showInputView = function(callback) {}; - -/** - * Hides the input view window. If the input view window is already hidden, this - * function will do nothing. - * @param {function(): void=} callback Called when the operation completes. - */ -chrome.inputMethodPrivate.hideInputView = function(callback) {}; - -/** - * Opens the options page for the input method extension. If the input method - * does not have options, this function will do nothing. - * @param {string} inputMethodId ID of the input method to open options for. - */ -chrome.inputMethodPrivate.openOptionsPage = function(inputMethodId) {}; - -/** - * Gets the surrounding text of the current selection. WARNING: This could - * return a stale cache that doesn't reflect reality, due to async between IMF - * and TextInputClient. - * @param {number} beforeLength The number of characters before the current - * selection. - * @param {number} afterLength The number of characters after the current - * selection. - * @param {function({ - * before: string, - * selected: string, - * after: string - * }): void} callback Callback which is called to provide the result - */ -chrome.inputMethodPrivate.getSurroundingText = function(beforeLength, afterLength, callback) {}; - -/** - * Gets the current values of all settings for a particular input method - * @param {string} engineID The ID of the engine (e.g. 'zh-t-i0-pinyin', - * 'xkb:us::eng') - * @param {function((!chrome.inputMethodPrivate.InputMethodSettings|undefined)): void} - * callback Callback to receive the settings - */ -chrome.inputMethodPrivate.getSettings = function(engineID, callback) {}; - -/** - * Sets the value of all settings for a particular input method - * @param {string} engineID The ID of the engine (e.g. 'zh-t-i0-pinyin', - * 'xkb:us::eng') - * @param {!chrome.inputMethodPrivate.InputMethodSettings} settings The settings - * to set - * @param {function(): void=} callback Callback to notify that the new value has - * been set - */ -chrome.inputMethodPrivate.setSettings = function(engineID, settings, callback) {}; - -/** - * (Deprecated) Set the composition range. If this extension does not own the - * active IME, this fails. Use setComposingRange instead. - * @param {{ - * contextID: number, - * selectionBefore: number, - * selectionAfter: number, - * segments: (!Array<{ - * start: number, - * end: number, - * style: !chrome.inputMethodPrivate.UnderlineStyle - * }>|undefined) - * }} parameters - * @param {function(boolean): void=} callback Called when the operation - * completes with a boolean indicating if the text was accepted or not. On - * failure, $(ref:runtime.lastError) is set. - */ -chrome.inputMethodPrivate.setCompositionRange = function(parameters, callback) {}; - -/** - * Resets the current engine to its initial state. Fires an OnReset event. - */ -chrome.inputMethodPrivate.reset = function() {}; - -/** - * Called after a word has been autocorrected to show some UI for autocorrect. - * @param {{ - * contextID: number, - * typedWord: string, - * correctedWord: string, - * startIndex: number - * }} parameters - */ -chrome.inputMethodPrivate.onAutocorrect = function(parameters) {}; - -/** - * Notifies Chrome that the current input method is ready to accept key events - * from Tast. - */ -chrome.inputMethodPrivate.notifyInputMethodReadyForTesting = function() {}; - -/** - * Gets the aggregate status of all language packs for a given input method. - * @param {string} inputMethodId Fully qualified ID of the input method - * @param {function(!chrome.inputMethodPrivate.LanguagePackStatus): void} - * callback Called with a LanguagePackStatus when the operation completes. - */ -chrome.inputMethodPrivate.getLanguagePackStatus = function(inputMethodId, callback) {}; - -/** - * Fired when the caret bounds change. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onCaretBoundsChanged; - -/** - * Fired when the input method is changed. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onChanged; - -/** - * Fired when the custom spelling dictionary is loaded. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onDictionaryLoaded; - -/** - * Fired when words are added or removed from the custom spelling dictionary. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onDictionaryChanged; - -/** - * Fired when the IME menu is activated or deactivated. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onImeMenuActivationChanged; - -/** - * Fired when the input method or the list of active input method IDs is - * changed. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onImeMenuListChanged; - -/** - * Fired when the input.ime.setMenuItems or input.ime.updateMenuItems API is - * called. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onImeMenuItemsChanged; - -/** - * This event is sent when focus enters a text box. It is sent to all extensions - * that are listening to this event, and enabled by the user. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onFocus; - -/** - * This event is sent when the settings for any input method changed. It is sent - * to all extensions that are listening to this event, and enabled by the user. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onSettingsChanged; - -/** - * This event is sent when the screen is being mirrored or the desktop is being - * cast. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onScreenProjectionChanged; - -/** - * This event is sent when a new set of suggestions has been generated - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onSuggestionsChanged; - -/** - * This event is sent when input method options are changed. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onInputMethodOptionsChanged; - -/** - * This event is sent when any IME's language pack status is changed. - * @type {!ChromeEvent} - */ -chrome.inputMethodPrivate.onLanguagePackStatusChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/language_settings_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/language_settings_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/language_settings_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/language_settings_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,215 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.languageSettingsPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: languageSettingsPrivate - * @externs - */ - -/** @const */ -chrome.languageSettingsPrivate = {}; - -/** - * @enum {string} - */ -chrome.languageSettingsPrivate.MoveType = { - TOP: 'TOP', - UP: 'UP', - DOWN: 'DOWN', - UNKNOWN: 'UNKNOWN', -}; - -/** - * @typedef {{ - * code: string, - * displayName: string, - * nativeDisplayName: string, - * supportsUI: (boolean|undefined), - * supportsSpellcheck: (boolean|undefined), - * supportsTranslate: (boolean|undefined), - * isProhibitedLanguage: (boolean|undefined) - * }} - */ -chrome.languageSettingsPrivate.Language; - -/** - * @typedef {{ - * languageCode: string, - * isReady: boolean, - * isDownloading: (boolean|undefined), - * downloadFailed: (boolean|undefined) - * }} - */ -chrome.languageSettingsPrivate.SpellcheckDictionaryStatus; - -/** - * @typedef {{ - * id: string, - * displayName: string, - * languageCodes: !Array, - * tags: !Array, - * enabled: (boolean|undefined), - * hasOptionsPage: (boolean|undefined), - * isProhibitedByPolicy: (boolean|undefined) - * }} - */ -chrome.languageSettingsPrivate.InputMethod; - -/** - * @typedef {{ - * componentExtensionImes: !Array, - * thirdPartyExtensionImes: !Array - * }} - */ -chrome.languageSettingsPrivate.InputMethodLists; - -/** - * Gets languages available for translate, spell checking, input and locale. - * @param {function(!Array): void} - * callback - */ -chrome.languageSettingsPrivate.getLanguageList = function(callback) {}; - -/** - * Enables a language, adding it to the Accept-Language list (used to decide - * which languages to translate, generate the Accept-Language header, etc.). - * @param {string} languageCode - */ -chrome.languageSettingsPrivate.enableLanguage = function(languageCode) {}; - -/** - * Disables a language, removing it from the Accept-Language list. - * @param {string} languageCode - */ -chrome.languageSettingsPrivate.disableLanguage = function(languageCode) {}; - -/** - * Enables or disables translation for a given language. - * @param {string} languageCode - * @param {boolean} enable - */ -chrome.languageSettingsPrivate.setEnableTranslationForLanguage = function(languageCode, enable) {}; - -/** - * Moves a language inside the language list. - * @param {string} languageCode - * @param {!chrome.languageSettingsPrivate.MoveType} moveType - */ -chrome.languageSettingsPrivate.moveLanguage = function(languageCode, moveType) {}; - -/** - * Gets languages that should always be automatically translated. - * @param {function(!Array): void} callback - */ -chrome.languageSettingsPrivate.getAlwaysTranslateLanguages = function(callback) {}; - -/** - * Sets whether a given language should always be automatically translated. - * @param {string} languageCode - * @param {boolean} alwaysTranslate - */ -chrome.languageSettingsPrivate.setLanguageAlwaysTranslateState = function(languageCode, alwaysTranslate) {}; - -/** - * Gets languages that should never be offered to translate. - * @param {function(!Array): void} callback - */ -chrome.languageSettingsPrivate.getNeverTranslateLanguages = function(callback) {}; - -/** - * Gets the current status of the chosen spell check dictionaries. - * @param {function(!Array): void} - * callback - */ -chrome.languageSettingsPrivate.getSpellcheckDictionaryStatuses = function(callback) {}; - -/** - * Gets the custom spell check words, in sorted order. - * @param {function(!Array): void} callback - */ -chrome.languageSettingsPrivate.getSpellcheckWords = function(callback) {}; - -/** - * Adds a word to the custom dictionary. - * @param {string} word - */ -chrome.languageSettingsPrivate.addSpellcheckWord = function(word) {}; - -/** - * Removes a word from the custom dictionary. - * @param {string} word - */ -chrome.languageSettingsPrivate.removeSpellcheckWord = function(word) {}; - -/** - * Gets the translate target language (in most cases, the display locale). - * @param {function(string): void} callback - */ -chrome.languageSettingsPrivate.getTranslateTargetLanguage = function(callback) {}; - -/** - * Sets the translate target language given a language code. - * @param {string} languageCode - */ -chrome.languageSettingsPrivate.setTranslateTargetLanguage = function(languageCode) {}; - -/** - * Gets all supported input methods, including third-party IMEs. Chrome OS only. - * @param {function(!chrome.languageSettingsPrivate.InputMethodLists): void} - * callback - */ -chrome.languageSettingsPrivate.getInputMethodLists = function(callback) {}; - -/** - * Adds the input method to the current user's list of enabled input methods, - * enabling the input method for the current user. Chrome OS only. - * @param {string} inputMethodId - */ -chrome.languageSettingsPrivate.addInputMethod = function(inputMethodId) {}; - -/** - * Removes the input method from the current user's list of enabled input - * methods, disabling the input method for the current user. Chrome OS only. - * @param {string} inputMethodId - */ -chrome.languageSettingsPrivate.removeInputMethod = function(inputMethodId) {}; - -/** - * Tries to download the dictionary after a failed download. - * @param {string} languageCode - */ -chrome.languageSettingsPrivate.retryDownloadDictionary = function(languageCode) {}; - -/** - * Called when the pref for the dictionaries used for spell checking changes or - * the status of one of the spell check dictionaries changes. - * @type {!ChromeEvent} - */ -chrome.languageSettingsPrivate.onSpellcheckDictionariesChanged; - -/** - * Called when words are added to and/or removed from the custom spell check - * dictionary. - * @type {!ChromeEvent} - */ -chrome.languageSettingsPrivate.onCustomDictionaryChanged; - -/** - * Called when an input method is added. - * @type {!ChromeEvent} - */ -chrome.languageSettingsPrivate.onInputMethodAdded; - -/** - * Called when an input method is removed. - * @type {!ChromeEvent} - */ -chrome.languageSettingsPrivate.onInputMethodRemoved; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/login_state.js chromium-132.0.6834.159/third_party/closure_compiler/externs/login_state.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/login_state.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/login_state.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.loginState.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: loginState - * @externs - */ - -/** @const */ -chrome.loginState = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/loginState#type-ProfileType - */ -chrome.loginState.ProfileType = { - SIGNIN_PROFILE: 'SIGNIN_PROFILE', - USER_PROFILE: 'USER_PROFILE', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/loginState#type-SessionState - */ -chrome.loginState.SessionState = { - UNKNOWN: 'UNKNOWN', - IN_OOBE_SCREEN: 'IN_OOBE_SCREEN', - IN_LOGIN_SCREEN: 'IN_LOGIN_SCREEN', - IN_SESSION: 'IN_SESSION', - IN_LOCK_SCREEN: 'IN_LOCK_SCREEN', - IN_RMA_SCREEN: 'IN_RMA_SCREEN', -}; - -/** - * Gets the type of the profile the extension is in. - * @param {function(!chrome.loginState.ProfileType): void} callback - * @see https://developer.chrome.com/extensions/loginState#method-getProfileType - */ -chrome.loginState.getProfileType = function(callback) {}; - -/** - * Gets the current session state. - * @param {function(!chrome.loginState.SessionState): void} callback - * @see https://developer.chrome.com/extensions/loginState#method-getSessionState - */ -chrome.loginState.getSessionState = function(callback) {}; - -/** - * Dispatched when the session state changes. sessionState is the - * new session state. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/loginState#event-onSessionStateChanged - */ -chrome.loginState.onSessionStateChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/mediasession.js chromium-132.0.6834.159/third_party/closure_compiler/externs/mediasession.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/mediasession.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/mediasession.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview The current spec of the Media Session API. - * @see https://wicg.github.io/mediasession/ - * @externs - */ - -/** - * @see https://wicg.github.io/mediasession/#the-mediaimage-dictionary - * @record - * @struct - */ -function MediaImage() {} - -/** @type {string} */ -MediaImage.prototype.src; - -/** @type {(string|undefined)} */ -MediaImage.prototype.sizes; - -/** @type {(string|undefined)} */ -MediaImage.prototype.type; - -/** - * A MediaMetadata object is a representation of the metadata associated with a - * MediaSession that can be used by user agents to provide customized user - * interface. - * @see https://wicg.github.io/mediasession/#the-mediametadata-interface - * @constructor - * @param {?MediaMetadataInit} init - */ -function MediaMetadata(init) {} - -/** @type {string} */ -MediaMetadata.prototype.album; - -/** @type {string} */ -MediaMetadata.prototype.artist; - -/** @type {!Array} */ -MediaMetadata.prototype.artwork; - -/** @type {string} */ -MediaMetadata.prototype.title; - -/** - * @see https://wicg.github.io/mediasession/#the-mediametadata-interface - * @record - * @struct - */ -function MediaMetadataInit() {} - -/** @type {(string|undefined)} */ -MediaMetadataInit.prototype.album; - -/** @type {(string|undefined)} */ -MediaMetadataInit.prototype.artist; - -/** @type {(!Array|undefined)} */ -MediaMetadataInit.prototype.artwork; - -/** @type {(string|undefined)} */ -MediaMetadataInit.prototype.title; - -/** - * A MediaSession objects represents a media session for a given document and - * allows a document to communicate to the user agent some information about the - * playback and how to handle it. - * @see https://wicg.github.io/mediasession/#the-mediasession-interface - * @interface - * @struct - */ -function MediaSession() {} - -/** @type {?MediaMetadata} */ -MediaSession.prototype.metadata; - -/** @type {string} */ -MediaSession.prototype.playbackState; - -/** @type {function(string, ?function())} */ -MediaSession.prototype.setActionHandler; - -/** @type {?MediaSession} */ -Navigator.prototype.mediaSession; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/metrics_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/metrics_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/metrics_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/metrics_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,192 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.metricsPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: metricsPrivate - * @externs - */ - -/** @const */ -chrome.metricsPrivate = {}; - -/** - * @enum {string} - */ -chrome.metricsPrivate.MetricTypeType = { - HISTOGRAM_LOG: 'histogram-log', - HISTOGRAM_LINEAR: 'histogram-linear', -}; - -/** - * Describes the type of metric that is to be collected. - * @typedef {{ - * metricName: string, - * type: !chrome.metricsPrivate.MetricTypeType, - * min: number, - * max: number, - * buckets: number - * }} - */ -chrome.metricsPrivate.MetricType; - -/** - * @typedef {{ - * min: number, - * max: number, - * count: number - * }} - */ -chrome.metricsPrivate.HistogramBucket; - -/** - * @typedef {{ - * sum: number, - * buckets: !Array - * }} - */ -chrome.metricsPrivate.Histogram; - -/** - * Get details about a histogram displayed at chrome://histogram. - * @param {string} name Histogram name, e.g. 'Accessibility.CrosAutoclick'. - * @param {function(!chrome.metricsPrivate.Histogram): void} callback Invoked - * with details. - */ -chrome.metricsPrivate.getHistogram = function(name, callback) {}; - -/** - * Returns true if the user opted in to sending crash reports. - * @param {function(boolean): void} callback - */ -chrome.metricsPrivate.getIsCrashReportingEnabled = function(callback) {}; - -/** - * Returns the group name chosen for the named trial, or the empty string if the - * trial does not exist or is not enabled. - * @param {string} name - * @param {function(string): void} callback - */ -chrome.metricsPrivate.getFieldTrial = function(name, callback) {}; - -/** - * Returns variation parameters for the named trial if available, or undefined - * otherwise. - * @param {string} name - * @param {function((Object|undefined)): void} callback - */ -chrome.metricsPrivate.getVariationParams = function(name, callback) {}; - -/** - * Records an action performed by the user. - * @param {string} name - */ -chrome.metricsPrivate.recordUserAction = function(name) {}; - -/** - * Records a percentage value from 1 to 100. - * @param {string} metricName - * @param {number} value - */ -chrome.metricsPrivate.recordPercentage = function(metricName, value) {}; - -/** - * Records a value than can range from 1 to 1,000,000. - * @param {string} metricName - * @param {number} value - */ -chrome.metricsPrivate.recordCount = function(metricName, value) {}; - -/** - * Records a value than can range from 1 to 100. - * @param {string} metricName - * @param {number} value - */ -chrome.metricsPrivate.recordSmallCount = function(metricName, value) {}; - -/** - * Records a value than can range from 1 to 10,000. - * @param {string} metricName - * @param {number} value - */ -chrome.metricsPrivate.recordMediumCount = function(metricName, value) {}; - -/** - * Records an elapsed time of no more than 10 seconds. The sample value is - * specified in milliseconds. - * @param {string} metricName - * @param {number} value - */ -chrome.metricsPrivate.recordTime = function(metricName, value) {}; - -/** - * Records an elapsed time of no more than 3 minutes. The sample value is - * specified in milliseconds. - * @param {string} metricName - * @param {number} value - */ -chrome.metricsPrivate.recordMediumTime = function(metricName, value) {}; - -/** - * Records an elapsed time of no more than 1 hour. The sample value is - * specified in milliseconds. - * @param {string} metricName - * @param {number} value - */ -chrome.metricsPrivate.recordLongTime = function(metricName, value) {}; - -/** - * Increments the count associated with the hash of |value| in the sparse - * histogram defined by the |metricName| using base::HashMetricName(value). - * @param {string} metricName - * @param {string} value - */ -chrome.metricsPrivate.recordSparseValueWithHashMetricName = function(metricName, value) {}; - -/** - * Increments the count associated with the hash of |value| in the sparse - * histogram defined by the |metricName| using base::PersistentHash(value). - * @param {string} metricName - * @param {string} value - */ -chrome.metricsPrivate.recordSparseValueWithPersistentHash = function(metricName, value) {}; - -/** - * Increments the count associated with |value| in the sparse histogram defined - * by the |metricName|. - * @param {string} metricName - * @param {number} value - */ -chrome.metricsPrivate.recordSparseValue = function(metricName, value) {}; - -/** - * Adds a value to the given metric. - * @param {!chrome.metricsPrivate.MetricType} metric - * @param {number} value - */ -chrome.metricsPrivate.recordValue = function(metric, value) {}; - -/** - * Records a boolean value to the given metric. Analogous to - * base::UmaHistogramBoolean(). - * @param {string} metricName - * @param {boolean} value - */ -chrome.metricsPrivate.recordBoolean = function(metricName, value) {}; - -/** - * Records an enumeration value to the given metric. Analogous to - * base::UmaHistogramEnumeration(). Use recordSparseValue for sparse enums or - * enums not starting at 0. - * @param {string} metricName - * @param {number} value - * @param {number} enumSize - */ -chrome.metricsPrivate.recordEnumerationValue = function(metricName, value, enumSize) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/metrics_private_individual_apis.js chromium-132.0.6834.159/third_party/closure_compiler/externs/metrics_private_individual_apis.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/metrics_private_individual_apis.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/metrics_private_individual_apis.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.metricsPrivateIndividualApis.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: metricsPrivateIndividualApis - * @externs - */ - -/** @const */ -chrome.metricsPrivateIndividualApis = {}; - -/** - * Records an action performed by the user. - * @param {string} name - * @see https://developer.chrome.com/extensions/metricsPrivateIndividualApis#method-recordUserAction - */ -chrome.metricsPrivateIndividualApis.recordUserAction = function(name) {}; - -/** - * Records an elapsed time of no more than 3 minutes. The sample value is - * specified in milliseconds. - * @param {string} metricName - * @param {number} value - * @see https://developer.chrome.com/extensions/metricsPrivateIndividualApis#method-recordMediumTime - */ -chrome.metricsPrivateIndividualApis.recordMediumTime = function(metricName, value) {}; - -/** - * Records an enumeration value to the given metric. Analogous to - * base::UmaHistogramEnumeration(). Use recordSparseValue for sparse enums or - * enums not starting at 0. - * @param {string} metricName - * @param {number} value - * @param {number} enumSize - * @see https://developer.chrome.com/extensions/metricsPrivateIndividualApis#method-recordEnumerationValue - */ -chrome.metricsPrivateIndividualApis.recordEnumerationValue = function(metricName, value, enumSize) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/mocha-2.5.js chromium-132.0.6834.159/third_party/closure_compiler/externs/mocha-2.5.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/mocha-2.5.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/mocha-2.5.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,126 +0,0 @@ -// SSSSSSSSSSSSSSS TTTTTTTTTTTTTTTTTTTTTTT OOOOOOOOO PPPPPPPPPPPPPPPPP -// SS:::::::::::::::ST:::::::::::::::::::::T OO:::::::::OO P::::::::::::::::P -// S:::::SSSSSS::::::ST:::::::::::::::::::::T OO:::::::::::::OO P::::::PPPPPP:::::P -// S:::::S SSSSSSST:::::TT:::::::TT:::::TO:::::::OOO:::::::OPP:::::P P:::::P -// S:::::S TTTTTT T:::::T TTTTTTO::::::O O::::::O P::::P P:::::P -// S:::::S T:::::T O:::::O O:::::O P::::P P:::::P -// S::::SSSS P::::PPPPPP:::::P -// SS::::::SSSSS This file is generated. To update it, P:::::::::::::PP -// SSS::::::::SS run roll_closure_compiler. P::::PPPPPPPPP -// SSSSSS::::S P::::P -// S:::::S T:::::T O:::::O O:::::O P::::P -// S:::::S T:::::T O::::::O O::::::O P::::P -// SSSSSSS S:::::S TT:::::::TT O:::::::OOO:::::::OPP::::::PP -// S::::::SSSSSS:::::S T:::::::::T OO:::::::::::::OO P::::::::P -// S:::::::::::::::SS T:::::::::T OO:::::::::OO P::::::::P -// SSSSSSSSSSSSSSS TTTTTTTTTTT OOOOOOOOO PPPPPPPPPP -/* - * Copyright 2016 The Closure Compiler Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @fileoverview Externs definitions for Mocha, 2.5 branch. - * - * This file currently only defines the TDD API, and that part should be - * complete. - * - * @externs - * @see https://mochajs.org/ - */ - -/** - * @typedef {function(function(*=): *): (*|IThenable<*>)} - */ -var ActionFunction; - -// Below are the externs for the TDD API: https://mochajs.org/#tdd - -/** - * @param {string} description - * @param {function(): void} spec - */ -var suite = function(description, spec) {}; - -/** - * @param {!ActionFunction} action - */ -var setup = function(action) {}; - -/** - * @param {!ActionFunction} action - */ -var teardown = function(action) {}; - -/** - * @param {!ActionFunction} action - */ -var suiteSetup = function(action) {}; - -/** - * @param {!ActionFunction} action - */ -var suiteTeardown = function(action) {}; - -/** - * @param {string} expectation - * @param {!ActionFunction=} assertion - */ -var test = function(expectation, assertion) {}; - -// Below are the externs for the BDD API: https://mochajs.org/#bdd - -/** - * @param {string} description - * @param {function(): void} spec - */ -var describe = function(description, spec) {}; - -/** - * @param {string} description - * @param {function(): void} spec - */ -var context = function(description, spec) {}; - -/** - * @param {string} expectation - * @param {!ActionFunction=} assertion - */ -var it = function(expectation, assertion) {}; - -/** - * @param {string} expectation - * @param {!ActionFunction=} assertion - */ -var specify = function(expectation, assertion) {}; - -/** - * @param {!ActionFunction} action - */ -var before = function(action) {}; - -/** - * @param {!ActionFunction} action - */ -var after = function(action) {}; - -/** - * @param {!ActionFunction} action - */ -var beforeEach = function(action) {}; - -/** - * @param {!ActionFunction} action - */ -var afterEach = function(action) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/mojo.js chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/mojo.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,204 +0,0 @@ -/** - * @fileoverview Closure definitions of Mojo core IDL and bindings objects. - * @externs - */ - -const Mojo = {}; - -/** - * @param {string} name - * @param {MojoHandle} handle - * @param {string=} scope - */ -Mojo.bindInterface = function(name, handle, scope) {}; - -const MojoHandle = class {}; - -const mojo = {}; - -// Core Mojo. - -mojo.Binding = class { - /** - * @param {!mojo.Interface} interfaceType - * @param {!Object} impl - * @param {mojo.InterfaceRequest=} request - */ - constructor(interfaceType, impl, request) {}; - - /** - * Closes the message pipe. The bound object will no longer receive messages. - */ - close() {} - - /** - * Binds to the given request. - * @param {!mojo.InterfaceRequest} request - */ - bind(request) {} - - /** @param {function()} callback */ - setConnectionErrorHandler(callback) {} - - /** - * Creates an interface ptr and bind it to this instance. - * @return {!mojo.InterfacePtr} The interface ptr. - */ - createInterfacePtrAndBind() {} -}; - - -mojo.InterfaceRequest = class { - constructor() { - /** @type {MojoHandle} */ - this.handle; - } - - /** - * Closes the message pipe. The object can no longer be bound to an - * implementation. - */ - close() {} -}; - - -/** @interface */ -mojo.InterfacePtr = class {}; - - -mojo.InterfacePtrController = class { - /** - * Closes the message pipe. Messages can no longer be sent with this object. - */ - reset() {} - - /** @param {function()} callback */ - setConnectionErrorHandler(callback) {} -}; - - -mojo.Interface = class { - constructor() { - /** @type {string} */ - this.name; - - /** @type {number} */ - this.kVersion; - - /** @type {function()} */ - this.ptrClass; - - /** @type {function()} */ - this.proxyClass; - - /** @type {function()} */ - this.stubClass; - - /** @type {function()} */ - this.validateRequest; - - /** @type {function()} */ - this.validateResponse; - } -} - -/** - * @param {!mojo.InterfacePtr} interfacePtr - * @return {!mojo.InterfaceRequest} - */ -mojo.makeRequest = function(interfacePtr) {}; - -/** @const */ -mojo.internal = {}; - -mojo.internal.InterfaceRemoteBase = class { - /** - * @param {MojoHandle=} opt_handle - */ - constructor(opt_handle) {} - - /** - * @param {!MojoHandle} handle - */ - bindHandle(handle) {} - - unbind() {} - - /** - * @param {number} ordinal - * @param {!Object} paramStruct - * @param {!Object} responseStruct - * @param {!Array} args - * @return {!Promise} - */ - sendMessage(ordinal, paramStruct, responseStruct, args) {} -}; - -mojo.internal.CallbackRouter = class { - constructor() {} - - /** - * @param {number} id - * @return {boolean} - */ - removeListener(id) {} -}; - -mojo.internal.InterfaceTarget = class { - constructor() {} - - /** - * @param {number} ordinal - * @param {!Object} paramStruct - * @param {!Object} responseStruct - * @param {!Function} handler - */ - registerHandler(ordinal, paramStruct, responseStruct, handler) {} - - /** - * @param {!MojoHandle} handle - */ - bindHandle(handle) {} - - closeBindings() {} -}; - -mojo.internal.InterfaceCallbackTarget = class { - /** - * @param {!mojo.internal.CallbackRouter} callbackRouter - */ - constructor(callbackRouter) {} - - /** - * @param {!Function} listener - * @return {number} - */ - addListener(listener) {} - - /** - * @param {number} id - * @return {boolean} - */ - removeListener(id) {} - - /** - * @param {boolean} expectsResponse - * @return {!Function} - */ - createTargetHandler(expectsResponse) {} -}; - -mojo.internal.ConnectionErrorEventRouter = class { - /** - * @param {!Function} listener - * @return {number} An ID which can be given to removeListener() to remove - * this listener. - */ - addListener(listener) {} - - /** - * @param {number} id An ID returned by a prior call to addListener. - * @return {boolean} True iff the identified listener was found and removed. - */ - removeListener(id) {} -}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/mojo_core.js chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo_core.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/mojo_core.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo_core.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -/** - * @fileoverview Closure definitions of Mojo core IDL objects only. - * @externs - */ - -const Mojo = {}; - -/** - * @param {string} name - * @param {MojoHandle} handle - * @param {string=} scope - */ -Mojo.bindInterface = function(name, handle, scope) {}; - -/** @typedef {number} */ -let MojoResult; - -/** @type {!MojoResult} */ -Mojo.RESULT_OK; - -/** @type {!MojoResult} */ -Mojo.RESULT_CANCELLED; - -/** @type {!MojoResult} */ -Mojo.RESULT_FAILED_PRECONDITION; - -/** @type {!MojoResult} */ -Mojo.RESULT_SHOULD_WAIT; - -/** - * @typedef {{ - * result: MojoResult, - * buffer: !ArrayBuffer, - * handles: !Array - * }} - */ -let MojoReadMessageResult; - -class MojoWatcher { - /** @return {MojoResult} */ - cancel() {} -} - -/** - * @typedef {{ - * readable: (?boolean|undefined), - * writable: (?boolean|undefined), - * peerClosed: (?boolean|undefined) - * }} - */ -let MojoHandleSignals; - -class MojoHandle { - close() {} - - /** - * @return {!MojoReadMessageResult} - */ - readMessage() {} - - /** - * @param {!ArrayBuffer} buffer - * @param {!Array} handles - * @return {MojoResult} - */ - writeMessage(buffer, handles) {} - - /** - * @param {!MojoHandleSignals} signals - * @param {function(MojoResult)} handler - * @return {!MojoWatcher} - */ - watch(signals, handler) {} -}; - -/** - * @typedef {{ - * result: !MojoResult, - * handle0: !MojoHandle, - * handle1: !MojoHandle, - * }} - */ -let MojoCreateMessagePipeResult; - -/** - * @return {!MojoCreateMessagePipeResult} - */ -Mojo.createMessagePipe = function() {} diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/mojo_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/mojo_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/mojo_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.mojoPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: mojoPrivate - * @externs - */ - -/** @const */ -chrome.mojoPrivate = {}; - -/** - * Returns a promise that will resolve to an asynchronously loaded module. - * @param {string} name - * @return {*} - */ -chrome.mojoPrivate.requireAsync = function(name) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/networking_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/networking_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/networking_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/networking_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,1275 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.networkingPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: networkingPrivate - * @externs - */ - -/** @const */ -chrome.networkingPrivate = {}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.ActivationStateType = { - ACTIVATED: 'Activated', - ACTIVATING: 'Activating', - NOT_ACTIVATED: 'NotActivated', - PARTIALLY_ACTIVATED: 'PartiallyActivated', -}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.CaptivePortalStatus = { - UNKNOWN: 'Unknown', - OFFLINE: 'Offline', - ONLINE: 'Online', - PORTAL: 'Portal', - PROXY_AUTH_REQUIRED: 'ProxyAuthRequired', -}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.ConnectionStateType = { - CONNECTED: 'Connected', - CONNECTING: 'Connecting', - NOT_CONNECTED: 'NotConnected', -}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.DeviceStateType = { - UNINITIALIZED: 'Uninitialized', - DISABLED: 'Disabled', - ENABLING: 'Enabling', - ENABLED: 'Enabled', - PROHIBITED: 'Prohibited', -}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.IPConfigType = { - DHCP: 'DHCP', - STATIC: 'Static', -}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.NetworkType = { - ALL: 'All', - CELLULAR: 'Cellular', - ETHERNET: 'Ethernet', - TETHER: 'Tether', - VPN: 'VPN', - WIRELESS: 'Wireless', - WI_FI: 'WiFi', -}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.ProxySettingsType = { - DIRECT: 'Direct', - MANUAL: 'Manual', - PAC: 'PAC', - WPAD: 'WPAD', -}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.ApnType = { - DEFAULT: 'Default', - ATTACH: 'Attach', - TETHER: 'Tether', -}; - -/** - * @enum {string} - */ -chrome.networkingPrivate.ApnSource = { - MODEM: 'Modem', - MODB: 'Modb', - UI: 'Ui', - ADMIN: 'Admin', -}; - -/** - * @typedef {{ - * Active: (boolean|undefined), - * Effective: (string|undefined), - * UserPolicy: (boolean|undefined), - * DevicePolicy: (boolean|undefined), - * UserSetting: (boolean|undefined), - * SharedSetting: (boolean|undefined), - * UserEditable: (boolean|undefined), - * DeviceEditable: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedBoolean; - -/** - * @typedef {{ - * Active: (number|undefined), - * Effective: (string|undefined), - * UserPolicy: (number|undefined), - * DevicePolicy: (number|undefined), - * UserSetting: (number|undefined), - * SharedSetting: (number|undefined), - * UserEditable: (boolean|undefined), - * DeviceEditable: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedLong; - -/** - * @typedef {{ - * Active: (string|undefined), - * Effective: (string|undefined), - * UserPolicy: (string|undefined), - * DevicePolicy: (string|undefined), - * UserSetting: (string|undefined), - * SharedSetting: (string|undefined), - * UserEditable: (boolean|undefined), - * DeviceEditable: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedDOMString; - -/** - * @typedef {{ - * Active: (!Array|undefined), - * Effective: (string|undefined), - * UserPolicy: (!Array|undefined), - * DevicePolicy: (!Array|undefined), - * UserSetting: (!Array|undefined), - * SharedSetting: (!Array|undefined), - * UserEditable: (boolean|undefined), - * DeviceEditable: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedDOMStringList; - -/** - * @typedef {{ - * Active: (!chrome.networkingPrivate.IPConfigType|undefined), - * Effective: (string|undefined), - * UserPolicy: (!chrome.networkingPrivate.IPConfigType|undefined), - * DevicePolicy: (!chrome.networkingPrivate.IPConfigType|undefined), - * UserSetting: (!chrome.networkingPrivate.IPConfigType|undefined), - * SharedSetting: (!chrome.networkingPrivate.IPConfigType|undefined), - * UserEditable: (boolean|undefined), - * DeviceEditable: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedIPConfigType; - -/** - * @typedef {{ - * Active: (!chrome.networkingPrivate.ProxySettingsType|undefined), - * Effective: (string|undefined), - * UserPolicy: (!chrome.networkingPrivate.ProxySettingsType|undefined), - * DevicePolicy: (!chrome.networkingPrivate.ProxySettingsType|undefined), - * UserSetting: (!chrome.networkingPrivate.ProxySettingsType|undefined), - * SharedSetting: (!chrome.networkingPrivate.ProxySettingsType|undefined), - * UserEditable: (boolean|undefined), - * DeviceEditable: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedProxySettingsType; - -/** - * @typedef {{ - * AccessPointName: string, - * Authentication: (string|undefined), - * Language: (string|undefined), - * LocalizedName: (string|undefined), - * Name: (string|undefined), - * Password: (string|undefined), - * Username: (string|undefined), - * ApnTypes: (!Array|undefined), - * Source: (!chrome.networkingPrivate.ApnSource|undefined) - * }} - */ -chrome.networkingPrivate.APNProperties; - -/** - * @typedef {{ - * AccessPointName: !chrome.networkingPrivate.ManagedDOMString, - * Authentication: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Language: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * LocalizedName: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Name: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Password: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Username: (!chrome.networkingPrivate.ManagedDOMString|undefined) - * }} - */ -chrome.networkingPrivate.ManagedAPNProperties; - -/** - * @typedef {{ - * Active: (!Array|undefined), - * Effective: (string|undefined), - * UserPolicy: (!Array|undefined), - * DevicePolicy: (!Array|undefined), - * UserSetting: (!Array|undefined), - * SharedSetting: (!Array|undefined), - * UserEditable: (boolean|undefined), - * DeviceEditable: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedAPNList; - -/** - * @typedef {{ - * Name: string, - * Code: string, - * Country: (string|undefined) - * }} - */ -chrome.networkingPrivate.CellularProviderProperties; - -/** - * @typedef {{ - * requirePin: boolean, - * currentPin: string, - * newPin: (string|undefined) - * }} - */ -chrome.networkingPrivate.CellularSimState; - -/** - * @typedef {{ - * CommonName: (string|undefined), - * Locality: (string|undefined), - * Organization: (string|undefined), - * OrganizationalUnit: (string|undefined) - * }} - */ -chrome.networkingPrivate.IssuerSubjectPattern; - -/** - * @typedef {{ - * CommonName: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Locality: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Organization: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * OrganizationalUnit: (!chrome.networkingPrivate.ManagedDOMString|undefined) - * }} - */ -chrome.networkingPrivate.ManagedIssuerSubjectPattern; - -/** - * @typedef {{ - * EnrollmentURI: (!Array|undefined), - * Issuer: (!chrome.networkingPrivate.IssuerSubjectPattern|undefined), - * IssuerCAPEMs: (!Array|undefined), - * IssuerCARef: (!Array|undefined), - * Subject: (!chrome.networkingPrivate.IssuerSubjectPattern|undefined) - * }} - */ -chrome.networkingPrivate.CertificatePattern; - -/** - * @typedef {{ - * EnrollmentURI: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * Issuer: (!chrome.networkingPrivate.ManagedIssuerSubjectPattern|undefined), - * IssuerCARef: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * Subject: (!chrome.networkingPrivate.ManagedIssuerSubjectPattern|undefined) - * }} - */ -chrome.networkingPrivate.ManagedCertificatePattern; - -/** - * @typedef {{ - * AnonymousIdentity: (string|undefined), - * ClientCertPattern: (!chrome.networkingPrivate.CertificatePattern|undefined), - * ClientCertPKCS11Id: (string|undefined), - * ClientCertProvisioningProfileId: (string|undefined), - * ClientCertRef: (string|undefined), - * ClientCertType: (string|undefined), - * Identity: (string|undefined), - * Inner: (string|undefined), - * Outer: (string|undefined), - * Password: (string|undefined), - * SaveCredentials: (boolean|undefined), - * ServerCAPEMs: (!Array|undefined), - * ServerCARefs: (!Array|undefined), - * SubjectMatch: (string|undefined), - * TLSVersionMax: (string|undefined), - * UseProactiveKeyCaching: (boolean|undefined), - * UseSystemCAs: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.EAPProperties; - -/** - * @typedef {{ - * AnonymousIdentity: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertPattern: (!chrome.networkingPrivate.ManagedCertificatePattern|undefined), - * ClientCertPKCS11Id: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertProvisioningProfileId: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertRef: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertType: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Identity: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Inner: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Outer: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Password: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * SaveCredentials: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * ServerCAPEMs: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * ServerCARefs: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * SubjectMatch: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * TLSVersionMax: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * UseProactiveKeyCaching: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * UseSystemCAs: (!chrome.networkingPrivate.ManagedBoolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedEAPProperties; - -/** - * @typedef {{ - * Status: string, - * NetworkId: string, - * Technology: string, - * ShortName: (string|undefined), - * LongName: (string|undefined) - * }} - */ -chrome.networkingPrivate.FoundNetworkProperties; - -/** - * @typedef {{ - * Gateway: (string|undefined), - * IPAddress: (string|undefined), - * ExcludedRoutes: (!Array|undefined), - * IncludedRoutes: (!Array|undefined), - * NameServers: (!Array|undefined), - * SearchDomains: (!Array|undefined), - * RoutingPrefix: (number|undefined), - * Type: (string|undefined), - * WebProxyAutoDiscoveryUrl: (string|undefined) - * }} - */ -chrome.networkingPrivate.IPConfigProperties; - -/** - * @typedef {{ - * Gateway: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * IPAddress: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * NameServers: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * RoutingPrefix: (!chrome.networkingPrivate.ManagedLong|undefined), - * Type: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * WebProxyAutoDiscoveryUrl: (!chrome.networkingPrivate.ManagedDOMString|undefined) - * }} - */ -chrome.networkingPrivate.ManagedIPConfigProperties; - -/** - * @typedef {{ - * Password: (string|undefined), - * SaveCredentials: (boolean|undefined), - * Username: (string|undefined) - * }} - */ -chrome.networkingPrivate.XAUTHProperties; - -/** - * @typedef {{ - * Password: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * SaveCredentials: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * Username: (!chrome.networkingPrivate.ManagedDOMString|undefined) - * }} - */ -chrome.networkingPrivate.ManagedXAUTHProperties; - -/** - * @typedef {{ - * AuthenticationType: string, - * ClientCertPattern: (!chrome.networkingPrivate.CertificatePattern|undefined), - * ClientCertPKCS11Id: (string|undefined), - * ClientCertProvisioningProfileId: (string|undefined), - * ClientCertRef: (string|undefined), - * ClientCertType: (string|undefined), - * EAP: (!chrome.networkingPrivate.EAPProperties|undefined), - * Group: (string|undefined), - * IKEVersion: (number|undefined), - * LocalIdentity: (string|undefined), - * PSK: (string|undefined), - * RemoteIdentity: (string|undefined), - * SaveCredentials: (boolean|undefined), - * ServerCAPEMs: (!Array|undefined), - * ServerCARefs: (!Array|undefined), - * XAUTH: (!chrome.networkingPrivate.XAUTHProperties|undefined) - * }} - */ -chrome.networkingPrivate.IPSecProperties; - -/** - * @typedef {{ - * AuthenticationType: !chrome.networkingPrivate.ManagedDOMString, - * ClientCertPattern: (!chrome.networkingPrivate.ManagedCertificatePattern|undefined), - * ClientCertPKCS11Id: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertProvisioningProfileId: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertRef: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertType: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * EAP: (!chrome.networkingPrivate.ManagedEAPProperties|undefined), - * Group: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * IKEVersion: (!chrome.networkingPrivate.ManagedLong|undefined), - * PSK: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * SaveCredentials: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * ServerCAPEMs: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * ServerCARefs: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * XAUTH: (!chrome.networkingPrivate.ManagedXAUTHProperties|undefined) - * }} - */ -chrome.networkingPrivate.ManagedIPSecProperties; - -/** - * @typedef {{ - * LcpEchoDisabled: (boolean|undefined), - * Password: (string|undefined), - * SaveCredentials: (boolean|undefined), - * Username: (string|undefined) - * }} - */ -chrome.networkingPrivate.L2TPProperties; - -/** - * @typedef {{ - * LcpEchoDisabled: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * Password: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * SaveCredentials: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * Username: (!chrome.networkingPrivate.ManagedDOMString|undefined) - * }} - */ -chrome.networkingPrivate.ManagedL2TPProperties; - -/** - * @typedef {{ - * Method: string, - * PostData: (string|undefined), - * Url: (string|undefined) - * }} - */ -chrome.networkingPrivate.PaymentPortal; - -/** - * @typedef {{ - * Host: string, - * Port: number - * }} - */ -chrome.networkingPrivate.ProxyLocation; - -/** - * @typedef {{ - * Host: !chrome.networkingPrivate.ManagedDOMString, - * Port: !chrome.networkingPrivate.ManagedLong - * }} - */ -chrome.networkingPrivate.ManagedProxyLocation; - -/** - * @typedef {{ - * HTTPProxy: (!chrome.networkingPrivate.ProxyLocation|undefined), - * SecureHTTPProxy: (!chrome.networkingPrivate.ProxyLocation|undefined), - * FTPProxy: (!chrome.networkingPrivate.ProxyLocation|undefined), - * SOCKS: (!chrome.networkingPrivate.ProxyLocation|undefined) - * }} - */ -chrome.networkingPrivate.ManualProxySettings; - -/** - * @typedef {{ - * HTTPProxy: (!chrome.networkingPrivate.ManagedProxyLocation|undefined), - * SecureHTTPProxy: (!chrome.networkingPrivate.ManagedProxyLocation|undefined), - * FTPProxy: (!chrome.networkingPrivate.ManagedProxyLocation|undefined), - * SOCKS: (!chrome.networkingPrivate.ManagedProxyLocation|undefined) - * }} - */ -chrome.networkingPrivate.ManagedManualProxySettings; - -/** - * @typedef {{ - * Type: !chrome.networkingPrivate.ProxySettingsType, - * Manual: (!chrome.networkingPrivate.ManualProxySettings|undefined), - * ExcludeDomains: (!Array|undefined), - * PAC: (string|undefined) - * }} - */ -chrome.networkingPrivate.ProxySettings; - -/** - * @typedef {{ - * Type: !chrome.networkingPrivate.ManagedProxySettingsType, - * Manual: (!chrome.networkingPrivate.ManagedManualProxySettings|undefined), - * ExcludeDomains: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * PAC: (!chrome.networkingPrivate.ManagedDOMString|undefined) - * }} - */ -chrome.networkingPrivate.ManagedProxySettings; - -/** - * @typedef {{ - * Name: (string|undefined), - * Type: (string|undefined) - * }} - */ -chrome.networkingPrivate.VerifyX509; - -/** - * @typedef {{ - * Name: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Type: (!chrome.networkingPrivate.ManagedDOMString|undefined) - * }} - */ -chrome.networkingPrivate.ManagedVerifyX509; - -/** - * @typedef {{ - * Auth: (string|undefined), - * AuthRetry: (string|undefined), - * AuthNoCache: (boolean|undefined), - * Cipher: (string|undefined), - * ClientCertPKCS11Id: (string|undefined), - * ClientCertPattern: (!chrome.networkingPrivate.CertificatePattern|undefined), - * ClientCertProvisioningProfileId: (string|undefined), - * ClientCertRef: (string|undefined), - * ClientCertType: (string|undefined), - * CompLZO: (string|undefined), - * CompNoAdapt: (boolean|undefined), - * ExtraHosts: (!Array|undefined), - * IgnoreDefaultRoute: (boolean|undefined), - * KeyDirection: (string|undefined), - * NsCertType: (string|undefined), - * OTP: (string|undefined), - * Password: (string|undefined), - * Port: (number|undefined), - * Proto: (string|undefined), - * PushPeerInfo: (boolean|undefined), - * RemoteCertEKU: (string|undefined), - * RemoteCertKU: (!Array|undefined), - * RemoteCertTLS: (string|undefined), - * RenegSec: (number|undefined), - * SaveCredentials: (boolean|undefined), - * ServerCAPEMs: (!Array|undefined), - * ServerCARefs: (!Array|undefined), - * ServerCertRef: (string|undefined), - * ServerPollTimeout: (number|undefined), - * Shaper: (number|undefined), - * StaticChallenge: (string|undefined), - * TLSAuthContents: (string|undefined), - * TLSRemote: (string|undefined), - * TLSVersionMin: (string|undefined), - * UserAuthenticationType: (string|undefined), - * Username: (string|undefined), - * Verb: (string|undefined), - * VerifyHash: (string|undefined), - * VerifyX509: (!chrome.networkingPrivate.VerifyX509|undefined) - * }} - */ -chrome.networkingPrivate.OpenVPNProperties; - -/** - * @typedef {{ - * Auth: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * AuthRetry: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * AuthNoCache: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * Cipher: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertPKCS11Id: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertPattern: (!chrome.networkingPrivate.ManagedCertificatePattern|undefined), - * ClientCertProvisioningProfileId: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertRef: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ClientCertType: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * CompLZO: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * CompNoAdapt: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * ExtraHosts: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * IgnoreDefaultRoute: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * KeyDirection: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * NsCertType: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * OTP: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Password: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Port: (!chrome.networkingPrivate.ManagedLong|undefined), - * Proto: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * PushPeerInfo: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * RemoteCertEKU: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * RemoteCertKU: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * RemoteCertTLS: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * RenegSec: (!chrome.networkingPrivate.ManagedLong|undefined), - * SaveCredentials: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * ServerCAPEMs: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * ServerCARefs: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), - * ServerCertRef: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * ServerPollTimeout: (!chrome.networkingPrivate.ManagedLong|undefined), - * Shaper: (!chrome.networkingPrivate.ManagedLong|undefined), - * StaticChallenge: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * TLSAuthContents: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * TLSRemote: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * TLSVersionMin: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * UserAuthenticationType: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Username: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Verb: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * VerifyHash: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * VerifyX509: (!chrome.networkingPrivate.ManagedVerifyX509|undefined) - * }} - */ -chrome.networkingPrivate.ManagedOpenVPNProperties; - -/** - * @typedef {{ - * LockType: string, - * LockEnabled: boolean, - * RetriesLeft: (number|undefined) - * }} - */ -chrome.networkingPrivate.SIMLockStatus; - -/** - * @typedef {{ - * ExtensionID: string, - * ProviderName: (string|undefined) - * }} - */ -chrome.networkingPrivate.ThirdPartyVPNProperties; - -/** - * @typedef {{ - * ExtensionID: !chrome.networkingPrivate.ManagedDOMString, - * ProviderName: (string|undefined) - * }} - */ -chrome.networkingPrivate.ManagedThirdPartyVPNProperties; - -/** - * @typedef {{ - * AutoConnect: (boolean|undefined), - * APN: (!chrome.networkingPrivate.APNProperties|undefined), - * APNList: (!Array|undefined), - * ActivationType: (string|undefined), - * ActivationState: (!chrome.networkingPrivate.ActivationStateType|undefined), - * AllowRoaming: (boolean|undefined), - * ESN: (string|undefined), - * Family: (string|undefined), - * FirmwareRevision: (string|undefined), - * FoundNetworks: (!Array|undefined), - * HardwareRevision: (string|undefined), - * HomeProvider: (!chrome.networkingPrivate.CellularProviderProperties|undefined), - * ICCID: (string|undefined), - * IMEI: (string|undefined), - * LastGoodAPN: (!chrome.networkingPrivate.APNProperties|undefined), - * Manufacturer: (string|undefined), - * MDN: (string|undefined), - * MEID: (string|undefined), - * MIN: (string|undefined), - * ModelID: (string|undefined), - * NetworkTechnology: (string|undefined), - * PaymentPortal: (!chrome.networkingPrivate.PaymentPortal|undefined), - * RoamingState: (string|undefined), - * Scanning: (boolean|undefined), - * ServingOperator: (!chrome.networkingPrivate.CellularProviderProperties|undefined), - * SIMLockStatus: (!chrome.networkingPrivate.SIMLockStatus|undefined), - * SIMPresent: (boolean|undefined), - * SignalStrength: (number|undefined), - * SupportNetworkScan: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.CellularProperties; - -/** - * @typedef {{ - * AutoConnect: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * APN: (!chrome.networkingPrivate.ManagedAPNProperties|undefined), - * APNList: (!chrome.networkingPrivate.ManagedAPNList|undefined), - * ActivationType: (string|undefined), - * ActivationState: (!chrome.networkingPrivate.ActivationStateType|undefined), - * AllowRoaming: (boolean|undefined), - * ESN: (string|undefined), - * Family: (string|undefined), - * FirmwareRevision: (string|undefined), - * FoundNetworks: (!Array|undefined), - * HardwareRevision: (string|undefined), - * HomeProvider: (!chrome.networkingPrivate.CellularProviderProperties|undefined), - * ICCID: (string|undefined), - * IMEI: (string|undefined), - * LastGoodAPN: (!chrome.networkingPrivate.APNProperties|undefined), - * Manufacturer: (string|undefined), - * MDN: (string|undefined), - * MEID: (string|undefined), - * MIN: (string|undefined), - * ModelID: (string|undefined), - * NetworkTechnology: (string|undefined), - * PaymentPortal: (!chrome.networkingPrivate.PaymentPortal|undefined), - * RoamingState: (string|undefined), - * Scanning: (boolean|undefined), - * ServingOperator: (!chrome.networkingPrivate.CellularProviderProperties|undefined), - * SIMLockStatus: (!chrome.networkingPrivate.SIMLockStatus|undefined), - * SIMPresent: (boolean|undefined), - * SignalStrength: (number|undefined), - * SupportNetworkScan: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.ManagedCellularProperties; - -/** - * @typedef {{ - * ActivationState: (!chrome.networkingPrivate.ActivationStateType|undefined), - * EID: (string|undefined), - * ICCID: (string|undefined), - * NetworkTechnology: (string|undefined), - * RoamingState: (string|undefined), - * Scanning: (boolean|undefined), - * SIMPresent: (boolean|undefined), - * SignalStrength: (number|undefined) - * }} - */ -chrome.networkingPrivate.CellularStateProperties; - -/** - * @typedef {{ - * Outer: (string|undefined) - * }} - */ -chrome.networkingPrivate.EAPStateProperties; - -/** - * @typedef {{ - * AutoConnect: (boolean|undefined), - * Authentication: (string|undefined), - * EAP: (!chrome.networkingPrivate.EAPProperties|undefined) - * }} - */ -chrome.networkingPrivate.EthernetProperties; - -/** - * @typedef {{ - * AutoConnect: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * Authentication: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * EAP: (!chrome.networkingPrivate.ManagedEAPProperties|undefined) - * }} - */ -chrome.networkingPrivate.ManagedEthernetProperties; - -/** - * @typedef {{ - * Authentication: string - * }} - */ -chrome.networkingPrivate.EthernetStateProperties; - -/** - * @typedef {{ - * BatteryPercentage: (number|undefined), - * Carrier: (string|undefined), - * HasConnectedToHost: boolean, - * SignalStrength: (number|undefined) - * }} - */ -chrome.networkingPrivate.TetherProperties; - -/** - * @typedef {{ - * AutoConnect: (boolean|undefined), - * Host: (string|undefined), - * IPsec: (!chrome.networkingPrivate.IPSecProperties|undefined), - * L2TP: (!chrome.networkingPrivate.L2TPProperties|undefined), - * OpenVPN: (!chrome.networkingPrivate.OpenVPNProperties|undefined), - * ThirdPartyVPN: (!chrome.networkingPrivate.ThirdPartyVPNProperties|undefined), - * Type: (string|undefined) - * }} - */ -chrome.networkingPrivate.VPNProperties; - -/** - * @typedef {{ - * AutoConnect: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * Host: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * IPsec: (!chrome.networkingPrivate.ManagedIPSecProperties|undefined), - * L2TP: (!chrome.networkingPrivate.ManagedL2TPProperties|undefined), - * OpenVPN: (!chrome.networkingPrivate.ManagedOpenVPNProperties|undefined), - * ThirdPartyVPN: (!chrome.networkingPrivate.ManagedThirdPartyVPNProperties|undefined), - * Type: (!chrome.networkingPrivate.ManagedDOMString|undefined) - * }} - */ -chrome.networkingPrivate.ManagedVPNProperties; - -/** - * @typedef {{ - * Type: string, - * IPsec: (!chrome.networkingPrivate.IPSecProperties|undefined), - * ThirdPartyVPN: (!chrome.networkingPrivate.ThirdPartyVPNProperties|undefined) - * }} - */ -chrome.networkingPrivate.VPNStateProperties; - -/** - * @typedef {{ - * AllowGatewayARPPolling: (boolean|undefined), - * AutoConnect: (boolean|undefined), - * BSSID: (string|undefined), - * EAP: (!chrome.networkingPrivate.EAPProperties|undefined), - * Frequency: (number|undefined), - * FrequencyList: (!Array|undefined), - * HexSSID: (string|undefined), - * HiddenSSID: (boolean|undefined), - * Passphrase: (string|undefined), - * SSID: (string|undefined), - * Security: (string|undefined), - * SignalStrength: (number|undefined) - * }} - */ -chrome.networkingPrivate.WiFiProperties; - -/** - * @typedef {{ - * AllowGatewayARPPolling: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * AutoConnect: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * BSSID: (string|undefined), - * EAP: (!chrome.networkingPrivate.ManagedEAPProperties|undefined), - * Frequency: (number|undefined), - * FrequencyList: (!Array|undefined), - * HexSSID: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * HiddenSSID: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * Passphrase: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * SSID: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * Security: !chrome.networkingPrivate.ManagedDOMString, - * SignalStrength: (number|undefined) - * }} - */ -chrome.networkingPrivate.ManagedWiFiProperties; - -/** - * @typedef {{ - * BSSID: (string|undefined), - * EAP: (!chrome.networkingPrivate.EAPStateProperties|undefined), - * Frequency: (number|undefined), - * HexSSID: (string|undefined), - * Security: string, - * SignalStrength: (number|undefined), - * SSID: (string|undefined) - * }} - */ -chrome.networkingPrivate.WiFiStateProperties; - -/** - * @typedef {{ - * Cellular: (!chrome.networkingPrivate.CellularProperties|undefined), - * Ethernet: (!chrome.networkingPrivate.EthernetProperties|undefined), - * GUID: (string|undefined), - * IPAddressConfigType: (!chrome.networkingPrivate.IPConfigType|undefined), - * Name: (string|undefined), - * NameServersConfigType: (!chrome.networkingPrivate.IPConfigType|undefined), - * Priority: (number|undefined), - * ProxySettings: (!chrome.networkingPrivate.ProxySettings|undefined), - * StaticIPConfig: (!chrome.networkingPrivate.IPConfigProperties|undefined), - * Type: (!chrome.networkingPrivate.NetworkType|undefined), - * VPN: (!chrome.networkingPrivate.VPNProperties|undefined), - * WiFi: (!chrome.networkingPrivate.WiFiProperties|undefined) - * }} - */ -chrome.networkingPrivate.NetworkConfigProperties; - -/** - * @typedef {{ - * Cellular: (!chrome.networkingPrivate.CellularProperties|undefined), - * Connectable: (boolean|undefined), - * ConnectionState: (!chrome.networkingPrivate.ConnectionStateType|undefined), - * ErrorState: (string|undefined), - * Ethernet: (!chrome.networkingPrivate.EthernetProperties|undefined), - * GUID: string, - * IPAddressConfigType: (!chrome.networkingPrivate.IPConfigType|undefined), - * IPConfigs: (!Array|undefined), - * MacAddress: (string|undefined), - * Metered: (boolean|undefined), - * Name: (string|undefined), - * NameServersConfigType: (!chrome.networkingPrivate.IPConfigType|undefined), - * Priority: (number|undefined), - * ProxySettings: (!chrome.networkingPrivate.ProxySettings|undefined), - * RestrictedConnectivity: (boolean|undefined), - * StaticIPConfig: (!chrome.networkingPrivate.IPConfigProperties|undefined), - * SavedIPConfig: (!chrome.networkingPrivate.IPConfigProperties|undefined), - * Source: (string|undefined), - * Tether: (!chrome.networkingPrivate.TetherProperties|undefined), - * TrafficCounterResetTime: (number|undefined), - * Type: !chrome.networkingPrivate.NetworkType, - * VPN: (!chrome.networkingPrivate.VPNProperties|undefined), - * WiFi: (!chrome.networkingPrivate.WiFiProperties|undefined) - * }} - */ -chrome.networkingPrivate.NetworkProperties; - -/** - * @typedef {{ - * Cellular: (!chrome.networkingPrivate.ManagedCellularProperties|undefined), - * Connectable: (boolean|undefined), - * ConnectionState: (!chrome.networkingPrivate.ConnectionStateType|undefined), - * ErrorState: (string|undefined), - * Ethernet: (!chrome.networkingPrivate.ManagedEthernetProperties|undefined), - * GUID: string, - * IPAddressConfigType: (!chrome.networkingPrivate.ManagedIPConfigType|undefined), - * IPConfigs: (!Array|undefined), - * MacAddress: (string|undefined), - * Metered: (!chrome.networkingPrivate.ManagedBoolean|undefined), - * Name: (!chrome.networkingPrivate.ManagedDOMString|undefined), - * NameServersConfigType: (!chrome.networkingPrivate.ManagedIPConfigType|undefined), - * Priority: (!chrome.networkingPrivate.ManagedLong|undefined), - * ProxySettings: (!chrome.networkingPrivate.ManagedProxySettings|undefined), - * RestrictedConnectivity: (boolean|undefined), - * StaticIPConfig: (!chrome.networkingPrivate.ManagedIPConfigProperties|undefined), - * SavedIPConfig: (!chrome.networkingPrivate.IPConfigProperties|undefined), - * Source: (string|undefined), - * Tether: (!chrome.networkingPrivate.TetherProperties|undefined), - * TrafficCounterResetTime: (number|undefined), - * Type: !chrome.networkingPrivate.NetworkType, - * VPN: (!chrome.networkingPrivate.ManagedVPNProperties|undefined), - * WiFi: (!chrome.networkingPrivate.ManagedWiFiProperties|undefined) - * }} - */ -chrome.networkingPrivate.ManagedProperties; - -/** - * @typedef {{ - * Cellular: (!chrome.networkingPrivate.CellularStateProperties|undefined), - * Connectable: (boolean|undefined), - * ConnectionState: (!chrome.networkingPrivate.ConnectionStateType|undefined), - * Ethernet: (!chrome.networkingPrivate.EthernetStateProperties|undefined), - * ErrorState: (string|undefined), - * GUID: string, - * Name: (string|undefined), - * Priority: (number|undefined), - * Source: (string|undefined), - * Tether: (!chrome.networkingPrivate.TetherProperties|undefined), - * Type: !chrome.networkingPrivate.NetworkType, - * VPN: (!chrome.networkingPrivate.VPNStateProperties|undefined), - * WiFi: (!chrome.networkingPrivate.WiFiStateProperties|undefined) - * }} - */ -chrome.networkingPrivate.NetworkStateProperties; - -/** - * @typedef {{ - * Scanning: (boolean|undefined), - * SIMLockStatus: (!chrome.networkingPrivate.SIMLockStatus|undefined), - * SIMPresent: (boolean|undefined), - * State: !chrome.networkingPrivate.DeviceStateType, - * Type: !chrome.networkingPrivate.NetworkType, - * ManagedNetworkAvailable: (boolean|undefined) - * }} - */ -chrome.networkingPrivate.DeviceStateProperties; - -/** - * @typedef {{ - * networkType: !chrome.networkingPrivate.NetworkType, - * visible: (boolean|undefined), - * configured: (boolean|undefined), - * limit: (number|undefined) - * }} - */ -chrome.networkingPrivate.NetworkFilter; - -/** - * @typedef {{ - * AllowOnlyPolicyNetworksToAutoconnect: (boolean|undefined), - * AllowOnlyPolicyNetworksToConnect: (boolean|undefined), - * AllowOnlyPolicyNetworksToConnectIfAvailable: (boolean|undefined), - * BlockedHexSSIDs: (!Array|undefined) - * }} - */ -chrome.networkingPrivate.GlobalPolicy; - -/** - * @typedef {{ - * hash: string, - * issuedBy: string, - * issuedTo: string, - * pem: (string|undefined), - * PKCS11Id: (string|undefined), - * hardwareBacked: boolean, - * deviceWide: boolean - * }} - */ -chrome.networkingPrivate.Certificate; - -/** - * @typedef {{ - * serverCaCertificates: !Array, - * userCertificates: !Array - * }} - */ -chrome.networkingPrivate.CertificateLists; - -/** - * Gets all the properties of the network with id networkGuid. Includes all - * properties of the network (read-only and read/write values). - * @param {string} networkGuid The GUID of the network to get properties for. - * @param {function(!chrome.networkingPrivate.NetworkProperties): void} callback - * Called with the network properties when received. - */ -chrome.networkingPrivate.getProperties = function(networkGuid, callback) {}; - -/** - * Gets the merged properties of the network with id networkGuid from the - * sources: User settings, shared settings, user policy, device policy and the - * currently active settings. - * @param {string} networkGuid The GUID of the network to get properties for. - * @param {function(!chrome.networkingPrivate.ManagedProperties): void} callback - * Called with the managed network properties when received. - */ -chrome.networkingPrivate.getManagedProperties = function(networkGuid, callback) {}; - -/** - * Gets the cached read-only properties of the network with id networkGuid. This - * is meant to be a higher performance function than $(ref:getProperties), which - * requires a round trip to query the networking subsystem. The following - * properties are returned for all networks: GUID, Type, Name, WiFi.Security. - * Additional properties are provided for visible networks: ConnectionState, - * ErrorState, WiFi.SignalStrength, Cellular.NetworkTechnology, - * Cellular.ActivationState, Cellular.RoamingState. - * @param {string} networkGuid The GUID of the network to get properties for. - * @param {function(!chrome.networkingPrivate.NetworkStateProperties): void} - * callback Called immediately with the network state properties. - */ -chrome.networkingPrivate.getState = function(networkGuid, callback) {}; - -/** - * Sets the properties of the network with id |networkGuid|. This is only valid - * for configured networks (Source != None). Unconfigured visible networks - * should use createNetwork instead. - * @param {string} networkGuid The GUID of the network to set properties for. - * @param {!chrome.networkingPrivate.NetworkConfigProperties} properties The - * properties to set. - * @param {function(): void=} callback Called when the operation has completed. - */ -chrome.networkingPrivate.setProperties = function(networkGuid, properties, callback) {}; - -/** - * Creates a new network configuration from properties. If a matching configured - * network already exists, this will fail. Otherwise returns the guid of the new - * network. - * @param {boolean} shared If true, share this network configuration with other - * users. - * @param {!chrome.networkingPrivate.NetworkConfigProperties} properties The - * properties to configure the new network with. - * @param {function(string): void=} callback Called with the GUID for the new - * network configuration once the network has been created. - */ -chrome.networkingPrivate.createNetwork = function(shared, properties, callback) {}; - -/** - * Forgets a network configuration by clearing any configured properties for the - * network with GUID 'networkGuid'. This may also include any other networks - * with matching identifiers (e.g. WiFi SSID and Security). If no such - * configuration exists, an error will be set and the operation will fail. - * @param {string} networkGuid The GUID of the network to forget. - * @param {function(): void=} callback Called when the operation has completed. - */ -chrome.networkingPrivate.forgetNetwork = function(networkGuid, callback) {}; - -/** - * Returns a list of network objects with the same properties provided by - * $(ref:networkingPrivate.getState). A filter is provided to specify the type - * of networks returned and to limit the number of networks. Networks are - * ordered by the system based on their priority, with connected or connecting - * networks listed first. - * @param {!chrome.networkingPrivate.NetworkFilter} filter Describes which - * networks to return. - * @param {function(!Array): void} - * callback Called with a dictionary of networks and their state - * properties when received. - */ -chrome.networkingPrivate.getNetworks = function(filter, callback) {}; - -/** - * Deprecated. Please use $(ref:networkingPrivate.getNetworks) with - * filter.visible = true instead. - * @param {!chrome.networkingPrivate.NetworkType} networkType - * @param {function(!Array): void} - * callback - * @deprecated Use getNetworks. - */ -chrome.networkingPrivate.getVisibleNetworks = function(networkType, callback) {}; - -/** - * Deprecated. Please use $(ref:networkingPrivate.getDeviceStates) instead. - * @param {function(!Array): void} - * callback - * @deprecated Use getDeviceStates. - */ -chrome.networkingPrivate.getEnabledNetworkTypes = function(callback) {}; - -/** - * Returns a list of $(ref:networkingPrivate.DeviceStateProperties) objects. - * @param {function(!Array): void} - * callback Called with a list of devices and their state. - */ -chrome.networkingPrivate.getDeviceStates = function(callback) {}; - -/** - * Enables any devices matching the specified network type. Note, the type might - * represent multiple network types (e.g. 'Wireless'). - * @param {!chrome.networkingPrivate.NetworkType} networkType The type of - * network to enable. - */ -chrome.networkingPrivate.enableNetworkType = function(networkType) {}; - -/** - * Disables any devices matching the specified network type. See note for - * $(ref:networkingPrivate.enableNetworkType). - * @param {!chrome.networkingPrivate.NetworkType} networkType The type of - * network to disable. - */ -chrome.networkingPrivate.disableNetworkType = function(networkType) {}; - -/** - * Requests that the networking subsystem scan for new networks and update the - * list returned by $(ref:getVisibleNetworks). This is only a request: the - * network subsystem can choose to ignore it. If the list is updated, then the - * $(ref:onNetworkListChanged) event will be fired. - * @param {!chrome.networkingPrivate.NetworkType=} networkType If provided, - * requests a scan specific to the type. For Cellular a mobile network - * scan will be requested if supported. - */ -chrome.networkingPrivate.requestNetworkScan = function(networkType) {}; - -/** - * Starts a connection to the network with networkGuid. - * @param {string} networkGuid The GUID of the network to connect to. - * @param {function(): void=} callback Called when the connect request has been - * sent. Note: the connection may not have completed. Observe - * $(ref:onNetworksChanged) to be notified when a network state changes. - * If the connect request immediately failed (e.g. the network is - * unconfigured), $(ref:runtime.lastError) will be set with a failure - * reason. - */ -chrome.networkingPrivate.startConnect = function(networkGuid, callback) {}; - -/** - * Starts a disconnect from the network with networkGuid. - * @param {string} networkGuid The GUID of the network to disconnect from. - * @param {function(): void=} callback Called when the disconnect request has - * been sent. See note for $(ref:startConnect). - */ -chrome.networkingPrivate.startDisconnect = function(networkGuid, callback) {}; - -/** - * Starts activation of the Cellular network with networkGuid. If called for a - * network that is already activated, or for a network with a carrier that can - * not be directly activated, this will show the account details page for the - * carrier if possible. - * @param {string} networkGuid The GUID of the Cellular network to activate. - * @param {string=} carrier Optional name of carrier to activate. - * @param {function(): void=} callback Called when the activation request has - * been sent. See note for $(ref:startConnect). - */ -chrome.networkingPrivate.startActivate = function(networkGuid, carrier, callback) {}; - -/** - * Returns captive portal status for the network matching 'networkGuid'. - * @param {string} networkGuid The GUID of the network to get captive portal - * status for. - * @param {function(!chrome.networkingPrivate.CaptivePortalStatus): void} - * callback A callback function that returns the results of the query for - * network captive portal status. - */ -chrome.networkingPrivate.getCaptivePortalStatus = function(networkGuid, callback) {}; - -/** - * Unlocks a Cellular SIM card. * If the SIM is PIN locked, |pin| will be used - * to unlock the SIM and the |puk| argument will be ignored if provided. * If - * the SIM is PUK locked, |puk| and |pin| must be provided. If the operation - * succeeds (|puk| is valid), the PIN will be set to |pin|. (If |pin| is empty - * or invalid the operation will fail). - * @param {string} networkGuid The GUID of the cellular network to unlock. - * If empty, the default cellular device will be used. - * @param {string} pin The current SIM PIN, or the new PIN if PUK is provided. - * @param {string=} puk The operator provided PUK for unblocking a blocked SIM. - * @param {function(): void=} callback Called when the operation has completed. - */ -chrome.networkingPrivate.unlockCellularSim = function(networkGuid, pin, puk, callback) {}; - -/** - * Sets whether or not SIM locking is enabled (i.e a PIN will be required when - * the device is powered) and changes the PIN if a new PIN is specified. If the - * new PIN is provided but not valid (e.g. too short) the operation will fail. - * This will not lock the SIM; that is handled automatically by the device. - * NOTE: If the SIM is locked, it must first be unlocked with - * unlockCellularSim() before this can be called (otherwise it will fail and - * $(ref:runtime.lastError) will be set to Error.SimLocked). - * @param {string} networkGuid The GUID of the cellular network to set the SIM - * state of. If empty, the default cellular device will be used. - * @param {!chrome.networkingPrivate.CellularSimState} simState The SIM state to - * set. - * @param {function(): void=} callback Called when the operation has completed. - */ -chrome.networkingPrivate.setCellularSimState = function(networkGuid, simState, callback) {}; - -/** - * Selects which Cellular Mobile Network to use. |networkId| must be the - * NetworkId property of a member of Cellular.FoundNetworks from the network - * properties for the specified Cellular network. - * @param {string} networkGuid The GUID of the cellular network to select the - * network for. If empty, the default cellular device will be used. - * @param {string} networkId The networkId to select. - * @param {function(): void=} callback Called when the operation has completed. - */ -chrome.networkingPrivate.selectCellularMobileNetwork = function(networkGuid, networkId, callback) {}; - -/** - * Gets the global policy properties. These properties are not expected to - * change during a session. - * @param {function(!chrome.networkingPrivate.GlobalPolicy): void} callback - */ -chrome.networkingPrivate.getGlobalPolicy = function(callback) {}; - -/** - * Gets the lists of certificates available for network configuration. - * @param {function(!chrome.networkingPrivate.CertificateLists): void} callback - */ -chrome.networkingPrivate.getCertificateLists = function(callback) {}; - -/** - * Fired when the properties change on any of the networks. Sends a list of - * GUIDs for networks whose properties have changed. - * @type {!ChromeEvent} - */ -chrome.networkingPrivate.onNetworksChanged; - -/** - * Fired when the list of networks has changed. Sends a complete list of GUIDs - * for all the current networks. - * @type {!ChromeEvent} - */ -chrome.networkingPrivate.onNetworkListChanged; - -/** - * Fired when the list of devices has changed or any device state properties - * have changed. - * @type {!ChromeEvent} - */ -chrome.networkingPrivate.onDeviceStateListChanged; - -/** - * Fired when a portal detection for a network completes. Sends the guid of the - * network and the corresponding captive portal status. - * @type {!ChromeEvent} - */ -chrome.networkingPrivate.onPortalDetectionCompleted; - -/** - * Fired when any certificate list has changed. - * @type {!ChromeEvent} - */ -chrome.networkingPrivate.onCertificateListsChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/pending.js chromium-132.0.6834.159/third_party/closure_compiler/externs/pending.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/pending.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/pending.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Externs for stuff not added to the Closure compiler yet, but - * should get added. - * @externs - */ - -/** - * TODO(katie): Remove this once length is added to the Closure - * chrome_extensions.js. - * An event from the TTS engine to communicate the status of an utterance. - * @constructor - */ -function TtsEvent() {} - -/** @type {number} */ -TtsEvent.prototype.length; - - -/** - * @see https://drafts.css-houdini.org/css-typed-om/#stylepropertymap - * @typedef {{set: function(string, *):void, - * append: function(string, *):void, - * delete: function(string):void, - * clear: function():void }} - * TODO(rbpotter): Remove this once it is added to Closure Compiler itself. - */ -class StylePropertyMap { - /** - * @param {string} property - * @param {*} values - */ - set(property, values) {} - - /** - * @param {string} property - * @param {*} values - */ - append(property, values) {} - - /** @param {string} property */ - delete(property) {} - - clear() {} -} - -/** @type {!StylePropertyMap} */ -HTMLElement.prototype.attributeStyleMap; - -/** - * @see https://drafts.css-houdini.org/css-typed-om/#stylepropertymapreadonly - */ -class StylePropertyMapReadOnly { - /** @param {string} property */ - get(property) {} -} - -/** @return {!StylePropertyMapReadOnly} */ -HTMLElement.prototype.computedStyleMap = function() {}; - -/** @return {!AnimationEffectTimingProperties} */ -AnimationEffect.prototype.getTiming = function() {}; - -/** @return {!Array} */ -AnimationEffect.prototype.getKeyframes = function() {}; - -/** - * https://developer.mozilla.org/en-US/docs/Web/API/structuredClone - * @param {T} obj - * @return {T} - * @template T - */ -function structuredClone(obj) {} diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/pending_polymer.js chromium-132.0.6834.159/third_party/closure_compiler/externs/pending_polymer.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/pending_polymer.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/pending_polymer.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Externs for Polymer not added to the polymer-1.0.js file. - * @externs - */ - -/** - * @see - * https://www.polymer-project.org/2.0/docs/api/namespaces/Polymer.RenderStatus - * Queue a function call to be run before the next render. - * @param {!Element} element The element on which the function call is made. - * @param {!function()} fn The function called on next render. - * @param {...*} args The function arguments. - * TODO(rbpotter): Remove this once it is added to Closure Compiler itself. - */ -Polymer.RenderStatus.beforeNextRender = function(element, fn, args) {}; - -/** - * @see - * https://polymer-library.polymer-project.org/2.0/api/namespaces/Polymer.Templatize - * @constructor - * TODO(rbpotter): Remove this once it is added to Closure Compiler itself. - */ -Polymer.Templatize = function() {}; - -/** - * @param {!HTMLTemplateElement} template - * @param {Object=} owner - * @param {Object=} options - * @return {!Function} - * TODO(rbpotter): Remove this once it is added to Closure Compiler itself. - */ -Polymer.Templatize.templatize = function(template, owner, options) {}; - -/** - * @see - * https://polymer-library.polymer-project.org/2.0/api/namespaces/Polymer.Templatize - * @constructor - * TODO(rbpotter): Remove this once it is added to Closure Compiler itself. - */ -let TemplateInstanceBase = function() {}; - -/** - * @see - * https://polymer-library.polymer-project.org/2.0/api/elements/Polymer.DomIf - * @constructor - */ -Polymer.DomIf = function() {}; - -/** - * @param {!HTMLTemplateElement} template - * @return {!HTMLElement} - * TODO(dpapad): Figure out if there is a better way to type-check Polymer2 - * while still using legacy Polymer1 syntax. - */ -Polymer.DomIf._contentForTemplate = function(template) {}; - -/** - * From: - * https://github.com/Polymer/polymer/blob/2.x/lib/mixins/property-effects.html - * - * @param {Object} props Bag of one or more key-value pairs whose key is - * a property and value is the new value to set for that property. - * @param {boolean=} setReadOnly When true, any private values set in - * `props` will be set. By default, `setProperties` will not set - * `readOnly: true` root properties. - * @return {void} - * @public - */ -PolymerElement.prototype.setProperties = function(props, setReadOnly) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/picture_in_picture.js chromium-132.0.6834.159/third_party/closure_compiler/externs/picture_in_picture.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/picture_in_picture.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/picture_in_picture.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Picture-in-picture APIs. - * @see https://wicg.github.io/picture-in-picture/ - * @externs - */ - -/** - * @interface - * @extends {EventTarget} - * @see https://wicg.github.io/picture-in-picture/#interface-picture-in-picture-window - */ -function PictureInPictureWindow() {} - -/** @type {number} */ -PictureInPictureWindow.prototype.width; - -/** @type {number} */ -PictureInPictureWindow.prototype.length; - -/** @type {?function(!Event)} */ -PictureInPictureWindow.prototype.onresize; - -/** - * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions - * @return {!Promise} - */ -HTMLVideoElement.prototype.requestPictureInPicture = function() {}; - -/** - * @type {?function(!Event)} - * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions - */ -HTMLVideoElement.prototype.onenterpictureinpicture; - -/** - * @type {?function(!Event)} - * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions - */ -HTMLVideoElement.prototype.onleavepictureinpicture; - -/** - * @type {boolean} - * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions - */ -HTMLVideoElement.prototype.autoPictureInPicture; - -/** - * @type {boolean} - * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions - */ -HTMLVideoElement.prototype.disablePictureInPicture; - -/** - * @type {boolean} - * @see https://wicg.github.io/picture-in-picture/#document-extensions - */ -Document.prototype.pictureInPictureEnabled; - -/** - * @see https://wicg.github.io/picture-in-picture/#document-extensions - * @return {!Promise} - */ -Document.prototype.exitPictureInPicture = function() {}; - -/** - * @type {?HTMLVideoElement} - * @see https://wicg.github.io/picture-in-picture/#documentorshadowroot-extension - */ -Document.prototype.pictureInPictureElement; \ No newline at end of file diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/polymer-1.0.js chromium-132.0.6834.159/third_party/closure_compiler/externs/polymer-1.0.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/polymer-1.0.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/polymer-1.0.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,1771 +0,0 @@ -// SSSSSSSSSSSSSSS TTTTTTTTTTTTTTTTTTTTTTT OOOOOOOOO PPPPPPPPPPPPPPPPP -// SS:::::::::::::::ST:::::::::::::::::::::T OO:::::::::OO P::::::::::::::::P -// S:::::SSSSSS::::::ST:::::::::::::::::::::T OO:::::::::::::OO P::::::PPPPPP:::::P -// S:::::S SSSSSSST:::::TT:::::::TT:::::TO:::::::OOO:::::::OPP:::::P P:::::P -// S:::::S TTTTTT T:::::T TTTTTTO::::::O O::::::O P::::P P:::::P -// S:::::S T:::::T O:::::O O:::::O P::::P P:::::P -// S::::SSSS P::::PPPPPP:::::P -// SS::::::SSSSS This file is generated. To update it, P:::::::::::::PP -// SSS::::::::SS run roll_closure_compiler. P::::PPPPPPPPP -// SSSSSS::::S P::::P -// S:::::S T:::::T O:::::O O:::::O P::::P -// S:::::S T:::::T O::::::O O::::::O P::::P -// SSSSSSS S:::::S TT:::::::TT O:::::::OOO:::::::OPP::::::PP -// S::::::SSSSSS:::::S T:::::::::T OO:::::::::::::OO P::::::::P -// S:::::::::::::::SS T:::::::::T OO:::::::::OO P::::::::P -// SSSSSSSSSSSSSSS TTTTTTTTTTT OOOOOOOOO PPPPPPPPPP -/* - * Copyright 2016 The Closure Compiler Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview Closure compiler externs for the Polymer library. - * Originally part of the Polymer Project. Original license below. - * - * @externs - * @suppress {strictMissingProperties} - * @license - * Copyright (c) 2015 The Polymer Project Authors. All rights reserved. - * This code may only be used under the BSD style license found at - * http://polymer.github.io/LICENSE.txt. The complete set of authors may be - * found at http://polymer.github.io/AUTHORS.txt. The complete set of - * contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt. Code - * distributed by Google as part of the polymer project is also subject to an - * additional IP rights grant found at http://polymer.github.io/PATENTS.txt. - */ - -if (Math.random() < 1) { - throw "polymer externs should not be executed"; -} - -/** - * @param {!{is: string}} descriptor The Polymer descriptor of the element. - * @see https://github.com/Polymer/polymer/blob/0.8-preview/PRIMER.md#custom-element-registration - */ -var Polymer = function(descriptor) {}; - - -/** - * Re-evaluates and applies custom CSS properties based on dynamic - * changes to this element's scope, such as adding or removing classes. - * - * For performance reasons, Polymer's custom CSS property shim relies - * on this explicit signal from the user to indicate when changes have - * been made that affect the values of custom properties. - * - * @param {Object=} properties Properties object which is mixed into - * the document root `customStyle` property. This argument provides a - * shortcut for setting `customStyle` and then calling `updateStyles`. - * - * @see http://polymer.github.io/polymer/ - */ -Polymer.updateStyles = function(properties) {}; - - -/** @constructor @extends {HTMLElement} */ -var PolymerElement = function() {}; - -/** - * A mapping from ID to element in this Polymer Element's local DOM. - * @type {!Object} - */ -PolymerElement.prototype.$; - -/** - * True if the element has been attached to the DOM. - * @type {boolean} - */ -PolymerElement.prototype.isAttached; - -/** - * The root node of the element. - * @type {!Node} - */ -PolymerElement.prototype.root; - -/** - * The root node for the element. - * Only exists if running under Shady Dom. - * You usually want to use `this.root`. - * - * @type {?Node|undefined} - */ -PolymerElement.prototype.shadyRoot; - -/** - * Returns the first node in this element’s local DOM that matches selector. - * @param {string} selector - * @return {Element} Element found by the selector, or null if not found. - */ -PolymerElement.prototype.$$ = function(selector) {}; - -/** @type {string} The custom element tag name. */ -PolymerElement.prototype.is; - -/** @type {null|!HTMLTemplateElement} The element's template. */ -PolymerElement.prototype._template; - -/** @type {string} The native element this element extends. */ -PolymerElement.prototype.extends; - -/** - * An array of objects whose properties get added to this element. - * @see https://www.polymer-project.org/1.0/docs/devguide/behaviors.html - * @type {!Array|undefined} - */ -PolymerElement.prototype.behaviors; - -/** - * A string-separated list of dependent properties that should result in a - * change function being called. These observers differ from single-property - * observers in that the change handler is called asynchronously. - * - * @type {!Object|undefined} - */ -PolymerElement.prototype.observers; - -/** On create callback. */ -PolymerElement.prototype.created = function() {}; -/** On ready callback. */ -PolymerElement.prototype.ready = function() {}; -/** On before register callback. */ -PolymerElement.prototype.beforeRegister = function() {}; -/** On registered callback. */ -PolymerElement.prototype.registered = function() {}; -/** On attached to the DOM callback. */ -PolymerElement.prototype.attached = function() {}; -/** On detached from the DOM callback. */ -PolymerElement.prototype.detached = function() {}; - -/** - * Callback fired when an attribute on the element has been changed. - * - * @param {string} name The name of the attribute that changed. - */ -PolymerElement.prototype.attributeChanged = function(name) {}; - -/** @typedef {!{ - * type: !Function, - * reflectToAttribute: (boolean|undefined), - * readOnly: (boolean|undefined), - * notify: (boolean|undefined), - * value: *, - * computed: (string|undefined), - * observer: (string|undefined) - * }} */ -PolymerElement.PropertyConfig; - -/** @typedef {!Object} */ -PolymerElement.Properties; - -/** @type {!PolymerElement.Properties} */ -PolymerElement.prototype.properties; - -/** @type {!Object} */ -PolymerElement.prototype.hostAttributes; - -/** - * An object that maps events to event handler function names. - * @type {!Object} - */ -PolymerElement.prototype.listeners; - -/** - * Force this element to distribute its children to its local dom. - * A user should call `distributeContent` if distribution has been - * invalidated due to changes to selectors on child elements that - * effect distribution that were not made via `Polymer.dom`. - * For example, if an element contains an insertion point with - * `` and a `foo` class is added to a child, - * then `distributeContent` must be called to update - * local dom distribution. - * @param {boolean} updateInsertionPoints Shady DOM does not detect - * insertion that is nested in a sub-tree being appended. - * Set to true to distribute to newly added nested 's. - */ -PolymerElement.prototype.distributeContent = function(updateInsertionPoints) {}; - -/** - * Return the element whose local dom within which this element is contained. - * @type {?Element} - */ -PolymerElement.prototype.domHost; - -/** - * Notifies the event binding system of a change to a property. - * @param {string} path The path to set. - * @param {*=} value The value to send in the update notification. - * @param {boolean=} fromAbove When true, specifies that the change came from - * above this element and thus upward notification is not necessary. - * @return {boolean} True if notification actually took place, based on a dirty - * check of whether the new value was already known. - */ -PolymerElement.prototype.notifyPath = function(path, value, fromAbove) {}; - -/** - * @param {string} path Path that should be notified. - * @param {!Array} splices Array of splice records indicating - * ordered changes that occurred to the array. - */ -PolymerElement.prototype.notifySplices = function(path, splices) {}; - -/** - * Convienence method for setting a value to a path and notifying any - * elements bound to the same path. - * - * Note, if any part in the path except for the last is undefined, - * this method does nothing (this method does not throw when - * dereferencing undefined paths). - * - * @param {(string|Array<(string|number)>)} path Path to the value - * to read. The path may be specified as a string (e.g. `foo.bar.baz`) - * or an array of path parts (e.g. `['foo.bar', 'baz']`). Note that - * bracketed expressions are not supported; string-based path parts - * *must* be separated by dots. Note that when dereferencing array - * indices, the index may be used as a dotted part directly - * (e.g. `users.12.name` or `['users', 12, 'name']`). - * @param {*} value Value to set at the specified path. - * @param {Object=} root Root object from which the path is evaluated. - */ -PolymerElement.prototype.set = function(path, value, root) {}; - -/** - * Convienence method for reading a value from a path. - * - * Note, if any part in the path is undefined, this method returns - * `undefined` (this method does not throw when dereferencing undefined - * paths). - * - * @param {(string|Array<(string|number)>)} path Path to the value - * to read. The path may be specified as a string (e.g. `foo.bar.baz`) - * or an array of path parts (e.g. `['foo.bar', 'baz']`). Note that - * bracketed expressions are not supported; string-based path parts - * *must* be separated by dots. Note that when dereferencing array - * indices, the index may be used as a dotted part directly - * (e.g. `users.12.name` or `['users', 12, 'name']`). - * @param {Object=} root Root object from which the path is evaluated. - * @return {*} Value at the path, or `undefined` if any part of the path - * is undefined. - */ -PolymerElement.prototype.get = function(path, root) {}; - -/** - * Adds items onto the end of the array at the path specified. - * - * The arguments after `path` and return value match that of - * `Array.prototype.push`. - * - * This method notifies other paths to the same array that a - * splice occurred to the array. - * - * @param {string} path Path to array. - * @param {...*} var_args Items to push onto array - * @return {number} New length of the array. - */ -PolymerElement.prototype.push = function(path, var_args) {}; - -/** - * Removes an item from the end of array at the path specified. - * - * The arguments after `path` and return value match that of - * `Array.prototype.pop`. - * - * This method notifies other paths to the same array that a - * splice occurred to the array. - * - * @param {string} path Path to array. - * @return {*} Item that was removed. - */ -PolymerElement.prototype.pop = function(path) {}; - -/** - * Starting from the start index specified, removes 0 or more items - * from the array and inserts 0 or more new itms in their place. - * - * The arguments after `path` and return value match that of - * `Array.prototype.splice`. - * - * This method notifies other paths to the same array that a - * splice occurred to the array. - * - * @param {string} path Path to array. - * @param {number} start Index from which to start removing/inserting. - * @param {number} deleteCount Number of items to remove. - * @param {...*} var_args Items to insert into array. - * @return {!Array} Array of removed items. - */ -PolymerElement.prototype.splice = function(path, start, deleteCount, var_args) {}; - -/** - * Removes an item from the beginning of array at the path specified. - * - * The arguments after `path` and return value match that of - * `Array.prototype.pop`. - * - * This method notifies other paths to the same array that a - * splice occurred to the array. - * - * @param {string} path Path to array. - * @return {*} Item that was removed. - */ -PolymerElement.prototype.shift = function(path) {}; - -/** - * Adds items onto the beginning of the array at the path specified. - * - * The arguments after `path` and return value match that of - * `Array.prototype.push`. - * - * This method notifies other paths to the same array that a - * splice occurred to the array. - * - * @param {string} path Path to array. - * @param {...*} var_args Items to insert info array - * @return {number} New length of the array. - */ -PolymerElement.prototype.unshift = function(path, var_args) {}; - -/** - * Returns a list of element children distributed to this element's - * ``. - * - * If this element contans more than one `` in its - * local DOM, an optional selector may be passed to choose the desired - * content. This method differs from `getContentChildNodes` in that only - * elements are returned. - * - * @param {string=} slctr CSS selector to choose the desired - * ``. Defaults to `content`. - * @return {!Array} List of distributed nodes for the - * ``. - */ -PolymerElement.prototype.getContentChildren = function(slctr) {}; - -/** - * Returns a list of nodes that are the effective childNodes. The effective - * childNodes list is the same as the element's childNodes except that - * any `` elements are replaced with the list of nodes distributed - * to the ``, the result of its `getDistributedNodes` method. - * - * @return {!Array} List of effective child nodes. - */ -PolymerElement.prototype.getEffectiveChildNodes = function() {}; - -/** - * Returns a list of elements that are the effective children. The effective - * children list is the same as the element's children except that - * any `` elements are replaced with the list of elements - * distributed to the ``. - * - * @return {!Array} List of effective children. - */ -PolymerElement.prototype.getEffectiveChildren = function() {}; - -/** - * Returns a string of text content that is the concatenation of the - * text content's of the element's effective childNodes (the elements - * returned by , - * removed: !Array - * }} - */ -var PolymerKeySplice; - -/** - * @typedef {{ - * indexSplices: ?Array, - * keySplices: ?Array - * }} - */ -var PolymerSpliceChange; - -/** - * The type of the object received by an observer function when deep - * sub-property observation is enabled. See: - * https://www.polymer-project.org/1.0/docs/devguide/properties.html#deep-observation - * - * @typedef {{ - * path: string, - * value: (?Object|undefined), - * base: (?Object|undefined) - * }} - */ -var PolymerDeepPropertyChange; - -/** - * The interface that iconsets should obey. Iconsets are registered by setting - * their name in the IronMeta 'iconset' db, and a value of type Polymer.Iconset. - * - * Used by iron-icon but needs to live here since iron-icon, iron-iconset, etc don't - * depend on each other at all and talk only through iron-meta. - * - * @interface - */ -Polymer.Iconset = function() {}; - -/** - * Applies an icon to the given element as a css background image. This - * method does not size the element, and it's usually necessary to set - * the element's height and width so that the background image is visible. - * - * @param {Element} element The element to which the icon is applied. - * @param {string} icon The name of the icon to apply. - * @param {string=} theme (optional) The name or index of the icon to apply. - * @param {number=} scale (optional, defaults to 1) Icon scaling factor. - */ -Polymer.Iconset.prototype.applyIcon = function( - element, icon, theme, scale) {}; - -/** - * Remove an icon from the given element by undoing the changes effected - * by `applyIcon`. - * - * @param {Element} element The element from which the icon is removed. - */ -Polymer.Iconset.prototype.removeIcon = function(element) {}; - -Polymer.ResolveUrl = {}; - -/** - * @param {string} cssText Some CSS text taken from ownerDocument. - * @param {!Document} ownerDocument The source of the css. - * @return {string} The given CSS text with its URLs rewritten to be based on - * the primary document of this window rather than the given ownerDocument. - */ -Polymer.ResolveUrl.resolveCss = function(cssText, ownerDocument) {} -/** - * @param {!Element} element An element whose URL attributes need to be renormed. - * @param {!Document} ownerDocument The document whose URL is the base of the - * element's current attributes. - */ -Polymer.ResolveUrl.resolveAttrs = function(element, ownerDocument) {} -/** - * @param {string} url A url that needs to be renormed. - * @param {?string} baseURI The current base of URL for the URL. - * @return {string} The given url rewritten to be based on - * the primary document of this window rather than the given url. - */ -Polymer.ResolveUrl.resolveUrl = function(url, baseURI) {} - -/** @const */ -Polymer.RenderStatus = {}; - -/** - * Makes callback when first render occurs or immediately if render has - * occurred. - * @param {!function()} cb Callback function to be invoked. - */ -Polymer.RenderStatus.whenReady = function(cb) {} - -/** - * Queue up function call on next render. - * @param {!Element} element The element on which the function call is made. - * @param {!function()} fn The function called on next render. - * @param {...*} args The function arguments. - */ -Polymer.RenderStatus.afterNextRender = function(element, fn, args) {} - - - -/** - * Static analysis for Polymer. - * @const - */ -var hydrolysis = {}; - -/** - * A database of Polymer metadata defined in HTML - * @param {boolean} attachAST If true, attach a parse5 compliant AST - * @param {Object=} opt_loader An optional FileLoader used to load - * external resources - */ -hydrolysis.Analyzer = function(attachAST, opt_loader) {}; - - -/** - * Shorthand for transitively loading and processing all imports - * beginning at href. - * @param {string} href The root import to begin loading from. - * @param {Object=} opt_options Any additional options for the load. - */ -hydrolysis.Analyzer.analyze = function(href, opt_options) {}; - - - -/** - * Contains information useful for debugging. Should not be used in production - * code and the API may change on short notice. - * @const - */ -Polymer.telemetry = {}; - -/** - * Number of elements instantiated so far. - * @type {number} - */ -Polymer.telemetry.instanceCount; - -/** - * Array of all registered element prototypes. Being prototypes, not all runtime - * properties will be available, but eg. `is` is always there. - * @type {!Array} - */ -Polymer.telemetry.registrations; - -/** @const */ -Polymer.AppLayout = {}; - -/** @constructor */ -Polymer.AppLayout.LocalDomWithBackground = function(){}; -/** @type {!HTMLElement} */ -Polymer.AppLayout.LocalDomWithBackground.prototype.backgroundFrontLayer; -/** @type {!HTMLElement} */ -Polymer.AppLayout.LocalDomWithBackground.prototype.backgroundRearLayer; -/** @type {!HTMLElement} */ -Polymer.AppLayout.LocalDomWithBackground.prototype.background; - -/** - * @constructor - * @extends {PolymerElement} - */ -Polymer.AppLayout.ElementWithBackground = function(){}; - -// TODO(ajo): Follow up with app-layout team and remove private api from this prototype -Polymer.AppLayout.ElementWithBackground.prototype = { - /** @type {!Polymer.AppLayout.LocalDomWithBackground} */ - $: null, - /** @return {boolean} True if there's content below the current element */ - isContentBelow: function(){}, - /** Updates the elements scroll state */ - _updateScrollState: function(){}, - /** @return {boolean} true if the element is on screen */ - isOnScreen: function(){}, - /** @type {number} Internal bookkeeping to track screen position */ - _deltaHeight: 0, - /** @return {?Element} Element in local dom by id. */ - _getDOMRef: function(title){} -} - -/** @const */ -Polymer.ArraySplice = {}; - -/** - * Returns an array of splice records indicating the minimum edits required - * to transform the `previous` array into the `current` array. - * - * Splice records are ordered by index and contain the following fields: - * - `index`: index where edit started - * - `removed`: array of removed items from this index - * - `addedCount`: number of items added at this index - * - * This function is based on the Levenshtein "minimum edit distance" - * algorithm. Note that updates are treated as removal followed by addition. - * - * The worst-case time complexity of this algorithm is `O(l * p)` - * l: The length of the current array - * p: The length of the previous array - * - * However, the worst-case complexity is reduced by an `O(n)` optimization - * to detect any shared prefix & suffix between the two arrays and only - * perform the more expensive minimum edit distance calculation over the - * non-shared portions of the arrays. - * - * @param {!Array} current The "changed" array for which splices will be - * calculated. - * @param {!Array} previous The "unchanged" original array to compare - * `current` against to determine the splices. - * @return {!Array} Returns an array of splice record objects. Each of these - * contains: `index` the location where the splice occurred; `removed` - * the array of removed items from this location; `addedCount` the number - * of items added at this location. - */ -Polymer.ArraySplice.calculateSplices = function(current, previous) {}; - -/** - * @constructor @extends {PolymerElement} - */ -Polymer.DomModule = function() {}; - -/** - * Retrieves the dom specified by `selector` in the module specified by - * `id`. For example, this.import('foo', 'img'); - * @param {string} id - * @param {string=} opt_selector - * @return {?HTMLElement} Returns the dom which matches `selector` in the module - * at the specified `id`. - */ -Polymer.DomModule.import = function(id, opt_selector) {}; - -/** @const */ -Polymer.Path = { - /** - * @param {string=} base - * @param {string=} newBase - * @param {string=} path - * @return {string} - */ - translate: function(base, newBase, path) {}, - - /** - * @param {string=} base - * @param {string=} wildcard - * @param {string=} path - * @return {boolean} - */ - matches: function(base, wildcard, path) {} -}; - -/** - * For compatibility with both Polymer 1.0 and 2.0, code may check for certain - * objects and properties which don't exist in Polymer 1.0. - * - * We give those objects and properties the `undefined` type here, because - * the dependency tree will either contain these externs and Polymer 1.0 or - * it will contain Polymer 2.0 which defines the full types. - */ - -/** @type {undefined} */ -var ShadyDOM; - -Polymer.flush; -Polymer.enqueueDebouncer; -Polymer.Async.animationFrame; -Polymer.Async.idlePeriod; -Polymer.Async.microTask; -Polymer.Debouncer.debounce; - -Polymer.Templatizer.mutableData; -Polymer.Templatizer.parentModel; -Polymer.Templatizer.forwardHostProp; -Polymer.Templatizer.notifyInstanceProp; -Polymer.Templatizer._setPendingPropertyOrPath; -Polymer.Templatizer._setPendingProperty; -Polymer.Templatizer._instanceProps; - -/** - * @param {number} index - * @return {boolean} - */ -ArraySelectorElement.prototype.isIndexSelected = function(index) {}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/quick_unlock_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/quick_unlock_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/quick_unlock_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/quick_unlock_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,156 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.quickUnlockPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: quickUnlockPrivate - * @externs - */ - -/** @const */ -chrome.quickUnlockPrivate = {}; - -/** - * @typedef {{ - * token: string, - * lifetimeSeconds: number - * }} - */ -chrome.quickUnlockPrivate.TokenInfo; - -/** - * @enum {string} - */ -chrome.quickUnlockPrivate.QuickUnlockMode = { - PIN: 'PIN', -}; - -/** - * @enum {string} - */ -chrome.quickUnlockPrivate.CredentialProblem = { - TOO_SHORT: 'TOO_SHORT', - TOO_LONG: 'TOO_LONG', - TOO_WEAK: 'TOO_WEAK', - CONTAINS_NONDIGIT: 'CONTAINS_NONDIGIT', -}; - -/** - * @typedef {{ - * errors: !Array, - * warnings: !Array - * }} - */ -chrome.quickUnlockPrivate.CredentialCheck; - -/** - * @typedef {{ - * minLength: number, - * maxLength: number - * }} - */ -chrome.quickUnlockPrivate.CredentialRequirements; - -/** - * Returns a token that can be used for future operations and the number of - * seconds until the token expires. - * @param {string} accountPassword The account password for the logged in user. - * @param {function(!chrome.quickUnlockPrivate.TokenInfo): void} onComplete - */ -chrome.quickUnlockPrivate.getAuthToken = function(accountPassword, onComplete) {}; - -/** - * Sets the lock screen enabled state. NOTE: The lock enabled state is reflected - * in the settings.enable_screen_lock pref, which can be read but not written - * using the settings_private API (which also provides policy information). This - * API must be used to change the pref. - * @param {string} token The token returned by $(ref:getAuthToken). - * @param {boolean} enabled Whether to enable the lock screen. - * @param {function(): void=} onComplete - */ -chrome.quickUnlockPrivate.setLockScreenEnabled = function(token, enabled, onComplete) {}; - -/** - * Sets the PIN auto submit enabled state. NOTE: The PIN autosubmit state is - * reflected in the pin_unlock_autosubmit_enabled pref, which can be read but - * not written using the settings_private API (which also provides policy - * information). This API must be used to change the pref. - * @param {string} token The authentication token. - * @param {string} pin The PIN of the logged in user. - * @param {boolean} enabled Whether to enable PIN auto submit. - * @param {function(boolean): void} onComplete Called with true if the quick - * unlock state was updated, false otherwise. The update is treated as a - * single atomic operation. - */ -chrome.quickUnlockPrivate.setPinAutosubmitEnabled = function(token, pin, enabled, onComplete) {}; - -/** - * Tests wether it is currently possible to authenticate using PIN. - * @param {function(boolean): void} onComplete - */ -chrome.quickUnlockPrivate.canAuthenticatePin = function(onComplete) {}; - -/** - * Returns the set of quick unlock modes that are available for the user to use. - * Some quick unlock modes may be disabled by policy. - * @param {function(!Array): void} - * onComplete - */ -chrome.quickUnlockPrivate.getAvailableModes = function(onComplete) {}; - -/** - * Returns the quick unlock modes that are currently enabled and usable on the - * lock screen. - * @param {function(!Array): void} - * onComplete - */ -chrome.quickUnlockPrivate.getActiveModes = function(onComplete) {}; - -/** - * Checks if the given credential can be used for the given unlock mode. - * Enterprise policy can change credential requirements. - * @param {!chrome.quickUnlockPrivate.QuickUnlockMode} mode The quick unlock - * mode that is used. - * @param {string} credential The given credential. - * @param {function(!chrome.quickUnlockPrivate.CredentialCheck): void} - * onComplete Called with a list of warnings and errors the given - * |credential| has (or an empty list if there are none). - */ -chrome.quickUnlockPrivate.checkCredential = function(mode, credential, onComplete) {}; - -/** - * Gets the credential requirements for the given unlock mode. - * @param {!chrome.quickUnlockPrivate.QuickUnlockMode} mode The quick unlock - * mode that is used. - * @param {function(!chrome.quickUnlockPrivate.CredentialRequirements): void} - * onComplete Called with the credential requirements of the given - * |mode|. - */ -chrome.quickUnlockPrivate.getCredentialRequirements = function(mode, onComplete) {}; - -/** - * Update the set of quick unlock modes that are currently active/enabled. - * @param {string} token The token returned by $(ref:getAuthToken). - * @param {!Array} modes The quick - * unlock modes that should be active. - * @param {!Array} credentials The associated credential for each mode. - * To keep the credential the same for the associated mode, pass an - * empty string. - * @param {function(): void} onComplete Called with true if the quick unlock - * state was updated, false otherwise. The update is treated as a single - * atomic operation. - */ -chrome.quickUnlockPrivate.setModes = function(token, modes, credentials, onComplete) {}; - -/** - * Called after the active set of quick unlock modes has changed. - * @type {!ChromeEvent} - */ -chrome.quickUnlockPrivate.onActiveModesChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/runtime.js chromium-132.0.6834.159/third_party/closure_compiler/externs/runtime.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/runtime.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/runtime.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,547 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.runtime.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -// TODO(crbug.com/543822): Disable automatic extern generation until fixed. -// s/chrome.runtime.tabs.Tab/chrome.tabs.Tab/ - -/** - * @fileoverview Externs generated from namespace: runtime - * @externs - */ - -/** @const */ -chrome.runtime = {}; - -/** - * An object which allows two way communication with other pages. See Long-lived connections for more information. - * @constructor - * @private - * @see https://developer.chrome.com/extensions/runtime#type-Port - */ -chrome.runtime.Port = function() {}; - -/** - * The name of the port, as specified in the call to $(ref:runtime.connect). - * @type {string} - * @see https://developer.chrome.com/extensions/runtime#type-name - */ -chrome.runtime.Port.prototype.name; - -/** - * Immediately disconnect the port. Calling disconnect() on an - * already-disconnected port has no effect. When a port is disconnected, no new - * events will be dispatched to this port. - * @see https://developer.chrome.com/extensions/runtime#method-disconnect - */ -chrome.runtime.Port.prototype.disconnect = function() {}; - -/** - * Send a message to the other end of the port. If the port is disconnected, an - * error is thrown. - * @param {*} message The message to send. This object should be JSON-ifiable. - * @see https://developer.chrome.com/extensions/runtime#method-postMessage - */ -chrome.runtime.Port.prototype.postMessage = function(message) {}; - -/** - * This property will only be present on ports passed to $(ref:runtime.onConnect onConnect) / $(ref:runtime.onConnectExternal onConnectExternal) / $(ref:runtime.onConnectExternal onConnectNative) listeners. - * @type {(!chrome.runtime.MessageSender|undefined)} - * @see https://developer.chrome.com/extensions/runtime#type-sender - */ -chrome.runtime.Port.prototype.sender; - - -/** - * An object containing information about the script context that sent a message or request. - * @typedef {{ - * tab: (!chrome.tabs.Tab|undefined), - * frameId: (number|undefined), - * guestProcessId: (number|undefined), - * guestRenderFrameRoutingId: (number|undefined), - * id: (string|undefined), - * url: (string|undefined), - * nativeApplication: (string|undefined), - * tlsChannelId: (string|undefined), - * origin: (string|undefined), - * documentId: (string|undefined), - * documentLifecycle: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/runtime#type-MessageSender - */ -chrome.runtime.MessageSender; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/runtime#type-PlatformOs - */ -chrome.runtime.PlatformOs = { - MAC: 'mac', - WIN: 'win', - ANDROID: 'android', - CROS: 'cros', - LINUX: 'linux', - OPENBSD: 'openbsd', - FUCHSIA: 'fuchsia', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/runtime#type-PlatformArch - */ -chrome.runtime.PlatformArch = { - ARM: 'arm', - ARM64: 'arm64', - X86_32: 'x86-32', - X86_64: 'x86-64', - MIPS: 'mips', - MIPS64: 'mips64', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/runtime#type-PlatformNaclArch - */ -chrome.runtime.PlatformNaclArch = { - ARM: 'arm', - X86_32: 'x86-32', - X86_64: 'x86-64', - MIPS: 'mips', - MIPS64: 'mips64', -}; - -/** - * An object containing information about the current platform. - * @typedef {{ - * os: !chrome.runtime.PlatformOs, - * arch: !chrome.runtime.PlatformArch, - * nacl_arch: !chrome.runtime.PlatformNaclArch - * }} - * @see https://developer.chrome.com/extensions/runtime#type-PlatformInfo - */ -chrome.runtime.PlatformInfo; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/runtime#type-RequestUpdateCheckStatus - */ -chrome.runtime.RequestUpdateCheckStatus = { - THROTTLED: 'throttled', - NO_UPDATE: 'no_update', - UPDATE_AVAILABLE: 'update_available', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/runtime#type-OnInstalledReason - */ -chrome.runtime.OnInstalledReason = { - INSTALL: 'install', - UPDATE: 'update', - CHROME_UPDATE: 'chrome_update', - SHARED_MODULE_UPDATE: 'shared_module_update', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/runtime#type-OnRestartRequiredReason - */ -chrome.runtime.OnRestartRequiredReason = { - APP_UPDATE: 'app_update', - OS_UPDATE: 'os_update', - PERIODIC: 'periodic', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/runtime#type-ContextType - */ -chrome.runtime.ContextType = { - TAB: 'TAB', - POPUP: 'POPUP', - BACKGROUND: 'BACKGROUND', - OFFSCREEN_DOCUMENT: 'OFFSCREEN_DOCUMENT', - SIDE_PANEL: 'SIDE_PANEL', -}; - -/** - * A context hosting extension content. - * @typedef {{ - * contextType: !chrome.runtime.ContextType, - * contextId: string, - * tabId: number, - * windowId: number, - * documentId: (string|undefined), - * frameId: number, - * documentUrl: (string|undefined), - * documentOrigin: (string|undefined), - * incognito: boolean - * }} - * @see https://developer.chrome.com/extensions/runtime#type-ExtensionContext - */ -chrome.runtime.ExtensionContext; - -/** - * A filter to match against certain extension contexts. Matching contexts must match all specified filters; any filter that is not specified matches all available contexts. Thus, a filter of `{}` will match all available contexts. - * @typedef {{ - * contextTypes: (!Array|undefined), - * contextIds: (!Array|undefined), - * tabIds: (!Array|undefined), - * windowIds: (!Array|undefined), - * documentIds: (!Array|undefined), - * frameIds: (!Array|undefined), - * documentUrls: (!Array|undefined), - * documentOrigins: (!Array|undefined), - * incognito: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/runtime#type-ContextFilter - */ -chrome.runtime.ContextFilter; - -/** - * This will be defined during an API method callback if there was an error - * @typedef {{ - * message: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/runtime#type-lastError - */ -chrome.runtime.lastError; - -/** - * The ID of the extension/app. - * @type {string} - * @see https://developer.chrome.com/extensions/runtime#type-id - */ -chrome.runtime.id; - -/** - * Retrieves the JavaScript 'window' object for the background page running - * inside the current extension/app. If the background page is an event page, - * the system will ensure it is loaded before calling the callback. If there is - * no background page, an error is set. - * @param {function((Window|undefined)): void} callback - * @see https://developer.chrome.com/extensions/runtime#method-getBackgroundPage - */ -chrome.runtime.getBackgroundPage = function(callback) {}; - -/** - *

Open your Extension's options page, if possible.

The precise - * behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support - * at the time. For example, the page may be opened in a new tab, within - * chrome://extensions, within an App, or it may just focus an open options - * page. It will never cause the caller page to reload.

If your Extension - * does not declare an options page, or Chrome failed to create one for some - * other reason, the callback will set $(ref:lastError).

- * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/runtime#method-openOptionsPage - */ -chrome.runtime.openOptionsPage = function(callback) {}; - -/** - * Returns details about the app or extension from the manifest. The object - * returned is a serialization of the full manifest - * file. - * @return {Object} The manifest details. - * @see https://developer.chrome.com/extensions/runtime#method-getManifest - */ -chrome.runtime.getManifest = function() {}; - -/** - * Converts a relative path within an app/extension install directory to a - * fully-qualified URL. - * @param {string} path A path to a resource within an app/extension expressed - * relative to its install directory. - * @return {string} The fully-qualified URL to the resource. - * @see https://developer.chrome.com/extensions/runtime#method-getURL - */ -chrome.runtime.getURL = function(path) {}; - -/** - * Sets the URL to be visited upon uninstallation. This may be used to clean up - * server-side data, do analytics, and implement surveys. Maximum 1023 - * characters. - * @param {string} url URL to be opened after the extension is uninstalled. This - * URL must have an http: or https: scheme. Set an empty string to not open - * a new tab upon uninstallation. - * @param {function(): void=} callback Called when the uninstall URL is set. If - * the given URL is invalid, $(ref:runtime.lastError) will be set. - * @see https://developer.chrome.com/extensions/runtime#method-setUninstallURL - */ -chrome.runtime.setUninstallURL = function(url, callback) {}; - -/** - * Reloads the app or extension. This method is not supported in kiosk mode. For - * kiosk mode, use chrome.runtime.restart() method. - * @see https://developer.chrome.com/extensions/runtime#method-reload - */ -chrome.runtime.reload = function() {}; - -/** - *

Requests an immediate update check be done for this app/extension.

- *

Important: Most extensions/apps should not use this method, - * since Chrome already does automatic checks every few hours, and you can - * listen for the $(ref:runtime.onUpdateAvailable) event without needing to call - * requestUpdateCheck.

This method is only appropriate to call in very - * limited circumstances, such as if your extension/app talks to a backend - * service, and the backend service has determined that the client extension/app - * version is very far out of date and you'd like to prompt a user to update. - * Most other uses of requestUpdateCheck, such as calling it unconditionally - * based on a repeating timer, probably only serve to waste client, network, and - * server resources.

Note: When called with a callback, instead of - * returning an object this function will return the two properties as separate - * arguments passed to the callback.

- * @param {function({ - * status: !chrome.runtime.RequestUpdateCheckStatus, - * version: (string|undefined) - * }): void} callback - * @see https://developer.chrome.com/extensions/runtime#method-requestUpdateCheck - */ -chrome.runtime.requestUpdateCheck = function(callback) {}; - -/** - * Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's - * no-op. - * @see https://developer.chrome.com/extensions/runtime#method-restart - */ -chrome.runtime.restart = function() {}; - -/** - * Restart the ChromeOS device when the app runs in kiosk mode after the given - * seconds. If called again before the time ends, the reboot will be delayed. If - * called with a value of -1, the reboot will be cancelled. It's a no-op in - * non-kiosk mode. It's only allowed to be called repeatedly by the first - * extension to invoke this API. - * @param {number} seconds Time to wait in seconds before rebooting the device, - * or -1 to cancel a scheduled reboot. - * @param {function(): void=} callback A callback to be invoked when a restart - * request was successfully rescheduled. - * @see https://developer.chrome.com/extensions/runtime#method-restartAfterDelay - */ -chrome.runtime.restartAfterDelay = function(seconds, callback) {}; - -/** - * Attempts to connect listeners within an extension/app (such as the background - * page), or other extensions/apps. This is useful for content scripts - * connecting to their extension processes, inter-app/extension communication, - * and web messaging. Note - * that this does not connect to any listeners in a content script. Extensions - * may connect to content scripts embedded in tabs via $(ref:tabs.connect). - * @param {string=} extensionId The ID of the extension or app to connect to. If - * omitted, a connection will be attempted with your own extension. Required - * if sending messages from a web page for web messaging. - * @param {{ - * name: (string|undefined), - * includeTlsChannelId: (boolean|undefined) - * }=} connectInfo - * @return {!chrome.runtime.Port} Port through which messages can be sent and - * received. The port's $(ref:Port onDisconnect) event is fired if the - * extension/app does not exist. - * @see https://developer.chrome.com/extensions/runtime#method-connect - */ -chrome.runtime.connect = function(extensionId, connectInfo) {}; - -/** - * Connects to a native application in the host machine. See Native Messaging for more information. - * @param {string} application The name of the registered application to connect - * to. - * @return {!chrome.runtime.Port} Port through which messages can be sent and - * received with the application - * @see https://developer.chrome.com/extensions/runtime#method-connectNative - */ -chrome.runtime.connectNative = function(application) {}; - -/** - * Sends a single message to event listeners within your extension/app or a - * different extension/app. Similar to $(ref:runtime.connect) but only sends a - * single message, with an optional response. If sending to your extension, the - * $(ref:runtime.onMessage) event will be fired in every frame of your extension - * (except for the sender's frame), or $(ref:runtime.onMessageExternal), if a - * different extension. Note that extensions cannot send messages to content - * scripts using this method. To send messages to content scripts, use - * $(ref:tabs.sendMessage). - * @param {?string|undefined} extensionId The ID of the extension/app to send - * the message to. If omitted, the message will be sent to your own - * extension/app. Required if sending messages from a web page for web messaging. - * @param {*} message The message to send. This message should be a JSON-ifiable - * object. - * @param {{ - * includeTlsChannelId: (boolean|undefined) - * }=} options - * @param {function(*): void=} callback - * @see https://developer.chrome.com/extensions/runtime#method-sendMessage - */ -chrome.runtime.sendMessage = function(extensionId, message, options, callback) {}; - -/** - * Send a single message to a native application. - * @param {string} application The name of the native messaging host. - * @param {Object} message The message that will be passed to the native - * messaging host. - * @param {function(*): void=} callback - * @see https://developer.chrome.com/extensions/runtime#method-sendNativeMessage - */ -chrome.runtime.sendNativeMessage = function(application, message, callback) {}; - -/** - * Returns information about the current platform. - * @param {function(!chrome.runtime.PlatformInfo): void} callback Called with - * results - * @see https://developer.chrome.com/extensions/runtime#method-getPlatformInfo - */ -chrome.runtime.getPlatformInfo = function(callback) {}; - -/** - * Returns a DirectoryEntry for the package directory. - * @param {function(DirectoryEntry): void} callback - * @see https://developer.chrome.com/extensions/runtime#method-getPackageDirectoryEntry - */ -chrome.runtime.getPackageDirectoryEntry = function(callback) {}; - -/** - * Fetches information about active contexts associated with this extension - * @param {!chrome.runtime.ContextFilter} filter A filter to find matching - * contexts. A context matches if it matches all specified fields in the - * filter. Any unspecified field in the filter matches all contexts. - * @param {function(!Array): void} callback - * Invoked with the matching contexts, if any. - * @see https://developer.chrome.com/extensions/runtime#method-getContexts - */ -chrome.runtime.getContexts = function(filter, callback) {}; - -/** - * Fired when a profile that has this extension installed first starts up. This - * event is not fired when an incognito profile is started, even if this - * extension is operating in 'split' incognito mode. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onStartup - */ -chrome.runtime.onStartup; - -/** - * Fired when the extension is first installed, when the extension is updated to - * a new version, and when Chrome is updated to a new version. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onInstalled - */ -chrome.runtime.onInstalled; - -/** - * Sent to the event page just before it is unloaded. This gives the extension - * opportunity to do some clean up. Note that since the page is unloading, any - * asynchronous operations started while handling this event are not guaranteed - * to complete. If more activity for the event page occurs before it gets - * unloaded the onSuspendCanceled event will be sent and the page won't be - * unloaded. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onSuspend - */ -chrome.runtime.onSuspend; - -/** - * Sent after onSuspend to indicate that the app won't be unloaded after all. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onSuspendCanceled - */ -chrome.runtime.onSuspendCanceled; - -/** - * Fired when an update is available, but isn't installed immediately because - * the app is currently running. If you do nothing, the update will be installed - * the next time the background page gets unloaded, if you want it to be - * installed sooner you can explicitly call chrome.runtime.reload(). If your - * extension is using a persistent background page, the background page of - * course never gets unloaded, so unless you call chrome.runtime.reload() - * manually in response to this event the update will not get installed until - * the next time Chrome itself restarts. If no handlers are listening for this - * event, and your extension has a persistent background page, it behaves as if - * chrome.runtime.reload() is called in response to this event. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onUpdateAvailable - */ -chrome.runtime.onUpdateAvailable; - -/** - * Fired when a Chrome update is available, but isn't installed immediately - * because a browser restart is required. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onBrowserUpdateAvailable - */ -chrome.runtime.onBrowserUpdateAvailable; - -/** - * Fired when a connection is made from either an extension process or a content - * script (by $(ref:runtime.connect)). - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onConnect - */ -chrome.runtime.onConnect; - -/** - * Fired when a connection is made from another extension (by - * $(ref:runtime.connect)). - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onConnectExternal - */ -chrome.runtime.onConnectExternal; - -/** - * Fired when a connection is made from a user script from this extension. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onUserScriptConnect - */ -chrome.runtime.onUserScriptConnect; - -/** - * Fired when a connection is made from a native application. Currently only - * supported on Chrome OS. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onConnectNative - */ -chrome.runtime.onConnectNative; - -/** - * Fired when a message is sent from either an extension process (by - * $(ref:runtime.sendMessage)) or a content script (by $(ref:tabs.sendMessage)). - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onMessage - */ -chrome.runtime.onMessage; - -/** - * Fired when a message is sent from another extension/app (by - * $(ref:runtime.sendMessage)). Cannot be used in a content script. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onMessageExternal - */ -chrome.runtime.onMessageExternal; - -/** - * Fired when a message is sent from a user script associated with the same - * extension. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onUserScriptMessage - */ -chrome.runtime.onUserScriptMessage; - -/** - * Fired when an app or the device that it runs on needs to be restarted. The - * app should close all its windows at its earliest convenient time to let the - * restart to happen. If the app does nothing, a restart will be enforced after - * a 24-hour grace period has passed. Currently, this event is only fired for - * Chrome OS kiosk apps. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/runtime#event-onRestartRequired - */ -chrome.runtime.onRestartRequired; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/settings_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/settings_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/settings_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/settings_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,114 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.settingsPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: settingsPrivate - * @externs - */ - -/** @const */ -chrome.settingsPrivate = {}; - -/** - * @enum {string} - */ -chrome.settingsPrivate.PrefType = { - BOOLEAN: 'BOOLEAN', - NUMBER: 'NUMBER', - STRING: 'STRING', - URL: 'URL', - LIST: 'LIST', - DICTIONARY: 'DICTIONARY', -}; - -/** - * @enum {string} - */ -chrome.settingsPrivate.ControlledBy = { - DEVICE_POLICY: 'DEVICE_POLICY', - USER_POLICY: 'USER_POLICY', - OWNER: 'OWNER', - PRIMARY_USER: 'PRIMARY_USER', - EXTENSION: 'EXTENSION', - PARENT: 'PARENT', - CHILD_RESTRICTION: 'CHILD_RESTRICTION', -}; - -/** - * @enum {string} - */ -chrome.settingsPrivate.Enforcement = { - ENFORCED: 'ENFORCED', - RECOMMENDED: 'RECOMMENDED', - PARENT_SUPERVISED: 'PARENT_SUPERVISED', -}; - -/** - * @typedef {{ - * key: string, - * type: !chrome.settingsPrivate.PrefType, - * value: (*|undefined), - * controlledBy: (!chrome.settingsPrivate.ControlledBy|undefined), - * controlledByName: (string|undefined), - * enforcement: (!chrome.settingsPrivate.Enforcement|undefined), - * recommendedValue: (*|undefined), - * userSelectableValues: (!Array<*>|undefined), - * userControlDisabled: (boolean|undefined), - * extensionId: (string|undefined), - * extensionCanBeDisabled: (boolean|undefined) - * }} - */ -chrome.settingsPrivate.PrefObject; - -/** - * Sets a pref value. - * @param {string} name The name of the pref. - * @param {*} value The new value of the pref. - * @param {string=} pageId An optional user metrics identifier. - * @param {function(boolean): void=} callback The callback for whether the pref - * was set or not. - */ -chrome.settingsPrivate.setPref = function(name, value, pageId, callback) {}; - -/** - * Gets an array of all the prefs. - * @param {function(!Array): void} callback - */ -chrome.settingsPrivate.getAllPrefs = function(callback) {}; - -/** - * Gets the value of a specific pref. - * @param {string} name - * @param {function(!chrome.settingsPrivate.PrefObject): void} callback - */ -chrome.settingsPrivate.getPref = function(name, callback) {}; - -/** - * Gets the default page zoom factor. Possible values are currently between 0.25 - * and 5. For a full list, see zoom::kPresetBrowserZoomFactors. - * @param {function(number): void} callback - */ -chrome.settingsPrivate.getDefaultZoom = function(callback) {}; - -/** - * Sets the page zoom factor. Must be less than 0.001 different than a value in - * zoom::kPresetBrowserZoomFactors. - * @param {number} zoom - * @param {function(boolean): void=} callback - */ -chrome.settingsPrivate.setDefaultZoom = function(zoom, callback) {}; - -/** - *

Fired when a set of prefs has changed.

|prefs| The prefs that - * changed.

- * @type {!ChromeEvent} - */ -chrome.settingsPrivate.onPrefsChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/speech_recognition_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/speech_recognition_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/speech_recognition_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/speech_recognition_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.speechRecognitionPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: speechRecognitionPrivate - * @externs - */ - -/** @const */ -chrome.speechRecognitionPrivate = {}; - -/** - * @enum {string} - */ -chrome.speechRecognitionPrivate.SpeechRecognitionType = { - ON_DEVICE: 'onDevice', - NETWORK: 'network', -}; - -/** - * @typedef {{ - * clientId: (number|undefined) - * }} - */ -chrome.speechRecognitionPrivate.SpeechRecognitionStopEvent; - -/** - * @typedef {{ - * clientId: (number|undefined), - * transcript: string, - * isFinal: boolean - * }} - */ -chrome.speechRecognitionPrivate.SpeechRecognitionResultEvent; - -/** - * @typedef {{ - * clientId: (number|undefined), - * message: string - * }} - */ -chrome.speechRecognitionPrivate.SpeechRecognitionErrorEvent; - -/** - * @typedef {{ - * clientId: (number|undefined), - * locale: (string|undefined), - * interimResults: (boolean|undefined) - * }} - */ -chrome.speechRecognitionPrivate.StartOptions; - -/** - * @typedef {{ - * clientId: (number|undefined) - * }} - */ -chrome.speechRecognitionPrivate.StopOptions; - -/** - * Starts listening to audio from the user. The callback is invoked when speech - * recognition has started. If speech recognition is already active when calling - * start(), the callback is run with an error. - * @param {!chrome.speechRecognitionPrivate.StartOptions} options - * @param {function(!chrome.speechRecognitionPrivate.SpeechRecognitionType): void} - * callback Called when speech recognition has begun listening to the user's - * audio. The callback's parameter specifies which type of speech - * recognition is being used. - */ -chrome.speechRecognitionPrivate.start = function(options, callback) {}; - -/** - * Stops listening to audio from the user. The callback is invoked when speech - * recognition has stopped. If speech recognition has already stopped when - * calling stop(), the callback is run with an error. - * @param {!chrome.speechRecognitionPrivate.StopOptions} options - * @param {function(): void} callback Called when speech recognition has stopped - * listening to the user's audio. - */ -chrome.speechRecognitionPrivate.stop = function(options, callback) {}; - -/** - * Fired when speech recognition stops. - * @type {!ChromeEvent} - */ -chrome.speechRecognitionPrivate.onStop; - -/** - * Fired when a speech recognition result is returned. - * @type {!ChromeEvent} - */ -chrome.speechRecognitionPrivate.onResult; - -/** - * Fired when a speech recognition error occurs. - * @type {!ChromeEvent} - */ -chrome.speechRecognitionPrivate.onError; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/tabs.js chromium-132.0.6834.159/third_party/closure_compiler/externs/tabs.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/tabs.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/tabs.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,599 +0,0 @@ -// 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. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.tabs.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -// TODO(crbug.com/543822): Disable automatic extern generation until fixed. -// s/chrome.tabs.extensionTypes.ImageDetails/chrome.extensionTypes.ImageDetails/ -// s/chrome.tabs.extensionTypes.InjectDetails/chrome.extensionTypes.InjectDetails/ -// s/chrome.tabs.runtime.Port/chrome.runtime.Port/ -// s/chrome.tabs.windows.Window/chrome.windows.Window/ - -/** - * @fileoverview Externs generated from namespace: tabs - * @externs - */ - -/** @const */ -chrome.tabs = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tabs#type-TabStatus - */ -chrome.tabs.TabStatus = { - UNLOADED: 'unloaded', - LOADING: 'loading', - COMPLETE: 'complete', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tabs#type-MutedInfoReason - */ -chrome.tabs.MutedInfoReason = { - USER: 'user', - CAPTURE: 'capture', - EXTENSION: 'extension', -}; - -/** - * The tab's muted state and the reason for the last state change. - * @typedef {{ - * muted: boolean, - * reason: (!chrome.tabs.MutedInfoReason|undefined), - * extensionId: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/tabs#type-MutedInfo - */ -chrome.tabs.MutedInfo; - -/** - * @typedef {{ - * id: (number|undefined), - * index: number, - * groupId: number, - * windowId: number, - * openerTabId: (number|undefined), - * selected: boolean, - * lastAccessed: number, - * highlighted: boolean, - * active: boolean, - * pinned: boolean, - * audible: (boolean|undefined), - * frozen: boolean, - * discarded: boolean, - * autoDiscardable: boolean, - * mutedInfo: (!chrome.tabs.MutedInfo|undefined), - * url: (string|undefined), - * pendingUrl: (string|undefined), - * title: (string|undefined), - * favIconUrl: (string|undefined), - * status: (!chrome.tabs.TabStatus|undefined), - * incognito: boolean, - * width: (number|undefined), - * height: (number|undefined), - * sessionId: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/tabs#type-Tab - */ -chrome.tabs.Tab; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tabs#type-ZoomSettingsMode - */ -chrome.tabs.ZoomSettingsMode = { - AUTOMATIC: 'automatic', - MANUAL: 'manual', - DISABLED: 'disabled', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tabs#type-ZoomSettingsScope - */ -chrome.tabs.ZoomSettingsScope = { - PER_ORIGIN: 'per-origin', - PER_TAB: 'per-tab', -}; - -/** - * Defines how zoom changes in a tab are handled and at what scope. - * @typedef {{ - * mode: (!chrome.tabs.ZoomSettingsMode|undefined), - * scope: (!chrome.tabs.ZoomSettingsScope|undefined), - * defaultZoomFactor: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/tabs#type-ZoomSettings - */ -chrome.tabs.ZoomSettings; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tabs#type-WindowType - */ -chrome.tabs.WindowType = { - NORMAL: 'normal', - POPUP: 'popup', - PANEL: 'panel', - APP: 'app', - DEVTOOLS: 'devtools', -}; - -/** - * An ID that represents the absence of a browser tab. - * @type {number} - * @see https://developer.chrome.com/extensions/tabs#type-TAB_ID_NONE - */ -chrome.tabs.TAB_ID_NONE; - -/** - * Retrieves details about the specified tab. - * @param {number} tabId - * @param {function(!chrome.tabs.Tab): void} callback - * @see https://developer.chrome.com/extensions/tabs#method-get - */ -chrome.tabs.get = function(tabId, callback) {}; - -/** - * Gets the tab that this script call is being made from. May be undefined if - * called from a non-tab context (for example, a background page or popup view). - * @param {function((!chrome.tabs.Tab|undefined)): void} callback - * @see https://developer.chrome.com/extensions/tabs#method-getCurrent - */ -chrome.tabs.getCurrent = function(callback) {}; - -/** - * Connects to the content script(s) in the specified tab. The - * $(ref:runtime.onConnect) event is fired in each content script running in the - * specified tab for the current extension. For more details, see Content Script Messaging. - * @param {number} tabId - * @param {{ - * name: (string|undefined), - * frameId: (number|undefined) - * }=} connectInfo - * @return {!chrome.runtime.Port} A port that can be used to communicate - * with the content scripts running in the specified tab. The port's - * $(ref:runtime.Port) event is fired if the tab closes or does not exist. - * @see https://developer.chrome.com/extensions/tabs#method-connect - */ -chrome.tabs.connect = function(tabId, connectInfo) {}; - -/** - * Sends a single request to the content script(s) in the specified tab, with an - * optional callback to run when a response is sent back. The - * $(ref:extension.onRequest) event is fired in each content script running in - * the specified tab for the current extension. - * @param {number} tabId - * @param {*} request - * @param {function(*): void=} responseCallback - * @deprecated Please use $(ref:runtime.sendMessage). - * @see https://developer.chrome.com/extensions/tabs#method-sendRequest - */ -chrome.tabs.sendRequest = function(tabId, request, responseCallback) {}; - -/** - * Sends a single message to the content script(s) in the specified tab, with an - * optional callback to run when a response is sent back. The - * $(ref:runtime.onMessage) event is fired in each content script running in the - * specified tab for the current extension. - * @param {number} tabId - * @param {*} message The message to send. This message should be a JSON-ifiable - * object. - * @param {{ - * frameId: (number|undefined) - * }=} options - * @param {function(*): void=} responseCallback - * @see https://developer.chrome.com/extensions/tabs#method-sendMessage - */ -chrome.tabs.sendMessage = function(tabId, message, options, responseCallback) {}; - -/** - * Gets the tab that is selected in the specified window. - * @param {?number|undefined} windowId Defaults to the current window. - * @param {function(!chrome.tabs.Tab): void} callback - * @deprecated Please use $(ref:tabs.query) {active: true}. - * @see https://developer.chrome.com/extensions/tabs#method-getSelected - */ -chrome.tabs.getSelected = function(windowId, callback) {}; - -/** - * Gets details about all tabs in the specified window. - * @param {?number|undefined} windowId Defaults to the current window. - * @param {function(!Array): void} callback - * @deprecated Please use $(ref:tabs.query) {windowId: windowId}. - * @see https://developer.chrome.com/extensions/tabs#method-getAllInWindow - */ -chrome.tabs.getAllInWindow = function(windowId, callback) {}; - -/** - * Creates a new tab. - * @param {{ - * windowId: (number|undefined), - * index: (number|undefined), - * url: (string|undefined), - * active: (boolean|undefined), - * selected: (boolean|undefined), - * pinned: (boolean|undefined), - * openerTabId: (number|undefined) - * }} createProperties - * @param {function(!chrome.tabs.Tab): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-create - */ -chrome.tabs.create = function(createProperties, callback) {}; - -/** - * Duplicates a tab. - * @param {number} tabId The ID of the tab to duplicate. - * @param {function((!chrome.tabs.Tab|undefined)): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-duplicate - */ -chrome.tabs.duplicate = function(tabId, callback) {}; - -/** - * Gets all tabs that have the specified properties, or all tabs if no - * properties are specified. - * @param {{ - * active: (boolean|undefined), - * pinned: (boolean|undefined), - * audible: (boolean|undefined), - * muted: (boolean|undefined), - * highlighted: (boolean|undefined), - * frozen: (boolean|undefined), - * discarded: (boolean|undefined), - * autoDiscardable: (boolean|undefined), - * currentWindow: (boolean|undefined), - * lastFocusedWindow: (boolean|undefined), - * status: (!chrome.tabs.TabStatus|undefined), - * title: (string|undefined), - * url: ((string|!Array)|undefined), - * groupId: (number|undefined), - * windowId: (number|undefined), - * windowType: (!chrome.tabs.WindowType|undefined), - * index: (number|undefined) - * }} queryInfo - * @param {function(!Array): void} callback - * @see https://developer.chrome.com/extensions/tabs#method-query - */ -chrome.tabs.query = function(queryInfo, callback) {}; - -/** - * Highlights the given tabs and focuses on the first of group. Will appear to - * do nothing if the specified tab is currently active. - * @param {{ - * windowId: (number|undefined), - * tabs: (!Array|number) - * }} highlightInfo - * @param {function(!chrome.windows.Window): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-highlight - */ -chrome.tabs.highlight = function(highlightInfo, callback) {}; - -/** - * Modifies the properties of a tab. Properties that are not specified in - * updateProperties are not modified. - * @param {?number|undefined} tabId Defaults to the selected tab of the current window. - * @param {{ - * url: (string|undefined), - * active: (boolean|undefined), - * highlighted: (boolean|undefined), - * selected: (boolean|undefined), - * pinned: (boolean|undefined), - * muted: (boolean|undefined), - * openerTabId: (number|undefined), - * autoDiscardable: (boolean|undefined) - * }} updateProperties - * @param {function((!chrome.tabs.Tab|undefined)): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-update - */ -chrome.tabs.update = function(tabId, updateProperties, callback) {}; - -/** - * Moves one or more tabs to a new position within its window, or to a new - * window. Note that tabs can only be moved to and from normal (window.type === - * "normal") windows. - * @param {(number|!Array)} tabIds The tab ID or list of tab IDs to - * move. - * @param {{ - * windowId: (number|undefined), - * index: number - * }} moveProperties - * @param {function((!chrome.tabs.Tab|!Array)): void=} - * callback - * @see https://developer.chrome.com/extensions/tabs#method-move - */ -chrome.tabs.move = function(tabIds, moveProperties, callback) {}; - -/** - * Reload a tab. - * @param {number=} tabId The ID of the tab to reload; defaults to the selected - * tab of the current window. - * @param {{ - * bypassCache: (boolean|undefined) - * }=} reloadProperties - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-reload - */ -chrome.tabs.reload = function(tabId, reloadProperties, callback) {}; - -/** - * Closes one or more tabs. - * @param {(number|!Array)} tabIds The tab ID or list of tab IDs to - * close. - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-remove - */ -chrome.tabs.remove = function(tabIds, callback) {}; - -/** - * Adds one or more tabs to a specified group, or if no group is specified, adds - * the given tabs to a newly created group. - * @param {{ - * tabIds: (number|!Array), - * groupId: (number|undefined), - * createProperties: ({ - * windowId: (number|undefined) - * }|undefined) - * }} options - * @param {function(number): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-group - */ -chrome.tabs.group = function(options, callback) {}; - -/** - * Removes one or more tabs from their respective groups. If any groups become - * empty, they are deleted. - * @param {(number|!Array)} tabIds The tab ID or list of tab IDs to - * remove from their respective groups. - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-ungroup - */ -chrome.tabs.ungroup = function(tabIds, callback) {}; - -/** - * Detects the primary language of the content in a tab. - * @param {?number|undefined} tabId Defaults to the active tab of the current window. - * @param {function(string): void} callback - * @see https://developer.chrome.com/extensions/tabs#method-detectLanguage - */ -chrome.tabs.detectLanguage = function(tabId, callback) {}; - -/** - * Captures the visible area of the currently active tab in the specified - * window. In order to call this method, the extension must have either the <all_urls> permission or the activeTab permission. In addition to sites that - * extensions can normally access, this method allows extensions to capture - * sensitive sites that are otherwise restricted, including chrome:-scheme - * pages, other extensions' pages, and data: URLs. These sensitive sites can - * only be captured with the activeTab permission. File URLs may be captured - * only if the extension has been granted file access. - * @param {?number|undefined} windowId The target window. Defaults to the current window. - * @param {?chrome.extensionTypes.ImageDetails|undefined} options - * @param {function(string): void} callback - * @see https://developer.chrome.com/extensions/tabs#method-captureVisibleTab - */ -chrome.tabs.captureVisibleTab = function(windowId, options, callback) {}; - -/** - * Injects JavaScript code into a page. For details, see the programmatic injection section of the content - * scripts doc. - * @param {?number|undefined} tabId The ID of the tab in which to run the - * script; defaults to the active tab of the current window. - * @param {!chrome.extensionTypes.InjectDetails} details Details of the - * script to run. Either the code or the file property must be set, but both - * may not be set at the same time. - * @param {function((!Array<*>|undefined)): void=} callback Called after all the - * JavaScript has been executed. - * @see https://developer.chrome.com/extensions/tabs#method-executeScript - */ -chrome.tabs.executeScript = function(tabId, details, callback) {}; - -/** - * Injects CSS into a page. For details, see the programmatic injection section of the content - * scripts doc. - * @param {?number|undefined} tabId The ID of the tab in which to insert the - * CSS; defaults to the active tab of the current window. - * @param {!chrome.extensionTypes.InjectDetails} details Details of the CSS - * text to insert. Either the code or the file property must be set, but - * both may not be set at the same time. - * @param {function(): void=} callback Called when all the CSS has been - * inserted. - * @see https://developer.chrome.com/extensions/tabs#method-insertCSS - */ -chrome.tabs.insertCSS = function(tabId, details, callback) {}; - -/** - * Zooms a specified tab. - * @param {?number|undefined} tabId The ID of the tab to zoom; defaults to the - * active tab of the current window. - * @param {number} zoomFactor The new zoom factor. A value of 0 - * sets the tab to its current default zoom factor. Values greater than - * 0 specify a (possibly non-default) zoom factor for the tab. - * @param {function(): void=} callback Called after the zoom factor has been - * changed. - * @see https://developer.chrome.com/extensions/tabs#method-setZoom - */ -chrome.tabs.setZoom = function(tabId, zoomFactor, callback) {}; - -/** - * Gets the current zoom factor of a specified tab. - * @param {?number|undefined} tabId The ID of the tab to get the current zoom - * factor from; defaults to the active tab of the current window. - * @param {function(number): void} callback Called with the tab's current zoom - * factor after it has been fetched. - * @see https://developer.chrome.com/extensions/tabs#method-getZoom - */ -chrome.tabs.getZoom = function(tabId, callback) {}; - -/** - * Sets the zoom settings for a specified tab, which define how zoom changes are - * handled. These settings are reset to defaults upon navigating the tab. - * @param {?number|undefined} tabId The ID of the tab to change the zoom - * settings for; defaults to the active tab of the current window. - * @param {!chrome.tabs.ZoomSettings} zoomSettings Defines how zoom changes are - * handled and at what scope. - * @param {function(): void=} callback Called after the zoom settings are - * changed. - * @see https://developer.chrome.com/extensions/tabs#method-setZoomSettings - */ -chrome.tabs.setZoomSettings = function(tabId, zoomSettings, callback) {}; - -/** - * Gets the current zoom settings of a specified tab. - * @param {?number|undefined} tabId The ID of the tab to get the current zoom - * settings from; defaults to the active tab of the current window. - * @param {function(!chrome.tabs.ZoomSettings): void} callback Called with the - * tab's current zoom settings. - * @see https://developer.chrome.com/extensions/tabs#method-getZoomSettings - */ -chrome.tabs.getZoomSettings = function(tabId, callback) {}; - -/** - * Discards a tab from memory. Discarded tabs are still visible on the tab strip - * and are reloaded when activated. - * @param {number=} tabId The ID of the tab to be discarded. If specified, the - * tab is discarded unless it is active or already discarded. If omitted, - * the browser discards the least important tab. This can fail if no - * discardable tabs exist. - * @param {function((!chrome.tabs.Tab|undefined)): void=} callback Called after - * the operation is completed. - * @see https://developer.chrome.com/extensions/tabs#method-discard - */ -chrome.tabs.discard = function(tabId, callback) {}; - -/** - * Go foward to the next page, if one is available. - * @param {number=} tabId The ID of the tab to navigate forward; defaults to the - * selected tab of the current window. - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-goForward - */ -chrome.tabs.goForward = function(tabId, callback) {}; - -/** - * Go back to the previous page, if one is available. - * @param {number=} tabId The ID of the tab to navigate back; defaults to the - * selected tab of the current window. - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/tabs#method-goBack - */ -chrome.tabs.goBack = function(tabId, callback) {}; - -/** - * Fired when a tab is created. Note that the tab's URL may not be set at the - * time this event is fired, but you can listen to onUpdated events so as to be - * notified when a URL is set. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onCreated - */ -chrome.tabs.onCreated; - -/** - * Fired when a tab is updated. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onUpdated - */ -chrome.tabs.onUpdated; - -/** - * Fired when a tab is moved within a window. Only one move event is fired, - * representing the tab the user directly moved. Move events are not fired for - * the other tabs that must move in response to the manually-moved tab. This - * event is not fired when a tab is moved between windows; for details, see - * $(ref:tabs.onDetached). - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onMoved - */ -chrome.tabs.onMoved; - -/** - * Fires when the selected tab in a window changes. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onSelectionChanged - */ -chrome.tabs.onSelectionChanged; - -/** - * Fires when the selected tab in a window changes. Note that the tab's URL may - * not be set at the time this event fired, but you can listen to - * $(ref:tabs.onUpdated) events so as to be notified when a URL is set. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onActiveChanged - */ -chrome.tabs.onActiveChanged; - -/** - * Fires when the active tab in a window changes. Note that the tab's URL may - * not be set at the time this event fired, but you can listen to onUpdated - * events so as to be notified when a URL is set. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onActivated - */ -chrome.tabs.onActivated; - -/** - * Fired when the highlighted or selected tabs in a window changes. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onHighlightChanged - */ -chrome.tabs.onHighlightChanged; - -/** - * Fired when the highlighted or selected tabs in a window changes. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onHighlighted - */ -chrome.tabs.onHighlighted; - -/** - * Fired when a tab is detached from a window; for example, because it was moved - * between windows. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onDetached - */ -chrome.tabs.onDetached; - -/** - * Fired when a tab is attached to a window; for example, because it was moved - * between windows. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onAttached - */ -chrome.tabs.onAttached; - -/** - * Fired when a tab is closed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onRemoved - */ -chrome.tabs.onRemoved; - -/** - * Fired when a tab is replaced with another tab due to prerendering or instant. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onReplaced - */ -chrome.tabs.onReplaced; - -/** - * Fired when a tab is zoomed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tabs#event-onZoomChange - */ -chrome.tabs.onZoomChange; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/terminal_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/terminal_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/terminal_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/terminal_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,152 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.terminalPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: terminalPrivate - * @externs - */ - -/** @const */ -chrome.terminalPrivate = {}; - -/** - * @enum {string} - */ -chrome.terminalPrivate.OutputType = { - STDOUT: 'stdout', - STDERR: 'stderr', - EXIT: 'exit', -}; - -/** - * Starts new process. - * @param {string} processName Name of the process to open. May be 'crosh' or - * 'vmshell'. - * @param {?Array|undefined} args Command line arguments to pass to the - * process. - * @param {function(string): void} callback Returns id of the launched process. - * If no process was launched returns -1. - */ -chrome.terminalPrivate.openTerminalProcess = function(processName, args, callback) {}; - -/** - * Starts new vmshell process. - * @param {?Array|undefined} args Command line arguments to pass to - * vmshell. - * @param {function(string): void} callback Returns id of the launched vmshell - * process. If no process was launched returns -1. - */ -chrome.terminalPrivate.openVmshellProcess = function(args, callback) {}; - -/** - * Closes previously opened process from either openTerminalProcess or - * openVmshellProcess. - * @param {string} id Unique id of the process we want to close. - * @param {function(boolean): void=} callback Function that gets called when - * close operation is started for the process. Returns success of the - * function. - */ -chrome.terminalPrivate.closeTerminalProcess = function(id, callback) {}; - -/** - * Sends input that will be routed to stdin of the process with the specified - * id. - * @param {string} id The id of the process to which we want to send input. - * @param {string} input Input we are sending to the process. - * @param {function(boolean): void=} callback Callback that will be called when - * sendInput method ends. Returns success. - */ -chrome.terminalPrivate.sendInput = function(id, input, callback) {}; - -/** - * Notify the process with the id id that terminal window size has changed. - * @param {string} id The id of the process. - * @param {number} width New window width (as column count). - * @param {number} height New window height (as row count). - * @param {function(boolean): void=} callback Callback that will be called when - * sendInput method ends. Returns success. - */ -chrome.terminalPrivate.onTerminalResize = function(id, width, height, callback) {}; - -/** - * Called from |onProcessOutput| when the event is dispatched to terminal - * extension. Observing the terminal process output will be paused after - * |onProcessOutput| is dispatched until this method is called. - * @param {string} id The id of the process to which |onProcessOutput| was - * dispatched. - */ -chrome.terminalPrivate.ackOutput = function(id) {}; - -/** - * Open a Terminal app window/tab - * @param {{ - * url: (string|undefined), - * asTab: (boolean|undefined) - * }=} data - */ -chrome.terminalPrivate.openWindow = function(data) {}; - -/** - * Open the Terminal Settings page. - * @param {function(): void} callback Callback that will be called when - * complete. - */ -chrome.terminalPrivate.openOptionsPage = function(callback) {}; - -/** - * Open the System Settings at the specified subpage. - * @param {string} subpage Name of subpage to open. Currently only 'crostini' - * supported. - * @param {function(): void} callback Callback that will be called when - * complete. - */ -chrome.terminalPrivate.openSettingsSubpage = function(subpage, callback) {}; - -/** - * Returns an object containing info about ChromeOS settings that affect the - * Terminal, e.g. which feature flags are enabled. - * @param {function({ - * tast: boolean - * }): void} callback Callback that will be called with the info object. - */ -chrome.terminalPrivate.getOSInfo = function(callback) {}; - -/** - * Returns specified pref values, ignoring any not in allowlist. - * @param {!Array} paths Paths of prefs to fetch. - * @param {function(Object): void} callback Callback that will be called with - * prefs. - */ -chrome.terminalPrivate.getPrefs = function(paths, callback) {}; - -/** - * Sets specified prefs, ignoring any not in allowlist. - * @param {Object} prefs Prefs to update keyed by paths. - * @param {function(): void} callback Callback that will be called when - * complete. - */ -chrome.terminalPrivate.setPrefs = function(prefs, callback) {}; - -/** - * Fired when an opened process writes something to its output. Observing - * further process output will be blocked until |ackOutput| for the terminal is - * called. Internally, first event argument will be ID of the tab that contains - * terminal instance for which this event is intended. This argument will be - * stripped before passing the event to the extension. - * @type {!ChromeEvent} - */ -chrome.terminalPrivate.onProcessOutput; - -/** - * Fired when pref changes. - * @type {!ChromeEvent} - */ -chrome.terminalPrivate.onPrefChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/test.js chromium-132.0.6834.159/third_party/closure_compiler/externs/test.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/test.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/test.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,279 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.test.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: test - * @externs - */ - -/** @const */ -chrome.test = {}; - -/** - * Gives configuration options set by the test. - * @param {function({ - * customArg: (string|undefined), - * ftpServer: ({ - * port: number - * }|undefined), - * testServer: ({ - * port: number - * }|undefined), - * testDataDirectory: (string|undefined), - * testWebSocketPort: (number|undefined), - * testWebTransportPort: (number|undefined), - * loginStatus: ({ - * isLoggedIn: (boolean|undefined), - * isScreenLocked: (boolean|undefined) - * }|undefined) - * }): void} callback - * @see https://developer.chrome.com/extensions/test#method-getConfig - */ -chrome.test.getConfig = function(callback) {}; - -/** - * Notifies the browser process that test code running in the extension failed. - * This is only used for internal unit testing. - * @param {string} message - * @see https://developer.chrome.com/extensions/test#method-notifyFail - */ -chrome.test.notifyFail = function(message) {}; - -/** - * Notifies the browser process that test code running in the extension passed. - * This is only used for internal unit testing. - * @param {string=} message - * @see https://developer.chrome.com/extensions/test#method-notifyPass - */ -chrome.test.notifyPass = function(message) {}; - -/** - * Logs a message during internal unit testing. - * @param {string} message - * @see https://developer.chrome.com/extensions/test#method-log - */ -chrome.test.log = function(message) {}; - -/** - * Open file: URLs for tests. - * @param {string} url - * @see https://developer.chrome.com/extensions/test#method-openFileUrl - */ -chrome.test.openFileUrl = function(url) {}; - -/** - * Sends a string message to the browser process, generating a Notification that - * C++ test code can wait for. - * @param {string} message - * @param {function(string): void=} callback - * @see https://developer.chrome.com/extensions/test#method-sendMessage - */ -chrome.test.sendMessage = function(message, callback) {}; - -/** - * Sends a result back to the browser as a result of script executing; this is - * handy for communicating results from browser-driven script execution. - * @param {*} result - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/test#method-sendScriptResult - */ -chrome.test.sendScriptResult = function(result, callback) {}; - -/** - * @see https://developer.chrome.com/extensions/test#method-callbackAdded - */ -chrome.test.callbackAdded = function() {}; - -/** - * @param {*=} message - * @see https://developer.chrome.com/extensions/test#method-fail - */ -chrome.test.fail = function(message) {}; - -/** - * @param {*=} message - * @see https://developer.chrome.com/extensions/test#method-succeed - */ -chrome.test.succeed = function(message) {}; - -/** - * Returns an instance of the module system for the given context. - * @param {*} context - * @return {*} The module system - * @see https://developer.chrome.com/extensions/test#method-getModuleSystem - */ -chrome.test.getModuleSystem = function(context) {}; - -/** - * @param {(string|boolean)} test - * @param {string=} message - * @see https://developer.chrome.com/extensions/test#method-assertTrue - */ -chrome.test.assertTrue = function(test, message) {}; - -/** - * @param {(string|boolean)} test - * @param {string=} message - * @see https://developer.chrome.com/extensions/test#method-assertFalse - */ -chrome.test.assertFalse = function(test, message) {}; - -/** - * @param {*=} expected - * @param {*=} actual - * @see https://developer.chrome.com/extensions/test#method-checkDeepEq - */ -chrome.test.checkDeepEq = function(expected, actual) {}; - -/** - * @param {*=} expected - * @param {*=} actual - * @param {string=} message - * @see https://developer.chrome.com/extensions/test#method-assertEq - */ -chrome.test.assertEq = function(expected, actual, message) {}; - -/** - * @param {*=} expected - * @param {*=} actual - * @param {string=} message A custom error message to print out with the test - * failure, if any. - * @see https://developer.chrome.com/extensions/test#method-assertNe - */ -chrome.test.assertNe = function(expected, actual, message) {}; - -/** - * @see https://developer.chrome.com/extensions/test#method-assertNoLastError - */ -chrome.test.assertNoLastError = function() {}; - -/** - * @param {string} expectedError - * @see https://developer.chrome.com/extensions/test#method-assertLastError - */ -chrome.test.assertLastError = function(expectedError) {}; - -/** - * @param {function(): void} fn - * @param {?Object|undefined} self - * @param {!Array<*>} args - * @param {(string|RegExp)=} message - * @see https://developer.chrome.com/extensions/test#method-assertThrows - */ -chrome.test.assertThrows = function(fn, self, args, message) {}; - -/** - * @param {Promise} promise The promise to evaluate, which is expected to - * reject. - * @param {(string|RegExp)} expectedMessage The expected error message from the - * promise rejection, either as a string or a regular expression. - * @return {Promise} A promise that will be resolved once the assertion is - * complete. The promise is rejected if the passed-in promise resolves - * unexpectedly or rejects with an unexpected error. - * @see https://developer.chrome.com/extensions/test#method-assertPromiseRejects - */ -chrome.test.assertPromiseRejects = function(promise, expectedMessage) {}; - -/** - * @param {function(): void=} func - * @param {string=} expectedError - * @see https://developer.chrome.com/extensions/test#method-callback - */ -chrome.test.callback = function(func, expectedError) {}; - -/** - * @param {*} event - * @param {function(): void} func - * @see https://developer.chrome.com/extensions/test#method-listenOnce - */ -chrome.test.listenOnce = function(event, func) {}; - -/** - * @param {*} event - * @param {function(): void} func - * @see https://developer.chrome.com/extensions/test#method-listenForever - */ -chrome.test.listenForever = function(event, func) {}; - -/** - * @param {function(): void=} func - * @see https://developer.chrome.com/extensions/test#method-callbackPass - */ -chrome.test.callbackPass = function(func) {}; - -/** - * @param {string} expectedError - * @param {function(): void=} func - * @see https://developer.chrome.com/extensions/test#method-callbackFail - */ -chrome.test.callbackFail = function(expectedError, func) {}; - -/** - * @param {!Array} tests - * @see https://developer.chrome.com/extensions/test#method-runTests - */ -chrome.test.runTests = function(tests) {}; - -/** - * @see https://developer.chrome.com/extensions/test#method-getApiFeatures - */ -chrome.test.getApiFeatures = function() {}; - -/** - * @param {!Array=} apiNames - * @see https://developer.chrome.com/extensions/test#method-getApiDefinitions - */ -chrome.test.getApiDefinitions = function(apiNames) {}; - -/** - * @see https://developer.chrome.com/extensions/test#method-isProcessingUserGesture - */ -chrome.test.isProcessingUserGesture = function() {}; - -/** - * Runs the provided function in the context of a user gesture. - * @param {function(): void} functionToRun - * @see https://developer.chrome.com/extensions/test#method-runWithUserGesture - */ -chrome.test.runWithUserGesture = function(functionToRun) {}; - -/** - * Sends a string message one round trip from the renderer to the browser - * process and back. - * @param {string} message - * @param {function(string): void} callback - * @see https://developer.chrome.com/extensions/test#method-waitForRoundTrip - */ -chrome.test.waitForRoundTrip = function(message, callback) {}; - -/** - * Loads a JS script in the current JS context. - * @param {string} scriptUrl - * @return {Promise} A promise that will be resolved once the script is loaded. - * @see https://developer.chrome.com/extensions/test#method-loadScript - */ -chrome.test.loadScript = function(scriptUrl) {}; - -/** - * Sets the function to be called when an exception occurs. By default this is a - * function which fails the test. This is reset for every test run through - * $ref:test.runTests. - * @param {function(string, *): void} handler - * @see https://developer.chrome.com/extensions/test#method-setExceptionHandler - */ -chrome.test.setExceptionHandler = function(handler) {}; - -/** - * Used to test sending messages to extensions. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/test#event-onMessage - */ -chrome.test.onMessage; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/tts.js chromium-132.0.6834.159/third_party/closure_compiler/externs/tts.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/tts.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/tts.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,238 +0,0 @@ -// Copyright 2024 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.tts.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: tts - * @externs - */ - -/** @const */ -chrome.tts = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tts#type-EventType - */ -chrome.tts.EventType = { - START: 'start', - END: 'end', - WORD: 'word', - SENTENCE: 'sentence', - MARKER: 'marker', - INTERRUPTED: 'interrupted', - CANCELLED: 'cancelled', - ERROR: 'error', - PAUSE: 'pause', - RESUME: 'resume', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/tts#type-VoiceGender - */ -chrome.tts.VoiceGender = { - MALE: 'male', - FEMALE: 'female', -}; - -/** - * The speech options for the TTS engine. - * @constructor - * @private - * @see https://developer.chrome.com/extensions/tts#type-TtsOptions - */ -chrome.tts.TtsOptions = function() {}; - -/** - * If true, enqueues this utterance if TTS is already in progress. If false (the - * default), interrupts any current speech and flushes the speech queue before - * speaking this new utterance. - * @type {(boolean|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-enqueue - */ -chrome.tts.TtsOptions.prototype.enqueue; - -/** - * The name of the voice to use for synthesis. If empty, uses any available - * voice. - * @type {(string|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-voiceName - */ -chrome.tts.TtsOptions.prototype.voiceName; - -/** - * The extension ID of the speech engine to use, if known. - * @type {(string|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-extensionId - */ -chrome.tts.TtsOptions.prototype.extensionId; - -/** - * The language to be used for synthesis, in the form - * language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. - * @type {(string|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-lang - */ -chrome.tts.TtsOptions.prototype.lang; - -/** - * Gender of voice for synthesized speech. - * @type {(!chrome.tts.VoiceGender|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-gender - */ -chrome.tts.TtsOptions.prototype.gender; - -/** - * Speaking rate relative to the default rate for this voice. 1.0 is the default - * rate, normally around 180 to 220 words per minute. 2.0 is twice as fast, and - * 0.5 is half as fast. Values below 0.1 or above 10.0 are strictly disallowed, - * but many voices will constrain the minimum and maximum rates - * further—for example a particular voice may not actually speak faster - * than 3 times normal even if you specify a value larger than 3.0. - * @type {(number|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-rate - */ -chrome.tts.TtsOptions.prototype.rate; - -/** - * Speaking pitch between 0 and 2 inclusive, with 0 being lowest and 2 being - * highest. 1.0 corresponds to a voice's default pitch. - * @type {(number|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-pitch - */ -chrome.tts.TtsOptions.prototype.pitch; - -/** - * Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being - * highest, with a default of 1.0. - * @type {(number|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-volume - */ -chrome.tts.TtsOptions.prototype.volume; - -/** - * The TTS event types the voice must support. - * @type {(!Array|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-requiredEventTypes - */ -chrome.tts.TtsOptions.prototype.requiredEventTypes; - -/** - * The TTS event types that you are interested in listening to. If missing, all - * event types may be sent. - * @type {(!Array|undefined)} - * @see https://developer.chrome.com/extensions/tts#type-desiredEventTypes - */ -chrome.tts.TtsOptions.prototype.desiredEventTypes; - -/** - * This function is called with events that occur in the process of speaking the - * utterance. - * @param {!chrome.tts.TtsEvent} event The update event from the text-to-speech - * engine indicating the status of this utterance. - * @see https://developer.chrome.com/extensions/tts#method-onEvent - */ -chrome.tts.TtsOptions.prototype.onEvent = function(event) {}; - - -/** - * An event from the TTS engine to communicate the status of an utterance. - * @typedef {{ - * type: !chrome.tts.EventType, - * charIndex: (number|undefined), - * errorMessage: (string|undefined), - * srcId: (number|undefined), - * isFinalEvent: (boolean|undefined), - * length: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/tts#type-TtsEvent - */ -chrome.tts.TtsEvent; - -/** - * A description of a voice available for speech synthesis. - * @typedef {{ - * voiceName: (string|undefined), - * lang: (string|undefined), - * gender: (!chrome.tts.VoiceGender|undefined), - * remote: (boolean|undefined), - * extensionId: (string|undefined), - * eventTypes: (!Array|undefined) - * }} - * @see https://developer.chrome.com/extensions/tts#type-TtsVoice - */ -chrome.tts.TtsVoice; - -/** - * Speaks text using a text-to-speech engine. - * @param {string} utterance The text to speak, either plain text or a complete, - * well-formed SSML document. Speech engines that do not support SSML will - * strip away the tags and speak the text. The maximum length of the text is - * 32,768 characters. - * @param {!chrome.tts.TtsOptions=} options The speech options. - * @param {function(): void=} callback Called right away, before speech - * finishes. Check $(ref:runtime.lastError) to make sure there were no - * errors. Use options.onEvent to get more detailed feedback. - * @see https://developer.chrome.com/extensions/tts#method-speak - */ -chrome.tts.speak = function(utterance, options, callback) {}; - -/** - * Stops any current speech and flushes the queue of any pending utterances. In - * addition, if speech was paused, it will now be un-paused for the next call to - * speak. - * @see https://developer.chrome.com/extensions/tts#method-stop - */ -chrome.tts.stop = function() {}; - -/** - * Pauses speech synthesis, potentially in the middle of an utterance. A call to - * resume or stop will un-pause speech. - * @see https://developer.chrome.com/extensions/tts#method-pause - */ -chrome.tts.pause = function() {}; - -/** - * If speech was paused, resumes speaking where it left off. - * @see https://developer.chrome.com/extensions/tts#method-resume - */ -chrome.tts.resume = function() {}; - -/** - * Checks whether the engine is currently speaking. On Mac OS X, the result is - * true whenever the system speech engine is speaking, even if the speech wasn't - * initiated by Chrome. - * @param {function(boolean): void=} callback - * @see https://developer.chrome.com/extensions/tts#method-isSpeaking - */ -chrome.tts.isSpeaking = function(callback) {}; - -/** - * Gets an array of all available voices. - * @param {function(!Array): void=} callback - * @see https://developer.chrome.com/extensions/tts#method-getVoices - */ -chrome.tts.getVoices = function(callback) {}; - -/** - * Used to pass events back to the function calling speak(). - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tts#event-onEvent - */ -chrome.tts.onEvent; - -/** - * Called when the list of $(ref:tts.TtsVoice) that would be returned by - * getVoices has changed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/tts#event-onVoicesChanged - */ -chrome.tts.onVoicesChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/ttsEngine.js chromium-132.0.6834.159/third_party/closure_compiler/externs/ttsEngine.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/ttsEngine.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/ttsEngine.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,222 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.ttsEngine.FooType'. -// Please run the closure compiler before committing changes. -// See -// https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: ttsEngine - * @externs - */ - -/** @const */ -chrome.ttsEngine = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/ttsEngine#type-TtsClientSource - */ -chrome.ttsEngine.TtsClientSource = { - CHROMEFEATURE: 'chromefeature', - EXTENSION: 'extension', -}; - -/** - * Identifier for the client requesting status. - * @typedef {{ - * id: string, - * source: !chrome.ttsEngine.TtsClientSource - * }} - * @see https://developer.chrome.com/extensions/ttsEngine#type-TtsClient - */ -chrome.ttsEngine.TtsClient; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/ttsEngine#type-VoiceGender - */ -chrome.ttsEngine.VoiceGender = { - MALE: 'male', - FEMALE: 'female', -}; - -/** - * Options for removing a given language. - * @typedef {{ - * uninstallImmediately: boolean - * }} - * @see https://developer.chrome.com/extensions/ttsEngine#type-LanguageUninstallOptions - */ -chrome.ttsEngine.LanguageUninstallOptions; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/ttsEngine#type-LanguageInstallStatus - */ -chrome.ttsEngine.LanguageInstallStatus = { - NOT_INSTALLED: 'notInstalled', - INSTALLING: 'installing', - INSTALLED: 'installed', - FAILED: 'failed', -}; - -/** - * Install status of a language. - * @typedef {{ - * lang: string, - * installStatus: !chrome.ttsEngine.LanguageInstallStatus, - * error: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/ttsEngine#type-LanguageStatus - */ -chrome.ttsEngine.LanguageStatus; - -/** - * Options specified to the tts.speak() method. - * @typedef {{ - * voiceName: (string|undefined), - * lang: (string|undefined), - * gender: (!chrome.ttsEngine.VoiceGender|undefined), - * rate: (number|undefined), - * pitch: (number|undefined), - * volume: (number|undefined) - * }} - * @see https://developer.chrome.com/extensions/ttsEngine#type-SpeakOptions - */ -chrome.ttsEngine.SpeakOptions; - -/** - * Contains the audio stream format expected to be produced by an engine. - * @typedef {{ - * sampleRate: number, - * bufferSize: number - * }} - * @see https://developer.chrome.com/extensions/ttsEngine#type-AudioStreamOptions - */ -chrome.ttsEngine.AudioStreamOptions; - -/** - * Parameters containing an audio buffer and associated data. - * @typedef {{ - * audioBuffer: ArrayBuffer, - * charIndex: (number|undefined), - * isLastBuffer: (boolean|undefined) - * }} - * @see https://developer.chrome.com/extensions/ttsEngine#type-AudioBuffer - */ -chrome.ttsEngine.AudioBuffer; - -/** - * Called by an engine to update its list of voices. This list overrides any - * voices declared in this extension's manifest. - * @param {!Array} voices Array of - * $(ref:tts.TtsVoice) objects representing the available voices for speech - * synthesis. - * @see https://developer.chrome.com/extensions/ttsEngine#method-updateVoices - */ -chrome.ttsEngine.updateVoices = function(voices) {}; - -/** - * Routes a TTS event from a speech engine to a client. - * @param {number} requestId - * @param {!chrome.ttsEngine.tts.TtsEvent} event The update event from the - * text-to-speech engine indicating the status of this utterance. - * @see https://developer.chrome.com/extensions/ttsEngine#method-sendTtsEvent - */ -chrome.ttsEngine.sendTtsEvent = function(requestId, event) {}; - -/** - * Routes TTS audio from a speech engine to a client. - * @param {number} requestId - * @param {!chrome.ttsEngine.AudioBuffer} audio An audio buffer from the - * text-to-speech engine. - * @see https://developer.chrome.com/extensions/ttsEngine#method-sendTtsAudio - */ -chrome.ttsEngine.sendTtsAudio = function(requestId, audio) {}; - -/** - * Called by an engine when a language install is attempted, and when a language - * is uninstalled. Also called in response to a status request from a client. - * When a voice is installed or uninstalled, the engine should also call - * ttsEngine.updateVoices to register the voice. - * @param {!chrome.ttsEngine.LanguageStatus} status The install status of the - * language. - * @see https://developer.chrome.com/extensions/ttsEngine#method-updateLanguage - */ -chrome.ttsEngine.updateLanguage = function(status) {}; - -/** - * Called when the user makes a call to tts.speak() and one of the voices from - * this extension's manifest is the first to match the options object. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/ttsEngine#event-onSpeak - */ -chrome.ttsEngine.onSpeak; - -/** - * Called when the user makes a call to tts.speak() and one of the voices from - * this extension's manifest is the first to match the options object. Differs - * from ttsEngine.onSpeak in that Chrome provides audio playback services and - * handles dispatching tts events. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/ttsEngine#event-onSpeakWithAudioStream - */ -chrome.ttsEngine.onSpeakWithAudioStream; - -/** - * Fired when a call is made to tts.stop and this extension may be in the middle - * of speaking. If an extension receives a call to onStop and speech is already - * stopped, it should do nothing (not raise an error). If speech is in the - * paused state, this should cancel the paused state. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/ttsEngine#event-onStop - */ -chrome.ttsEngine.onStop; - -/** - * Optional: if an engine supports the pause event, it should pause the current - * utterance being spoken, if any, until it receives a resume event or stop - * event. Note that a stop event should also clear the paused state. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/ttsEngine#event-onPause - */ -chrome.ttsEngine.onPause; - -/** - * Optional: if an engine supports the pause event, it should also support the - * resume event, to continue speaking the current utterance, if any. Note that a - * stop event should also clear the paused state. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/ttsEngine#event-onResume - */ -chrome.ttsEngine.onResume; - -/** - * Fired when a TTS client requests to install a new language. The engine should - * attempt to download and install the language, and call - * ttsEngine.updateLanguage with the result. On success, the engine should also - * call ttsEngine.updateVoices to register the newly available voices. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/ttsEngine#event-onInstallLanguageRequest - */ -chrome.ttsEngine.onInstallLanguageRequest; - -/** - * Fired when a TTS client indicates a language is no longer needed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/ttsEngine#event-onUninstallLanguageRequest - */ -chrome.ttsEngine.onUninstallLanguageRequest; - -/** - * Fired when a TTS client requests the install status of a language. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/ttsEngine#event-onLanguageStatusRequest - */ -chrome.ttsEngine.onLanguageStatusRequest; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/virtual_keyboard_private.js chromium-132.0.6834.159/third_party/closure_compiler/externs/virtual_keyboard_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/virtual_keyboard_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/virtual_keyboard_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,279 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.virtualKeyboardPrivate.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -/** - * @fileoverview Externs generated from namespace: virtualKeyboardPrivate - * @externs - */ - -/** @const */ -chrome.virtualKeyboardPrivate = {}; - -/** - * @enum {string} - */ -chrome.virtualKeyboardPrivate.VirtualKeyboardEventType = { - KEYUP: 'keyup', - KEYDOWN: 'keydown', -}; - -/** - * @typedef {{ - * type: !chrome.virtualKeyboardPrivate.VirtualKeyboardEventType, - * charValue: number, - * keyCode: number, - * keyName: string, - * modifiers: (number|undefined) - * }} - */ -chrome.virtualKeyboardPrivate.VirtualKeyboardEvent; - -/** - * @enum {string} - */ -chrome.virtualKeyboardPrivate.KeyboardMode = { - FULL_WIDTH: 'FULL_WIDTH', - FLOATING: 'FLOATING', -}; - -/** - * @enum {string} - */ -chrome.virtualKeyboardPrivate.KeyboardState = { - ENABLED: 'ENABLED', - DISABLED: 'DISABLED', - AUTO: 'AUTO', -}; - -/** - * @typedef {{ - * left: number, - * top: number, - * width: number, - * height: number - * }} - */ -chrome.virtualKeyboardPrivate.Bounds; - -/** - * @typedef {{ - * layout: string, - * hotrodmode: boolean, - * a11ymode: boolean, - * features: !Array - * }} - */ -chrome.virtualKeyboardPrivate.KeyboardConfig; - -/** - * @typedef {{ - * mode: !chrome.virtualKeyboardPrivate.KeyboardMode, - * bounds: !chrome.virtualKeyboardPrivate.Bounds - * }} - */ -chrome.virtualKeyboardPrivate.ContainerBehaviorOptions; - -/** - * @enum {string} - */ -chrome.virtualKeyboardPrivate.DisplayFormat = { - TEXT: 'text', - PNG: 'png', - HTML: 'html', - FILE: 'file', -}; - -/** - * @typedef {{ - * id: string, - * imageData: (string|undefined), - * textData: (string|undefined), - * displayFormat: !chrome.virtualKeyboardPrivate.DisplayFormat, - * timeCopied: number - * }} - */ -chrome.virtualKeyboardPrivate.ClipboardItem; - -/** - * Inserts text into the currently focused text field. - * @param {string} text The text that will be inserted. - * @param {function(): void=} callback Called when the insertion is completed. - */ -chrome.virtualKeyboardPrivate.insertText = function(text, callback) {}; - -/** - * Sends a fabricated key event to the focused input field. - * @param {!chrome.virtualKeyboardPrivate.VirtualKeyboardEvent} keyEvent - * @param {function(): void=} callback Called after processing the event. - */ -chrome.virtualKeyboardPrivate.sendKeyEvent = function(keyEvent, callback) {}; - -/** - * Hides the virtual keyboard. - * @param {function(): void=} callback Called when the keyboard is hidden. - */ -chrome.virtualKeyboardPrivate.hideKeyboard = function(callback) {}; - -/** - * Sets the state of the hotrod virtual keyboard. This API should only be used - * by hotrod. - * @param {boolean} enable - */ -chrome.virtualKeyboardPrivate.setHotrodKeyboard = function(enable) {}; - -/** - * Sets the lock state of the virtual keyboard. A locked keyboard remains - * visible even after a text area loses input focus. - * @param {boolean} lock - */ -chrome.virtualKeyboardPrivate.lockKeyboard = function(lock) {}; - -/** - * Inform the system that the keyboard has loaded. - * @param {function(): void=} callback Called when load acknowledgement is - * complete. - */ -chrome.virtualKeyboardPrivate.keyboardLoaded = function(callback) {}; - -/** - * Gets the virtual keyboard configuration. - * @param {function(!chrome.virtualKeyboardPrivate.KeyboardConfig): void} - * callback Called when querying virtual keyboard configuration is complete. - */ -chrome.virtualKeyboardPrivate.getKeyboardConfig = function(callback) {}; - -/** - * Opens chrome://os-settings/osLanguages page. - */ -chrome.virtualKeyboardPrivate.openSettings = function() {}; - -/** - * Opens chrome://os-settings/osLanguages/smartInputs page. - */ -chrome.virtualKeyboardPrivate.openSuggestionSettings = function() {}; - -/** - * Sets the virtual keyboard container behavior - * @param {!chrome.virtualKeyboardPrivate.ContainerBehaviorOptions} options - * Optional parameters for new container behavior. - * @param {function(boolean): void=} callback Called when container mode is - * ready to change, or if the operation failed. - */ -chrome.virtualKeyboardPrivate.setContainerBehavior = function(options, callback) {}; - -/** - * Sets the virtual keyboard draggable area bounds. - * @param {!chrome.virtualKeyboardPrivate.Bounds} bounds The value of draggable - * rect area of floating keyboard. - */ -chrome.virtualKeyboardPrivate.setDraggableArea = function(bounds) {}; - -/** - * Requests the virtual keyboard to change state. - * @param {!chrome.virtualKeyboardPrivate.KeyboardState} state The value of the - * virtual keyboard state to change to. - */ -chrome.virtualKeyboardPrivate.setKeyboardState = function(state) {}; - -/** - * Sets the areas on the screen that are blocked by the virtual keyboard. - * @param {!Array} boundsList List of - * rectangles representing regions occluded by the keyboard. - */ -chrome.virtualKeyboardPrivate.setOccludedBounds = function(boundsList) {}; - -/** - * Sets the areas on the keyboard window where events are handled. Any event - * outside of these areas are passed on to the window behind it. - * @param {!Array} boundsList List of - * rectangles representing regions where events targeting the keyboard - * should be handled. - */ -chrome.virtualKeyboardPrivate.setHitTestBounds = function(boundsList) {}; - -/** - * Sets the area of the keyboard window that should not move off screen. Any - * area outside of this can be moved off the user's screen. - * @param {!chrome.virtualKeyboardPrivate.Bounds} bounds The bounds of the area - * inside the keyboard window, relative to the window origin, that should - * not be moved off screen. Any area outside of this bounds can be moved off - * screen. - */ -chrome.virtualKeyboardPrivate.setAreaToRemainOnScreen = function(bounds) {}; - -/** - * Sets the bounds of the keyboard window in screen coordinates. - * @param {!chrome.virtualKeyboardPrivate.Bounds} bounds A rectangle defining - * the new bounds of the window in screen coordinates. - */ -chrome.virtualKeyboardPrivate.setWindowBoundsInScreen = function(bounds) {}; - -/** - * Get the clipboard history - * @param {{ - * itemIds: (!Array|undefined) - * }} options - * @param {function(!Array): void} - * callback Called when querying the ClipboardHistory is complete. - */ -chrome.virtualKeyboardPrivate.getClipboardHistory = function(options, callback) {}; - -/** - * Pastes a clipboard item from the clipboard history. - * @param {string} itemId The unique id which identifies this clipboard item. - */ -chrome.virtualKeyboardPrivate.pasteClipboardItem = function(itemId) {}; - -/** - * Deletes a clipboard item from the clipboard history. - * @param {string} itemId The unique id which identifies this clipboard item. - */ -chrome.virtualKeyboardPrivate.deleteClipboardItem = function(itemId) {}; - -/** - * This event is sent when virtual keyboard bounds changed and overscroll/resize - * is enabled. - * @type {!ChromeEvent} - */ -chrome.virtualKeyboardPrivate.onBoundsChanged; - -/** - * Fired when the virtual keyboard window has been closed. For example, this can - * happen when turning off on-screen keyboard or exiting tablet mode. - * @type {!ChromeEvent} - */ -chrome.virtualKeyboardPrivate.onKeyboardClosed; - -/** - * Fired when a configuration for virtual keyboard IME has changed, e.g. auto - * complete disabled. - * @type {!ChromeEvent} - */ -chrome.virtualKeyboardPrivate.onKeyboardConfigChanged; - -/** - * Fired when the list of items in the clipboard history changes. - * @type {!ChromeEvent} - */ -chrome.virtualKeyboardPrivate.onClipboardHistoryChanged; - -/** - * Fired when the data in a specific clipboard item is updated (mainly used for - * sending updated rendered html image). - * @type {!ChromeEvent} - */ -chrome.virtualKeyboardPrivate.onClipboardItemUpdated; - -/** - * Fired when the color provider of virtual keyboard window has changed. - * @type {!ChromeEvent} - */ -chrome.virtualKeyboardPrivate.onColorProviderChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/webview_tag.js chromium-132.0.6834.159/third_party/closure_compiler/externs/webview_tag.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/webview_tag.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/webview_tag.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,527 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// TODO(crbug.com/1085633): Inline enums need to be cleaned up in the source -// specification before we can autogenerate this. - -/** - * @fileoverview Externs generated from namespace: webview - * @externs - */ - -/** - * @typedef {{ - * since: (number|undefined) - * }} - * @see https://developer.chrome.com/apps/tags/webview#type-ClearDataOptions - */ -var ClearDataOptions; - -/** - * @typedef {{ - * appcache: (boolean|undefined), - * cookies: (boolean|undefined), - * fileSystems: (boolean|undefined), - * indexedDB: (boolean|undefined), - * localStorage: (boolean|undefined), - * webSQL: (boolean|undefined) - * }} - * @see https://developer.chrome.com/apps/tags/webview#type-ClearDataTypeSet - */ -var ClearDataTypeSet; - -/** - * @typedef {{ - * code: (string|undefined), - * file: (string|undefined) - * }} - * @see https://developer.chrome.com/apps/tags/webview#type-InjectDetails - */ -var InjectDetails; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-ContentWindow - */ -function ContentWindow() {} - -/** - * @param {?} message - * @param {string} targetOrigin - */ -ContentWindow.prototype.postMessage = function(message, targetOrigin) {}; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-DialogController - */ -function DialogController() {} - -/** - * @param {string} response - */ -DialogController.prototype.ok = function(response) {}; - -DialogController.prototype.cancel = function() {}; - -/** - * @typedef {{ - * numberOfMatches: number, - * activeMatchOrdinal: number, - * selectionRect: SelectionRect, - * canceled: boolean - * }} - * @see https://developer.chrome.com/apps/tags/webview#type-FindCallbackResults - */ -var FindCallbackResults; - -/** - * @typedef {{ - * backward: (boolean|undefined), - * matchCase: (boolean|undefined) - * }} - * @see https://developer.chrome.com/apps/tags/webview#type-FindOptions - */ -var FindOptions; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-NewWindow - */ -function NewWindow() {} - -/** - * @param {!Object} webview - */ -NewWindow.prototype.attach = function(webview) {}; - -NewWindow.prototype.discard = function() {}; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-MediaPermissionRequest - */ -function MediaPermissionRequest() {} - -/** @type {string} */ -MediaPermissionRequest.prototype.url; - -MediaPermissionRequest.prototype.allow = function() {}; - -MediaPermissionRequest.prototype.deny = function() {}; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-GeolocationPermissionRequest - */ -function GeolocationPermissionRequest() {} - -/** @type {string} */ -GeolocationPermissionRequest.prototype.url; - -GeolocationPermissionRequest.prototype.allow = function() {}; - -GeolocationPermissionRequest.prototype.deny = function() {}; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-PointerLockPermissionRequest - */ -function PointerLockPermissionRequest() {} - -/** @type {boolean} */ -PointerLockPermissionRequest.prototype.userGesture; - -/** @type {boolean} */ -PointerLockPermissionRequest.prototype.lastUnlockedBySelf; - -/** @type {string} */ -PointerLockPermissionRequest.prototype.url; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-DownloadPermissionRequest - */ -function DownloadPermissionRequest() {} - -/** @type {string} */ -DownloadPermissionRequest.prototype.requestMethod; - -/** @type {string} */ -DownloadPermissionRequest.prototype.url; - -DownloadPermissionRequest.prototype.allow = function() {}; - -DownloadPermissionRequest.prototype.deny = function() {}; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-FileSystemPermissionRequest - */ -function FileSystemPermissionRequest() {} - -/** @type {string} */ -FileSystemPermissionRequest.prototype.url; - -FileSystemPermissionRequest.prototype.allow = function() {}; - -FileSystemPermissionRequest.prototype.deny = function() {}; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-LoadPluginPermissionRequest - */ -function LoadPluginPermissionRequest() {} - -/** @type {string} */ -LoadPluginPermissionRequest.prototype.identifier; - -/** @type {string} */ -LoadPluginPermissionRequest.prototype.name; - -LoadPluginPermissionRequest.prototype.allow = function() {}; - -LoadPluginPermissionRequest.prototype.deny = function() {}; - -/** - * @typedef {{ - * left: number, - * top: number, - * width: number, - * height: number - * }} - */ -var SelectionRect; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-WebRequestEventInterface - */ -function WebRequestEventInterface() {} - -/** @type {!WebRequestOptionallySynchronousEvent} */ -WebRequestEventInterface.prototype.onBeforeRequest; - -/** @type {!WebRequestOptionallySynchronousEvent} */ -WebRequestEventInterface.prototype.onBeforeSendHeaders; - -/** @type {!WebRequestEvent} */ -WebRequestEventInterface.prototype.onCompleted; - -/** @type {!WebRequestEvent} */ -WebRequestEventInterface.prototype.onBeforeRedirect; - -/** @type {!WebRequestOnErrorOccurredEvent} */ -WebRequestEventInterface.prototype.onErrorOccurred; - -/** @type {!WebRequestOptionallySynchronousEvent} */ -WebRequestEventInterface.prototype.onHeadersReceived; - -/** - * @constructor - * @extends {HTMLIFrameElement} - */ -function WebView() {} - -/** - * @type {ContentWindow} - * @see https://developer.chrome.com/apps/tags/webview#property-contentWindow - */ -WebView.prototype.contentWindow; - -/** - * @type {!WebRequestEventInterface} - * @see https://developer.chrome.com/apps/tags/webview#property-request - */ -WebView.prototype.request; - -/** - * @constructor - * @see https://developer.chrome.com/apps/tags/webview#type-ContextMenus - */ -function ContextMenus() {} -ContextMenus.prototype.onShow; -ContextMenus.prototype.onShow.addListener = function() {}; - -/** - * @type {ContextMenus} - * @see https://developer.chrome.com/apps/tags/webview#property-contextMenus - */ -WebView.prototype.contextMenus; - -/** - * @typedef{{ - * code: ?string, - * files: ?Array - * }} - * @see https://developer.chrome.com/apps/tags/webview#type-InjectionItems - */ -var InjectionItems; - -/** - * Details of the content script to inject. - * @typedef{{ - * name: string, - * matches: Array, - * exclude_matches: ?Array, - * match_about_blank: ?boolean, - * css: ?InjectionItems, - * js: ?InjectionItems, - * run_at: ?string, - * all_frames: ?boolean, - * include_globs: ?Array, - * exclude_globs: ?Array, - * }} - * @see https://developer.chrome.com/apps/tags/webview#type-ContentScriptDetails - */ -var ContentScriptDetails; - -/** - * @param {Array} contentScriptList - * @see https://developer.chrome.com/apps/tags/webview#method-addContentScripts - */ -WebView.prototype.addContentScripts = function(contentScriptList) {}; - -/** - * @see https://developer.chrome.com/apps/tags/webview#method-back - */ -WebView.prototype.back = function() {}; - -/** - * @return {boolean} - * @see https://developer.chrome.com/apps/tags/webview#method-canGoBack - */ -WebView.prototype.canGoBack = function() {}; - -/** - * @return {boolean} - * @see https://developer.chrome.com/apps/tags/webview#method-canGoBack - */ -WebView.prototype.canGoForward = function() {}; - -/** - * @param {ClearDataOptions} options - * @param {ClearDataTypeSet} types - * @param {Function=} opt_callback - * @see https://developer.chrome.com/apps/tags/webview#method-clearData - */ -WebView.prototype.clearData = function(options, types, opt_callback) {}; - -/** - * @param {InjectDetails} details - * @param {Function=} opt_callback - * @see https://developer.chrome.com/apps/tags/webview#method-executeScript - */ -WebView.prototype.executeScript = function(details, opt_callback) {}; - -/** - * @param {string} searchText - * @param {FindOptions=} opt_options - * @param {Function=} opt_callback - * @see https://developer.chrome.com/apps/tags/webview#method-find - */ -WebView.prototype.find = function(searchText, opt_options, opt_callback) {}; - -/** - * @see https://developer.chrome.com/apps/tags/webview#method-forward - */ -WebView.prototype.forward = function() {}; - -/** - * @return {number} - * @see https://developer.chrome.com/apps/tags/webview#method-getProcessId - */ -WebView.prototype.getProcessId = function() {}; - -/** - * @return {string} - * @see https://developer.chrome.com/apps/tags/webview#method-getUserAgent - */ -WebView.prototype.getUserAgent = function() {}; - -/** - * @param {Function} callback - * @see https://developer.chrome.com/apps/tags/webview#method-getZoom - */ -WebView.prototype.getZoom = function(callback) {}; - -/** - * @param {number} relativeIndex - * @param {Function=} opt_callback - * @see https://developer.chrome.com/apps/tags/webview#method-go - */ -WebView.prototype.go = function(relativeIndex, opt_callback) {}; - -/** - * @param {InjectDetails} details - * @param {Function=} opt_callback - * @see https://developer.chrome.com/apps/tags/webview#method-insertCSS - */ -WebView.prototype.insertCSS = function(details, opt_callback) {}; - -/** - * @return {boolean} - * @see https://developer.chrome.com/apps/tags/webview#method-isUserAgentOverridden - */ -WebView.prototype.isUserAgentOverridden = function() {}; - -/** - * @see https://developer.chrome.com/apps/tags/webview#method-print - */ -WebView.prototype.print = function() {}; - -/** - * @see https://developer.chrome.com/apps/tags/webview#method-reload - */ -WebView.prototype.reload = function() {}; - -/** - * @param {Array} contentScriptList - * @see https://developer.chrome.com/apps/tags/webview#method-removeContentScripts - */ -WebView.prototype.removeContentScripts = function(contentScriptList) {}; - -/** - * @param {string} userAgent - * @see https://developer.chrome.com/apps/tags/webview#method-setUserAgentOverride - */ -WebView.prototype.setUserAgentOverride = function(userAgent) {}; - -/** - * @param {number} zoomFactor - * @param {Function=} opt_callback - * @see https://developer.chrome.com/apps/tags/webview#method-setZoom - */ -WebView.prototype.setZoom = function(zoomFactor, opt_callback) {}; - -/** - * @param {string} zoomMode Allowed values: "per-origin", "per-view", "disabled" - * @see https://developer.chrome.com/apps/tags/webview#type-ZoomMode - * @param {Function=} opt_callback - * @see https://developer.chrome.com/apps/tags/webview#method-setZoomMode - */ -WebView.prototype.setZoomMode = function(zoomMode, opt_callback) {}; - -/** - * @see https://developer.chrome.com/apps/tags/webview#method-stop - */ -WebView.prototype.stop = function() {}; - -/** - * @param {?=} opt_action - */ -WebView.prototype.stopFinding = function(opt_action) {}; - -/** - * @param {string} dataUrl - * @param {string} baseUrl - * @param {string=} opt_virtualUrl - * @see https://developer.chrome.com/apps/tags/webview#method-stopFinding - */ -WebView.prototype.loadDataWithBaseUrl = - function(dataUrl, baseUrl, opt_virtualUrl) {}; - -/** - * @see https://developer.chrome.com/apps/tags/webview#method-terminate - */ -WebView.prototype.terminate = function() {}; - -/** - * @constructor - * @extends {Event} - */ -function NewWindowEvent() {} - -/** @type {NewWindow} */ -NewWindowEvent.prototype.window; - -/** @type {string} */ -NewWindowEvent.prototype.targetUrl; - -/** @type {number} */ -NewWindowEvent.prototype.initialWidth; - -/** @type {number} */ -NewWindowEvent.prototype.initialHeight; - -/** @type {string} */ -NewWindowEvent.prototype.name; - - -/** - * @typedef {{ - * url: string, - * isTopLevel: boolean, - * code: number, - * reason: string - * }} - * @see https://developer.chrome.com/apps/tags/webview#event-loadabort - */ -var WebviewLoadAbortEventData; - - -/** @type {!ChromeEvent} */ -WebView.prototype.close; - -/** @type {!ChromeEvent} */ -WebView.prototype.consolemessage; - -/** @type {!ChromeEvent} */ -WebView.prototype.contentload; - -/** @type {!ChromeEvent} */ -WebView.prototype.dialog; - -/** @type {!ChromeEvent} */ -WebView.prototype.exit; - -/** @type {!ChromeEvent} */ -WebView.prototype.findupdate; - -/** @type {!ChromeBaseEvent} */ -WebView.prototype.loadabort; - -/** @type {!ChromeEvent} */ -WebView.prototype.loadcommit; - -/** @type {!ChromeEvent} */ -WebView.prototype.loadredirect; - -/** @type {!ChromeEvent} */ -WebView.prototype.loadstart; - -/** @type {!ChromeEvent} */ -WebView.prototype.loadstop; - -/** - * "newwindow" event object properties. - * @typedef{{ - * window: NewWindow, - * targetUrl: string, - * initialWidth: number, - * initialHeight: number, - * name: string, - * windowOpenDisposition: string - * }} - * @see https://developer.chrome.com/apps/tags/webview#event-newwindow - */ -var NewWindowProperties; - -/** @type {!ChromeEvent} */ -WebView.prototype.newwindow; - -/** @type {!ChromeEvent} */ -WebView.prototype.permissionrequest; - -/** @type {!ChromeEvent} */ -WebView.prototype.responsive; - -/** @type {!ChromeEvent} */ -WebView.prototype.sizechanged; - -/** @type {!ChromeEvent} */ -WebView.prototype.unresponsive; - -/** @type {!ChromeEvent} */ -WebView.prototype.zoomchange; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/externs/windows.js chromium-132.0.6834.159/third_party/closure_compiler/externs/windows.js --- chromium-132.0.6834.110/third_party/closure_compiler/externs/windows.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/externs/windows.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,211 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. -// NOTE: The format of types has changed. 'FooType' is now -// 'chrome.windows.FooType'. -// Please run the closure compiler before committing changes. -// See https://chromium.googlesource.com/chromium/src/+/main/docs/closure_compilation.md - -// TODO(crbug.com/543822): Disable automatic extern generation until fixed. -// s/chrome.windows.tabs.Tab/chrome.tabs.Tab/ - -/** - * @fileoverview Externs generated from namespace: windows - * @externs - */ - -/** @const */ -chrome.windows = {}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/windows#type-WindowType - */ -chrome.windows.WindowType = { - NORMAL: 'normal', - POPUP: 'popup', - PANEL: 'panel', - APP: 'app', - DEVTOOLS: 'devtools', -}; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/windows#type-WindowState - */ -chrome.windows.WindowState = { - NORMAL: 'normal', - MINIMIZED: 'minimized', - MAXIMIZED: 'maximized', - FULLSCREEN: 'fullscreen', - LOCKED_FULLSCREEN: 'locked-fullscreen', -}; - -/** - * @typedef {{ - * id: (number|undefined), - * focused: boolean, - * top: (number|undefined), - * left: (number|undefined), - * width: (number|undefined), - * height: (number|undefined), - * tabs: (!Array|undefined), - * incognito: boolean, - * type: (!chrome.windows.WindowType|undefined), - * state: (!chrome.windows.WindowState|undefined), - * alwaysOnTop: boolean, - * sessionId: (string|undefined) - * }} - * @see https://developer.chrome.com/extensions/windows#type-Window - */ -chrome.windows.Window; - -/** - * @enum {string} - * @see https://developer.chrome.com/extensions/windows#type-CreateType - */ -chrome.windows.CreateType = { - NORMAL: 'normal', - POPUP: 'popup', - PANEL: 'panel', -}; - -/** - * @typedef {{ - * populate: (boolean|undefined), - * windowTypes: (!Array|undefined) - * }} - * @see https://developer.chrome.com/extensions/windows#type-QueryOptions - */ -chrome.windows.QueryOptions; - -/** - * The windowId value that represents the absence of a Chrome browser window. - * @type {number} - * @see https://developer.chrome.com/extensions/windows#type-WINDOW_ID_NONE - */ -chrome.windows.WINDOW_ID_NONE; - -/** - * The windowId value that represents the current window. - * @type {number} - * @see https://developer.chrome.com/extensions/windows#type-WINDOW_ID_CURRENT - */ -chrome.windows.WINDOW_ID_CURRENT; - -/** - * Gets details about a window. - * @param {number} windowId - * @param {?chrome.windows.QueryOptions|undefined} queryOptions - * @param {function(!chrome.windows.Window): void} callback - * @see https://developer.chrome.com/extensions/windows#method-get - */ -chrome.windows.get = function(windowId, queryOptions, callback) {}; - -/** - * Gets the current window. - * @param {?chrome.windows.QueryOptions|undefined} queryOptions - * @param {function(!chrome.windows.Window): void} callback - * @see https://developer.chrome.com/extensions/windows#method-getCurrent - */ -chrome.windows.getCurrent = function(queryOptions, callback) {}; - -/** - * Gets the window that was most recently focused — typically the window - * 'on top'. - * @param {?chrome.windows.QueryOptions|undefined} queryOptions - * @param {function(!chrome.windows.Window): void} callback - * @see https://developer.chrome.com/extensions/windows#method-getLastFocused - */ -chrome.windows.getLastFocused = function(queryOptions, callback) {}; - -/** - * Gets all windows. - * @param {?chrome.windows.QueryOptions|undefined} queryOptions - * @param {function(!Array): void} callback - * @see https://developer.chrome.com/extensions/windows#method-getAll - */ -chrome.windows.getAll = function(queryOptions, callback) {}; - -/** - * Creates (opens) a new browser window with any optional sizing, position, or - * default URL provided. - * @param {{ - * url: ((string|!Array)|undefined), - * tabId: (number|undefined), - * left: (number|undefined), - * top: (number|undefined), - * width: (number|undefined), - * height: (number|undefined), - * focused: (boolean|undefined), - * incognito: (boolean|undefined), - * type: (!chrome.windows.CreateType|undefined), - * state: (!chrome.windows.WindowState|undefined), - * setSelfAsOpener: (boolean|undefined) - * }=} createData - * @param {function((!chrome.windows.Window|undefined)): void=} callback - * @see https://developer.chrome.com/extensions/windows#method-create - */ -chrome.windows.create = function(createData, callback) {}; - -/** - * Updates the properties of a window. Specify only the properties that to be - * changed; unspecified properties are unchanged. - * @param {number} windowId - * @param {{ - * left: (number|undefined), - * top: (number|undefined), - * width: (number|undefined), - * height: (number|undefined), - * focused: (boolean|undefined), - * drawAttention: (boolean|undefined), - * state: (!chrome.windows.WindowState|undefined) - * }} updateInfo - * @param {function(!chrome.windows.Window): void=} callback - * @see https://developer.chrome.com/extensions/windows#method-update - */ -chrome.windows.update = function(windowId, updateInfo, callback) {}; - -/** - * Removes (closes) a window and all the tabs inside it. - * @param {number} windowId - * @param {function(): void=} callback - * @see https://developer.chrome.com/extensions/windows#method-remove - */ -chrome.windows.remove = function(windowId, callback) {}; - -/** - * Fired when a window is created. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/windows#event-onCreated - */ -chrome.windows.onCreated; - -/** - * Fired when a window is removed (closed). - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/windows#event-onRemoved - */ -chrome.windows.onRemoved; - -/** - * Fired when the currently focused window changes. Returns - * chrome.windows.WINDOW_ID_NONE if all Chrome windows have lost - * focus. Note: On some Linux window managers, - * WINDOW_ID_NONE is always sent immediately preceding a switch - * from one Chrome window to another. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/windows#event-onFocusChanged - */ -chrome.windows.onFocusChanged; - -/** - * Fired when a window has been resized; this event is only dispatched when the - * new bounds are committed, and not for in-progress changes. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/windows#event-onBoundsChanged - */ -chrome.windows.onBoundsChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/OWNERS chromium-132.0.6834.159/third_party/closure_compiler/interfaces/OWNERS --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/OWNERS 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/OWNERS 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -rdevlin.cronin@chromium.org -stevenjb@chromium.org diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/README.md chromium-132.0.6834.159/third_party/closure_compiler/interfaces/README.md --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/README.md 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -## Creating or Updating an Interface - -`~/chromium/src/tools/json_schema_compiler/compiler.py` is used to generate or update an existing interface. - -Example: Run `~/chromium/src/tools/json_schema_compiler/compiler.py --root ~/chromium/src --namespace extensions --generator interface extensions/common/api/system_display.idl > ~/chromium/src/third_party/closure_compiler/interfaces/system_display_interface.js` to generate an up-to-date system_display_interface. \ No newline at end of file diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/bluetooth_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/bluetooth_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/bluetooth_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/bluetooth_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -// 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. - -// This file was generated by: -// ./tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for bluetooth that can be overriden. */ - -/** @interface */ -function Bluetooth() {} - -Bluetooth.prototype = { - /** - * Get information about the Bluetooth adapter. - * @param {function(!chrome.bluetooth.AdapterState): void} callback Called - * with an AdapterState object describing the adapter state. - * @see https://developer.chrome.com/extensions/bluetooth#method-getAdapterState - */ - getAdapterState: function(callback) {}, - - /** - * Get information about a Bluetooth device known to the system. - * @param {string} deviceAddress Address of device to get. - * @param {function(!chrome.bluetooth.Device): void} callback Called with the - * Device object describing the device. - * @see https://developer.chrome.com/extensions/bluetooth#method-getDevice - */ - getDevice: function(deviceAddress, callback) {}, - - /** - * Get a list of Bluetooth devices known to the system, including paired and - * recently discovered devices. - * @param {?chrome.bluetooth.BluetoothFilter|undefined} filter Some criteria - * to filter the list of returned bluetooth devices. If the filter is not - * set or set to {}, returned device list will contain all - * bluetooth devices. Right now this is only supported in ChromeOS, for - * other platforms, a full list is returned. - * @param {function(!Array): void} callback Called - * when the search is completed. - * @see https://developer.chrome.com/extensions/bluetooth#method-getDevices - */ - getDevices: function(filter, callback) {}, - - /** - *

Start discovery. Newly discovered devices will be returned via the - * onDeviceAdded event. Previously discovered devices already known to the - * adapter must be obtained using getDevices and will only be updated using - * the |onDeviceChanged| event if information about them - * changes.

Discovery will fail to start if this application has already - * called startDiscovery. Discovery can be resource intensive: stopDiscovery - * should be called as soon as possible.

- * @param {function(): void=} callback Called to indicate success or failure. - * @see https://developer.chrome.com/extensions/bluetooth#method-startDiscovery - */ - startDiscovery: function(callback) {}, - - /** - * Stop discovery. - * @param {function(): void=} callback Called to indicate success or failure. - * @see https://developer.chrome.com/extensions/bluetooth#method-stopDiscovery - */ - stopDiscovery: function(callback) {}, -}; - -/** - * Fired when the state of the Bluetooth adapter changes. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/bluetooth#event-onAdapterStateChanged - */ -Bluetooth.prototype.onAdapterStateChanged; - -/** - * Fired when information about a new Bluetooth device is available. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/bluetooth#event-onDeviceAdded - */ -Bluetooth.prototype.onDeviceAdded; - -/** - * Fired when information about a known Bluetooth device has changed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/bluetooth#event-onDeviceChanged - */ -Bluetooth.prototype.onDeviceChanged; - -/** - * Fired when a Bluetooth device that was previously discovered has been out of - * range for long enough to be considered unavailable again, and when a paired - * device is removed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/bluetooth#event-onDeviceRemoved - */ -Bluetooth.prototype.onDeviceRemoved; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/bluetooth_private_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/bluetooth_private_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/bluetooth_private_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/bluetooth_private_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,101 +0,0 @@ -// 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. - -// This file was generated by: -// ./tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for bluetoothPrivate that can be overriden. */ - -/** @interface */ -function BluetoothPrivate() {} - -BluetoothPrivate.prototype = { - /** - * Changes the state of the Bluetooth adapter. - * @param {!chrome.bluetoothPrivate.NewAdapterState} adapterState The new - * state of the adapter. - * @param {function(): void=} callback Called when all the state changes have - * been completed. - */ - setAdapterState: function(adapterState, callback) {}, - - /** - * @param {!chrome.bluetoothPrivate.SetPairingResponseOptions} options - * @param {function(): void=} callback - */ - setPairingResponse: function(options, callback) {}, - - /** - * Tears down all connections to the given device. - * @param {string} deviceAddress - * @param {function(): void=} callback - */ - disconnectAll: function(deviceAddress, callback) {}, - - /** - * Forgets the given device. - * @param {string} deviceAddress - * @param {function(): void=} callback - */ - forgetDevice: function(deviceAddress, callback) {}, - - /** - * Set or clear discovery filter. - * @param {!chrome.bluetoothPrivate.DiscoveryFilter} discoveryFilter - * @param {function(): void=} callback - */ - setDiscoveryFilter: function(discoveryFilter, callback) {}, - - /** - * Connects to the given device. This will only throw an error if the device - * address is invalid or the device is already connected. Otherwise this will - * succeed and invoke |callback| with ConnectResultType. - * @param {string} deviceAddress - * @param {function(!chrome.bluetoothPrivate.ConnectResultType): void=} - * callback - */ - connect: function(deviceAddress, callback) {}, - - /** - * Pairs the given device. - * @param {string} deviceAddress - * @param {function(): void=} callback - */ - pair: function(deviceAddress, callback) {}, - - /** - * Record that a pairing attempt finished. Ignores cancellations. - * @param {!chrome.bluetoothPrivate.TransportType} transport - * @param {number} pairingDurationMs - * @param {!chrome.bluetoothPrivate.ConnectResultType=} result - */ - recordPairing: function(transport, pairingDurationMs, result) {}, - - /** - * Record that a user-initiated reconnection attempt to an already paired - * device finished. Ignores cancellations. - * @param {!chrome.bluetoothPrivate.ConnectResultType=} result - */ - recordReconnection: function(result) {}, - - /** - * Record that a user selected a device to connect to. - * @param {number} selectionDurationMs - * @param {boolean} wasPaired - * @param {!chrome.bluetoothPrivate.TransportType} transport - */ - recordDeviceSelection: function(selectionDurationMs, wasPaired, transport) {}, -}; - -/** - * Fired when a pairing event occurs. - * @type {!ChromeEvent} - */ -BluetoothPrivate.prototype.onPairing; - -/** - * Fired when a Bluetooth device changed its address. - * @type {!ChromeEvent} - */ -BluetoothPrivate.prototype.onDeviceAddressChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/input_method_private_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/input_method_private_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/input_method_private_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/input_method_private_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,276 +0,0 @@ -// 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. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for inputMethodPrivate that can be overriden. */ - -/** @interface */ -function InputMethodPrivate() {} - -InputMethodPrivate.prototype = { - /** - * Gets configurations for input methods. - * @param {function({ - * isPhysicalKeyboardAutocorrectEnabled: boolean, - * isImeMenuActivated: boolean - * }): void} callback Callback which is called with the config object. - */ - getInputMethodConfig: function(callback) {}, - - /** - * Gets all whitelisted input methods. - * @param {function(!Array<{ - * id: string, - * name: string, - * indicator: string - * }>): void} callback Callback which is called with the input method objects. - */ - getInputMethods: function(callback) {}, - - /** - * Gets the current input method. - * @param {function(string): void} callback Callback which is called with the - * current input method. - */ - getCurrentInputMethod: function(callback) {}, - - /** - * Sets the current input method. - * @param {string} inputMethodId The input method ID to be set as current - * input method. - * @param {function(): void=} callback Callback which is called once the - * current input method is set. If unsuccessful $(ref:runtime.lastError) - * is set. - */ - setCurrentInputMethod: function(inputMethodId, callback) {}, - - /** - * Fetches a list of all the words currently in the dictionary. - * @param {function(!Array): void} callback Callback which is called - * once the list of dictionary words are ready. - */ - fetchAllDictionaryWords: function(callback) {}, - - /** - * Adds a single word to be stored in the dictionary. - * @param {string} word A new word to add to the dictionary. - * @param {function(): void=} callback Callback which is called once the word - * is added. If unsuccessful $(ref:runtime.lastError) is set. - */ - addWordToDictionary: function(word, callback) {}, - - /** - * Gets whether the encrypt sync is enabled. - * @param {function(boolean): void=} callback Callback which is called to - * provide the result. - */ - getEncryptSyncEnabled: function(callback) {}, - - /** - * Sets the XKB layout for the given input method. - * @param {string} xkb_name The XKB layout name. - * @param {function(): void=} callback Callback which is called when the - * layout is set. - */ - setXkbLayout: function(xkb_name, callback) {}, - - /** - * Commits the text currently being composed without moving the selected text - * range. This is a no-op if the context is incorrect. - * @param {{ - * contextID: number - * }} parameters - * @param {function(): void=} callback Called when the operation completes. - */ - finishComposingText: function(parameters, callback) {}, - - /** - * Sets the selection range - * @param {{ - * contextID: number, - * selectionStart: (number|undefined), - * selectionEnd: (number|undefined) - * }} parameters - * @param {function(boolean): void=} callback Called when the operation - * completes with a boolean indicating if the text was accepted or not. - */ - setSelectionRange: function(parameters, callback) {}, - - /** - * Shows the input view window. If the input view window is already shown, - * this function will do nothing. - * @param {function(): void=} callback Called when the operation completes. - */ - showInputView: function(callback) {}, - - /** - * Hides the input view window. If the input view window is already hidden, - * this function will do nothing. - * @param {function(): void=} callback Called when the operation completes. - */ - hideInputView: function(callback) {}, - - /** - * Opens the options page for the input method extension. If the input method - * does not have options, this function will do nothing. - * @param {string} inputMethodId ID of the input method to open options for. - */ - openOptionsPage: function(inputMethodId) {}, - - /** - * Gets the composition bounds - * @param {function(!Array<{ - * x: number, - * y: number, - * w: number, - * h: number - * }>): void} callback Callback which is called to provide the result - */ - getCompositionBounds: function(callback) {}, - - /** - * Gets the surrounding text of the current selection - * @param {number} beforeLength The number of characters before the current - * selection. - * @param {number} afterLength The number of characters after the current - * selection. - * @param {function({ - * before: string, - * selected: string, - * after: string - * }): void} callback Callback which is called to provide the result - */ - getSurroundingText: function(beforeLength, afterLength, callback) {}, - - /** - * Gets the current values of all settings for a particular input method - * @param {string} engineID The ID of the engine (e.g. 'zh-t-i0-pinyin', - * 'xkb:us::eng') - * @param {function((!chrome.inputMethodPrivate.InputMethodSettings|undefined)): void} - * callback Callback to receive the settings - */ - getSettings: function(engineID, callback) {}, - - /** - * Sets the value of all settings for a particular input method - * @param {string} engineID The ID of the engine (e.g. 'zh-t-i0-pinyin', - * 'xkb:us::eng') - * @param {!chrome.inputMethodPrivate.InputMethodSettings} settings The - * settings to set - * @param {function(): void=} callback Callback to notify that the new value - * has been set - */ - setSettings: function(engineID, settings, callback) {}, - - /** - * Set the composition range. If this extension does not own the active IME, - * this fails. - * @param {{ - * contextID: number, - * selectionBefore: number, - * selectionAfter: number, - * segments: (!Array<{ - * start: number, - * end: number, - * style: !chrome.inputMethodPrivate.UnderlineStyle - * }>|undefined) - * }} parameters - * @param {function(boolean): void=} callback Called when the operation - * completes with a boolean indicating if the text was accepted or not. On - * failure, $(ref:runtime.lastError) is set. - */ - setCompositionRange: function(parameters, callback) {}, - - /** - * Set the autocorrect range and autocorrect word. If this extension does not - * own the active IME, this fails. - * @param {{ - * contextID: number, - * autocorrectString: string, - * selectionStart: number, - * selectionEnd: number - * }} parameters - * @param {function(): void=} callback Called when the operation completes. On - * failure, chrome.runtime.lastError is set. - */ - setAutocorrectRange: function(parameters, callback) {}, - - /** - * Resets the current engine to its initial state. Fires an OnReset event. - */ - reset: function() {}, -}; - -/** - * Fired when the input method is changed. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onChanged; - -/** - * Fired when the custom spelling dictionary is loaded. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onDictionaryLoaded; - -/** - * Fired when words are added or removed from the custom spelling dictionary. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onDictionaryChanged; - -/** - * Fired when the IME menu is activated or deactivated. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onImeMenuActivationChanged; - -/** - * Fired when the input method or the list of active input method IDs is - * changed. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onImeMenuListChanged; - -/** - * Fired when the input.ime.setMenuItems or input.ime.updateMenuItems API is - * called. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onImeMenuItemsChanged; - -/** - * This event is sent when focus enters a text box. It is sent to all extensions - * that are listening to this event, and enabled by the user. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onFocus; - -/** - * This event is sent when the settings for any input method changed. It is sent - * to all extensions that are listening to this event, and enabled by the user. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onSettingsChanged; - -/** - * This event is sent when the screen is being mirrored or the desktop is being - * cast. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onScreenProjectionChanged; - -/** - * This event is sent when a new set of suggestions has been generated - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onSuggestionsChanged; - -/** - * This event is sent when input method options are changed. - * @type {!ChromeEvent} - */ -InputMethodPrivate.prototype.onInputMethodOptionsChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/language_settings_private.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/language_settings_private.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/language_settings_private.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/language_settings_private.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,157 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// ./tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for languageSettingsPrivate that can be overriden. */ - -/** @interface */ -function LanguageSettingsPrivate() {} - -LanguageSettingsPrivate.prototype = { - /** - * Gets languages available for translate, spell checking, input and locale. - * @param {function(!Array): void} - * callback - */ - getLanguageList: function(callback) {}, - - /** - * Enables a language, adding it to the Accept-Language list (used to decide - * which languages to translate, generate the Accept-Language header, etc.). - * @param {string} languageCode - */ - enableLanguage: function(languageCode) {}, - - /** - * Disables a language, removing it from the Accept-Language list. - * @param {string} languageCode - */ - disableLanguage: function(languageCode) {}, - - /** - * Enables or disables translation for a given language. - * @param {string} languageCode - * @param {boolean} enable - */ - setEnableTranslationForLanguage: function(languageCode, enable) {}, - - /** - * Moves a language inside the language list. - * @param {string} languageCode - * @param {!chrome.languageSettingsPrivate.MoveType} moveType - */ - moveLanguage: function(languageCode, moveType) {}, - - /** - * Gets languages that should always be automatically translated. - * @param {function(!Array): void} callback - */ - getAlwaysTranslateLanguages: function(callback) {}, - - /** - * Sets whether a given language should always be automatically translated. - * @param {string} languageCode - * @param {boolean} alwaysTranslate - */ - setLanguageAlwaysTranslateState: function(languageCode, alwaysTranslate) {}, - - /** - * Gets languages that should never be offered to translate. - * @param {function(!Array): void} callback - */ - getNeverTranslateLanguages: function(callback) {}, - - /** - * Gets the current status of the chosen spell check dictionaries. - * @param {function(!Array): void} - * callback - */ - getSpellcheckDictionaryStatuses: function(callback) {}, - - /** - * Gets the custom spell check words, in sorted order. - * @param {function(!Array): void} callback - */ - getSpellcheckWords: function(callback) {}, - - /** - * Adds a word to the custom dictionary. - * @param {string} word - */ - addSpellcheckWord: function(word) {}, - - /** - * Removes a word from the custom dictionary. - * @param {string} word - */ - removeSpellcheckWord: function(word) {}, - - /** - * Gets the translate target language (in most cases, the display locale). - * @param {function(string): void} callback - */ - getTranslateTargetLanguage: function(callback) {}, - - /** - * Sets the translate target language given a language code. - * @param {string} languageCode - */ - setTranslateTargetLanguage: function(languageCode) {}, - - /** - * Gets all supported input methods, including third-party IMEs. Chrome OS - * only. - * @param {function(!chrome.languageSettingsPrivate.InputMethodLists): void} - * callback - */ - getInputMethodLists: function(callback) {}, - - /** - * Adds the input method to the current user's list of enabled input methods, - * enabling the input method for the current user. Chrome OS only. - * @param {string} inputMethodId - */ - addInputMethod: function(inputMethodId) {}, - - /** - * Removes the input method from the current user's list of enabled input - * methods, disabling the input method for the current user. Chrome OS only. - * @param {string} inputMethodId - */ - removeInputMethod: function(inputMethodId) {}, - - /** - * Tries to download the dictionary after a failed download. - * @param {string} languageCode - */ - retryDownloadDictionary: function(languageCode) {}, -}; - -/** - * Called when the pref for the dictionaries used for spell checking changes or - * the status of one of the spell check dictionaries changes. - * @type {!ChromeEvent} - */ -LanguageSettingsPrivate.prototype.onSpellcheckDictionariesChanged; - -/** - * Called when words are added to and/or removed from the custom spell check - * dictionary. - * @type {!ChromeEvent} - */ -LanguageSettingsPrivate.prototype.onCustomDictionaryChanged; - -/** - * Called when an input method is added. - * @type {!ChromeEvent} - */ -LanguageSettingsPrivate.prototype.onInputMethodAdded; - -/** - * Called when an input method is removed. - * @type {!ChromeEvent} - */ -LanguageSettingsPrivate.prototype.onInputMethodRemoved; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/language_settings_private_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/language_settings_private_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/language_settings_private_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/language_settings_private_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,157 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// ./tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for languageSettingsPrivate that can be overriden. */ - -/** @interface */ -function LanguageSettingsPrivate() {} - -LanguageSettingsPrivate.prototype = { - /** - * Gets languages available for translate, spell checking, input and locale. - * @param {function(!Array): void} - * callback - */ - getLanguageList: function(callback) {}, - - /** - * Enables a language, adding it to the Accept-Language list (used to decide - * which languages to translate, generate the Accept-Language header, etc.). - * @param {string} languageCode - */ - enableLanguage: function(languageCode) {}, - - /** - * Disables a language, removing it from the Accept-Language list. - * @param {string} languageCode - */ - disableLanguage: function(languageCode) {}, - - /** - * Enables or disables translation for a given language. - * @param {string} languageCode - * @param {boolean} enable - */ - setEnableTranslationForLanguage: function(languageCode, enable) {}, - - /** - * Moves a language inside the language list. - * @param {string} languageCode - * @param {!chrome.languageSettingsPrivate.MoveType} moveType - */ - moveLanguage: function(languageCode, moveType) {}, - - /** - * Gets languages that should always be automatically translated. - * @param {function(!Array): void} callback - */ - getAlwaysTranslateLanguages: function(callback) {}, - - /** - * Sets whether a given language should always be automatically translated. - * @param {string} languageCode - * @param {boolean} alwaysTranslate - */ - setLanguageAlwaysTranslateState: function(languageCode, alwaysTranslate) {}, - - /** - * Gets languages that should never be offered to translate. - * @param {function(!Array): void} callback - */ - getNeverTranslateLanguages: function(callback) {}, - - /** - * Gets the current status of the chosen spell check dictionaries. - * @param {function(!Array): void} - * callback - */ - getSpellcheckDictionaryStatuses: function(callback) {}, - - /** - * Gets the custom spell check words, in sorted order. - * @param {function(!Array): void} callback - */ - getSpellcheckWords: function(callback) {}, - - /** - * Adds a word to the custom dictionary. - * @param {string} word - */ - addSpellcheckWord: function(word) {}, - - /** - * Removes a word from the custom dictionary. - * @param {string} word - */ - removeSpellcheckWord: function(word) {}, - - /** - * Gets the translate target language (in most cases, the display locale). - * @param {function(string): void} callback - */ - getTranslateTargetLanguage: function(callback) {}, - - /** - * Sets the translate target language given a language code. - * @param {string} languageCode - */ - setTranslateTargetLanguage: function(languageCode) {}, - - /** - * Gets all supported input methods, including third-party IMEs. Chrome OS - * only. - * @param {function(!chrome.languageSettingsPrivate.InputMethodLists): void} - * callback - */ - getInputMethodLists: function(callback) {}, - - /** - * Adds the input method to the current user's list of enabled input methods, - * enabling the input method for the current user. Chrome OS only. - * @param {string} inputMethodId - */ - addInputMethod: function(inputMethodId) {}, - - /** - * Removes the input method from the current user's list of enabled input - * methods, disabling the input method for the current user. Chrome OS only. - * @param {string} inputMethodId - */ - removeInputMethod: function(inputMethodId) {}, - - /** - * Tries to download the dictionary after a failed download. - * @param {string} languageCode - */ - retryDownloadDictionary: function(languageCode) {}, -}; - -/** - * Called when the pref for the dictionaries used for spell checking changes or - * the status of one of the spell check dictionaries changes. - * @type {!ChromeEvent} - */ -LanguageSettingsPrivate.prototype.onSpellcheckDictionariesChanged; - -/** - * Called when words are added to and/or removed from the custom spell check - * dictionary. - * @type {!ChromeEvent} - */ -LanguageSettingsPrivate.prototype.onCustomDictionaryChanged; - -/** - * Called when an input method is added. - * @type {!ChromeEvent} - */ -LanguageSettingsPrivate.prototype.onInputMethodAdded; - -/** - * Called when an input method is removed. - * @type {!ChromeEvent} - */ -LanguageSettingsPrivate.prototype.onInputMethodRemoved; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/mojo_private_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/mojo_private_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/mojo_private_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/mojo_private_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// ./tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for mojoPrivate that can be overriden. */ - -/** @interface */ -function MojoPrivate() {} - -MojoPrivate.prototype = { - /** - * Returns a promise that will resolve to an asynchronously loaded module. - * @param {string} name - * @return {*} - */ - requireAsync: function(name) {}, -}; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/networking_private_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/networking_private_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/networking_private_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/networking_private_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,282 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// ./tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for networkingPrivate that can be overriden. */ - -/** @interface */ -function NetworkingPrivate() {} - -NetworkingPrivate.prototype = { - /** - * Gets all the properties of the network with id networkGuid. Includes all - * properties of the network (read-only and read/write values). - * @param {string} networkGuid The GUID of the network to get properties for. - * @param {function(!chrome.networkingPrivate.NetworkProperties):void} - * callback Called with the network properties when received. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-getProperties - */ - getProperties: function(networkGuid, callback) {}, - - /** - * Gets the merged properties of the network with id networkGuid from the - * sources: User settings, shared settings, user policy, device policy and the - * currently active settings. - * @param {string} networkGuid The GUID of the network to get properties for. - * @param {function(!chrome.networkingPrivate.ManagedProperties):void} - * callback Called with the managed network properties when received. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-getManagedProperties - */ - getManagedProperties: function(networkGuid, callback) {}, - - /** - * Gets the cached read-only properties of the network with id networkGuid. - * This is meant to be a higher performance function than - * $(ref:getProperties), which requires a round trip to query the networking - * subsystem. The following properties are returned for all networks: GUID, - * Type, Name, WiFi.Security. Additional properties are provided for visible - * networks: ConnectionState, ErrorState, WiFi.SignalStrength, - * Cellular.NetworkTechnology, Cellular.ActivationState, - * Cellular.RoamingState. - * @param {string} networkGuid The GUID of the network to get properties for. - * @param {function(!chrome.networkingPrivate.NetworkStateProperties):void} - * callback Called immediately with the network state properties. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-getState - */ - getState: function(networkGuid, callback) {}, - - /** - * Sets the properties of the network with id networkGuid. - * @param {string} networkGuid The GUID of the network to set properties for. - * @param {!chrome.networkingPrivate.NetworkConfigProperties} properties The - * properties to set. - * @param {function():void=} callback Called when the operation has completed. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-setProperties - */ - setProperties: function(networkGuid, properties, callback) {}, - - /** - * Creates a new network configuration from properties. If a matching - * configured network already exists, this will fail. Otherwise returns the - * guid of the new network. - * @param {boolean} shared If true, share this network configuration with - * other users. - * @param {!chrome.networkingPrivate.NetworkConfigProperties} properties The - * properties to configure the new network with. - * @param {function(string):void=} callback Called with the GUID for the new - * network configuration once the network has been created. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-createNetwork - */ - createNetwork: function(shared, properties, callback) {}, - - /** - * Forgets a network configuration by clearing any configured properties for - * the network with GUID 'networkGuid'. This may also include any other - * networks with matching identifiers (e.g. WiFi SSID and Security). If no - * such configuration exists, an error will be set and the operation will - * fail. - * @param {string} networkGuid The GUID of the network to forget. - * @param {function():void=} callback Called when the operation has completed. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-forgetNetwork - */ - forgetNetwork: function(networkGuid, callback) {}, - - /** - * Returns a list of network objects with the same properties provided by - * $(ref:networkingPrivate.getState). A filter is provided to specify the type - * of networks returned and to limit the number of networks. Networks are - * ordered by the system based on their priority, with connected or connecting - * networks listed first. - * @param {!chrome.networkingPrivate.NetworkFilter} filter Describes which - * networks to return. - * @param {function(!Array):void} - * callback Called with a dictionary of networks and their state - * properties when received. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-getNetworks - */ - getNetworks: function(filter, callback) {}, - - /** - * Returns a list of $(ref:networkingPrivate.DeviceStateProperties) objects. - * @param {function(!Array):void} - * callback Called with a list of devices and their state. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-getDeviceStates - */ - getDeviceStates: function(callback) {}, - - /** - * Enables any devices matching the specified network type. Note, the type - * might represent multiple network types (e.g. 'Wireless'). - * @param {!chrome.networkingPrivate.NetworkType} networkType The type of - * network to enable. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-enableNetworkType - */ - enableNetworkType: function(networkType) {}, - - /** - * Disables any devices matching the specified network type. See note for - * $(ref:networkingPrivate.enableNetworkType). - * @param {!chrome.networkingPrivate.NetworkType} networkType The type of - * network to disable. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-disableNetworkType - */ - disableNetworkType: function(networkType) {}, - - /** - * Requests that the networking subsystem scan for new networks and update the - * list returned by $(ref:getVisibleNetworks). This is only a request: the - * network subsystem can choose to ignore it. If the list is updated, then - * the $(ref:onNetworkListChanged) event will be fired. - * @param {!chrome.networkingPrivate.NetworkType=} networkType If provided, - * requests a scan specific to the type. For Cellular a mobile network - * scan will be requested if supported. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-requestNetworkScan - */ - requestNetworkScan: function(networkType) {}, - - /** - * Starts a connection to the network with networkGuid. - * @param {string} networkGuid The GUID of the network to connect to. - * @param {function():void=} callback Called when the connect request has been - * sent. Note: the connection may not have completed. Observe - * $(ref:onNetworksChanged) to be notified when a network state - * changes. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-startConnect - */ - startConnect: function(networkGuid, callback) {}, - - /** - * Starts a disconnect from the network with networkGuid. - * @param {string} networkGuid The GUID of the network to disconnect from. - * @param {function():void=} callback Called when the disconnect request has - * been sent. See note for $(ref:startConnect). - * @see https://developer.chrome.com/extensions/networkingPrivate#method-startDisconnect - */ - startDisconnect: function(networkGuid, callback) {}, - - /** - * Starts activation of the Cellular network with networkGuid. If called for a - * network that is already activated, or for a network with a carrier that can - * not be directly activated, this will show the account details page for the - * carrier if possible. - * @param {string} networkGuid The GUID of the Cellular network to activate. - * @param {string=} carrier Optional name of carrier to activate. - * @param {function():void=} callback Called when the activation request has - * been sent. See note for $(ref:startConnect). - * @see https://developer.chrome.com/extensions/networkingPrivate#method-startActivate - */ - startActivate: function(networkGuid, carrier, callback) {}, - - /** - * Returns captive portal status for the network matching 'networkGuid'. - * @param {string} networkGuid The GUID of the network to get captive portal - * status for. - * @param {function(!chrome.networkingPrivate.CaptivePortalStatus):void} - * callback A callback function that returns the results of the query for - * network captive portal status. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-getCaptivePortalStatus - */ - getCaptivePortalStatus: function(networkGuid, callback) {}, - - /** - * Unlocks a Cellular SIM card. * If the SIM is PIN locked, |pin| will be used - * to unlock the SIM and the |puk| argument will be ignored if provided. * - * If the SIM is PUK locked, |puk| and |pin| must be provided. If the - * operation succeeds (|puk| is valid), the PIN will be set to |pin|. (If - * |pin| is empty or invalid the operation will fail). - * @param {string} networkGuid The GUID of the cellular network to unlock. - * If empty, the default cellular device will be used. - * @param {string} pin The current SIM PIN, or the new PIN if PUK is provided. - * @param {string=} puk The operator provided PUK for unblocking a blocked - * SIM. - * @param {function():void=} callback Called when the operation has completed. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-unlockCellularSim - */ - unlockCellularSim: function(networkGuid, pin, puk, callback) {}, - - /** - * Sets whether or not SIM locking is enabled (i.e a PIN will be required when - * the device is powered) and changes the PIN if a new PIN is specified. If - * the new PIN is provided but not valid (e.g. too short) the operation will - * fail. This will not lock the SIM; that is handled automatically by the - * device. NOTE: If the SIM is locked, it must first be unlocked with - * unlockCellularSim() before this can be called (otherwise it will fail and - * chrome.runtime.lastError will be set to Error.SimLocked). - * @param {string} networkGuid The GUID of the cellular network to set the SIM - * state of. If empty, the default cellular device will be used. - * @param {!chrome.networkingPrivate.CellularSimState} simState The SIM state - * to set. - * @param {function():void=} callback Called when the operation has completed. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-setCellularSimState - */ - setCellularSimState: function(networkGuid, simState, callback) {}, - - /** - * Selects which Cellular Mobile Network to use. |networkId| must be the - * NetworkId property of a member of Cellular.FoundNetworks from the network - * properties for the specified Cellular network. - * @param {string} networkGuid The GUID of the cellular network to select the - * network for. If empty, the default cellular device will be used. - * @param {string} networkId The networkId to select. - * @param {function():void=} callback Called when the operation has completed. - * @see https://developer.chrome.com/extensions/networkingPrivate#method-selectCellularMobileNetwork - */ - selectCellularMobileNetwork: function(networkGuid, networkId, callback) {}, - - /** - * Gets the global policy properties. These properties are not expected to - * change during a session. - * @param {function(!chrome.networkingPrivate.GlobalPolicy):void} callback - * @see https://developer.chrome.com/extensions/networkingPrivate#method-getGlobalPolicy - */ - getGlobalPolicy: function(callback) {}, - - /** - * Gets the lists of certificates available for network configuration. - * @param {function(!chrome.networkingPrivate.CertificateLists):void} callback - * @see https://developer.chrome.com/extensions/networkingPrivate#method-getCertificateLists - */ - getCertificateLists: function(callback) {}, -}; - -/** - * Fired when the properties change on any of the networks. Sends a list of - * GUIDs for networks whose properties have changed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/networkingPrivate#event-onNetworksChanged - */ -NetworkingPrivate.prototype.onNetworksChanged; - -/** - * Fired when the list of networks has changed. Sends a complete list of GUIDs - * for all the current networks. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/networkingPrivate#event-onNetworkListChanged - */ -NetworkingPrivate.prototype.onNetworkListChanged; - -/** - * Fired when the list of devices has changed or any device state properties - * have changed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/networkingPrivate#event-onDeviceStateListChanged - */ -NetworkingPrivate.prototype.onDeviceStateListChanged; - -/** - * Fired when a portal detection for a network completes. Sends the guid of the - * network and the corresponding captive portal status. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/networkingPrivate#event-onPortalDetectionCompleted - */ -NetworkingPrivate.prototype.onPortalDetectionCompleted; - -/** - * Fired when any certificate list has changed. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/networkingPrivate#event-onCertificateListsChanged - */ -NetworkingPrivate.prototype.onCertificateListsChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/quick_unlock_private_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/quick_unlock_private_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/quick_unlock_private_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/quick_unlock_private_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,111 +0,0 @@ -// 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. - -// This file was generated by: -// ./tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for quickUnlockPrivate that can be overriden. */ - -/** @interface */ -function QuickUnlockPrivate() {} - -QuickUnlockPrivate.prototype = { - /** - * Returns a token that can be used for future operations and the number of - * seconds until the token expires. - * @param {string} accountPassword The account password for the logged in - * user. - * @param {function(!chrome.quickUnlockPrivate.TokenInfo): void} onComplete - */ - getAuthToken: function(accountPassword, onComplete) {}, - - /** - * Sets the lock screen enabled state. NOTE: The lock enabled state is - * reflected in the settings.enable_screen_lock pref, which can be read but - * not written using the settings_private API (which also provides policy - * information). This API must be used to change the pref. - * @param {string} token The token returned by $(ref:getAuthToken). - * @param {boolean} enabled Whether to enable the lock screen. - * @param {function(): void=} onComplete - */ - setLockScreenEnabled: function(token, enabled, onComplete) {}, - - /** - * Sets the PIN auto submit enabled state. NOTE: The PIN autosubmit state is - * reflected in the pin_unlock_autosubmit_enabled pref, which can be read but - * not written using the settings_private API (which also provides policy - * information). This API must be used to change the pref. - * @param {string} token The authentication token. - * @param {string} pin The PIN of the logged in user. - * @param {boolean} enabled Whether to enable PIN auto submit. - * @param {function(boolean): void} onComplete Called with true if the quick - * unlock state was updated, false otherwise. The update is treated as - * a single atomic operation. - */ - setPinAutosubmitEnabled: function(token, pin, enabled, onComplete) {}, - - /** - * Tests wether it is currently possible to authenticate using PIN. - * @param {function(boolean): void} onComplete - */ - canAuthenticatePin: function(onComplete) {}, - - /** - * Returns the set of quick unlock modes that are available for the user to - * use. Some quick unlock modes may be disabled by policy. - * @param {function(!Array): void} - * onComplete - */ - getAvailableModes: function(onComplete) {}, - - /** - * Returns the quick unlock modes that are currently enabled and usable on the - * lock screen. - * @param {function(!Array): void} - * onComplete - */ - getActiveModes: function(onComplete) {}, - - /** - * Checks if the given credential can be used for the given unlock mode. - * Enterprise policy can change credential requirements. - * @param {!chrome.quickUnlockPrivate.QuickUnlockMode} mode The quick unlock - * mode that is used. - * @param {string} credential The given credential. - * @param {function(!chrome.quickUnlockPrivate.CredentialCheck): void} - * onComplete Called with a list of warnings and errors the given - * |credential| has (or an empty list if there are none). - */ - checkCredential: function(mode, credential, onComplete) {}, - - /** - * Gets the credential requirements for the given unlock mode. - * @param {!chrome.quickUnlockPrivate.QuickUnlockMode} mode The quick unlock - * mode that is used. - * @param {function(!chrome.quickUnlockPrivate.CredentialRequirements): void} - * onComplete Called with the credential requirements of the given - * |mode|. - */ - getCredentialRequirements: function(mode, onComplete) {}, - - /** - * Update the set of quick unlock modes that are currently active/enabled. - * @param {string} token The token returned by $(ref:getAuthToken). - * @param {!Array} modes The quick - * unlock modes that should be active. - * @param {!Array} credentials The associated credential for each - * mode. To keep the credential the same for the associated mode, pass - * an empty string. - * @param {function(): void} onComplete Called with true if the quick unlock - * state was updated, false otherwise. The update is treated as a - * single atomic operation. - */ - setModes: function(token, modes, credentials, onComplete) {}, -}; - -/** - * Called after the active set of quick unlock modes has changed. - * @type {!ChromeEvent} - */ -QuickUnlockPrivate.prototype.onActiveModesChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/settings_private_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/settings_private_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/settings_private_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/settings_private_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// tools/json_schema_compiler/compiler.py. - -/** @fileoverview Interface for settingsPrivate that can be overriden. */ - -/** @interface */ -function SettingsPrivate() {} - -SettingsPrivate.prototype = { - /** - * Sets a settings value. - * @param {string} name The name of the pref. - * @param {*} value The new value of the pref. - * @param {string} pageId The user metrics identifier or null. - * @param {function(boolean):void} callback The callback for whether the pref - * was set or not. - * @see https://developer.chrome.com/extensions/settingsPrivate#method-setPref - */ - setPref: function(name, value, pageId, callback) {}, - - /** - * Gets an array of all the prefs. - * @param {function(!Array):void} callback - * @see https://developer.chrome.com/extensions/settingsPrivate#method-getAllPrefs - */ - getAllPrefs: function(callback) {}, - - /** - * Gets the value of a specific pref. - * @param {string} name - * @param {function(!chrome.settingsPrivate.PrefObject):void} callback - * @see https://developer.chrome.com/extensions/settingsPrivate#method-getPref - */ - getPref: function(name, callback) {}, - - /** - * Gets the default page zoom factor. Possible values are currently between - * 0.25 and 5. For a full list, see zoom::kPresetBrowserZoomFactors. - * @param {function(number):void} callback - * @see https://developer.chrome.com/extensions/settingsPrivate#method-getDefaultZoom - */ - getDefaultZoom: function(callback) {}, - - /** - * Sets the page zoom factor. Must be less than 0.001 different than a value - * in zoom::kPresetBrowserZoomFactors. - * @param {number} zoom - * @param {function(boolean):void=} callback - * @see https://developer.chrome.com/extensions/settingsPrivate#method-setDefaultZoom - */ - setDefaultZoom: function(zoom, callback) {}, -}; - -/** - *

Fired when a set of prefs has changed.

|prefs| The prefs that - * changed.

- * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/settingsPrivate#event-onPrefsChanged - */ -SettingsPrivate.prototype.onPrefsChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/interfaces/system_display_interface.js chromium-132.0.6834.159/third_party/closure_compiler/interfaces/system_display_interface.js --- chromium-132.0.6834.110/third_party/closure_compiler/interfaces/system_display_interface.js 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/interfaces/system_display_interface.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,181 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file was generated by: -// ./tools/json_schema_compiler/compiler.py. - -// This was modified to replace System.display with SystemDisplay. - -/** @fileoverview Interface for system.display that can be overriden. */ - -assertNotReached('Interface file for Closure Compiler should not be executed.'); - -/** @interface */ -function SystemDisplay() {} - -SystemDisplay.prototype = { - /** - * Requests the information for all attached display devices. - * @param {!chrome.system.display.GetInfoFlags} flags Options affecting how - * the information is returned. - * @param {function(!Array):void} - * callback The callback to invoke with the results. - * @see https://developer.chrome.com/extensions/system.display#method-getInfo - */ - getInfo: assertNotReached, - - /** - * Requests the layout info for all displays. NOTE: This is only available to - * Chrome OS Kiosk apps and Web UI. - * @param {function(!Array):void} - * callback The callback to invoke with the results. - * @see https://developer.chrome.com/extensions/system.display#method-getDisplayLayout - */ - getDisplayLayout: assertNotReached, - - /** - * Updates the properties for the display specified by |id|, according to the - * information provided in |info|. On failure, $(ref:runtime.lastError) will - * be set. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. - * @param {string} id The display's unique identifier. - * @param {!chrome.system.display.DisplayProperties} info The information - * about display properties that should be changed. A property will be - * changed only if a new value for it is specified in |info|. - * @param {function():void=} callback Empty function called when the function - * finishes. To find out whether the function succeeded, - * $(ref:runtime.lastError) should be queried. - * @see https://developer.chrome.com/extensions/system.display#method-setDisplayProperties - */ - setDisplayProperties: assertNotReached, - - /** - * Set the layout for all displays. Any display not included will use the - * default layout. If a layout would overlap or be otherwise invalid it will - * be adjusted to a valid layout. After layout is resolved, an - * onDisplayChanged event will be triggered. NOTE: This is only available to - * Chrome OS Kiosk apps and Web UI. - * @param {!Array} layouts The layout - * information, required for all displays except the primary display. - * @param {function():void=} callback Empty function called when the function - * finishes. To find out whether the function succeeded, - * $(ref:runtime.lastError) should be queried. - * @see https://developer.chrome.com/extensions/system.display#method-setDisplayLayout - */ - setDisplayLayout: assertNotReached, - - /** - * Enables/disables the unified desktop feature. Note that this simply enables - * the feature, but will not change the actual desktop mode. (That is, if the - * desktop is in mirror mode, it will stay in mirror mode) NOTE: This is only - * available to Chrome OS Kiosk apps and Web UI. - * @param {boolean} enabled True if unified desktop should be enabled. - * @see https://developer.chrome.com/extensions/system.display#method-enableUnifiedDesktop - */ - enableUnifiedDesktop: assertNotReached, - - /** - * Starts overscan calibration for a display. This will show an overlay on the - * screen indicating the current overscan insets. If overscan calibration for - * display |id| is in progress this will reset calibration. - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-overscanCalibrationStart - */ - overscanCalibrationStart: assertNotReached, - - /** - * Adjusts the current overscan insets for a display. Typically this should - * etiher move the display along an axis (e.g. left+right have the same value) - * or scale it along an axis (e.g. top+bottom have opposite values). Each - * Adjust call is cumulative with previous calls since Start. - * @param {string} id The display's unique identifier. - * @param {!chrome.system.display.Insets} delta The amount to change the - * overscan insets. - * @see https://developer.chrome.com/extensions/system.display#method-overscanCalibrationAdjust - */ - overscanCalibrationAdjust: assertNotReached, - - /** - * Resets the overscan insets for a display to the last saved value (i.e - * before Start was called). - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-overscanCalibrationReset - */ - overscanCalibrationReset: assertNotReached, - - /** - * Complete overscan adjustments for a display by saving the current values - * and hiding the overlay. - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-overscanCalibrationComplete - */ - overscanCalibrationComplete: assertNotReached, - - /** - * Displays the native touch calibration UX for the display with |id| as - * display id. This will show an overlay on the screen with required - * instructions on how to proceed. The callback will be invoked in case of - * successful calibraion only. If the calibration fails, this will throw an - * error. - * @param {string} id The display's unique identifier. - * @param {function(boolean):void=} callback Optional callback to inform the - * caller that the touch calibration has ended. The argument of the - * callback informs if the calibration was a success or not. - * @see https://developer.chrome.com/extensions/system.display#method-showNativeTouchCalibration - */ - showNativeTouchCalibration: assertNotReached, - - /** - * Starts custom touch calibration for a display. This should be called when - * using a custom UX for collecting calibration data. If another touch - * calibration is already in progress this will throw an error. - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-startCustomTouchCalibration - */ - startCustomTouchCalibration: assertNotReached, - - /** - * Sets the touch calibration pairs for a display. These |pairs| would be used - * to calibrate the touch screen for display with |id| called in - * startCustomTouchCalibration(). Always call |startCustomTouchCalibration| - * before calling this method. If another touch calibration is already in - * progress this will throw an error. - * @param {!chrome.system.display.TouchCalibrationPairQuad} pairs The pairs of - * point used to calibrate the display. - * @param {!chrome.system.display.Bounds} bounds Bounds of the display when - * the touch calibration was performed. |bounds.left| and |bounds.top| - * values are ignored. - * @see https://developer.chrome.com/extensions/system.display#method-completeCustomTouchCalibration - */ - completeCustomTouchCalibration: assertNotReached, - - /** - * Resets the touch calibration for the display and brings it back to its - * default state by clearing any touch calibration data associated with the - * display. - * @param {string} id The display's unique identifier. - * @see https://developer.chrome.com/extensions/system.display#method-clearTouchCalibration - */ - clearTouchCalibration: assertNotReached, - - /** - * Sets the display mode to the specified mirror mode. Each call resets the - * state from previous calls. Calling setDisplayProperties() will fail for the - * mirroring destination displays. NOTE: This is only available to Chrome OS - * Kiosk apps and Web UI. - * @param {!chrome.system.display.MirrorModeInfo} info The information of the - * mirror mode that should be applied to the display mode. - * @param {function(): void=} callback Empty function called when the function - * finishes. To find out whether the function succeeded, - * $(ref:runtime.lastError) should be queried. - * @see https://developer.chrome.com/extensions/system.display#method-setMirrorMode - */ - setMirrorMode: function(info, callback) {}, -}; - -/** - * Fired when anything changes to the display configuration. - * @type {!ChromeEvent} - * @see https://developer.chrome.com/extensions/system.display#event-onDisplayChanged - */ -SystemDisplay.prototype.onDisplayChanged; diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/js_binary.py chromium-132.0.6834.159/third_party/closure_compiler/js_binary.py --- chromium-132.0.6834.110/third_party/closure_compiler/js_binary.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/js_binary.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,162 +0,0 @@ -# Copyright 2017 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -"""Used by a js_binary action to compile javascript files. - -This script takes in a list of sources and dependencies and compiles them all -together into a single compiled .js file. The dependencies are ordered in a -post-order, left-to-right traversal order. If multiple instances of the same -source file are read, only the first is kept. The script can also take in -optional --flags argument which will add custom flags to the compiler. Any -extern files can also be passed in using the --extern flag. -""" - -from __future__ import print_function - -import argparse -import os -import sys - -import compiler - - -def ParseDepList(dep): - """Parses a dependency list, returns |sources, deps, externs|.""" - assert os.path.isfile(dep), (dep + - ' is not a js_library target') - with open(dep, 'r') as dep_list: - lines = dep_list.read().splitlines() - assert 'deps:' in lines, dep + ' is not formated correctly, missing "deps:"' - deps_start = lines.index('deps:') - assert 'externs:' in lines, dep + ' is not formated correctly, missing "externs:"' - externs_start = lines.index('externs:') - - return (lines[1:deps_start], - lines[deps_start+1:externs_start], - lines[externs_start+1:]) - - -# Cache, to avoid reading the same file twice in the dependency tree and -# processing its dependencies again. -depcache = {} - -def AppendUnique(items, new_items): - """Append items in |new_items| to |items|, avoiding duplicates.""" - # Note this is O(n*n), and assumes |new_items| is already unique, but this is - # not a bottleneck overall. - items += [i for i in new_items if i not in items] - -def CrawlDepsTree(deps): - """Parses the dependency tree creating a post-order listing of sources.""" - global depcache - - if len(deps) == 0: - return ([], []) - - new_sources = [] - new_externs = [] - for dep in deps: - if dep in depcache: - cur_sources, cur_externs = depcache[dep] - else: - dep_sources, dep_deps, dep_externs = ParseDepList(dep) - cur_sources, cur_externs = CrawlDepsTree(dep_deps) - # Add child dependencies of this node before the current node, then cache. - AppendUnique(cur_sources, dep_sources) - AppendUnique(cur_externs, dep_externs) - depcache[dep] = (cur_sources, cur_externs) - - # Add the current node's sources and dedupe. - AppendUnique(new_sources, cur_sources) - AppendUnique(new_externs, cur_externs) - - return new_sources, new_externs - - -def CrawlRootDepsTree(deps, target_sources, target_externs): - """Parses the dependency tree and adds target sources.""" - sources, externs = CrawlDepsTree(deps) - AppendUnique(sources, target_sources) - AppendUnique(externs, target_externs) - return sources, externs - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('-c', '--compiler', required=True, - help='Path to compiler') - parser.add_argument('-s', '--sources', nargs='*', default=[], - help='List of js source files') - parser.add_argument('-o', '--output', required=False, - help='Compile to output') - parser.add_argument('--chunks', action='store_true', - help='Compile each source to its own chunk') - parser.add_argument('--chunk_suffix', required=False, - help='String appended to the source when naming a chunk') - parser.add_argument('-d', '--deps', nargs='*', default=[], - help='List of js_libarary dependencies') - parser.add_argument('-b', '--bootstrap', - help='A file to include before all others') - parser.add_argument('-cf', '--config', nargs='*', default=[], - help='A list of files to include after bootstrap and ' - 'before all others') - parser.add_argument('-f', '--flags', nargs='*', default=[], - help='A list of custom flags to pass to the compiler. ' - 'Do not include leading dashes') - parser.add_argument('-e', '--externs', nargs='*', default=[], - help='A list of extern files to pass to the compiler') - parser.add_argument('-co', '--checks-only', action='store_true', - help='Only performs checks and writes an empty output') - - args = parser.parse_args() - - # If --chunks is used, args.sources will be added later - sources, externs = CrawlRootDepsTree(args.deps, [] if args.chunks else args.sources, args.externs) - compiler_args = ['--%s' % flag for flag in args.flags] - compiler_args += ['--externs=%s' % e for e in externs] - - if not args.chunks: - compiler_args += [ - '--js_output_file', - args.output, - ] - - compiler_args += [ - '--js', - ] - - if args.bootstrap: - compiler_args += [args.bootstrap] - - compiler_args += args.config - compiler_args += sources - - if args.chunks: - chunk_suffix = args.chunk_suffix - common_chunk_name = 'common' + chunk_suffix - compiler_args += [ - '--chunk_output_path_prefix {}'.format(args.output), - '--chunk {}:auto'.format(common_chunk_name) - ] - - for s in args.sources: - # '//path/to/target.js' becomes 'target' - chunk_name = '{}{}'.format(s.split('/')[-1].split('.')[0], chunk_suffix) - compiler_args += [ - '--chunk {}:1:{}: {}'.format(chunk_name, common_chunk_name, s) - ] - - if args.checks_only: - compiler_args += ['--checks-only'] - open(args.output, 'w').close() - - returncode, errors = compiler.Compiler().run_jar(args.compiler, compiler_args) - if returncode != 0: - print(args.compiler, ' '.join(compiler_args)) - print(errors) - - return returncode - - -if __name__ == '__main__': - sys.exit(main()) diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/js_library.py chromium-132.0.6834.159/third_party/closure_compiler/js_library.py --- chromium-132.0.6834.110/third_party/closure_compiler/js_library.py 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/js_library.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -# Copyright 2017 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -"""Generates a file describing the js_library to be used by js_binary action. - -This script takes in a list of sources and dependencies as described by a -js_library action. It creates a file listing the sources and dependencies -that can later be used by a js_binary action to compile the javascript. -""" - -from argparse import ArgumentParser - - -def main(): - parser = ArgumentParser() - parser.add_argument('-s', '--sources', nargs='*', default=[], - help='List of js source files') - parser.add_argument('-e', '--externs', nargs='*', default=[], - help='List of js source files') - parser.add_argument('-o', '--output', help='Write list to output') - parser.add_argument('-d', '--deps', nargs='*', default=[], - help='List of js_library dependencies') - args = parser.parse_args() - - with open(args.output, 'w') as out: - out.write('sources:\n') - for s in args.sources: - out.write('%s\n' % s) - out.write('deps:\n') - for d in args.deps: - out.write('%s\n' % d) - out.write('externs:\n') - for e in args.externs: - out.write('%s\n' % e) - -if __name__ == '__main__': - main() diff -Nru chromium-132.0.6834.110/third_party/closure_compiler/roll_closure_compiler chromium-132.0.6834.159/third_party/closure_compiler/roll_closure_compiler --- chromium-132.0.6834.110/third_party/closure_compiler/roll_closure_compiler 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/third_party/closure_compiler/roll_closure_compiler 1970-01-01 00:00:00.000000000 +0000 @@ -1,140 +0,0 @@ -#!/bin/bash -# Copyright 2014 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -# -# Download the newest version of Closure Compiler (pre-compiled), and put into -# Chrome source tree. Also download latest versions of various externs files. - -readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -readonly TEMP_DIR=$(mktemp -d) -readonly EXTERNS_NPM_DIR="node_modules/google-closure-compiler/contrib/externs" -readonly EXTERNS_DIR="${SCRIPT_DIR}/externs" -readonly README="${SCRIPT_DIR}/README.chromium" - -cleanup() { - rm -rf "${TEMP_DIR}" -} - -get_sha1() { - sha1sum "$1" | cut -d" " -f1 -} - -trap cleanup SIGINT SIGHUP SIGTERM - -old_chrome_sha1=$(get_sha1 "${EXTERNS_DIR}/chrome.js") -old_extensions_sha1=$(get_sha1 "${EXTERNS_DIR}/chrome_extensions.js") -old_polymer_sha1=$(get_sha1 "${EXTERNS_DIR}/polymer-1.0.js") -old_mocha_sha1=$(get_sha1 "${EXTERNS_DIR}/mocha-2.5.js") - -cd "${TEMP_DIR}" - -# Check if NPM is installed. -command -v npm >/dev/null 2>&1 || { - echo >&2 "NPM is required to run this script. Aborting."; - exit 1; -} - -echo "Downloading Closure Compiler latest..." -npm install --prefix . --no-bin-links --only=prod google-closure-compiler - -json_file=node_modules/google-closure-compiler-java/package.json -new_version=$(cat $json_file | grep version | cut -f2 -d ":" | tr -d '" ') -new_date="$(date --utc '+%Y/%m/%d %H:%M')" - -jar_file=node_modules/google-closure-compiler-java/compiler.jar -cp "${jar_file}" "${SCRIPT_DIR}/compiler/compiler.jar" - -readonly WARNING="$(cat < "${EXTERNS_DIR}/chrome.js" -(echo "${WARNING}" && cat ${EXTERNS_NPM_DIR}/chrome_extensions.js) > "${EXTERNS_DIR}/chrome_extensions.js" -(echo "${WARNING}" && cat ${EXTERNS_NPM_DIR}/polymer-1.0.js) > "${EXTERNS_DIR}/polymer-1.0.js" -(echo "${WARNING}" && cat ${EXTERNS_NPM_DIR}/mocha-2.5.js) > "${EXTERNS_DIR}/mocha-2.5.js" - -# Apply local Chromium patch. -cd "${SCRIPT_DIR}" -git apply chromium_patch.diff - -new_chrome_sha1=$(get_sha1 "${EXTERNS_DIR}/chrome.js") -if [[ "${new_chrome_sha1}" != "${old_chrome_sha1}" ]]; then - chrome_range="chrome.js: ${old_chrome_sha1} -> ${new_chrome_sha1}" -fi - -new_extensions_sha1=$(get_sha1 "${EXTERNS_DIR}/chrome_extensions.js") -if [[ "${new_extensions_sha1}" != "${old_extensions_sha1}" ]]; then - extensions_range="chrome_extensions.js: ${old_extensions_sha1} -> ${new_extensions_sha1}" -fi - -new_polymer_sha1=$(get_sha1 "${EXTERNS_DIR}/polymer-1.0.js") -if [[ "${new_polymer_sha1}" != "${old_polymer_sha1}" ]]; then - polymer_range="polymer-1.0.js: ${old_polymer_sha1} -> ${new_polymer_sha1}" -fi - -new_mocha_sha1=$(get_sha1 "${EXTERNS_DIR}/mocha-2.5.js") -if [[ "${new_mocha_sha1}" != "${old_mocha_sha1}" ]]; then - mocha_range="mocha-2.5.js: ${old_mocha_sha1} -> ${new_mocha_sha1}" -fi - -echo -echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" -echo "@" -echo "@ ROLL RESULTS:" -echo "@" -echo "@ closure-compiler-latest.zip version:" -echo "@ Old: ${old_version}" -echo "@ New: ${new_version}" -echo "@" -echo "@ externs/chrome.js SHA1:" -echo "@ Old: ${old_chrome_sha1}" -echo "@ New: ${new_chrome_sha1}" -echo "@" -echo "@ externs/chrome_extensions.js SHA1:" -echo "@ Old: ${old_extensions_sha1}" -echo "@ New: ${new_extensions_sha1}" -echo "@" -echo "@ externs/polymer-1.0.js SHA1:" -echo "@ Old: ${old_polymer_sha1}" -echo "@ New: ${new_polymer_sha1}" -echo "@" -echo "@ externs/mocha-2.5.js SHA1:" -echo "@ Old: ${old_mocha_sha1}" -echo "@ New: ${new_mocha_sha1}" -echo "@" -echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" -echo - -sed -i "s,^Date: .*,Date: ${new_date},; s,^Version: .*,Version: ${new_version}," "${README}" - -echo "git commit -a -m 'Roll closure compiler" -echo - -if [[ ! -z "${chrome_range}" ]]; then echo "${chrome_range}"; fi -if [[ ! -z "${extensions_range}" ]]; then echo "${extensions_range}"; fi -if [[ ! -z "${polymer_range}" ]]; then echo "${polymer_range}"; fi -if [[ ! -z "${mocha_range}" ]]; then echo "${mocha_range}"; fi -echo -echo "TBR=" -echo "BUG='" -echo -echo "git cl upload" - -cleanup diff -Nru chromium-132.0.6834.110/ui/accessibility/ax_tree.cc chromium-132.0.6834.159/ui/accessibility/ax_tree.cc --- chromium-132.0.6834.110/ui/accessibility/ax_tree.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ui/accessibility/ax_tree.cc 2025-01-27 17:37:37.000000000 +0000 @@ -1289,7 +1289,8 @@ if (!root_) { ACCESSIBILITY_TREE_UNSERIALIZE_ERROR_HISTOGRAM( AXTreeUnserializeError::kNoRoot); - RecordError(update_state, "Tree has no root.", true); + // TODO(b/368660753): make this fatal once root cause resolved. + RecordError(update_state, "Tree has no root.", /*is_fatal=*/false); return false; } diff -Nru chromium-132.0.6834.110/ui/accessibility/extensions/strings/accessibility_extensions_strings_iw.xtb chromium-132.0.6834.159/ui/accessibility/extensions/strings/accessibility_extensions_strings_iw.xtb --- chromium-132.0.6834.110/ui/accessibility/extensions/strings/accessibility_extensions_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ui/accessibility/extensions/strings/accessibility_extensions_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -19,7 +19,7 @@ ‏יש ללחוץ לחיצה ארוכה על ‎<span class='key'>‎Option</span>‎ כדי לעבור לפי מילים. תוסף זה מספק סמן הניתן להזזה בדף האינטרנט, כך שניתן לבחור טקסט באמצעות המקלדת. שלב 1: בוחרים את השורה המכילה את הכוכבים העמומים ביותר: -‏<p>כשמגיעים לקישור או לפקד, מתבצע מיקוד אוטומטי בהם. יש להקיש על ‎<span class='key'>Enter</span>‎ כדי ללחוץ על קישור או על לחצן. ‎</p> <p>‎כאשר פקד ממוקד (כגון תיבת טקסט או תיבת רשימה) לוכד מקשי חצים, יש להקיש על ‎<span class='key'>Esc</span>‎ ולאחר מכן על מקש החץ שמאלה או ימינה, כדי להמשיך דפדוף עם סמן. ‎</p> <p>‎לחלופין, אפשר להקיש על ‎<span class='key'>Tab</span>‎ כדי לעבור לפקד הבא הניתן למיקוד. ‎</p>‎ +‏<p>כשמגיעים לקישור או לפקד, מתבצע מיקוד אוטומטי בהם. יש ללחוץ על ‎<span class='key'>Enter</span>‎ כדי ללחוץ על קישור או על כפתור. ‎</p> <p>‎כאשר פקד ממוקד (כגון תיבת טקסט או תיבת רשימה) לוכד מקשי חצים, יש ללחוץ על ‎<span class='key'>Esc</span>‎ ולאחר מכן על מקש החץ שמאלה או ימינה, כדי להמשיך דפדוף עם סמן. ‎</p> <p>‎לחלופין, אפשר ללחוץ על ‎<span class='key'>Tab</span>‎ כדי לעבור לפקד הבא הניתן למיקוד. ‎</p>‎ הגדרות לא לזכור את ההתאמות האישיות של האתר הפעלה diff -Nru chromium-132.0.6834.110/ui/strings/translations/ax_strings_fa.xtb chromium-132.0.6834.159/ui/strings/translations/ax_strings_fa.xtb --- chromium-132.0.6834.110/ui/strings/translations/ax_strings_fa.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ui/strings/translations/ax_strings_fa.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -86,7 +86,7 @@ ضمیمه کد جلد -جابجایی برش نمایشگر تمام‌صفحه +جابه‌جایی برش نمایشگر تمام‌صفحه پانل برگه ویدیو جستجو diff -Nru chromium-132.0.6834.110/ui/strings/translations/ax_strings_iw.xtb chromium-132.0.6834.159/ui/strings/translations/ax_strings_iw.xtb --- chromium-132.0.6834.110/ui/strings/translations/ax_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ui/strings/translations/ax_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -2,7 +2,7 @@ פריט בתפריט -לחצן החלפה +כפתור החלפה שניות הצגת בוחר השבוע משלים @@ -47,7 +47,7 @@ אובייקט גרפי כותרת תחתונה אודיו -לחצן קופץ +כפתור קופץ פרטים קבוצת לחצני בחירה לחיצה @@ -120,7 +120,7 @@ הדגשה time תקציר -לחצן +כפתור אפשרויות נוספות כתב עילי מבוא @@ -130,7 +130,7 @@ תיבת חיפוש פועל שבוע -לחצן קביעת ערך +כפתור קביעת ערך מחוון עוצמת קול שנה תיבת רשימה @@ -171,7 +171,7 @@ הצעה המיקום הנוכחי הקדמה -לחצן קופץ של תפריט +כפתור קופץ של תפריט פרטי תוכן דגש כותרת הקטע @@ -204,7 +204,7 @@ הזמן שחלף: חלק סרגל כלים -לחצן בחירה +כפתור בחירה הקדשה שגיאת דפוס דקות @@ -219,7 +219,7 @@ פלט פרק main -לחצן קופץ של תיבת דו-שיח +כפתור קופץ של תיבת דו-שיח גוון לחצן החלפת פורמט חודש diff -Nru chromium-132.0.6834.110/ui/strings/translations/ui_strings_iw.xtb chromium-132.0.6834.159/ui/strings/translations/ui_strings_iw.xtb --- chromium-132.0.6834.110/ui/strings/translations/ui_strings_iw.xtb 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/ui/strings/translations/ui_strings_iw.xtb 2025-01-27 17:37:37.000000000 +0000 @@ -144,7 +144,7 @@ {HOURS,plural, =1{שעה אחת}one{# שעות}two{שעתיים}other{# שעות}} התוסף הוצמד סגירה -הלחצן המרכזי +הכפתור המרכזי רווח Del B/s @@ -215,7 +215,7 @@ בוצע {HOURS,plural, =1{שעה}one{# שע}two{# שע}other{# שע}} ברירת מחדל -לחצן 'הקודם' +כפתור 'הקודם' ההודעה נשלחת... פורמט: KB‏ diff -Nru chromium-132.0.6834.110/v8/include/v8-version.h chromium-132.0.6834.159/v8/include/v8-version.h --- chromium-132.0.6834.110/v8/include/v8-version.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/include/v8-version.h 2025-01-27 17:37:37.000000000 +0000 @@ -10,8 +10,8 @@ // system so their names cannot be changed without changing the scripts. #define V8_MAJOR_VERSION 13 #define V8_MINOR_VERSION 2 -#define V8_BUILD_NUMBER 1010152 -#define V8_PATCH_LEVEL 0 +#define V8_BUILD_NUMBER 152 +#define V8_PATCH_LEVEL 36 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff -Nru chromium-132.0.6834.110/v8/src/compiler/turboshaft/maglev-graph-building-phase.cc chromium-132.0.6834.159/v8/src/compiler/turboshaft/maglev-graph-building-phase.cc --- chromium-132.0.6834.110/v8/src/compiler/turboshaft/maglev-graph-building-phase.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/src/compiler/turboshaft/maglev-graph-building-phase.cc 2025-01-27 17:37:37.000000000 +0000 @@ -2412,7 +2412,14 @@ __ DeoptimizeIf(RootEqual(node->object_input(), RootIndex::kTheHoleValue), frame_state, DeoptimizeReason::kHole, node->eager_deopt_info()->feedback_to_update()); - SetMap(node, Map(node->object_input())); + return maglev::ProcessResult::kContinue; + } + maglev::ProcessResult Process(maglev::CheckHoleyFloat64NotHole* node, + const maglev::ProcessingState& state) { + GET_FRAME_STATE_MAYBE_ABORT(frame_state, node->eager_deopt_info()); + __ DeoptimizeIf(__ Float64IsHole(Map(node->float64_input())), frame_state, + DeoptimizeReason::kHole, + node->eager_deopt_info()->feedback_to_update()); return maglev::ProcessResult::kContinue; } maglev::ProcessResult Process(maglev::CheckInt32Condition* node, diff -Nru chromium-132.0.6834.110/v8/src/maglev/maglev-ir.cc chromium-132.0.6834.159/v8/src/maglev/maglev-ir.cc --- chromium-132.0.6834.110/v8/src/maglev/maglev-ir.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/src/maglev/maglev-ir.cc 2025-01-27 17:37:37.000000000 +0000 @@ -110,7 +110,7 @@ #define CASE(op) \ case Opcode::k##op: { \ DCHECK_EQ(old_input_count, StaticInputCount(static_cast(this))); \ - DCHECK_EQ(sizeof(op), old_sizeof); \ + DCHECK_LE(sizeof(op), old_sizeof); \ break; \ } NODE_BASE_LIST(CASE) @@ -3569,6 +3569,19 @@ DeoptimizeReason::kHole, this); } +void CheckHoleyFloat64NotHole::SetValueLocationConstraints() { + UseRegister(float64_input()); + set_temporaries_needed(1); +} +void CheckHoleyFloat64NotHole::GenerateCode(MaglevAssembler* masm, + const ProcessingState& state) { + MaglevAssembler::TemporaryRegisterScope temps(masm); + Register scratch = temps.AcquireScratch(); + __ JumpIfHoleNan(ToDoubleRegister(float64_input()), scratch, + __ GetDeoptLabel(this, DeoptimizeReason::kHole), + Label::kFar); +} + void ConvertHoleToUndefined::SetValueLocationConstraints() { UseRegister(object_input()); DefineSameAsFirst(this); diff -Nru chromium-132.0.6834.110/v8/src/maglev/maglev-ir.h chromium-132.0.6834.159/v8/src/maglev/maglev-ir.h --- chromium-132.0.6834.110/v8/src/maglev/maglev-ir.h 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/src/maglev/maglev-ir.h 2025-01-27 17:37:37.000000000 +0000 @@ -310,6 +310,7 @@ V(CheckMapsWithMigration) \ V(CheckDetectableCallable) \ V(CheckNotHole) \ + V(CheckHoleyFloat64NotHole) \ V(CheckNumber) \ V(CheckSmi) \ V(CheckString) \ @@ -598,7 +599,7 @@ V(Oddball, (1 << 6) | kAnyHeapObject | kNumberOrOddball) \ V(Boolean, (1 << 7) | kOddball | kNumberOrBoolean) \ V(Name, (1 << 8) | kAnyHeapObject) \ - V(StringOrStringWrapper, (1 << 9)) \ + V(StringOrStringWrapper, (1 << 9) | kAnyHeapObject) \ V(String, (1 << 10) | kName | kStringOrStringWrapper) \ V(InternalizedString, (1 << 11) | kString) \ V(Symbol, (1 << 12) | kName) \ @@ -9336,6 +9337,24 @@ void SetValueLocationConstraints(); void GenerateCode(MaglevAssembler*, const ProcessingState&); + void PrintParams(std::ostream&, MaglevGraphLabeller*) const {} +}; + +class CheckHoleyFloat64NotHole + : public FixedInputNodeT<1, CheckHoleyFloat64NotHole> { + using Base = FixedInputNodeT<1, CheckHoleyFloat64NotHole>; + + public: + explicit CheckHoleyFloat64NotHole(uint64_t bitfield) : Base(bitfield) {} + + static constexpr OpProperties kProperties = OpProperties::EagerDeopt(); + static constexpr + typename Base::InputTypes kInputTypes{ValueRepresentation::kHoleyFloat64}; + + Input& float64_input() { return input(0); } + + void SetValueLocationConstraints(); + void GenerateCode(MaglevAssembler*, const ProcessingState&); void PrintParams(std::ostream&, MaglevGraphLabeller*) const {} }; diff -Nru chromium-132.0.6834.110/v8/src/maglev/maglev-phi-representation-selector.cc chromium-132.0.6834.159/v8/src/maglev/maglev-phi-representation-selector.cc --- chromium-132.0.6834.110/v8/src/maglev/maglev-phi-representation-selector.cc 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/src/maglev/maglev-phi-representation-selector.cc 2025-01-27 17:37:37.000000000 +0000 @@ -788,13 +788,23 @@ ProcessResult MaglevPhiRepresentationSelector::UpdateNodePhiInput( CheckNumber* node, Phi* phi, int input_index, const ProcessingState* state) { - if (phi->value_representation() != ValueRepresentation::kTagged) { - // The phi was untagged, so we know that it's a number. We thus remove this - // CheckNumber from the graph. - return ProcessResult::kRemove; + switch (phi->value_representation()) { + case ValueRepresentation::kInt32: + case ValueRepresentation::kFloat64: + // The phi was untagged to a Int32 or Float64, so we know that it's a + // number. We thus remove this CheckNumber from the graph. + return ProcessResult::kRemove; + case ValueRepresentation::kHoleyFloat64: + // We need to check that the phi is not the hole nan. + node->OverwriteWith(); + return ProcessResult::kContinue; + case ValueRepresentation::kTagged: + // {phi} wasn't untagged, so we don't need to do anything. + return ProcessResult::kContinue; + case ValueRepresentation::kUint32: + case ValueRepresentation::kIntPtr: + UNREACHABLE(); } - return UpdateNodePhiInput(static_cast(node), phi, input_index, - state); } // If the input of a StoreTaggedFieldNoWriteBarrier was a Phi that got diff -Nru chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/meta.json chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/meta.json --- chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/meta.json 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/meta.json 2025-01-27 17:37:37.000000000 +0000 @@ -1 +1 @@ -{"build_link": "https://cr-buildbucket.appspot.com/build/8725122062311675713", "profile": ["x86", "x64", "x86-rl", "x64-rl"], "revision": "625e932f21c984db3f9fba8b56b9afa4e977994c", "version": "13.2.1010152.0"} \ No newline at end of file +{"build_link": "https://cr-buildbucket.appspot.com/build/8724574704671287793", "profile": ["x86", "x64", "x86-rl", "x64-rl"], "revision": "210ec27ca748c70580fe374f9811761667312b41", "version": "13.2.152.36"} \ No newline at end of file diff -Nru chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/x64-rl.profile chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x64-rl.profile --- chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/x64-rl.profile 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x64-rl.profile 2025-01-27 17:37:37.000000000 +0000 @@ -15,7 +15,10 @@ block_hint,RecordWriteIgnoreFP,5,4,1 block_hint,RecordWriteIgnoreFP,9,6,0 block_hint,RecordWriteIgnoreFP,8,7,0 -block_hint,RecordWriteIgnoreFP,13,25,0 +block_hint,RecordWriteIgnoreFP,14,17,0 +block_hint,RecordWriteIgnoreFP,19,18,1 +block_hint,RecordWriteIgnoreFP,23,20,0 +block_hint,RecordWriteIgnoreFP,22,21,0 block_hint,RecordWriteIgnoreFP,28,27,0 block_hint,RecordWriteIgnoreFP,57,47,0 block_hint,RecordWriteIgnoreFP,49,48,1 @@ -93,12 +96,10 @@ block_hint,CallWithSpread_Baseline,75,74,1 block_hint,CallWithSpread_Baseline,85,76,0 block_hint,CallWithSpread_Baseline,84,77,0 -block_hint,CallWithSpread_Baseline,83,78,1 block_hint,CallWithSpread_Baseline,96,88,0 block_hint,CallWithSpread_Baseline,89,94,1 block_hint,CallWithSpread_Baseline,91,90,1 block_hint,CallWithSpread_Baseline,93,92,1 -block_hint,CallWithSpread_Baseline,99,132,0 block_hint,CallWithArrayLike,1,75,1 block_hint,CallWithArrayLike,3,2,1 block_hint,CallWithArrayLike,4,34,1 @@ -640,6 +641,10 @@ block_hint,StoreFastElementIC_InBounds,275,281,0 block_hint,StoreFastElementIC_InBounds,286,283,0 block_hint,StoreFastElementIC_InBounds,285,284,1 +block_hint,StoreFastElementIC_InBounds,289,296,0 +block_hint,StoreFastElementIC_InBounds,299,305,0 +block_hint,StoreFastElementIC_InBounds,310,307,0 +block_hint,StoreFastElementIC_InBounds,309,308,1 block_hint,StoreFastElementIC_InBounds,313,320,0 block_hint,StoreFastElementIC_InBounds,323,329,0 block_hint,StoreFastElementIC_InBounds,334,331,0 @@ -1035,7 +1040,6 @@ block_hint,CloneFastJSArray,7,6,1 block_hint,CloneFastJSArray,12,11,0 block_hint,CloneFastJSArray,33,22,1 -block_hint,CloneFastJSArray,28,29,1 block_hint,CloneFastJSArray,58,39,0 block_hint,CloneFastJSArray,41,40,1 block_hint,CloneFastJSArray,43,42,1 @@ -1075,9 +1079,6 @@ block_hint,ExtractFastJSArray,11,10,1 block_hint,ExtractFastJSArray,16,15,0 block_hint,ExtractFastJSArray,37,26,1 -block_hint,ExtractFastJSArray,28,27,1 -block_hint,ExtractFastJSArray,32,33,1 -block_hint,ExtractFastJSArray,36,35,1 block_hint,ExtractFastJSArray,60,41,0 block_hint,ExtractFastJSArray,43,42,1 block_hint,ExtractFastJSArray,45,44,1 @@ -1540,7 +1541,6 @@ block_hint,StoreIC,7,8,0 block_hint,StoreIC,11,10,1 block_hint,StoreIC,13,12,0 -block_hint,StoreIC,16,17,1 block_hint,StoreIC,21,22,1 block_hint,StoreIC,27,28,1 block_hint,StoreIC,172,34,0 @@ -1601,7 +1601,6 @@ block_hint,StoreIC,380,379,0 block_hint,StoreIC_Megamorphic,1,2,1 block_hint,StoreIC_Megamorphic,5,4,0 -block_hint,StoreIC_Megamorphic,8,9,1 block_hint,StoreIC_Megamorphic,12,15,1 block_hint,StoreIC_Megamorphic,13,14,1 block_hint,StoreIC_Megamorphic,17,268,1 @@ -2037,9 +2036,6 @@ block_hint,BitwiseAndSmi_Baseline,23,22,0 block_hint,BitwiseAndSmi_Baseline,35,34,0 block_hint,BitwiseOr_Baseline,97,4,1 -block_hint,BitwiseOr_Baseline,17,5,0 -block_hint,BitwiseOr_Baseline,13,6,1 -block_hint,BitwiseOr_Baseline,15,16,1 block_hint,BitwiseOr_Baseline,95,94,1 block_hint,BitwiseOr_Baseline,100,99,0 block_hint,BitwiseOr_Baseline,119,102,1 @@ -2062,6 +2058,7 @@ block_hint,BitwiseXorSmi_Baseline,12,5,1 block_hint,BitwiseXorSmi_Baseline,14,15,1 block_hint,BitwiseXorSmi_Baseline,35,34,0 +block_hint,ShiftLeft_Baseline,2,1,0 block_hint,ShiftLeft_Baseline,46,45,0 block_hint,ShiftLeftSmi_Baseline,20,3,1 block_hint,ShiftLeftSmi_Baseline,34,33,0 @@ -2149,10 +2146,10 @@ block_hint,LessThan_Baseline,128,119,1 block_hint,LessThan_Baseline,144,143,1 block_hint,GreaterThan_Baseline,95,4,1 -block_hint,GreaterThan_Baseline,105,96,1 block_hint,GreaterThan_Baseline,101,97,0 block_hint,GreaterThan_Baseline,112,108,0 block_hint,GreaterThan_Baseline,118,129,0 +block_hint,GreaterThan_Baseline,128,119,1 block_hint,GreaterThan_Baseline,144,143,1 block_hint,LessThanOrEqual_Baseline,49,5,0 block_hint,LessThanOrEqual_Baseline,27,6,1 @@ -3413,10 +3410,7 @@ block_hint,ArraySome,62,65,1 block_hint,ArraySome,64,63,0 block_hint,ArraySome,68,77,0 -block_hint,ArraySome,79,94,1 block_hint,ArraySome,92,81,1 -block_hint,ArraySome,91,82,1 -block_hint,ArraySome,96,95,1 block_hint,ArrayPrototypeSplice,2,1,1 block_hint,ArrayPrototypeSplice,4,24,1 block_hint,ArrayPrototypeSplice,5,6,1 @@ -3472,9 +3466,6 @@ block_hint,ArrayPrototypeSplice,529,514,1 block_hint,ArrayPrototypeSplice,516,519,0 block_hint,ArrayPrototypeSplice,527,523,1 -block_hint,ArrayPrototypeSplice,545,544,0 -block_hint,ArrayPrototypeSplice,571,548,0 -block_hint,ArrayPrototypeSplice,560,549,0 block_hint,ArrayPrototypeSplice,566,567,1 block_hint,ArrayPrototypeSplice,599,602,0 block_hint,ArrayPrototypeSplice,605,604,1 @@ -3984,6 +3975,7 @@ block_hint,Equal,94,89,0 block_hint,Equal,93,90,0 block_hint,Equal,91,92,1 +block_hint,Equal,95,96,0 block_hint,Equal,104,103,0 block_hint,Equal,108,107,0 block_hint,StrictEqual,2,52,1 @@ -4947,17 +4939,10 @@ block_hint,MergeAt,68,73,1 block_hint,MergeAt,69,72,1 block_hint,MergeAt,71,70,0 -block_hint,MergeAt,82,79,0 -block_hint,MergeAt,80,81,0 block_hint,MergeAt,86,85,1 block_hint,MergeAt,88,115,1 block_hint,MergeAt,94,114,1 block_hint,MergeAt,95,113,1 -block_hint,MergeAt,112,96,0 -block_hint,MergeAt,97,111,1 -block_hint,MergeAt,105,110,1 -block_hint,MergeAt,106,109,1 -block_hint,MergeAt,107,108,1 block_hint,MergeAt,121,120,1 block_hint,MergeAt,123,122,1 block_hint,MergeAt,127,126,1 @@ -5177,9 +5162,6 @@ block_hint,StaCurrentScriptContextSlotHandler,4,99,1 block_hint,StaCurrentScriptContextSlotHandler,6,97,1 block_hint,StaCurrentScriptContextSlotHandler,8,7,1 -block_hint,StaCurrentScriptContextSlotHandler,91,10,0 -block_hint,StaCurrentScriptContextSlotHandler,12,11,1 -block_hint,StaCurrentScriptContextSlotHandler,14,13,0 block_hint,LdaLookupGlobalSlotHandler,2,237,1 block_hint,LdaLookupGlobalSlotHandler,4,3,1 block_hint,LdaLookupGlobalSlotHandler,5,8,1 @@ -5196,7 +5178,6 @@ block_hint,GetNamedPropertyHandler,23,20,0 block_hint,GetNamedPropertyHandler,22,21,1 block_hint,GetNamedPropertyHandler,26,83,0 -block_hint,GetNamedPropertyHandler,34,33,0 block_hint,GetNamedPropertyHandler,97,84,0 block_hint,GetNamedPropertyHandler,96,85,1 block_hint,GetNamedPropertyHandler,100,106,1 @@ -5309,6 +5290,7 @@ block_hint,ShiftLeftSmiHandler,24,3,1 block_hint,ShiftLeftSmiHandler,38,37,0 block_hint,ShiftLeftSmiHandler,51,48,0 +block_hint,ShiftRightSmiHandler,1,36,0 block_hint,ShiftRightSmiHandler,24,3,1 block_hint,ShiftRightSmiHandler,27,26,0 block_hint,ShiftRightSmiHandler,41,38,1 @@ -5335,12 +5317,6 @@ block_hint,FindNonDefaultConstructorOrConstructHandler,6,13,1 block_hint,FindNonDefaultConstructorOrConstructHandler,12,7,0 block_hint,CallAnyReceiverHandler,66,2,1 -block_hint,CallPropertyHandler,46,45,1 -block_hint,CallPropertyHandler,48,47,0 -block_hint,CallPropertyHandler,55,63,1 -block_hint,CallPropertyHandler,57,58,0 -block_hint,CallPropertyHandler,62,59,0 -block_hint,CallPropertyHandler,60,61,1 block_hint,CallProperty0Handler,38,5,0 block_hint,CallProperty0Handler,6,7,0 block_hint,CallProperty0Handler,26,8,0 @@ -5529,11 +5505,6 @@ block_hint,CreateRestParameterHandler,38,2,0 block_hint,CreateRestParameterHandler,4,3,1 block_hint,CreateRestParameterHandler,7,6,1 -block_hint,CreateRestParameterHandler,31,12,0 -block_hint,CreateRestParameterHandler,30,13,0 -block_hint,CreateRestParameterHandler,29,14,0 -block_hint,CreateRestParameterHandler,15,18,1 -block_hint,CreateRestParameterHandler,17,16,1 block_hint,CreateRestParameterHandler,27,23,0 block_hint,CreateRestParameterHandler,25,24,0 block_hint,JumpLoopHandler,10,7,1 @@ -5581,10 +5552,6 @@ block_hint,GetNamedPropertyWideHandler,305,1,0 block_hint,GetNamedPropertyWideHandler,2,3,1 block_hint,GetNamedPropertyWideHandler,108,18,0 -block_hint,GetNamedPropertyWideHandler,23,20,0 -block_hint,GetNamedPropertyWideHandler,22,21,1 -block_hint,GetNamedPropertyWideHandler,100,106,1 -block_hint,GetNamedPropertyWideHandler,103,102,0 block_hint,GetNamedPropertyWideHandler,259,249,0 block_hint,GetNamedPropertyWideHandler,302,301,0 block_hint,AddWideHandler,2,5,0 @@ -5626,6 +5593,7 @@ block_hint,IncWideHandler,20,19,0 block_hint,IncWideHandler,30,27,1 block_hint,CallProperty1WideHandler,1,67,0 +block_hint,CallUndefinedReceiverWideHandler,1,67,0 block_hint,CallUndefinedReceiver0WideHandler,1,67,0 block_hint,CallUndefinedReceiver1WideHandler,1,67,0 block_hint,ConstructWideHandler,1,46,0 @@ -5664,29 +5632,21 @@ block_hint,ForInNextWideHandler,7,4,1 block_hint,LdaGlobalExtraWideHandler,2,218,0 block_hint,MulSmiExtraWideHandler,48,47,1 -block_hint,DivSmiExtraWideHandler,27,1,0 -block_hint,DivSmiExtraWideHandler,15,2,0 -block_hint,DivSmiExtraWideHandler,4,3,0 -block_hint,DivSmiExtraWideHandler,9,8,0 -block_hint,DivSmiExtraWideHandler,13,14,0 -block_hint,DivSmiExtraWideHandler,25,22,1 -block_hint,DivSmiExtraWideHandler,48,45,1 block_hint,BitwiseOrSmiExtraWideHandler,1,36,0 block_hint,BitwiseOrSmiExtraWideHandler,41,38,1 block_hint,BitwiseAndSmiExtraWideHandler,24,3,1 block_hint,BitwiseAndSmiExtraWideHandler,27,26,0 block_hint,BitwiseAndSmiExtraWideHandler,41,38,1 block_hint,CallUndefinedReceiver1ExtraWideHandler,1,67,0 -builtin_count,RecordWriteSaveFP,2604 -builtin_count,RecordWriteIgnoreFP,35 +builtin_count,RecordWriteSaveFP,2605 +builtin_count,RecordWriteIgnoreFP,37 builtin_count,EphemeronKeyBarrierSaveFP,0 -builtin_count,IndirectPointerBarrierIgnoreFP,0 builtin_count,AdaptorWithBuiltinExitFrame0,104 builtin_count,AdaptorWithBuiltinExitFrame1,3 builtin_count,AdaptorWithBuiltinExitFrame2,0 builtin_count,AdaptorWithBuiltinExitFrame3,7 -builtin_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,142 -builtin_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,597 +builtin_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,141 +builtin_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,594 builtin_count,Call_ReceiverIsAny_Baseline_Compact,2 builtin_count,CallProxy,0 builtin_count,CallWithSpread,23 @@ -5700,9 +5660,9 @@ builtin_count,ConstructForwardAllArgs_WithFeedback,1 builtin_count,Construct_Baseline,54 builtin_count,Construct_WithFeedback,39 -builtin_count,FastNewObject,313 +builtin_count,FastNewObject,297 builtin_count,FastNewClosure,170 -builtin_count,StringEqual,665 +builtin_count,StringEqual,666 builtin_count,StringGreaterThan,0 builtin_count,StringGreaterThanOrEqual,4 builtin_count,StringLessThan,421 @@ -5722,23 +5682,23 @@ builtin_count,GrowFastSmiOrObjectElements,308 builtin_count,ToNumber,0 builtin_count,ToNumber_Baseline,0 -builtin_count,ToNumeric_Baseline,29 +builtin_count,ToNumeric_Baseline,27 builtin_count,ToNumberConvertBigInt,2 builtin_count,Typeof,27 builtin_count,Typeof_Baseline,1 builtin_count,KeyedLoadIC_PolymorphicName,1 -builtin_count,KeyedStoreIC_Megamorphic,302 +builtin_count,KeyedStoreIC_Megamorphic,365 builtin_count,DefineKeyedOwnIC_Megamorphic,2 builtin_count,LoadGlobalIC_NoFeedback,14 builtin_count,LoadIC_FunctionPrototype,181 -builtin_count,LoadIC_StringLength,39 +builtin_count,LoadIC_StringLength,38 builtin_count,LoadIC_StringWrapperLength,0 builtin_count,LoadIC_NoFeedback,39 builtin_count,StoreIC_NoFeedback,5 builtin_count,DefineNamedOwnIC_NoFeedback,3 builtin_count,KeyedLoadIC_SloppyArguments,1 -builtin_count,StoreFastElementIC_InBounds,184 -builtin_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,20 +builtin_count,StoreFastElementIC_InBounds,181 +builtin_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,19 builtin_count,StoreFastElementIC_NoTransitionHandleCOW,0 builtin_count,ElementsTransitionAndStore_InBounds,0 builtin_count,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,0 @@ -5751,7 +5711,7 @@ builtin_count,SetDataProperties,1 builtin_count,ReturnReceiver,7 builtin_count,ArrayConstructor,2 -builtin_count,ArrayConstructorImpl,218 +builtin_count,ArrayConstructorImpl,217 builtin_count,ArrayNoArgumentConstructor_PackedSmi_DontOverride,0 builtin_count,ArrayNoArgumentConstructor_HoleySmi_DontOverride,0 builtin_count,ArrayNoArgumentConstructor_PackedSmi_DisableAllocationSites,0 @@ -5759,7 +5719,7 @@ builtin_count,ArrayNoArgumentConstructor_Holey_DisableAllocationSites,0 builtin_count,ArrayNoArgumentConstructor_PackedDouble_DisableAllocationSites,0 builtin_count,ArraySingleArgumentConstructor_HoleySmi_DontOverride,0 -builtin_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,98 +builtin_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,97 builtin_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,2 builtin_count,ArraySingleArgumentConstructor_HoleyDouble_DisableAllocationSites,1 builtin_count,ArrayIncludesSmi,0 @@ -5767,9 +5727,9 @@ builtin_count,ArrayIncludes,2 builtin_count,ArrayIndexOfSmi,0 builtin_count,ArrayIndexOfSmiOrObject,125 -builtin_count,ArrayIndexOf,29 +builtin_count,ArrayIndexOf,28 builtin_count,ArrayPrototypePop,5 -builtin_count,ArrayPrototypePush,285 +builtin_count,ArrayPrototypePush,284 builtin_count,CloneFastJSArray,170 builtin_count,CloneFastJSArrayFillingHoles,36 builtin_count,ExtractFastJSArray,179 @@ -5779,8 +5739,8 @@ builtin_count,CreateObjectFromSlowBoilerplateHelper,44 builtin_count,ArrayPrototypeEntries,0 builtin_count,ArrayPrototypeKeys,0 -builtin_count,ArrayPrototypeValues,18 -builtin_count,ArrayIteratorPrototypeNext,91 +builtin_count,ArrayPrototypeValues,17 +builtin_count,ArrayIteratorPrototypeNext,90 builtin_count,AsyncFunctionEnter,0 builtin_count,AsyncFunctionResolve,0 builtin_count,AsyncFunctionAwait,4 @@ -5805,42 +5765,42 @@ builtin_count,CallIteratorWithFeedbackLazyDeoptContinuation,0 builtin_count,GlobalIsFinite,0 builtin_count,GlobalIsNaN,0 -builtin_count,LoadIC,2817 -builtin_count,LoadIC_Megamorphic,8810 +builtin_count,LoadIC,2808 +builtin_count,LoadIC_Megamorphic,8808 builtin_count,LoadIC_Noninlined,2 -builtin_count,LoadICTrampoline,267 -builtin_count,LoadICBaseline,2260 -builtin_count,LoadICTrampoline_Megamorphic,5080 +builtin_count,LoadICTrampoline,273 +builtin_count,LoadICBaseline,2252 +builtin_count,LoadICTrampoline_Megamorphic,5532 builtin_count,LoadSuperIC,2 builtin_count,LoadSuperICBaseline,2 -builtin_count,KeyedLoadIC,336 +builtin_count,KeyedLoadIC,330 builtin_count,EnumeratedKeyedLoadIC,4 builtin_count,KeyedLoadIC_Megamorphic,2107 builtin_count,KeyedLoadICTrampoline,1 -builtin_count,KeyedLoadICBaseline,315 +builtin_count,KeyedLoadICBaseline,310 builtin_count,EnumeratedKeyedLoadICBaseline,2 -builtin_count,KeyedLoadICTrampoline_Megamorphic,722 -builtin_count,StoreGlobalIC,334 -builtin_count,StoreGlobalICTrampoline,0 +builtin_count,KeyedLoadICTrampoline_Megamorphic,720 +builtin_count,StoreGlobalIC,528 +builtin_count,StoreGlobalICTrampoline,194 builtin_count,StoreGlobalICBaseline,1 builtin_count,StoreIC,333 builtin_count,StoreIC_Megamorphic,1211 builtin_count,StoreICTrampoline,24 builtin_count,StoreICTrampoline_Megamorphic,573 -builtin_count,StoreICBaseline,278 -builtin_count,DefineNamedOwnIC,40 -builtin_count,DefineNamedOwnICBaseline,35 -builtin_count,KeyedStoreIC,199 +builtin_count,StoreICBaseline,277 +builtin_count,DefineNamedOwnIC,41 +builtin_count,DefineNamedOwnICBaseline,36 +builtin_count,KeyedStoreIC,194 builtin_count,KeyedStoreICTrampoline,0 -builtin_count,KeyedStoreICTrampoline_Megamorphic,223 -builtin_count,KeyedStoreICBaseline,186 +builtin_count,KeyedStoreICTrampoline_Megamorphic,285 +builtin_count,KeyedStoreICBaseline,182 builtin_count,DefineKeyedOwnIC,2 -builtin_count,StoreInArrayLiteralIC,19 -builtin_count,StoreInArrayLiteralICBaseline,17 -builtin_count,LoadGlobalIC,1086 +builtin_count,StoreInArrayLiteralIC,20 +builtin_count,StoreInArrayLiteralICBaseline,18 +builtin_count,LoadGlobalIC,1078 builtin_count,LoadGlobalICInsideTypeof,0 -builtin_count,LoadGlobalICTrampoline,661 -builtin_count,LoadGlobalICBaseline,367 +builtin_count,LoadGlobalICTrampoline,663 +builtin_count,LoadGlobalICBaseline,365 builtin_count,LoadGlobalICInsideTypeofBaseline,0 builtin_count,LookupGlobalICTrampoline,2 builtin_count,LookupGlobalICBaseline,1 @@ -5852,11 +5812,11 @@ builtin_count,IterableToListWithSymbolLookup,0 builtin_count,IterableToListMayPreserveHoles,0 builtin_count,IterableToListConvertHoles,35 -builtin_count,FindOrderedHashMapEntry,347 +builtin_count,FindOrderedHashMapEntry,344 builtin_count,MapConstructor,67 builtin_count,MapPrototypeSet,58 builtin_count,MapPrototypeDelete,0 -builtin_count,MapPrototypeGet,21 +builtin_count,MapPrototypeGet,18 builtin_count,MapPrototypeHas,2 builtin_count,MapPrototypeEntries,0 builtin_count,MapPrototypeGetSize,0 @@ -5865,27 +5825,27 @@ builtin_count,MapPrototypeValues,0 builtin_count,MapIteratorPrototypeNext,11 builtin_count,MapIteratorToList,0 -builtin_count,Add_Baseline,199 -builtin_count,AddSmi_Baseline,217 -builtin_count,Subtract_Baseline,64 -builtin_count,SubtractSmi_Baseline,21 -builtin_count,Multiply_Baseline,84 -builtin_count,MultiplySmi_Baseline,6 +builtin_count,Add_Baseline,205 +builtin_count,AddSmi_Baseline,218 +builtin_count,Subtract_Baseline,63 +builtin_count,SubtractSmi_Baseline,20 +builtin_count,Multiply_Baseline,92 +builtin_count,MultiplySmi_Baseline,5 builtin_count,Divide_Baseline,6 -builtin_count,DivideSmi_Baseline,2 +builtin_count,DivideSmi_Baseline,1 builtin_count,Modulus_Baseline,1 builtin_count,ModulusSmi_Baseline,1 builtin_count,Exponentiate_Baseline,0 builtin_count,BitwiseAnd_Baseline,11 -builtin_count,BitwiseAndSmi_Baseline,30 -builtin_count,BitwiseOr_Baseline,22 -builtin_count,BitwiseOrSmi_Baseline,161 -builtin_count,BitwiseXor_Baseline,9 +builtin_count,BitwiseAndSmi_Baseline,31 +builtin_count,BitwiseOr_Baseline,23 +builtin_count,BitwiseOrSmi_Baseline,160 +builtin_count,BitwiseXor_Baseline,8 builtin_count,BitwiseXorSmi_Baseline,0 builtin_count,ShiftLeft_Baseline,1 builtin_count,ShiftLeftSmi_Baseline,28 builtin_count,ShiftRight_Baseline,1 -builtin_count,ShiftRightSmi_Baseline,102 +builtin_count,ShiftRightSmi_Baseline,103 builtin_count,ShiftRightLogical_Baseline,0 builtin_count,ShiftRightLogicalSmi_Baseline,3 builtin_count,Add_WithFeedback,39 @@ -5894,19 +5854,19 @@ builtin_count,Modulus_WithFeedback,0 builtin_count,BitwiseOr_WithFeedback,0 builtin_count,Equal_Baseline,156 -builtin_count,StrictEqual_Baseline,218 -builtin_count,LessThan_Baseline,155 -builtin_count,GreaterThan_Baseline,46 +builtin_count,StrictEqual_Baseline,226 +builtin_count,LessThan_Baseline,148 +builtin_count,GreaterThan_Baseline,44 builtin_count,LessThanOrEqual_Baseline,22 -builtin_count,GreaterThanOrEqual_Baseline,44 +builtin_count,GreaterThanOrEqual_Baseline,43 builtin_count,Equal_WithFeedback,13 -builtin_count,StrictEqual_WithFeedback,100 +builtin_count,StrictEqual_WithFeedback,99 builtin_count,LessThan_WithFeedback,2 builtin_count,GreaterThan_WithFeedback,1 builtin_count,GreaterThanOrEqual_WithFeedback,0 builtin_count,BitwiseNot_Baseline,1 builtin_count,Decrement_Baseline,16 -builtin_count,Increment_Baseline,106 +builtin_count,Increment_Baseline,103 builtin_count,Negate_Baseline,6 builtin_count,ObjectAssign,1 builtin_count,ObjectCreate,6 @@ -5917,10 +5877,10 @@ builtin_count,ObjectKeys,13 builtin_count,ObjectPrototypeHasOwnProperty,212 builtin_count,ObjectToString,55 -builtin_count,OrdinaryHasInstance,84 +builtin_count,OrdinaryHasInstance,85 builtin_count,InstanceOf,6 builtin_count,InstanceOf_WithFeedback,3 -builtin_count,InstanceOf_Baseline,42 +builtin_count,InstanceOf_Baseline,41 builtin_count,ForInEnumerate,52 builtin_count,ForInPrepare,4 builtin_count,ForInFilter,194 @@ -5938,12 +5898,12 @@ builtin_count,SetPrototypeValues,5 builtin_count,SetIteratorPrototypeNext,44 builtin_count,SetOrSetIteratorToList,0 -builtin_count,StringFromCharCode,14 +builtin_count,StringFromCharCode,15 builtin_count,StringPrototypeReplace,215 builtin_count,StringPrototypeSplit,47 builtin_count,TypedArrayConstructor,2 builtin_count,TypedArrayPrototypeByteLength,0 -builtin_count,TypedArrayPrototypeLength,37 +builtin_count,TypedArrayPrototypeLength,32 builtin_count,TypedArrayPrototypeToStringTag,0 builtin_count,WasmToJsWrapperCSA,0 builtin_count,WeakMapConstructor,0 @@ -6010,14 +5970,14 @@ builtin_count,ToString,64 builtin_count,StringPrototypeToString,16 builtin_count,StringPrototypeCharAt,113 -builtin_count,StringPrototypeCharCodeAt,63 +builtin_count,StringPrototypeCharCodeAt,61 builtin_count,StringPrototypeCodePointAt,0 builtin_count,StringPrototypeConcat,0 builtin_count,StringConstructor,28 builtin_count,StringAddConvertLeft,15 builtin_count,StringAddConvertRight,179 builtin_count,StringCharAt,8 -builtin_count,FastNewClosureBaseline,31 +builtin_count,FastNewClosureBaseline,32 builtin_count,FastNewFunctionContextFunction,60 builtin_count,CreateRegExpLiteral,10 builtin_count,CreateShallowArrayLiteral,9 @@ -6030,7 +5990,7 @@ builtin_count,NonNumberToNumber,4 builtin_count,NonNumberToNumeric,885 builtin_count,ToNumeric,14 -builtin_count,NumberToString,1322 +builtin_count,NumberToString,1321 builtin_count,ToBoolean,19 builtin_count,ToBooleanForBaselineJump,480 builtin_count,ToLength,2 @@ -6051,7 +6011,7 @@ builtin_count,ForInNext,31 builtin_count,GetIteratorWithFeedback,0 builtin_count,GetIteratorBaseline,13 -builtin_count,CallIteratorWithFeedback,14 +builtin_count,CallIteratorWithFeedback,13 builtin_count,MathAbs,0 builtin_count,MathCeil,0 builtin_count,MathFloor,0 @@ -6077,7 +6037,7 @@ builtin_count,NumberIsNaN,0 builtin_count,NumberParseFloat,10 builtin_count,ParseInt,118 -builtin_count,NumberParseInt,7 +builtin_count,NumberParseInt,6 builtin_count,Add,43 builtin_count,Subtract,0 builtin_count,Multiply,0 @@ -6123,7 +6083,7 @@ builtin_count,RegExpSearchFast,1 builtin_count,RegExpPrototypeSourceGetter,0 builtin_count,RegExpSplit,12 -builtin_count,RegExpPrototypeTest,100 +builtin_count,RegExpPrototypeTest,101 builtin_count,RegExpPrototypeTestFast,377 builtin_count,RegExpPrototypeGlobalGetter,0 builtin_count,RegExpPrototypeIgnoreCaseGetter,0 @@ -6144,7 +6104,7 @@ builtin_count,StringRepeat,0 builtin_count,StringPrototypeSlice,20 builtin_count,StringPrototypeStartsWith,0 -builtin_count,StringPrototypeSubstr,1 +builtin_count,StringPrototypeSubstr,2 builtin_count,StringPrototypeSubstring,3 builtin_count,StringPrototypeTrim,1 builtin_count,SymbolPrototypeToString,2 @@ -6156,7 +6116,7 @@ builtin_count,NewStrictArgumentsElements,3 builtin_count,NewRestArgumentsElements,14 builtin_count,FastNewSloppyArguments,1 -builtin_count,FastNewStrictArguments,1 +builtin_count,FastNewStrictArguments,2 builtin_count,FastNewRestArguments,0 builtin_count,StoreCurrentScriptContextSlotBaseline,0 builtin_count,StoreScriptContextSlotBaseline,0 @@ -6188,11 +6148,11 @@ builtin_count,CanUseSameAccessor_FastObjectElements_0,33 builtin_count,StringPrototypeToLowerCaseIntl,3 builtin_count,StringToLowerCaseIntl,129 -builtin_count,WideHandler,55 +builtin_count,WideHandler,54 builtin_count,ExtraWideHandler,9 -builtin_count,LdarHandler,76 -builtin_count,LdaZeroHandler,9 -builtin_count,LdaSmiHandler,11 +builtin_count,LdarHandler,74 +builtin_count,LdaZeroHandler,10 +builtin_count,LdaSmiHandler,10 builtin_count,LdaUndefinedHandler,7 builtin_count,LdaNullHandler,1 builtin_count,LdaTheHoleHandler,0 @@ -6201,10 +6161,10 @@ builtin_count,LdaConstantHandler,12 builtin_count,LdaContextSlotHandler,0 builtin_count,LdaImmutableContextSlotHandler,6 -builtin_count,LdaCurrentContextSlotHandler,6 +builtin_count,LdaCurrentContextSlotHandler,5 builtin_count,LdaImmutableCurrentContextSlotHandler,17 -builtin_count,StarHandler,18 -builtin_count,MovHandler,17 +builtin_count,StarHandler,17 +builtin_count,MovHandler,16 builtin_count,PushContextHandler,1 builtin_count,PopContextHandler,0 builtin_count,TestReferenceEqualHandler,0 @@ -6212,7 +6172,7 @@ builtin_count,TestNullHandler,0 builtin_count,TestUndefinedHandler,0 builtin_count,TestTypeOfHandler,0 -builtin_count,LdaGlobalHandler,22 +builtin_count,LdaGlobalHandler,20 builtin_count,LdaGlobalInsideTypeofHandler,0 builtin_count,StaGlobalHandler,0 builtin_count,StaContextSlotHandler,0 @@ -6222,17 +6182,17 @@ builtin_count,LdaLookupGlobalSlotHandler,0 builtin_count,LdaLookupGlobalSlotInsideTypeofHandler,0 builtin_count,StaLookupSlotHandler,0 -builtin_count,GetNamedPropertyHandler,67 +builtin_count,GetNamedPropertyHandler,65 builtin_count,GetNamedPropertyFromSuperHandler,0 -builtin_count,GetKeyedPropertyHandler,18 +builtin_count,GetKeyedPropertyHandler,17 builtin_count,GetEnumeratedKeyedPropertyHandler,1 -builtin_count,SetNamedPropertyHandler,9 +builtin_count,SetNamedPropertyHandler,10 builtin_count,DefineNamedOwnPropertyHandler,2 -builtin_count,SetKeyedPropertyHandler,11 +builtin_count,SetKeyedPropertyHandler,10 builtin_count,DefineKeyedOwnPropertyHandler,0 builtin_count,StaInArrayLiteralHandler,1 builtin_count,DefineKeyedOwnPropertyInLiteralHandler,0 -builtin_count,AddHandler,10 +builtin_count,AddHandler,9 builtin_count,SubHandler,1 builtin_count,MulHandler,4 builtin_count,DivHandler,0 @@ -6244,7 +6204,7 @@ builtin_count,ShiftLeftHandler,0 builtin_count,ShiftRightHandler,0 builtin_count,ShiftRightLogicalHandler,0 -builtin_count,AddSmiHandler,5 +builtin_count,AddSmiHandler,4 builtin_count,SubSmiHandler,1 builtin_count,MulSmiHandler,1 builtin_count,DivSmiHandler,0 @@ -6255,7 +6215,7 @@ builtin_count,ShiftLeftSmiHandler,1 builtin_count,ShiftRightSmiHandler,2 builtin_count,ShiftRightLogicalSmiHandler,0 -builtin_count,IncHandler,11 +builtin_count,IncHandler,10 builtin_count,DecHandler,2 builtin_count,NegateHandler,0 builtin_count,BitwiseNotHandler,0 @@ -6266,7 +6226,7 @@ builtin_count,DeletePropertySloppyHandler,0 builtin_count,FindNonDefaultConstructorOrConstructHandler,0 builtin_count,CallAnyReceiverHandler,0 -builtin_count,CallPropertyHandler,2 +builtin_count,CallPropertyHandler,1 builtin_count,CallProperty0Handler,4 builtin_count,CallProperty1Handler,11 builtin_count,CallProperty2Handler,3 @@ -6283,7 +6243,7 @@ builtin_count,ConstructForwardAllArgsHandler,0 builtin_count,TestEqualHandler,4 builtin_count,TestEqualStrictHandler,6 -builtin_count,TestLessThanHandler,10 +builtin_count,TestLessThanHandler,9 builtin_count,TestGreaterThanHandler,2 builtin_count,TestLessThanOrEqualHandler,0 builtin_count,TestGreaterThanOrEqualHandler,1 @@ -6309,7 +6269,7 @@ builtin_count,CreateUnmappedArgumentsHandler,0 builtin_count,CreateRestParameterHandler,0 builtin_count,JumpLoopHandler,12 -builtin_count,JumpHandler,4 +builtin_count,JumpHandler,3 builtin_count,JumpConstantHandler,0 builtin_count,JumpIfUndefinedConstantHandler,0 builtin_count,JumpIfNotUndefinedConstantHandler,0 @@ -6322,7 +6282,7 @@ builtin_count,JumpIfToBooleanTrueHandler,5 builtin_count,JumpIfToBooleanFalseHandler,10 builtin_count,JumpIfTrueHandler,5 -builtin_count,JumpIfFalseHandler,21 +builtin_count,JumpIfFalseHandler,20 builtin_count,JumpIfNullHandler,0 builtin_count,JumpIfNotNullHandler,0 builtin_count,JumpIfUndefinedHandler,1 @@ -6338,7 +6298,7 @@ builtin_count,SetPendingMessageHandler,0 builtin_count,ThrowHandler,2 builtin_count,ReThrowHandler,0 -builtin_count,ReturnHandler,18 +builtin_count,ReturnHandler,17 builtin_count,ThrowReferenceErrorIfHoleHandler,1 builtin_count,ThrowSuperNotCalledIfHoleHandler,0 builtin_count,ThrowSuperAlreadyCalledIfNotHoleHandler,0 @@ -6347,7 +6307,7 @@ builtin_count,SuspendGeneratorHandler,0 builtin_count,ResumeGeneratorHandler,0 builtin_count,GetIteratorHandler,0 -builtin_count,ShortStarHandler,48 +builtin_count,ShortStarHandler,47 builtin_count,LdarWideHandler,0 builtin_count,LdaSmiWideHandler,6 builtin_count,LdaConstantWideHandler,1 @@ -6445,34 +6405,34 @@ builtin_count,CallUndefinedReceiverExtraWideHandler,0 builtin_count,CallUndefinedReceiver1ExtraWideHandler,4 builtin_count,CallUndefinedReceiver2ExtraWideHandler,0 -block_count,RecordWriteSaveFP,0,2604 -block_count,RecordWriteSaveFP,1,2589 +block_count,RecordWriteSaveFP,0,2605 +block_count,RecordWriteSaveFP,1,2571 block_count,RecordWriteSaveFP,2,0 -block_count,RecordWriteSaveFP,3,2589 +block_count,RecordWriteSaveFP,3,2571 block_count,RecordWriteSaveFP,4,0 -block_count,RecordWriteSaveFP,5,2589 -block_count,RecordWriteSaveFP,6,2589 -block_count,RecordWriteSaveFP,7,2587 +block_count,RecordWriteSaveFP,5,2571 +block_count,RecordWriteSaveFP,6,2570 +block_count,RecordWriteSaveFP,7,2568 block_count,RecordWriteSaveFP,8,2 block_count,RecordWriteSaveFP,9,0 block_count,RecordWriteSaveFP,10,2 -block_count,RecordWriteSaveFP,11,2589 -block_count,RecordWriteSaveFP,12,14 -block_count,RecordWriteSaveFP,13,3 -block_count,RecordWriteSaveFP,14,2 -block_count,RecordWriteSaveFP,15,2 +block_count,RecordWriteSaveFP,11,2571 +block_count,RecordWriteSaveFP,12,33 +block_count,RecordWriteSaveFP,13,20 +block_count,RecordWriteSaveFP,14,16 +block_count,RecordWriteSaveFP,15,16 block_count,RecordWriteSaveFP,16,0 -block_count,RecordWriteSaveFP,17,0 +block_count,RecordWriteSaveFP,17,3 block_count,RecordWriteSaveFP,18,0 -block_count,RecordWriteSaveFP,19,0 -block_count,RecordWriteSaveFP,20,0 -block_count,RecordWriteSaveFP,21,0 +block_count,RecordWriteSaveFP,19,3 +block_count,RecordWriteSaveFP,20,3 +block_count,RecordWriteSaveFP,21,3 block_count,RecordWriteSaveFP,22,0 block_count,RecordWriteSaveFP,23,0 block_count,RecordWriteSaveFP,24,0 -block_count,RecordWriteSaveFP,25,10 -block_count,RecordWriteSaveFP,26,14 -block_count,RecordWriteSaveFP,27,14 +block_count,RecordWriteSaveFP,25,13 +block_count,RecordWriteSaveFP,26,33 +block_count,RecordWriteSaveFP,27,33 block_count,RecordWriteSaveFP,28,0 block_count,RecordWriteSaveFP,29,0 block_count,RecordWriteSaveFP,30,0 @@ -6491,17 +6451,17 @@ block_count,RecordWriteSaveFP,43,0 block_count,RecordWriteSaveFP,44,0 block_count,RecordWriteSaveFP,45,0 -block_count,RecordWriteSaveFP,46,14 -block_count,RecordWriteSaveFP,47,14 +block_count,RecordWriteSaveFP,46,33 +block_count,RecordWriteSaveFP,47,33 block_count,RecordWriteSaveFP,48,0 -block_count,RecordWriteSaveFP,49,14 -block_count,RecordWriteSaveFP,50,11 -block_count,RecordWriteSaveFP,51,11 +block_count,RecordWriteSaveFP,49,33 +block_count,RecordWriteSaveFP,50,28 +block_count,RecordWriteSaveFP,51,28 block_count,RecordWriteSaveFP,52,0 block_count,RecordWriteSaveFP,53,0 block_count,RecordWriteSaveFP,54,0 -block_count,RecordWriteSaveFP,55,2 -block_count,RecordWriteSaveFP,56,2 +block_count,RecordWriteSaveFP,55,5 +block_count,RecordWriteSaveFP,56,5 block_count,RecordWriteSaveFP,57,0 block_count,RecordWriteSaveFP,58,0 block_count,RecordWriteSaveFP,59,0 @@ -6509,33 +6469,33 @@ block_count,RecordWriteSaveFP,61,0 block_count,RecordWriteSaveFP,62,0 block_count,RecordWriteSaveFP,63,0 -block_count,RecordWriteSaveFP,64,14 -block_count,RecordWriteIgnoreFP,0,35 -block_count,RecordWriteIgnoreFP,1,33 +block_count,RecordWriteSaveFP,64,33 +block_count,RecordWriteIgnoreFP,0,37 +block_count,RecordWriteIgnoreFP,1,35 block_count,RecordWriteIgnoreFP,2,0 -block_count,RecordWriteIgnoreFP,3,33 +block_count,RecordWriteIgnoreFP,3,35 block_count,RecordWriteIgnoreFP,4,0 -block_count,RecordWriteIgnoreFP,5,33 -block_count,RecordWriteIgnoreFP,6,33 -block_count,RecordWriteIgnoreFP,7,33 +block_count,RecordWriteIgnoreFP,5,35 +block_count,RecordWriteIgnoreFP,6,35 +block_count,RecordWriteIgnoreFP,7,34 block_count,RecordWriteIgnoreFP,8,0 block_count,RecordWriteIgnoreFP,9,0 block_count,RecordWriteIgnoreFP,10,0 -block_count,RecordWriteIgnoreFP,11,33 +block_count,RecordWriteIgnoreFP,11,35 block_count,RecordWriteIgnoreFP,12,1 -block_count,RecordWriteIgnoreFP,13,0 +block_count,RecordWriteIgnoreFP,13,1 block_count,RecordWriteIgnoreFP,14,0 block_count,RecordWriteIgnoreFP,15,0 block_count,RecordWriteIgnoreFP,16,0 -block_count,RecordWriteIgnoreFP,17,0 +block_count,RecordWriteIgnoreFP,17,1 block_count,RecordWriteIgnoreFP,18,0 -block_count,RecordWriteIgnoreFP,19,0 -block_count,RecordWriteIgnoreFP,20,0 -block_count,RecordWriteIgnoreFP,21,0 +block_count,RecordWriteIgnoreFP,19,1 +block_count,RecordWriteIgnoreFP,20,1 +block_count,RecordWriteIgnoreFP,21,1 block_count,RecordWriteIgnoreFP,22,0 block_count,RecordWriteIgnoreFP,23,0 block_count,RecordWriteIgnoreFP,24,0 -block_count,RecordWriteIgnoreFP,25,1 +block_count,RecordWriteIgnoreFP,25,0 block_count,RecordWriteIgnoreFP,26,1 block_count,RecordWriteIgnoreFP,27,1 block_count,RecordWriteIgnoreFP,28,0 @@ -6560,13 +6520,13 @@ block_count,RecordWriteIgnoreFP,47,1 block_count,RecordWriteIgnoreFP,48,0 block_count,RecordWriteIgnoreFP,49,1 -block_count,RecordWriteIgnoreFP,50,1 -block_count,RecordWriteIgnoreFP,51,1 +block_count,RecordWriteIgnoreFP,50,0 +block_count,RecordWriteIgnoreFP,51,0 block_count,RecordWriteIgnoreFP,52,0 block_count,RecordWriteIgnoreFP,53,0 block_count,RecordWriteIgnoreFP,54,0 -block_count,RecordWriteIgnoreFP,55,0 -block_count,RecordWriteIgnoreFP,56,0 +block_count,RecordWriteIgnoreFP,55,1 +block_count,RecordWriteIgnoreFP,56,1 block_count,RecordWriteIgnoreFP,57,0 block_count,RecordWriteIgnoreFP,58,0 block_count,RecordWriteIgnoreFP,59,0 @@ -6576,7 +6536,6 @@ block_count,RecordWriteIgnoreFP,63,0 block_count,RecordWriteIgnoreFP,64,1 block_count,EphemeronKeyBarrierSaveFP,0,0 -block_count,IndirectPointerBarrierIgnoreFP,0,0 block_count,AdaptorWithBuiltinExitFrame0,0,104 block_count,AdaptorWithBuiltinExitFrame1,0,3 block_count,AdaptorWithBuiltinExitFrame1,1,0 @@ -6590,16 +6549,16 @@ block_count,AdaptorWithBuiltinExitFrame3,1,6 block_count,AdaptorWithBuiltinExitFrame3,2,1 block_count,AdaptorWithBuiltinExitFrame3,3,7 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,0,142 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,142 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,2,42 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,0,141 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,141 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,2,43 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,3,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,4,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,5,38 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,4,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,5,37 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,6,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,7,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,8,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,9,38 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,7,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,8,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,9,37 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,10,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,11,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,12,0 @@ -6617,9 +6576,9 @@ block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,24,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,25,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,26,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,27,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,28,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,29,38 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,27,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,28,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,29,37 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,30,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,31,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,32,0 @@ -6655,12 +6614,12 @@ block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,62,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,63,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,64,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,65,4 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,66,99 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,65,5 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,66,98 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,67,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,68,142 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,0,597 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1,597 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,68,141 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,0,594 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1,594 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,2,32 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,3,13 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,4,12 @@ -6668,7 +6627,7 @@ block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,6,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,7,12 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,8,12 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,9,10 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,9,9 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,10,2 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,11,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,12,2 @@ -6686,15 +6645,15 @@ block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,24,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,25,2 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,26,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,27,10 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,28,10 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,29,10 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,27,9 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,28,9 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,29,9 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,30,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,31,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,32,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,33,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,34,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,35,10 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,35,9 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,36,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,37,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,38,0 @@ -6724,10 +6683,10 @@ block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,62,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,63,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,64,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,65,19 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,66,565 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,65,18 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,66,561 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,67,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,68,597 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,68,594 block_count,Call_ReceiverIsAny_Baseline_Compact,0,2 block_count,Call_ReceiverIsAny_Baseline_Compact,1,2 block_count,Call_ReceiverIsAny_Baseline_Compact,2,0 @@ -7600,13 +7559,13 @@ block_count,Construct_WithFeedback,44,29 block_count,Construct_WithFeedback,45,0 block_count,Construct_WithFeedback,46,35 -block_count,FastNewObject,0,313 +block_count,FastNewObject,0,297 block_count,FastNewObject,1,0 -block_count,FastNewObject,2,313 -block_count,FastNewObject,3,313 -block_count,FastNewObject,4,310 -block_count,FastNewObject,5,310 -block_count,FastNewObject,6,310 +block_count,FastNewObject,2,297 +block_count,FastNewObject,3,297 +block_count,FastNewObject,4,294 +block_count,FastNewObject,5,294 +block_count,FastNewObject,6,294 block_count,FastNewObject,7,0 block_count,FastNewObject,8,0 block_count,FastNewObject,9,0 @@ -7632,25 +7591,25 @@ block_count,FastNewObject,29,0 block_count,FastNewObject,30,0 block_count,FastNewObject,31,0 -block_count,FastNewObject,32,310 -block_count,FastNewObject,33,310 +block_count,FastNewObject,32,294 +block_count,FastNewObject,33,294 block_count,FastNewObject,34,0 -block_count,FastNewObject,35,310 +block_count,FastNewObject,35,294 block_count,FastNewObject,36,0 block_count,FastNewObject,37,0 -block_count,FastNewObject,38,310 -block_count,FastNewObject,39,310 +block_count,FastNewObject,38,294 +block_count,FastNewObject,39,294 block_count,FastNewObject,40,1 -block_count,FastNewObject,41,308 +block_count,FastNewObject,41,293 block_count,FastNewObject,42,40 -block_count,FastNewObject,43,268 -block_count,FastNewObject,44,443 -block_count,FastNewObject,45,175 -block_count,FastNewObject,46,268 -block_count,FastNewObject,47,308 -block_count,FastNewObject,48,223 +block_count,FastNewObject,43,252 +block_count,FastNewObject,44,397 +block_count,FastNewObject,45,145 +block_count,FastNewObject,46,252 +block_count,FastNewObject,47,293 +block_count,FastNewObject,48,207 block_count,FastNewObject,49,85 -block_count,FastNewObject,50,310 +block_count,FastNewObject,50,294 block_count,FastNewObject,51,0 block_count,FastNewObject,52,0 block_count,FastNewObject,53,0 @@ -7694,7 +7653,7 @@ block_count,FastNewClosure,11,0 block_count,FastNewClosure,12,0 block_count,FastNewClosure,13,170 -block_count,FastNewClosure,14,60 +block_count,FastNewClosure,14,61 block_count,FastNewClosure,15,109 block_count,FastNewClosure,16,109 block_count,FastNewClosure,17,0 @@ -7705,14 +7664,14 @@ block_count,FastNewClosure,22,0 block_count,FastNewClosure,23,109 block_count,FastNewClosure,24,170 -block_count,FastNewClosure,25,60 +block_count,FastNewClosure,25,61 block_count,FastNewClosure,26,109 -block_count,StringEqual,0,665 +block_count,StringEqual,0,666 block_count,StringEqual,1,678 block_count,StringEqual,2,266 block_count,StringEqual,3,16 block_count,StringEqual,4,15 -block_count,StringEqual,5,7 +block_count,StringEqual,5,8 block_count,StringEqual,6,3 block_count,StringEqual,7,4 block_count,StringEqual,8,7 @@ -7737,30 +7696,30 @@ block_count,StringEqual,27,13 block_count,StringEqual,28,12 block_count,StringEqual,29,0 -block_count,StringEqual,30,249 -block_count,StringEqual,31,249 +block_count,StringEqual,30,250 +block_count,StringEqual,31,250 block_count,StringEqual,32,10 block_count,StringEqual,33,10 block_count,StringEqual,34,0 -block_count,StringEqual,35,238 -block_count,StringEqual,36,238 +block_count,StringEqual,35,239 +block_count,StringEqual,36,239 block_count,StringEqual,37,0 -block_count,StringEqual,38,238 -block_count,StringEqual,39,238 +block_count,StringEqual,38,239 +block_count,StringEqual,39,239 block_count,StringEqual,40,0 -block_count,StringEqual,41,238 -block_count,StringEqual,42,238 +block_count,StringEqual,41,239 +block_count,StringEqual,42,239 block_count,StringEqual,43,0 -block_count,StringEqual,44,238 +block_count,StringEqual,44,239 block_count,StringEqual,45,68 -block_count,StringEqual,46,170 +block_count,StringEqual,46,171 block_count,StringEqual,47,189 block_count,StringEqual,48,80 block_count,StringEqual,49,78 block_count,StringEqual,50,18 block_count,StringEqual,51,59 block_count,StringEqual,52,2 -block_count,StringEqual,53,108 +block_count,StringEqual,53,109 block_count,StringEqual,54,127 block_count,StringEqual,55,41 block_count,StringEqual,56,86 @@ -8102,7 +8061,7 @@ block_count,StringSubstring,0,489 block_count,StringSubstring,1,479 block_count,StringSubstring,2,479 -block_count,StringSubstring,3,388 +block_count,StringSubstring,3,389 block_count,StringSubstring,4,595 block_count,StringSubstring,5,206 block_count,StringSubstring,6,206 @@ -8114,8 +8073,8 @@ block_count,StringSubstring,12,0 block_count,StringSubstring,13,206 block_count,StringSubstring,14,0 -block_count,StringSubstring,15,388 -block_count,StringSubstring,16,388 +block_count,StringSubstring,15,389 +block_count,StringSubstring,16,389 block_count,StringSubstring,17,172 block_count,StringSubstring,18,4 block_count,StringSubstring,19,0 @@ -8207,11 +8166,11 @@ block_count,StringSubstring,105,183 block_count,StringSubstring,106,0 block_count,StringSubstring,107,183 -block_count,StringSubstring,108,420 +block_count,StringSubstring,108,421 block_count,StringSubstring,109,237 block_count,StringSubstring,110,183 block_count,StringSubstring,111,183 -block_count,StringSubstring,112,111 +block_count,StringSubstring,112,112 block_count,StringSubstring,113,71 block_count,StringSubstring,114,183 block_count,StringSubstring,115,216 @@ -8503,16 +8462,16 @@ block_count,GrowFastSmiOrObjectElements,11,308 block_count,GrowFastSmiOrObjectElements,12,0 block_count,GrowFastSmiOrObjectElements,13,308 -block_count,GrowFastSmiOrObjectElements,14,4052 -block_count,GrowFastSmiOrObjectElements,15,3743 +block_count,GrowFastSmiOrObjectElements,14,4053 +block_count,GrowFastSmiOrObjectElements,15,3744 block_count,GrowFastSmiOrObjectElements,16,308 block_count,GrowFastSmiOrObjectElements,17,308 block_count,GrowFastSmiOrObjectElements,18,16 block_count,GrowFastSmiOrObjectElements,19,292 block_count,GrowFastSmiOrObjectElements,20,308 block_count,GrowFastSmiOrObjectElements,21,42 -block_count,GrowFastSmiOrObjectElements,22,6188 -block_count,GrowFastSmiOrObjectElements,23,6146 +block_count,GrowFastSmiOrObjectElements,22,6192 +block_count,GrowFastSmiOrObjectElements,23,6150 block_count,GrowFastSmiOrObjectElements,24,42 block_count,GrowFastSmiOrObjectElements,25,266 block_count,GrowFastSmiOrObjectElements,26,0 @@ -8565,7 +8524,7 @@ block_count,ToNumber_Baseline,22,0 block_count,ToNumber_Baseline,23,0 block_count,ToNumber_Baseline,24,0 -block_count,ToNumeric_Baseline,0,29 +block_count,ToNumeric_Baseline,0,27 block_count,ToNumeric_Baseline,1,0 block_count,ToNumeric_Baseline,2,0 block_count,ToNumeric_Baseline,3,0 @@ -8593,10 +8552,10 @@ block_count,ToNumeric_Baseline,25,0 block_count,ToNumeric_Baseline,26,0 block_count,ToNumeric_Baseline,27,0 -block_count,ToNumeric_Baseline,28,29 -block_count,ToNumeric_Baseline,29,29 +block_count,ToNumeric_Baseline,28,27 +block_count,ToNumeric_Baseline,29,27 block_count,ToNumeric_Baseline,30,0 -block_count,ToNumeric_Baseline,31,29 +block_count,ToNumeric_Baseline,31,27 block_count,ToNumberConvertBigInt,0,2 block_count,ToNumberConvertBigInt,1,2 block_count,ToNumberConvertBigInt,2,0 @@ -8802,7 +8761,7 @@ block_count,KeyedLoadIC_PolymorphicName,99,0 block_count,KeyedLoadIC_PolymorphicName,100,0 block_count,KeyedLoadIC_PolymorphicName,101,0 -block_count,KeyedLoadIC_PolymorphicName,102,0 +block_count,KeyedLoadIC_PolymorphicName,102,1 block_count,KeyedLoadIC_PolymorphicName,103,1 block_count,KeyedLoadIC_PolymorphicName,104,0 block_count,KeyedLoadIC_PolymorphicName,105,0 @@ -8990,9 +8949,9 @@ block_count,KeyedLoadIC_PolymorphicName,287,0 block_count,KeyedLoadIC_PolymorphicName,288,0 block_count,KeyedLoadIC_PolymorphicName,289,0 -block_count,KeyedStoreIC_Megamorphic,0,302 -block_count,KeyedStoreIC_Megamorphic,1,302 -block_count,KeyedStoreIC_Megamorphic,2,302 +block_count,KeyedStoreIC_Megamorphic,0,365 +block_count,KeyedStoreIC_Megamorphic,1,365 +block_count,KeyedStoreIC_Megamorphic,2,365 block_count,KeyedStoreIC_Megamorphic,3,265 block_count,KeyedStoreIC_Megamorphic,4,265 block_count,KeyedStoreIC_Megamorphic,5,0 @@ -9171,14 +9130,14 @@ block_count,KeyedStoreIC_Megamorphic,178,10 block_count,KeyedStoreIC_Megamorphic,179,0 block_count,KeyedStoreIC_Megamorphic,180,10 -block_count,KeyedStoreIC_Megamorphic,181,87 -block_count,KeyedStoreIC_Megamorphic,182,87 +block_count,KeyedStoreIC_Megamorphic,181,86 +block_count,KeyedStoreIC_Megamorphic,182,86 block_count,KeyedStoreIC_Megamorphic,183,0 -block_count,KeyedStoreIC_Megamorphic,184,87 -block_count,KeyedStoreIC_Megamorphic,185,38 -block_count,KeyedStoreIC_Megamorphic,186,49 -block_count,KeyedStoreIC_Megamorphic,187,87 -block_count,KeyedStoreIC_Megamorphic,188,77 +block_count,KeyedStoreIC_Megamorphic,184,86 +block_count,KeyedStoreIC_Megamorphic,185,37 +block_count,KeyedStoreIC_Megamorphic,186,48 +block_count,KeyedStoreIC_Megamorphic,187,86 +block_count,KeyedStoreIC_Megamorphic,188,76 block_count,KeyedStoreIC_Megamorphic,189,10 block_count,KeyedStoreIC_Megamorphic,190,10 block_count,KeyedStoreIC_Megamorphic,191,10 @@ -9198,7 +9157,7 @@ block_count,KeyedStoreIC_Megamorphic,205,0 block_count,KeyedStoreIC_Megamorphic,206,8 block_count,KeyedStoreIC_Megamorphic,207,21 -block_count,KeyedStoreIC_Megamorphic,208,17 +block_count,KeyedStoreIC_Megamorphic,208,18 block_count,KeyedStoreIC_Megamorphic,209,13 block_count,KeyedStoreIC_Megamorphic,210,13 block_count,KeyedStoreIC_Megamorphic,211,0 @@ -9905,9 +9864,9 @@ block_count,KeyedStoreIC_Megamorphic,912,0 block_count,KeyedStoreIC_Megamorphic,913,0 block_count,KeyedStoreIC_Megamorphic,914,0 -block_count,KeyedStoreIC_Megamorphic,915,36 -block_count,KeyedStoreIC_Megamorphic,916,37 -block_count,KeyedStoreIC_Megamorphic,917,82 +block_count,KeyedStoreIC_Megamorphic,915,99 +block_count,KeyedStoreIC_Megamorphic,916,100 +block_count,KeyedStoreIC_Megamorphic,917,145 block_count,KeyedStoreIC_Megamorphic,918,1 block_count,KeyedStoreIC_Megamorphic,919,0 block_count,KeyedStoreIC_Megamorphic,920,0 @@ -9931,13 +9890,13 @@ block_count,KeyedStoreIC_Megamorphic,938,0 block_count,KeyedStoreIC_Megamorphic,939,0 block_count,KeyedStoreIC_Megamorphic,940,0 -block_count,KeyedStoreIC_Megamorphic,941,81 +block_count,KeyedStoreIC_Megamorphic,941,144 block_count,KeyedStoreIC_Megamorphic,942,7 block_count,KeyedStoreIC_Megamorphic,943,1 block_count,KeyedStoreIC_Megamorphic,944,6 -block_count,KeyedStoreIC_Megamorphic,945,73 -block_count,KeyedStoreIC_Megamorphic,946,31 -block_count,KeyedStoreIC_Megamorphic,947,31 +block_count,KeyedStoreIC_Megamorphic,945,136 +block_count,KeyedStoreIC_Megamorphic,946,94 +block_count,KeyedStoreIC_Megamorphic,947,94 block_count,KeyedStoreIC_Megamorphic,948,0 block_count,KeyedStoreIC_Megamorphic,949,0 block_count,KeyedStoreIC_Megamorphic,950,0 @@ -10199,22 +10158,22 @@ block_count,KeyedStoreIC_Megamorphic,1206,0 block_count,KeyedStoreIC_Megamorphic,1207,0 block_count,KeyedStoreIC_Megamorphic,1208,0 -block_count,KeyedStoreIC_Megamorphic,1209,31 -block_count,KeyedStoreIC_Megamorphic,1210,31 -block_count,KeyedStoreIC_Megamorphic,1211,31 -block_count,KeyedStoreIC_Megamorphic,1212,31 -block_count,KeyedStoreIC_Megamorphic,1213,94 -block_count,KeyedStoreIC_Megamorphic,1214,63 -block_count,KeyedStoreIC_Megamorphic,1215,63 +block_count,KeyedStoreIC_Megamorphic,1209,94 +block_count,KeyedStoreIC_Megamorphic,1210,94 +block_count,KeyedStoreIC_Megamorphic,1211,94 +block_count,KeyedStoreIC_Megamorphic,1212,94 +block_count,KeyedStoreIC_Megamorphic,1213,283 +block_count,KeyedStoreIC_Megamorphic,1214,189 +block_count,KeyedStoreIC_Megamorphic,1215,189 block_count,KeyedStoreIC_Megamorphic,1216,0 block_count,KeyedStoreIC_Megamorphic,1217,0 block_count,KeyedStoreIC_Megamorphic,1218,0 -block_count,KeyedStoreIC_Megamorphic,1219,63 -block_count,KeyedStoreIC_Megamorphic,1220,63 +block_count,KeyedStoreIC_Megamorphic,1219,189 +block_count,KeyedStoreIC_Megamorphic,1220,189 block_count,KeyedStoreIC_Megamorphic,1221,0 -block_count,KeyedStoreIC_Megamorphic,1222,31 -block_count,KeyedStoreIC_Megamorphic,1223,31 -block_count,KeyedStoreIC_Megamorphic,1224,31 +block_count,KeyedStoreIC_Megamorphic,1222,94 +block_count,KeyedStoreIC_Megamorphic,1223,94 +block_count,KeyedStoreIC_Megamorphic,1224,94 block_count,KeyedStoreIC_Megamorphic,1225,0 block_count,KeyedStoreIC_Megamorphic,1226,0 block_count,KeyedStoreIC_Megamorphic,1227,0 @@ -10373,7 +10332,7 @@ block_count,KeyedStoreIC_Megamorphic,1380,0 block_count,KeyedStoreIC_Megamorphic,1381,0 block_count,KeyedStoreIC_Megamorphic,1382,0 -block_count,KeyedStoreIC_Megamorphic,1383,42 +block_count,KeyedStoreIC_Megamorphic,1383,41 block_count,KeyedStoreIC_Megamorphic,1384,48 block_count,KeyedStoreIC_Megamorphic,1385,48 block_count,KeyedStoreIC_Megamorphic,1386,6 @@ -11551,7 +11510,7 @@ block_count,LoadIC_FunctionPrototype,2,1 block_count,LoadIC_FunctionPrototype,3,180 block_count,LoadIC_FunctionPrototype,4,0 -block_count,LoadIC_StringLength,0,39 +block_count,LoadIC_StringLength,0,38 block_count,LoadIC_StringWrapperLength,0,0 block_count,LoadIC_NoFeedback,0,39 block_count,LoadIC_NoFeedback,1,39 @@ -11571,7 +11530,7 @@ block_count,LoadIC_NoFeedback,15,0 block_count,LoadIC_NoFeedback,16,0 block_count,LoadIC_NoFeedback,17,0 -block_count,LoadIC_NoFeedback,18,39 +block_count,LoadIC_NoFeedback,18,38 block_count,LoadIC_NoFeedback,19,28 block_count,LoadIC_NoFeedback,20,26 block_count,LoadIC_NoFeedback,21,25 @@ -12676,10 +12635,10 @@ block_count,KeyedLoadIC_SloppyArguments,20,0 block_count,KeyedLoadIC_SloppyArguments,21,0 block_count,KeyedLoadIC_SloppyArguments,22,0 -block_count,StoreFastElementIC_InBounds,0,184 +block_count,StoreFastElementIC_InBounds,0,181 block_count,StoreFastElementIC_InBounds,1,0 -block_count,StoreFastElementIC_InBounds,2,3 -block_count,StoreFastElementIC_InBounds,3,3 +block_count,StoreFastElementIC_InBounds,2,4 +block_count,StoreFastElementIC_InBounds,3,4 block_count,StoreFastElementIC_InBounds,4,0 block_count,StoreFastElementIC_InBounds,5,0 block_count,StoreFastElementIC_InBounds,6,0 @@ -12687,17 +12646,17 @@ block_count,StoreFastElementIC_InBounds,8,0 block_count,StoreFastElementIC_InBounds,9,0 block_count,StoreFastElementIC_InBounds,10,0 -block_count,StoreFastElementIC_InBounds,11,3 -block_count,StoreFastElementIC_InBounds,12,3 +block_count,StoreFastElementIC_InBounds,11,4 +block_count,StoreFastElementIC_InBounds,12,4 block_count,StoreFastElementIC_InBounds,13,0 -block_count,StoreFastElementIC_InBounds,14,3 +block_count,StoreFastElementIC_InBounds,14,4 block_count,StoreFastElementIC_InBounds,15,0 -block_count,StoreFastElementIC_InBounds,16,3 -block_count,StoreFastElementIC_InBounds,17,3 +block_count,StoreFastElementIC_InBounds,16,4 +block_count,StoreFastElementIC_InBounds,17,4 block_count,StoreFastElementIC_InBounds,18,0 -block_count,StoreFastElementIC_InBounds,19,3 +block_count,StoreFastElementIC_InBounds,19,4 block_count,StoreFastElementIC_InBounds,20,0 -block_count,StoreFastElementIC_InBounds,21,3 +block_count,StoreFastElementIC_InBounds,21,4 block_count,StoreFastElementIC_InBounds,22,0 block_count,StoreFastElementIC_InBounds,23,2 block_count,StoreFastElementIC_InBounds,24,2 @@ -12720,8 +12679,8 @@ block_count,StoreFastElementIC_InBounds,41,0 block_count,StoreFastElementIC_InBounds,42,2 block_count,StoreFastElementIC_InBounds,43,0 -block_count,StoreFastElementIC_InBounds,44,10 -block_count,StoreFastElementIC_InBounds,45,10 +block_count,StoreFastElementIC_InBounds,44,11 +block_count,StoreFastElementIC_InBounds,45,11 block_count,StoreFastElementIC_InBounds,46,0 block_count,StoreFastElementIC_InBounds,47,0 block_count,StoreFastElementIC_InBounds,48,0 @@ -12729,15 +12688,15 @@ block_count,StoreFastElementIC_InBounds,50,0 block_count,StoreFastElementIC_InBounds,51,0 block_count,StoreFastElementIC_InBounds,52,0 -block_count,StoreFastElementIC_InBounds,53,10 -block_count,StoreFastElementIC_InBounds,54,10 +block_count,StoreFastElementIC_InBounds,53,11 +block_count,StoreFastElementIC_InBounds,54,11 block_count,StoreFastElementIC_InBounds,55,0 -block_count,StoreFastElementIC_InBounds,56,10 -block_count,StoreFastElementIC_InBounds,57,10 +block_count,StoreFastElementIC_InBounds,56,11 +block_count,StoreFastElementIC_InBounds,57,11 block_count,StoreFastElementIC_InBounds,58,0 -block_count,StoreFastElementIC_InBounds,59,10 +block_count,StoreFastElementIC_InBounds,59,11 block_count,StoreFastElementIC_InBounds,60,0 -block_count,StoreFastElementIC_InBounds,61,10 +block_count,StoreFastElementIC_InBounds,61,11 block_count,StoreFastElementIC_InBounds,62,0 block_count,StoreFastElementIC_InBounds,63,0 block_count,StoreFastElementIC_InBounds,64,0 @@ -12811,8 +12770,8 @@ block_count,StoreFastElementIC_InBounds,132,0 block_count,StoreFastElementIC_InBounds,133,0 block_count,StoreFastElementIC_InBounds,134,0 -block_count,StoreFastElementIC_InBounds,135,3 -block_count,StoreFastElementIC_InBounds,136,3 +block_count,StoreFastElementIC_InBounds,135,2 +block_count,StoreFastElementIC_InBounds,136,2 block_count,StoreFastElementIC_InBounds,137,0 block_count,StoreFastElementIC_InBounds,138,0 block_count,StoreFastElementIC_InBounds,139,0 @@ -12820,15 +12779,15 @@ block_count,StoreFastElementIC_InBounds,141,0 block_count,StoreFastElementIC_InBounds,142,0 block_count,StoreFastElementIC_InBounds,143,0 -block_count,StoreFastElementIC_InBounds,144,3 -block_count,StoreFastElementIC_InBounds,145,3 +block_count,StoreFastElementIC_InBounds,144,2 +block_count,StoreFastElementIC_InBounds,145,2 block_count,StoreFastElementIC_InBounds,146,0 -block_count,StoreFastElementIC_InBounds,147,3 -block_count,StoreFastElementIC_InBounds,148,3 +block_count,StoreFastElementIC_InBounds,147,2 +block_count,StoreFastElementIC_InBounds,148,2 block_count,StoreFastElementIC_InBounds,149,0 -block_count,StoreFastElementIC_InBounds,150,3 +block_count,StoreFastElementIC_InBounds,150,2 block_count,StoreFastElementIC_InBounds,151,0 -block_count,StoreFastElementIC_InBounds,152,3 +block_count,StoreFastElementIC_InBounds,152,2 block_count,StoreFastElementIC_InBounds,153,0 block_count,StoreFastElementIC_InBounds,154,0 block_count,StoreFastElementIC_InBounds,155,0 @@ -12916,7 +12875,7 @@ block_count,StoreFastElementIC_InBounds,237,4 block_count,StoreFastElementIC_InBounds,238,0 block_count,StoreFastElementIC_InBounds,239,4 -block_count,StoreFastElementIC_InBounds,240,14 +block_count,StoreFastElementIC_InBounds,240,13 block_count,StoreFastElementIC_InBounds,241,0 block_count,StoreFastElementIC_InBounds,242,0 block_count,StoreFastElementIC_InBounds,243,0 @@ -12924,23 +12883,23 @@ block_count,StoreFastElementIC_InBounds,245,0 block_count,StoreFastElementIC_InBounds,246,0 block_count,StoreFastElementIC_InBounds,247,0 -block_count,StoreFastElementIC_InBounds,248,14 -block_count,StoreFastElementIC_InBounds,249,14 -block_count,StoreFastElementIC_InBounds,250,14 +block_count,StoreFastElementIC_InBounds,248,13 +block_count,StoreFastElementIC_InBounds,249,13 +block_count,StoreFastElementIC_InBounds,250,13 block_count,StoreFastElementIC_InBounds,251,0 block_count,StoreFastElementIC_InBounds,252,0 block_count,StoreFastElementIC_InBounds,253,0 block_count,StoreFastElementIC_InBounds,254,0 block_count,StoreFastElementIC_InBounds,255,0 block_count,StoreFastElementIC_InBounds,256,0 -block_count,StoreFastElementIC_InBounds,257,14 -block_count,StoreFastElementIC_InBounds,258,14 -block_count,StoreFastElementIC_InBounds,259,14 +block_count,StoreFastElementIC_InBounds,257,13 +block_count,StoreFastElementIC_InBounds,258,13 +block_count,StoreFastElementIC_InBounds,259,13 block_count,StoreFastElementIC_InBounds,260,0 -block_count,StoreFastElementIC_InBounds,261,14 +block_count,StoreFastElementIC_InBounds,261,13 block_count,StoreFastElementIC_InBounds,262,0 block_count,StoreFastElementIC_InBounds,263,0 -block_count,StoreFastElementIC_InBounds,264,3 +block_count,StoreFastElementIC_InBounds,264,2 block_count,StoreFastElementIC_InBounds,265,0 block_count,StoreFastElementIC_InBounds,266,0 block_count,StoreFastElementIC_InBounds,267,0 @@ -12948,20 +12907,20 @@ block_count,StoreFastElementIC_InBounds,269,0 block_count,StoreFastElementIC_InBounds,270,0 block_count,StoreFastElementIC_InBounds,271,0 -block_count,StoreFastElementIC_InBounds,272,3 -block_count,StoreFastElementIC_InBounds,273,3 -block_count,StoreFastElementIC_InBounds,274,3 +block_count,StoreFastElementIC_InBounds,272,2 +block_count,StoreFastElementIC_InBounds,273,2 +block_count,StoreFastElementIC_InBounds,274,2 block_count,StoreFastElementIC_InBounds,275,0 block_count,StoreFastElementIC_InBounds,276,0 block_count,StoreFastElementIC_InBounds,277,0 block_count,StoreFastElementIC_InBounds,278,0 block_count,StoreFastElementIC_InBounds,279,0 block_count,StoreFastElementIC_InBounds,280,0 -block_count,StoreFastElementIC_InBounds,281,3 -block_count,StoreFastElementIC_InBounds,282,3 -block_count,StoreFastElementIC_InBounds,283,3 +block_count,StoreFastElementIC_InBounds,281,2 +block_count,StoreFastElementIC_InBounds,282,2 +block_count,StoreFastElementIC_InBounds,283,2 block_count,StoreFastElementIC_InBounds,284,0 -block_count,StoreFastElementIC_InBounds,285,3 +block_count,StoreFastElementIC_InBounds,285,2 block_count,StoreFastElementIC_InBounds,286,0 block_count,StoreFastElementIC_InBounds,287,0 block_count,StoreFastElementIC_InBounds,288,0 @@ -13042,7 +13001,7 @@ block_count,StoreFastElementIC_InBounds,363,0 block_count,StoreFastElementIC_InBounds,364,0 block_count,StoreFastElementIC_InBounds,365,0 -block_count,StoreFastElementIC_InBounds,366,103 +block_count,StoreFastElementIC_InBounds,366,102 block_count,StoreFastElementIC_InBounds,367,0 block_count,StoreFastElementIC_InBounds,368,0 block_count,StoreFastElementIC_InBounds,369,0 @@ -13050,9 +13009,9 @@ block_count,StoreFastElementIC_InBounds,371,0 block_count,StoreFastElementIC_InBounds,372,0 block_count,StoreFastElementIC_InBounds,373,0 -block_count,StoreFastElementIC_InBounds,374,103 -block_count,StoreFastElementIC_InBounds,375,103 -block_count,StoreFastElementIC_InBounds,376,103 +block_count,StoreFastElementIC_InBounds,374,102 +block_count,StoreFastElementIC_InBounds,375,102 +block_count,StoreFastElementIC_InBounds,376,102 block_count,StoreFastElementIC_InBounds,377,2 block_count,StoreFastElementIC_InBounds,378,2 block_count,StoreFastElementIC_InBounds,379,0 @@ -13060,10 +13019,10 @@ block_count,StoreFastElementIC_InBounds,381,0 block_count,StoreFastElementIC_InBounds,382,2 block_count,StoreFastElementIC_InBounds,383,100 -block_count,StoreFastElementIC_InBounds,384,103 -block_count,StoreFastElementIC_InBounds,385,103 +block_count,StoreFastElementIC_InBounds,384,102 +block_count,StoreFastElementIC_InBounds,385,102 block_count,StoreFastElementIC_InBounds,386,0 -block_count,StoreFastElementIC_InBounds,387,103 +block_count,StoreFastElementIC_InBounds,387,102 block_count,StoreFastElementIC_InBounds,388,0 block_count,StoreFastElementIC_InBounds,389,0 block_count,StoreFastElementIC_InBounds,390,0 @@ -13122,7 +13081,7 @@ block_count,StoreFastElementIC_InBounds,443,0 block_count,StoreFastElementIC_InBounds,444,0 block_count,StoreFastElementIC_InBounds,445,0 -block_count,StoreFastElementIC_InBounds,446,21 +block_count,StoreFastElementIC_InBounds,446,19 block_count,StoreFastElementIC_InBounds,447,0 block_count,StoreFastElementIC_InBounds,448,0 block_count,StoreFastElementIC_InBounds,449,0 @@ -13130,20 +13089,20 @@ block_count,StoreFastElementIC_InBounds,451,0 block_count,StoreFastElementIC_InBounds,452,0 block_count,StoreFastElementIC_InBounds,453,0 -block_count,StoreFastElementIC_InBounds,454,21 -block_count,StoreFastElementIC_InBounds,455,21 -block_count,StoreFastElementIC_InBounds,456,21 -block_count,StoreFastElementIC_InBounds,457,17 -block_count,StoreFastElementIC_InBounds,458,17 +block_count,StoreFastElementIC_InBounds,454,19 +block_count,StoreFastElementIC_InBounds,455,19 +block_count,StoreFastElementIC_InBounds,456,19 +block_count,StoreFastElementIC_InBounds,457,19 +block_count,StoreFastElementIC_InBounds,458,19 block_count,StoreFastElementIC_InBounds,459,0 block_count,StoreFastElementIC_InBounds,460,0 block_count,StoreFastElementIC_InBounds,461,0 -block_count,StoreFastElementIC_InBounds,462,17 -block_count,StoreFastElementIC_InBounds,463,4 -block_count,StoreFastElementIC_InBounds,464,21 -block_count,StoreFastElementIC_InBounds,465,21 +block_count,StoreFastElementIC_InBounds,462,19 +block_count,StoreFastElementIC_InBounds,463,0 +block_count,StoreFastElementIC_InBounds,464,19 +block_count,StoreFastElementIC_InBounds,465,19 block_count,StoreFastElementIC_InBounds,466,0 -block_count,StoreFastElementIC_InBounds,467,21 +block_count,StoreFastElementIC_InBounds,467,19 block_count,StoreFastElementIC_InBounds,468,0 block_count,StoreFastElementIC_InBounds,469,0 block_count,StoreFastElementIC_InBounds,470,0 @@ -14023,7 +13982,7 @@ block_count,StoreFastElementIC_InBounds,1344,0 block_count,StoreFastElementIC_InBounds,1345,0 block_count,StoreFastElementIC_InBounds,1346,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,0,20 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,0,19 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,1,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,2,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,3,0 @@ -14066,8 +14025,8 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,40,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,41,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,42,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,43,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,44,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,43,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,44,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,45,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,46,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,47,0 @@ -14122,7 +14081,7 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,96,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,97,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,98,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,99,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,99,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,100,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,101,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,102,0 @@ -14130,13 +14089,13 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,104,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,105,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,106,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,107,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,108,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,107,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,108,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,109,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,110,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,110,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,111,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,112,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,113,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,112,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,113,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,114,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,115,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,116,0 @@ -14186,8 +14145,8 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,160,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,161,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,162,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,163,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,164,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,163,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,164,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,165,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,166,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,167,0 @@ -14216,9 +14175,9 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,190,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,191,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,192,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,193,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,193,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,194,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,195,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,195,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,196,15 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,197,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,198,0 @@ -14277,7 +14236,7 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,251,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,252,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,253,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,254,13 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,254,12 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,255,14 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,256,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,257,14 @@ -14509,8 +14468,8 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,483,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,484,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,485,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,486,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,487,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,486,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,487,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,488,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,489,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,490,0 @@ -14677,8 +14636,8 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,651,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,652,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,653,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,654,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,655,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,654,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,655,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,656,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,657,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,658,1 @@ -19559,7 +19518,7 @@ block_count,ArrayConstructor,1,0 block_count,ArrayConstructor,2,2 block_count,ArrayConstructor,3,2 -block_count,ArrayConstructorImpl,0,218 +block_count,ArrayConstructorImpl,0,217 block_count,ArrayConstructorImpl,1,104 block_count,ArrayConstructorImpl,2,6 block_count,ArrayConstructorImpl,3,5 @@ -19596,10 +19555,10 @@ block_count,ArrayConstructorImpl,34,0 block_count,ArrayConstructorImpl,35,0 block_count,ArrayConstructorImpl,36,0 -block_count,ArrayConstructorImpl,37,98 -block_count,ArrayConstructorImpl,38,98 +block_count,ArrayConstructorImpl,37,97 +block_count,ArrayConstructorImpl,38,97 block_count,ArrayConstructorImpl,39,0 -block_count,ArrayConstructorImpl,40,98 +block_count,ArrayConstructorImpl,40,97 block_count,ArrayConstructorImpl,41,0 block_count,ArrayConstructorImpl,42,113 block_count,ArrayConstructorImpl,43,114 @@ -19685,13 +19644,13 @@ block_count,ArraySingleArgumentConstructor_HoleySmi_DontOverride,43,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DontOverride,44,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DontOverride,45,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,0,98 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,0,97 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,1,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,2,98 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,2,97 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,3,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,4,98 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,5,98 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,6,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,4,97 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,5,97 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,6,50 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,7,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,8,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,9,0 @@ -19706,25 +19665,25 @@ block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,18,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,19,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,20,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,21,51 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,22,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,21,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,22,50 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,23,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,24,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,24,50 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,25,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,26,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,27,51 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,28,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,27,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,28,50 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,29,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,30,51 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,31,33 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,30,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,31,32 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,32,18 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,33,23 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,34,5 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,35,18 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,36,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,36,50 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,37,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,38,50 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,39,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,39,50 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,40,46 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,41,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,42,46 @@ -20486,14 +20445,14 @@ block_count,ArrayIndexOfSmiOrObject,151,0 block_count,ArrayIndexOfSmiOrObject,152,0 block_count,ArrayIndexOfSmiOrObject,153,0 -block_count,ArrayIndexOf,0,29 +block_count,ArrayIndexOf,0,28 block_count,ArrayIndexOf,1,0 -block_count,ArrayIndexOf,2,29 -block_count,ArrayIndexOf,3,29 -block_count,ArrayIndexOf,4,29 +block_count,ArrayIndexOf,2,28 +block_count,ArrayIndexOf,3,28 +block_count,ArrayIndexOf,4,28 block_count,ArrayIndexOf,5,0 -block_count,ArrayIndexOf,6,29 -block_count,ArrayIndexOf,7,29 +block_count,ArrayIndexOf,6,28 +block_count,ArrayIndexOf,7,28 block_count,ArrayIndexOf,8,28 block_count,ArrayIndexOf,9,28 block_count,ArrayIndexOf,10,0 @@ -20571,26 +20530,26 @@ block_count,ArrayPrototypePop,37,0 block_count,ArrayPrototypePop,38,0 block_count,ArrayPrototypePop,39,0 -block_count,ArrayPrototypePush,0,285 +block_count,ArrayPrototypePush,0,284 block_count,ArrayPrototypePush,1,0 -block_count,ArrayPrototypePush,2,285 -block_count,ArrayPrototypePush,3,285 -block_count,ArrayPrototypePush,4,285 -block_count,ArrayPrototypePush,5,285 -block_count,ArrayPrototypePush,6,285 +block_count,ArrayPrototypePush,2,284 +block_count,ArrayPrototypePush,3,284 +block_count,ArrayPrototypePush,4,284 +block_count,ArrayPrototypePush,5,284 +block_count,ArrayPrototypePush,6,284 block_count,ArrayPrototypePush,7,0 -block_count,ArrayPrototypePush,8,285 -block_count,ArrayPrototypePush,9,285 -block_count,ArrayPrototypePush,10,285 +block_count,ArrayPrototypePush,8,284 +block_count,ArrayPrototypePush,9,284 +block_count,ArrayPrototypePush,10,284 block_count,ArrayPrototypePush,11,0 -block_count,ArrayPrototypePush,12,285 -block_count,ArrayPrototypePush,13,285 +block_count,ArrayPrototypePush,12,284 +block_count,ArrayPrototypePush,13,284 block_count,ArrayPrototypePush,14,0 -block_count,ArrayPrototypePush,15,285 -block_count,ArrayPrototypePush,16,285 +block_count,ArrayPrototypePush,15,284 +block_count,ArrayPrototypePush,16,284 block_count,ArrayPrototypePush,17,6 block_count,ArrayPrototypePush,18,6 -block_count,ArrayPrototypePush,19,6 +block_count,ArrayPrototypePush,19,5 block_count,ArrayPrototypePush,20,0 block_count,ArrayPrototypePush,21,0 block_count,ArrayPrototypePush,22,0 @@ -20604,16 +20563,16 @@ block_count,ArrayPrototypePush,30,0 block_count,ArrayPrototypePush,31,0 block_count,ArrayPrototypePush,32,0 -block_count,ArrayPrototypePush,33,8 -block_count,ArrayPrototypePush,34,7 +block_count,ArrayPrototypePush,33,7 +block_count,ArrayPrototypePush,34,6 block_count,ArrayPrototypePush,35,0 block_count,ArrayPrototypePush,36,0 block_count,ArrayPrototypePush,37,0 block_count,ArrayPrototypePush,38,0 block_count,ArrayPrototypePush,39,0 block_count,ArrayPrototypePush,40,0 -block_count,ArrayPrototypePush,41,15 -block_count,ArrayPrototypePush,42,15 +block_count,ArrayPrototypePush,41,12 +block_count,ArrayPrototypePush,42,12 block_count,ArrayPrototypePush,43,0 block_count,ArrayPrototypePush,44,0 block_count,ArrayPrototypePush,45,0 @@ -20622,14 +20581,14 @@ block_count,ArrayPrototypePush,48,6 block_count,ArrayPrototypePush,49,6 block_count,ArrayPrototypePush,50,6 -block_count,ArrayPrototypePush,51,6 -block_count,ArrayPrototypePush,52,6 +block_count,ArrayPrototypePush,51,5 +block_count,ArrayPrototypePush,52,5 block_count,ArrayPrototypePush,53,0 -block_count,ArrayPrototypePush,54,6 +block_count,ArrayPrototypePush,54,5 block_count,ArrayPrototypePush,55,0 block_count,ArrayPrototypePush,56,0 block_count,ArrayPrototypePush,57,0 -block_count,ArrayPrototypePush,58,6 +block_count,ArrayPrototypePush,58,5 block_count,ArrayPrototypePush,59,0 block_count,ArrayPrototypePush,60,0 block_count,ArrayPrototypePush,61,0 @@ -20700,7 +20659,7 @@ block_count,ArrayPrototypePush,126,0 block_count,ArrayPrototypePush,127,278 block_count,ArrayPrototypePush,128,277 -block_count,ArrayPrototypePush,129,258 +block_count,ArrayPrototypePush,129,257 block_count,ArrayPrototypePush,130,19 block_count,ArrayPrototypePush,131,19 block_count,ArrayPrototypePush,132,19 @@ -20722,7 +20681,7 @@ block_count,ArrayPrototypePush,148,18 block_count,ArrayPrototypePush,149,19 block_count,ArrayPrototypePush,150,1 -block_count,ArrayPrototypePush,151,256 +block_count,ArrayPrototypePush,151,255 block_count,ArrayPrototypePush,152,254 block_count,ArrayPrototypePush,153,1 block_count,ArrayPrototypePush,154,18 @@ -21308,7 +21267,7 @@ block_count,CreateObjectFromSlowBoilerplateHelper,79,0 block_count,CreateObjectFromSlowBoilerplateHelper,80,44 block_count,CreateObjectFromSlowBoilerplateHelper,81,44 -block_count,CreateObjectFromSlowBoilerplateHelper,82,94 +block_count,CreateObjectFromSlowBoilerplateHelper,82,93 block_count,CreateObjectFromSlowBoilerplateHelper,83,93 block_count,CreateObjectFromSlowBoilerplateHelper,84,41 block_count,CreateObjectFromSlowBoilerplateHelper,85,0 @@ -21375,8 +21334,8 @@ block_count,CreateObjectFromSlowBoilerplateHelper,146,44 block_count,CreateObjectFromSlowBoilerplateHelper,147,44 block_count,CreateObjectFromSlowBoilerplateHelper,148,43 -block_count,CreateObjectFromSlowBoilerplateHelper,149,1 -block_count,CreateObjectFromSlowBoilerplateHelper,150,1 +block_count,CreateObjectFromSlowBoilerplateHelper,149,0 +block_count,CreateObjectFromSlowBoilerplateHelper,150,0 block_count,CreateObjectFromSlowBoilerplateHelper,151,0 block_count,CreateObjectFromSlowBoilerplateHelper,152,0 block_count,CreateObjectFromSlowBoilerplateHelper,153,0 @@ -21387,7 +21346,7 @@ block_count,CreateObjectFromSlowBoilerplateHelper,158,0 block_count,CreateObjectFromSlowBoilerplateHelper,159,0 block_count,CreateObjectFromSlowBoilerplateHelper,160,0 -block_count,CreateObjectFromSlowBoilerplateHelper,161,1 +block_count,CreateObjectFromSlowBoilerplateHelper,161,0 block_count,CreateObjectFromSlowBoilerplateHelper,162,44 block_count,CreateObjectFromSlowBoilerplateHelper,163,0 block_count,CreateObjectFromSlowBoilerplateHelper,164,0 @@ -21483,28 +21442,28 @@ block_count,ArrayPrototypeKeys,12,0 block_count,ArrayPrototypeKeys,13,0 block_count,ArrayPrototypeKeys,14,0 -block_count,ArrayPrototypeValues,0,18 +block_count,ArrayPrototypeValues,0,17 block_count,ArrayPrototypeValues,1,0 -block_count,ArrayPrototypeValues,2,18 -block_count,ArrayPrototypeValues,3,18 -block_count,ArrayPrototypeValues,4,18 +block_count,ArrayPrototypeValues,2,17 +block_count,ArrayPrototypeValues,3,17 +block_count,ArrayPrototypeValues,4,17 block_count,ArrayPrototypeValues,5,0 -block_count,ArrayPrototypeValues,6,18 +block_count,ArrayPrototypeValues,6,17 block_count,ArrayPrototypeValues,7,0 block_count,ArrayPrototypeValues,8,0 -block_count,ArrayPrototypeValues,9,18 +block_count,ArrayPrototypeValues,9,17 block_count,ArrayPrototypeValues,10,0 -block_count,ArrayPrototypeValues,11,18 +block_count,ArrayPrototypeValues,11,17 block_count,ArrayPrototypeValues,12,0 -block_count,ArrayPrototypeValues,13,18 -block_count,ArrayPrototypeValues,14,18 -block_count,ArrayIteratorPrototypeNext,0,91 +block_count,ArrayPrototypeValues,13,17 +block_count,ArrayPrototypeValues,14,17 +block_count,ArrayIteratorPrototypeNext,0,90 block_count,ArrayIteratorPrototypeNext,1,0 -block_count,ArrayIteratorPrototypeNext,2,91 -block_count,ArrayIteratorPrototypeNext,3,91 -block_count,ArrayIteratorPrototypeNext,4,91 +block_count,ArrayIteratorPrototypeNext,2,90 +block_count,ArrayIteratorPrototypeNext,3,90 +block_count,ArrayIteratorPrototypeNext,4,90 block_count,ArrayIteratorPrototypeNext,5,0 -block_count,ArrayIteratorPrototypeNext,6,91 +block_count,ArrayIteratorPrototypeNext,6,90 block_count,ArrayIteratorPrototypeNext,7,2 block_count,ArrayIteratorPrototypeNext,8,2 block_count,ArrayIteratorPrototypeNext,9,0 @@ -21666,22 +21625,22 @@ block_count,ArrayIteratorPrototypeNext,165,0 block_count,ArrayIteratorPrototypeNext,166,0 block_count,ArrayIteratorPrototypeNext,167,0 -block_count,ArrayIteratorPrototypeNext,168,88 +block_count,ArrayIteratorPrototypeNext,168,87 block_count,ArrayIteratorPrototypeNext,169,0 -block_count,ArrayIteratorPrototypeNext,170,88 -block_count,ArrayIteratorPrototypeNext,171,88 +block_count,ArrayIteratorPrototypeNext,170,87 +block_count,ArrayIteratorPrototypeNext,171,87 block_count,ArrayIteratorPrototypeNext,172,0 -block_count,ArrayIteratorPrototypeNext,173,88 -block_count,ArrayIteratorPrototypeNext,174,88 +block_count,ArrayIteratorPrototypeNext,173,87 +block_count,ArrayIteratorPrototypeNext,174,87 block_count,ArrayIteratorPrototypeNext,175,24 -block_count,ArrayIteratorPrototypeNext,176,64 -block_count,ArrayIteratorPrototypeNext,177,64 +block_count,ArrayIteratorPrototypeNext,176,63 +block_count,ArrayIteratorPrototypeNext,177,63 block_count,ArrayIteratorPrototypeNext,178,0 block_count,ArrayIteratorPrototypeNext,179,0 block_count,ArrayIteratorPrototypeNext,180,0 block_count,ArrayIteratorPrototypeNext,181,0 -block_count,ArrayIteratorPrototypeNext,182,64 -block_count,ArrayIteratorPrototypeNext,183,64 +block_count,ArrayIteratorPrototypeNext,182,63 +block_count,ArrayIteratorPrototypeNext,183,63 block_count,ArrayIteratorPrototypeNext,184,0 block_count,ArrayIteratorPrototypeNext,185,0 block_count,ArrayIteratorPrototypeNext,186,0 @@ -21705,9 +21664,9 @@ block_count,ArrayIteratorPrototypeNext,204,0 block_count,ArrayIteratorPrototypeNext,205,0 block_count,ArrayIteratorPrototypeNext,206,0 -block_count,ArrayIteratorPrototypeNext,207,59 +block_count,ArrayIteratorPrototypeNext,207,58 block_count,ArrayIteratorPrototypeNext,208,0 -block_count,ArrayIteratorPrototypeNext,209,59 +block_count,ArrayIteratorPrototypeNext,209,58 block_count,ArrayIteratorPrototypeNext,210,0 block_count,ArrayIteratorPrototypeNext,211,4 block_count,ArrayIteratorPrototypeNext,212,0 @@ -21728,7 +21687,7 @@ block_count,ArrayIteratorPrototypeNext,227,0 block_count,ArrayIteratorPrototypeNext,228,0 block_count,ArrayIteratorPrototypeNext,229,0 -block_count,ArrayIteratorPrototypeNext,230,64 +block_count,ArrayIteratorPrototypeNext,230,63 block_count,ArrayIteratorPrototypeNext,231,0 block_count,ArrayIteratorPrototypeNext,232,0 block_count,ArrayIteratorPrototypeNext,233,0 @@ -21754,12 +21713,12 @@ block_count,ArrayIteratorPrototypeNext,253,0 block_count,ArrayIteratorPrototypeNext,254,0 block_count,ArrayIteratorPrototypeNext,255,65 -block_count,ArrayIteratorPrototypeNext,256,91 +block_count,ArrayIteratorPrototypeNext,256,90 block_count,ArrayIteratorPrototypeNext,257,0 -block_count,ArrayIteratorPrototypeNext,258,91 +block_count,ArrayIteratorPrototypeNext,258,90 block_count,ArrayIteratorPrototypeNext,259,0 -block_count,ArrayIteratorPrototypeNext,260,91 -block_count,ArrayIteratorPrototypeNext,261,91 +block_count,ArrayIteratorPrototypeNext,260,90 +block_count,ArrayIteratorPrototypeNext,261,90 block_count,AsyncFunctionEnter,0,0 block_count,AsyncFunctionEnter,1,0 block_count,AsyncFunctionEnter,2,0 @@ -22168,14 +22127,14 @@ block_count,GlobalIsNaN,8,0 block_count,GlobalIsNaN,9,0 block_count,GlobalIsNaN,10,0 -block_count,LoadIC,0,2817 -block_count,LoadIC,1,2816 +block_count,LoadIC,0,2808 +block_count,LoadIC,1,2807 block_count,LoadIC,2,0 -block_count,LoadIC,3,2817 -block_count,LoadIC,4,2817 -block_count,LoadIC,5,831 +block_count,LoadIC,3,2808 +block_count,LoadIC,4,2808 +block_count,LoadIC,5,823 block_count,LoadIC,6,0 -block_count,LoadIC,7,830 +block_count,LoadIC,7,822 block_count,LoadIC,8,144 block_count,LoadIC,9,1 block_count,LoadIC,10,1 @@ -22190,36 +22149,36 @@ block_count,LoadIC,19,0 block_count,LoadIC,20,0 block_count,LoadIC,21,0 -block_count,LoadIC,22,142 -block_count,LoadIC,23,142 +block_count,LoadIC,22,143 +block_count,LoadIC,23,143 block_count,LoadIC,24,0 -block_count,LoadIC,25,142 -block_count,LoadIC,26,119 -block_count,LoadIC,27,118 +block_count,LoadIC,25,143 +block_count,LoadIC,26,122 +block_count,LoadIC,27,120 block_count,LoadIC,28,1 -block_count,LoadIC,29,23 -block_count,LoadIC,30,24 -block_count,LoadIC,31,23 -block_count,LoadIC,32,23 +block_count,LoadIC,29,21 +block_count,LoadIC,30,23 +block_count,LoadIC,31,21 +block_count,LoadIC,32,21 block_count,LoadIC,33,0 block_count,LoadIC,34,1 -block_count,LoadIC,35,686 -block_count,LoadIC,36,1115 -block_count,LoadIC,37,429 -block_count,LoadIC,38,429 +block_count,LoadIC,35,677 +block_count,LoadIC,36,1099 +block_count,LoadIC,37,421 +block_count,LoadIC,38,421 block_count,LoadIC,39,0 -block_count,LoadIC,40,686 -block_count,LoadIC,41,1986 -block_count,LoadIC,42,2813 -block_count,LoadIC,43,904 -block_count,LoadIC,44,899 -block_count,LoadIC,45,690 -block_count,LoadIC,46,689 +block_count,LoadIC,40,677 +block_count,LoadIC,41,1985 +block_count,LoadIC,42,2804 +block_count,LoadIC,43,895 +block_count,LoadIC,44,890 +block_count,LoadIC,45,682 +block_count,LoadIC,46,681 block_count,LoadIC,47,0 -block_count,LoadIC,48,689 +block_count,LoadIC,48,681 block_count,LoadIC,49,0 -block_count,LoadIC,50,689 -block_count,LoadIC,51,75 +block_count,LoadIC,50,682 +block_count,LoadIC,51,73 block_count,LoadIC,52,32 block_count,LoadIC,53,32 block_count,LoadIC,54,0 @@ -22276,8 +22235,8 @@ block_count,LoadIC,105,0 block_count,LoadIC,106,0 block_count,LoadIC,107,1 -block_count,LoadIC,108,42 -block_count,LoadIC,109,42 +block_count,LoadIC,108,41 +block_count,LoadIC,109,41 block_count,LoadIC,110,0 block_count,LoadIC,111,0 block_count,LoadIC,112,0 @@ -22289,27 +22248,27 @@ block_count,LoadIC,118,0 block_count,LoadIC,119,0 block_count,LoadIC,120,0 -block_count,LoadIC,121,42 +block_count,LoadIC,121,41 block_count,LoadIC,122,0 -block_count,LoadIC,123,614 -block_count,LoadIC,124,688 -block_count,LoadIC,125,688 -block_count,LoadIC,126,639 -block_count,LoadIC,127,639 +block_count,LoadIC,123,608 +block_count,LoadIC,124,680 +block_count,LoadIC,125,680 +block_count,LoadIC,126,631 +block_count,LoadIC,127,631 block_count,LoadIC,128,0 block_count,LoadIC,129,48 -block_count,LoadIC,130,688 +block_count,LoadIC,130,680 block_count,LoadIC,131,0 -block_count,LoadIC,132,209 +block_count,LoadIC,132,208 block_count,LoadIC,133,4 block_count,LoadIC,134,4 block_count,LoadIC,135,0 block_count,LoadIC,136,1909 -block_count,LoadIC,137,2597 -block_count,LoadIC,138,923 -block_count,LoadIC,139,379 -block_count,LoadIC,140,330 -block_count,LoadIC,141,119 +block_count,LoadIC,137,2589 +block_count,LoadIC,138,915 +block_count,LoadIC,139,376 +block_count,LoadIC,140,328 +block_count,LoadIC,141,117 block_count,LoadIC,142,25 block_count,LoadIC,143,2 block_count,LoadIC,144,2 @@ -22379,7 +22338,7 @@ block_count,LoadIC,208,0 block_count,LoadIC,209,0 block_count,LoadIC,210,23 -block_count,LoadIC,211,94 +block_count,LoadIC,211,92 block_count,LoadIC,212,210 block_count,LoadIC,213,210 block_count,LoadIC,214,0 @@ -22437,19 +22396,19 @@ block_count,LoadIC,266,0 block_count,LoadIC,267,210 block_count,LoadIC,268,48 -block_count,LoadIC,269,544 -block_count,LoadIC,270,1674 -block_count,LoadIC,271,1674 -block_count,LoadIC,272,449 -block_count,LoadIC,273,1225 -block_count,LoadIC,274,1674 +block_count,LoadIC,269,538 +block_count,LoadIC,270,1673 +block_count,LoadIC,271,1673 +block_count,LoadIC,272,451 +block_count,LoadIC,273,1222 +block_count,LoadIC,274,1673 block_count,LoadIC,275,1582 -block_count,LoadIC,276,92 -block_count,LoadIC,277,92 -block_count,LoadIC,278,92 +block_count,LoadIC,276,91 +block_count,LoadIC,277,91 +block_count,LoadIC,278,91 block_count,LoadIC,279,0 -block_count,LoadIC,280,92 -block_count,LoadIC,281,92 +block_count,LoadIC,280,91 +block_count,LoadIC,281,91 block_count,LoadIC,282,0 block_count,LoadIC,283,0 block_count,LoadIC,284,0 @@ -22492,31 +22451,31 @@ block_count,LoadIC,321,0 block_count,LoadIC,322,0 block_count,LoadIC,323,3 -block_count,LoadIC_Megamorphic,0,8810 -block_count,LoadIC_Megamorphic,1,8809 +block_count,LoadIC_Megamorphic,0,8808 +block_count,LoadIC_Megamorphic,1,8807 block_count,LoadIC_Megamorphic,2,1 -block_count,LoadIC_Megamorphic,3,8810 -block_count,LoadIC_Megamorphic,4,8810 +block_count,LoadIC_Megamorphic,3,8808 +block_count,LoadIC_Megamorphic,4,8808 block_count,LoadIC_Megamorphic,5,0 -block_count,LoadIC_Megamorphic,6,8810 -block_count,LoadIC_Megamorphic,7,7283 -block_count,LoadIC_Megamorphic,8,7213 -block_count,LoadIC_Megamorphic,9,69 -block_count,LoadIC_Megamorphic,10,1527 -block_count,LoadIC_Megamorphic,11,1596 -block_count,LoadIC_Megamorphic,12,1582 -block_count,LoadIC_Megamorphic,13,1579 +block_count,LoadIC_Megamorphic,6,8808 +block_count,LoadIC_Megamorphic,7,7524 +block_count,LoadIC_Megamorphic,8,7440 +block_count,LoadIC_Megamorphic,9,84 +block_count,LoadIC_Megamorphic,10,1283 +block_count,LoadIC_Megamorphic,11,1368 +block_count,LoadIC_Megamorphic,12,1353 +block_count,LoadIC_Megamorphic,13,1351 block_count,LoadIC_Megamorphic,14,2 block_count,LoadIC_Megamorphic,15,14 -block_count,LoadIC_Megamorphic,16,8793 -block_count,LoadIC_Megamorphic,17,3218 -block_count,LoadIC_Megamorphic,18,3218 -block_count,LoadIC_Megamorphic,19,3208 -block_count,LoadIC_Megamorphic,20,3208 +block_count,LoadIC_Megamorphic,16,8791 +block_count,LoadIC_Megamorphic,17,3216 +block_count,LoadIC_Megamorphic,18,3216 +block_count,LoadIC_Megamorphic,19,3206 +block_count,LoadIC_Megamorphic,20,3206 block_count,LoadIC_Megamorphic,21,0 -block_count,LoadIC_Megamorphic,22,3208 +block_count,LoadIC_Megamorphic,22,3206 block_count,LoadIC_Megamorphic,23,0 -block_count,LoadIC_Megamorphic,24,3208 +block_count,LoadIC_Megamorphic,24,3206 block_count,LoadIC_Megamorphic,25,7 block_count,LoadIC_Megamorphic,26,4 block_count,LoadIC_Megamorphic,27,4 @@ -22589,22 +22548,22 @@ block_count,LoadIC_Megamorphic,94,0 block_count,LoadIC_Megamorphic,95,3 block_count,LoadIC_Megamorphic,96,0 -block_count,LoadIC_Megamorphic,97,3200 -block_count,LoadIC_Megamorphic,98,3208 -block_count,LoadIC_Megamorphic,99,3206 -block_count,LoadIC_Megamorphic,100,2523 -block_count,LoadIC_Megamorphic,101,2523 +block_count,LoadIC_Megamorphic,97,3199 +block_count,LoadIC_Megamorphic,98,3206 +block_count,LoadIC_Megamorphic,99,3204 +block_count,LoadIC_Megamorphic,100,2521 +block_count,LoadIC_Megamorphic,101,2521 block_count,LoadIC_Megamorphic,102,0 -block_count,LoadIC_Megamorphic,103,683 -block_count,LoadIC_Megamorphic,104,3206 +block_count,LoadIC_Megamorphic,103,682 +block_count,LoadIC_Megamorphic,104,3204 block_count,LoadIC_Megamorphic,105,1 block_count,LoadIC_Megamorphic,106,10 block_count,LoadIC_Megamorphic,107,0 block_count,LoadIC_Megamorphic,108,0 block_count,LoadIC_Megamorphic,109,0 block_count,LoadIC_Megamorphic,110,5574 -block_count,LoadIC_Megamorphic,111,8781 -block_count,LoadIC_Megamorphic,112,3827 +block_count,LoadIC_Megamorphic,111,8778 +block_count,LoadIC_Megamorphic,112,3825 block_count,LoadIC_Megamorphic,113,2009 block_count,LoadIC_Megamorphic,114,1326 block_count,LoadIC_Megamorphic,115,1321 @@ -22734,11 +22693,11 @@ block_count,LoadIC_Megamorphic,239,0 block_count,LoadIC_Megamorphic,240,0 block_count,LoadIC_Megamorphic,241,5 -block_count,LoadIC_Megamorphic,242,683 -block_count,LoadIC_Megamorphic,243,1817 +block_count,LoadIC_Megamorphic,242,682 +block_count,LoadIC_Megamorphic,243,1816 block_count,LoadIC_Megamorphic,244,4953 block_count,LoadIC_Megamorphic,245,4953 -block_count,LoadIC_Megamorphic,246,260 +block_count,LoadIC_Megamorphic,246,261 block_count,LoadIC_Megamorphic,247,4692 block_count,LoadIC_Megamorphic,248,4953 block_count,LoadIC_Megamorphic,249,4934 @@ -23102,15 +23061,15 @@ block_count,LoadIC_Noninlined,309,0 block_count,LoadIC_Noninlined,310,0 block_count,LoadIC_Noninlined,311,1 -block_count,LoadICTrampoline,0,267 -block_count,LoadICTrampoline,1,267 +block_count,LoadICTrampoline,0,273 +block_count,LoadICTrampoline,1,273 block_count,LoadICTrampoline,2,0 -block_count,LoadICTrampoline,3,267 -block_count,LoadICBaseline,0,2260 -block_count,LoadICTrampoline_Megamorphic,0,5080 -block_count,LoadICTrampoline_Megamorphic,1,5080 +block_count,LoadICTrampoline,3,273 +block_count,LoadICBaseline,0,2252 +block_count,LoadICTrampoline_Megamorphic,0,5532 +block_count,LoadICTrampoline_Megamorphic,1,5532 block_count,LoadICTrampoline_Megamorphic,2,0 -block_count,LoadICTrampoline_Megamorphic,3,5080 +block_count,LoadICTrampoline_Megamorphic,3,5532 block_count,LoadSuperIC,0,2 block_count,LoadSuperIC,1,2 block_count,LoadSuperIC,2,2 @@ -23707,16 +23666,16 @@ block_count,LoadSuperIC,593,0 block_count,LoadSuperIC,594,0 block_count,LoadSuperICBaseline,0,2 -block_count,KeyedLoadIC,0,336 -block_count,KeyedLoadIC,1,336 +block_count,KeyedLoadIC,0,330 +block_count,KeyedLoadIC,1,330 block_count,KeyedLoadIC,2,0 -block_count,KeyedLoadIC,3,336 -block_count,KeyedLoadIC,4,336 -block_count,KeyedLoadIC,5,333 -block_count,KeyedLoadIC,6,45 +block_count,KeyedLoadIC,3,330 +block_count,KeyedLoadIC,4,330 +block_count,KeyedLoadIC,5,328 +block_count,KeyedLoadIC,6,44 block_count,KeyedLoadIC,7,0 -block_count,KeyedLoadIC,8,45 -block_count,KeyedLoadIC,9,25 +block_count,KeyedLoadIC,8,44 +block_count,KeyedLoadIC,9,24 block_count,KeyedLoadIC,10,1 block_count,KeyedLoadIC,11,1 block_count,KeyedLoadIC,12,0 @@ -23758,13 +23717,13 @@ block_count,KeyedLoadIC,48,0 block_count,KeyedLoadIC,49,23 block_count,KeyedLoadIC,50,19 -block_count,KeyedLoadIC,51,32 +block_count,KeyedLoadIC,51,31 block_count,KeyedLoadIC,52,12 block_count,KeyedLoadIC,53,12 block_count,KeyedLoadIC,54,0 block_count,KeyedLoadIC,55,19 -block_count,KeyedLoadIC,56,288 -block_count,KeyedLoadIC,57,308 +block_count,KeyedLoadIC,56,283 +block_count,KeyedLoadIC,57,303 block_count,KeyedLoadIC,58,1 block_count,KeyedLoadIC,59,1 block_count,KeyedLoadIC,60,0 @@ -23858,9 +23817,9 @@ block_count,KeyedLoadIC,148,0 block_count,KeyedLoadIC,149,0 block_count,KeyedLoadIC,150,0 -block_count,KeyedLoadIC,151,306 -block_count,KeyedLoadIC,152,306 -block_count,KeyedLoadIC,153,2 +block_count,KeyedLoadIC,151,301 +block_count,KeyedLoadIC,152,301 +block_count,KeyedLoadIC,153,3 block_count,KeyedLoadIC,154,0 block_count,KeyedLoadIC,155,0 block_count,KeyedLoadIC,156,0 @@ -24077,7 +24036,7 @@ block_count,KeyedLoadIC,367,0 block_count,KeyedLoadIC,368,0 block_count,KeyedLoadIC,369,0 -block_count,KeyedLoadIC,370,2 +block_count,KeyedLoadIC,370,3 block_count,KeyedLoadIC,371,0 block_count,KeyedLoadIC,372,0 block_count,KeyedLoadIC,373,0 @@ -24085,19 +24044,19 @@ block_count,KeyedLoadIC,375,0 block_count,KeyedLoadIC,376,0 block_count,KeyedLoadIC,377,0 -block_count,KeyedLoadIC,378,2 -block_count,KeyedLoadIC,379,2 -block_count,KeyedLoadIC,380,2 -block_count,KeyedLoadIC,381,4 -block_count,KeyedLoadIC,382,1 -block_count,KeyedLoadIC,383,1 +block_count,KeyedLoadIC,378,3 +block_count,KeyedLoadIC,379,3 +block_count,KeyedLoadIC,380,3 +block_count,KeyedLoadIC,381,5 +block_count,KeyedLoadIC,382,2 +block_count,KeyedLoadIC,383,2 block_count,KeyedLoadIC,384,0 block_count,KeyedLoadIC,385,0 block_count,KeyedLoadIC,386,0 -block_count,KeyedLoadIC,387,1 -block_count,KeyedLoadIC,388,1 +block_count,KeyedLoadIC,387,2 +block_count,KeyedLoadIC,388,2 block_count,KeyedLoadIC,389,0 -block_count,KeyedLoadIC,390,1 +block_count,KeyedLoadIC,390,2 block_count,KeyedLoadIC,391,0 block_count,KeyedLoadIC,392,0 block_count,KeyedLoadIC,393,0 @@ -24108,16 +24067,16 @@ block_count,KeyedLoadIC,398,0 block_count,KeyedLoadIC,399,0 block_count,KeyedLoadIC,400,0 -block_count,KeyedLoadIC,401,2 -block_count,KeyedLoadIC,402,2 +block_count,KeyedLoadIC,401,3 +block_count,KeyedLoadIC,402,3 block_count,KeyedLoadIC,403,0 -block_count,KeyedLoadIC,404,2 -block_count,KeyedLoadIC,405,2 +block_count,KeyedLoadIC,404,3 +block_count,KeyedLoadIC,405,3 block_count,KeyedLoadIC,406,0 block_count,KeyedLoadIC,407,0 block_count,KeyedLoadIC,408,0 block_count,KeyedLoadIC,409,0 -block_count,KeyedLoadIC,410,2 +block_count,KeyedLoadIC,410,3 block_count,KeyedLoadIC,411,0 block_count,KeyedLoadIC,412,0 block_count,KeyedLoadIC,413,0 @@ -24125,7 +24084,7 @@ block_count,KeyedLoadIC,415,0 block_count,KeyedLoadIC,416,0 block_count,KeyedLoadIC,417,0 -block_count,KeyedLoadIC,418,303 +block_count,KeyedLoadIC,418,297 block_count,KeyedLoadIC,419,0 block_count,KeyedLoadIC,420,0 block_count,KeyedLoadIC,421,0 @@ -24138,43 +24097,43 @@ block_count,KeyedLoadIC,428,0 block_count,KeyedLoadIC,429,0 block_count,KeyedLoadIC,430,0 -block_count,KeyedLoadIC,431,303 -block_count,KeyedLoadIC,432,303 -block_count,KeyedLoadIC,433,303 -block_count,KeyedLoadIC,434,184 +block_count,KeyedLoadIC,431,297 +block_count,KeyedLoadIC,432,297 +block_count,KeyedLoadIC,433,297 +block_count,KeyedLoadIC,434,179 block_count,KeyedLoadIC,435,4 -block_count,KeyedLoadIC,436,179 -block_count,KeyedLoadIC,437,184 +block_count,KeyedLoadIC,436,174 +block_count,KeyedLoadIC,437,179 block_count,KeyedLoadIC,438,0 -block_count,KeyedLoadIC,439,183 +block_count,KeyedLoadIC,439,178 block_count,KeyedLoadIC,440,0 block_count,KeyedLoadIC,441,10 -block_count,KeyedLoadIC,442,104 +block_count,KeyedLoadIC,442,101 block_count,KeyedLoadIC,443,0 block_count,KeyedLoadIC,444,0 block_count,KeyedLoadIC,445,0 block_count,KeyedLoadIC,446,0 -block_count,KeyedLoadIC,447,114 +block_count,KeyedLoadIC,447,112 block_count,KeyedLoadIC,448,6 -block_count,KeyedLoadIC,449,32 +block_count,KeyedLoadIC,449,31 block_count,KeyedLoadIC,450,0 block_count,KeyedLoadIC,451,0 block_count,KeyedLoadIC,452,0 -block_count,KeyedLoadIC,453,39 -block_count,KeyedLoadIC,454,37 +block_count,KeyedLoadIC,453,38 +block_count,KeyedLoadIC,454,36 block_count,KeyedLoadIC,455,1 block_count,KeyedLoadIC,456,15 block_count,KeyedLoadIC,457,0 block_count,KeyedLoadIC,458,15 block_count,KeyedLoadIC,459,15 -block_count,KeyedLoadIC,460,13 -block_count,KeyedLoadIC,461,13 +block_count,KeyedLoadIC,460,12 +block_count,KeyedLoadIC,461,12 block_count,KeyedLoadIC,462,0 -block_count,KeyedLoadIC,463,13 -block_count,KeyedLoadIC,464,13 +block_count,KeyedLoadIC,463,12 +block_count,KeyedLoadIC,464,12 block_count,KeyedLoadIC,465,0 -block_count,KeyedLoadIC,466,119 -block_count,KeyedLoadIC,467,119 +block_count,KeyedLoadIC,466,118 +block_count,KeyedLoadIC,467,118 block_count,KeyedLoadIC,468,0 block_count,KeyedLoadIC,469,0 block_count,KeyedLoadIC,470,0 @@ -24197,18 +24156,18 @@ block_count,KeyedLoadIC,487,0 block_count,KeyedLoadIC,488,0 block_count,KeyedLoadIC,489,0 -block_count,KeyedLoadIC,490,119 -block_count,KeyedLoadIC,491,119 +block_count,KeyedLoadIC,490,118 +block_count,KeyedLoadIC,491,118 block_count,KeyedLoadIC,492,0 -block_count,KeyedLoadIC,493,119 +block_count,KeyedLoadIC,493,118 block_count,KeyedLoadIC,494,0 -block_count,KeyedLoadIC,495,14 +block_count,KeyedLoadIC,495,13 block_count,KeyedLoadIC,496,0 block_count,KeyedLoadIC,497,0 block_count,KeyedLoadIC,498,3 block_count,KeyedLoadIC,499,0 -block_count,KeyedLoadIC,500,0 -block_count,KeyedLoadIC,501,83 +block_count,KeyedLoadIC,500,1 +block_count,KeyedLoadIC,501,82 block_count,KeyedLoadIC,502,17 block_count,KeyedLoadIC,503,0 block_count,KeyedLoadIC,504,0 @@ -24262,14 +24221,14 @@ block_count,KeyedLoadIC,552,0 block_count,KeyedLoadIC,553,0 block_count,KeyedLoadIC,554,0 -block_count,KeyedLoadIC,555,0 +block_count,KeyedLoadIC,555,1 block_count,KeyedLoadIC,556,0 block_count,KeyedLoadIC,557,0 block_count,KeyedLoadIC,558,0 block_count,KeyedLoadIC,559,0 block_count,KeyedLoadIC,560,0 -block_count,KeyedLoadIC,561,83 -block_count,KeyedLoadIC,562,82 +block_count,KeyedLoadIC,561,82 +block_count,KeyedLoadIC,562,81 block_count,KeyedLoadIC,563,0 block_count,KeyedLoadIC,564,0 block_count,KeyedLoadIC,565,0 @@ -24321,7 +24280,7 @@ block_count,KeyedLoadIC,611,0 block_count,KeyedLoadIC,612,0 block_count,KeyedLoadIC,613,0 -block_count,KeyedLoadIC,614,2 +block_count,KeyedLoadIC,614,1 block_count,KeyedLoadIC,615,1 block_count,KeyedLoadIC,616,1 block_count,KeyedLoadIC,617,0 @@ -24338,7 +24297,7 @@ block_count,KeyedLoadIC,628,0 block_count,KeyedLoadIC,629,0 block_count,KeyedLoadIC,630,2 -block_count,KeyedLoadIC,631,26 +block_count,KeyedLoadIC,631,25 block_count,KeyedLoadIC,632,0 block_count,KeyedLoadIC,633,0 block_count,EnumeratedKeyedLoadIC,0,4 @@ -25020,12 +24979,12 @@ block_count,KeyedLoadIC_Megamorphic,16,1777 block_count,KeyedLoadIC_Megamorphic,17,1692 block_count,KeyedLoadIC_Megamorphic,18,1692 -block_count,KeyedLoadIC_Megamorphic,19,1627 +block_count,KeyedLoadIC_Megamorphic,19,1628 block_count,KeyedLoadIC_Megamorphic,20,0 block_count,KeyedLoadIC_Megamorphic,21,0 block_count,KeyedLoadIC_Megamorphic,22,0 -block_count,KeyedLoadIC_Megamorphic,23,1627 -block_count,KeyedLoadIC_Megamorphic,24,888 +block_count,KeyedLoadIC_Megamorphic,23,1628 +block_count,KeyedLoadIC_Megamorphic,24,889 block_count,KeyedLoadIC_Megamorphic,25,739 block_count,KeyedLoadIC_Megamorphic,26,64 block_count,KeyedLoadIC_Megamorphic,27,0 @@ -25229,7 +25188,7 @@ block_count,KeyedLoadIC_Megamorphic,225,26 block_count,KeyedLoadIC_Megamorphic,226,659 block_count,KeyedLoadIC_Megamorphic,227,2674 -block_count,KeyedLoadIC_Megamorphic,228,2613 +block_count,KeyedLoadIC_Megamorphic,228,2612 block_count,KeyedLoadIC_Megamorphic,229,2537 block_count,KeyedLoadIC_Megamorphic,230,2015 block_count,KeyedLoadIC_Megamorphic,231,522 @@ -25419,13 +25378,13 @@ block_count,KeyedLoadIC_Megamorphic,415,98 block_count,KeyedLoadIC_Megamorphic,416,0 block_count,KeyedLoadIC_Megamorphic,417,98 -block_count,KeyedLoadIC_Megamorphic,418,75 -block_count,KeyedLoadIC_Megamorphic,419,75 +block_count,KeyedLoadIC_Megamorphic,418,74 +block_count,KeyedLoadIC_Megamorphic,419,74 block_count,KeyedLoadIC_Megamorphic,420,0 -block_count,KeyedLoadIC_Megamorphic,421,23 -block_count,KeyedLoadIC_Megamorphic,422,23 -block_count,KeyedLoadIC_Megamorphic,423,9 -block_count,KeyedLoadIC_Megamorphic,424,9 +block_count,KeyedLoadIC_Megamorphic,421,24 +block_count,KeyedLoadIC_Megamorphic,422,24 +block_count,KeyedLoadIC_Megamorphic,423,10 +block_count,KeyedLoadIC_Megamorphic,424,10 block_count,KeyedLoadIC_Megamorphic,425,0 block_count,KeyedLoadIC_Megamorphic,426,14 block_count,KeyedLoadIC_Megamorphic,427,84 @@ -25947,7 +25906,7 @@ block_count,KeyedLoadIC_Megamorphic,943,286 block_count,KeyedLoadIC_Megamorphic,944,352 block_count,KeyedLoadIC_Megamorphic,945,8 -block_count,KeyedLoadIC_Megamorphic,946,344 +block_count,KeyedLoadIC_Megamorphic,946,343 block_count,KeyedLoadIC_Megamorphic,947,0 block_count,KeyedLoadIC_Megamorphic,948,0 block_count,KeyedLoadIC_Megamorphic,949,280 @@ -26143,18 +26102,18 @@ block_count,KeyedLoadICTrampoline,1,1 block_count,KeyedLoadICTrampoline,2,0 block_count,KeyedLoadICTrampoline,3,1 -block_count,KeyedLoadICBaseline,0,315 +block_count,KeyedLoadICBaseline,0,310 block_count,EnumeratedKeyedLoadICBaseline,0,2 -block_count,KeyedLoadICTrampoline_Megamorphic,0,722 -block_count,KeyedLoadICTrampoline_Megamorphic,1,722 +block_count,KeyedLoadICTrampoline_Megamorphic,0,720 +block_count,KeyedLoadICTrampoline_Megamorphic,1,720 block_count,KeyedLoadICTrampoline_Megamorphic,2,0 -block_count,KeyedLoadICTrampoline_Megamorphic,3,722 -block_count,StoreGlobalIC,0,334 -block_count,StoreGlobalIC,1,334 -block_count,StoreGlobalIC,2,334 -block_count,StoreGlobalIC,3,334 -block_count,StoreGlobalIC,4,334 -block_count,StoreGlobalIC,5,334 +block_count,KeyedLoadICTrampoline_Megamorphic,3,720 +block_count,StoreGlobalIC,0,528 +block_count,StoreGlobalIC,1,528 +block_count,StoreGlobalIC,2,528 +block_count,StoreGlobalIC,3,528 +block_count,StoreGlobalIC,4,528 +block_count,StoreGlobalIC,5,528 block_count,StoreGlobalIC,6,1 block_count,StoreGlobalIC,7,0 block_count,StoreGlobalIC,8,0 @@ -26164,7 +26123,7 @@ block_count,StoreGlobalIC,12,1 block_count,StoreGlobalIC,13,0 block_count,StoreGlobalIC,14,1 -block_count,StoreGlobalIC,15,332 +block_count,StoreGlobalIC,15,526 block_count,StoreGlobalIC,16,0 block_count,StoreGlobalIC,17,0 block_count,StoreGlobalIC,18,0 @@ -26592,10 +26551,10 @@ block_count,StoreGlobalIC,440,0 block_count,StoreGlobalIC,441,0 block_count,StoreGlobalIC,442,0 -block_count,StoreGlobalICTrampoline,0,0 -block_count,StoreGlobalICTrampoline,1,0 +block_count,StoreGlobalICTrampoline,0,194 +block_count,StoreGlobalICTrampoline,1,194 block_count,StoreGlobalICTrampoline,2,0 -block_count,StoreGlobalICTrampoline,3,0 +block_count,StoreGlobalICTrampoline,3,194 block_count,StoreGlobalICBaseline,0,1 block_count,StoreIC,0,333 block_count,StoreIC,1,333 @@ -26603,9 +26562,9 @@ block_count,StoreIC,3,333 block_count,StoreIC,4,333 block_count,StoreIC,5,327 -block_count,StoreIC,6,110 +block_count,StoreIC,6,109 block_count,StoreIC,7,0 -block_count,StoreIC,8,110 +block_count,StoreIC,8,109 block_count,StoreIC,9,26 block_count,StoreIC,10,0 block_count,StoreIC,11,26 @@ -26613,23 +26572,23 @@ block_count,StoreIC,13,0 block_count,StoreIC,14,26 block_count,StoreIC,15,25 -block_count,StoreIC,16,25 +block_count,StoreIC,16,24 block_count,StoreIC,17,0 -block_count,StoreIC,18,0 +block_count,StoreIC,18,1 block_count,StoreIC,19,1 -block_count,StoreIC,20,0 -block_count,StoreIC,21,0 +block_count,StoreIC,20,1 +block_count,StoreIC,21,1 block_count,StoreIC,22,0 block_count,StoreIC,23,0 -block_count,StoreIC,24,83 -block_count,StoreIC,25,135 +block_count,StoreIC,24,82 +block_count,StoreIC,25,134 block_count,StoreIC,26,51 block_count,StoreIC,27,51 block_count,StoreIC,28,0 -block_count,StoreIC,29,83 -block_count,StoreIC,30,216 +block_count,StoreIC,29,82 +block_count,StoreIC,30,218 block_count,StoreIC,31,326 -block_count,StoreIC,32,125 +block_count,StoreIC,32,127 block_count,StoreIC,33,4 block_count,StoreIC,34,4 block_count,StoreIC,35,4 @@ -26770,42 +26729,42 @@ block_count,StoreIC,170,0 block_count,StoreIC,171,0 block_count,StoreIC,172,0 -block_count,StoreIC,173,120 -block_count,StoreIC,174,120 -block_count,StoreIC,175,110 -block_count,StoreIC,176,110 -block_count,StoreIC,177,110 +block_count,StoreIC,173,123 +block_count,StoreIC,174,123 +block_count,StoreIC,175,113 +block_count,StoreIC,176,113 +block_count,StoreIC,177,113 block_count,StoreIC,178,0 -block_count,StoreIC,179,110 +block_count,StoreIC,179,113 block_count,StoreIC,180,0 -block_count,StoreIC,181,110 -block_count,StoreIC,182,110 +block_count,StoreIC,181,113 +block_count,StoreIC,182,113 block_count,StoreIC,183,0 block_count,StoreIC,184,0 block_count,StoreIC,185,0 -block_count,StoreIC,186,110 -block_count,StoreIC,187,94 -block_count,StoreIC,188,92 -block_count,StoreIC,189,2 -block_count,StoreIC,190,2 +block_count,StoreIC,186,113 +block_count,StoreIC,187,96 +block_count,StoreIC,188,94 +block_count,StoreIC,189,3 +block_count,StoreIC,190,3 block_count,StoreIC,191,0 -block_count,StoreIC,192,90 -block_count,StoreIC,193,90 +block_count,StoreIC,192,91 +block_count,StoreIC,193,91 block_count,StoreIC,194,14 block_count,StoreIC,195,0 block_count,StoreIC,196,14 -block_count,StoreIC,197,75 +block_count,StoreIC,197,76 block_count,StoreIC,198,0 block_count,StoreIC,199,1 block_count,StoreIC,200,1 block_count,StoreIC,201,1 block_count,StoreIC,202,0 block_count,StoreIC,203,0 -block_count,StoreIC,204,16 +block_count,StoreIC,204,17 block_count,StoreIC,205,0 -block_count,StoreIC,206,16 -block_count,StoreIC,207,110 -block_count,StoreIC,208,22 +block_count,StoreIC,206,17 +block_count,StoreIC,207,113 +block_count,StoreIC,208,24 block_count,StoreIC,209,0 block_count,StoreIC,210,0 block_count,StoreIC,211,0 @@ -26813,43 +26772,43 @@ block_count,StoreIC,213,0 block_count,StoreIC,214,0 block_count,StoreIC,215,0 -block_count,StoreIC,216,22 -block_count,StoreIC,217,22 -block_count,StoreIC,218,22 +block_count,StoreIC,216,24 +block_count,StoreIC,217,24 +block_count,StoreIC,218,24 block_count,StoreIC,219,0 -block_count,StoreIC,220,22 -block_count,StoreIC,221,10 -block_count,StoreIC,222,10 +block_count,StoreIC,220,24 +block_count,StoreIC,221,11 +block_count,StoreIC,222,11 block_count,StoreIC,223,0 -block_count,StoreIC,224,10 +block_count,StoreIC,224,11 block_count,StoreIC,225,0 block_count,StoreIC,226,0 -block_count,StoreIC,227,10 +block_count,StoreIC,227,11 block_count,StoreIC,228,0 -block_count,StoreIC,229,10 +block_count,StoreIC,229,11 block_count,StoreIC,230,0 -block_count,StoreIC,231,10 -block_count,StoreIC,232,10 +block_count,StoreIC,231,11 +block_count,StoreIC,232,11 block_count,StoreIC,233,0 -block_count,StoreIC,234,10 -block_count,StoreIC,235,10 +block_count,StoreIC,234,11 +block_count,StoreIC,235,11 block_count,StoreIC,236,0 -block_count,StoreIC,237,10 -block_count,StoreIC,238,10 +block_count,StoreIC,237,11 +block_count,StoreIC,238,11 block_count,StoreIC,239,7 block_count,StoreIC,240,3 block_count,StoreIC,241,0 block_count,StoreIC,242,3 -block_count,StoreIC,243,7 +block_count,StoreIC,243,8 block_count,StoreIC,244,4 block_count,StoreIC,245,3 block_count,StoreIC,246,3 -block_count,StoreIC,247,0 +block_count,StoreIC,247,1 block_count,StoreIC,248,2 -block_count,StoreIC,249,10 -block_count,StoreIC,250,12 -block_count,StoreIC,251,22 -block_count,StoreIC,252,87 +block_count,StoreIC,249,11 +block_count,StoreIC,250,13 +block_count,StoreIC,251,24 +block_count,StoreIC,252,88 block_count,StoreIC,253,86 block_count,StoreIC,254,1 block_count,StoreIC,255,1 @@ -26878,7 +26837,7 @@ block_count,StoreIC,278,0 block_count,StoreIC,279,0 block_count,StoreIC,280,0 -block_count,StoreIC,281,201 +block_count,StoreIC,281,199 block_count,StoreIC,282,12 block_count,StoreIC,283,12 block_count,StoreIC,284,12 @@ -26903,9 +26862,9 @@ block_count,StoreIC,303,0 block_count,StoreIC,304,0 block_count,StoreIC,305,0 -block_count,StoreIC,306,188 -block_count,StoreIC,307,171 -block_count,StoreIC,308,171 +block_count,StoreIC,306,186 +block_count,StoreIC,307,169 +block_count,StoreIC,308,169 block_count,StoreIC,309,20 block_count,StoreIC,310,19 block_count,StoreIC,311,19 @@ -26931,30 +26890,30 @@ block_count,StoreIC,331,0 block_count,StoreIC,332,0 block_count,StoreIC,333,0 -block_count,StoreIC,334,81 -block_count,StoreIC,335,81 -block_count,StoreIC,336,81 +block_count,StoreIC,334,80 +block_count,StoreIC,335,80 +block_count,StoreIC,336,80 block_count,StoreIC,337,3 block_count,StoreIC,338,0 block_count,StoreIC,339,3 block_count,StoreIC,340,77 block_count,StoreIC,341,0 -block_count,StoreIC,342,81 -block_count,StoreIC,343,20 -block_count,StoreIC,344,60 -block_count,StoreIC,345,81 -block_count,StoreIC,346,81 +block_count,StoreIC,342,80 +block_count,StoreIC,343,19 +block_count,StoreIC,344,61 +block_count,StoreIC,345,80 +block_count,StoreIC,346,80 block_count,StoreIC,347,0 block_count,StoreIC,348,0 block_count,StoreIC,349,0 block_count,StoreIC,350,0 -block_count,StoreIC,351,67 +block_count,StoreIC,351,65 block_count,StoreIC,352,0 -block_count,StoreIC,353,67 -block_count,StoreIC,354,11 -block_count,StoreIC,355,56 -block_count,StoreIC,356,67 -block_count,StoreIC,357,67 +block_count,StoreIC,353,65 +block_count,StoreIC,354,10 +block_count,StoreIC,355,55 +block_count,StoreIC,356,65 +block_count,StoreIC,357,65 block_count,StoreIC,358,0 block_count,StoreIC,359,0 block_count,StoreIC,360,0 @@ -26988,16 +26947,16 @@ block_count,StoreIC_Megamorphic,4,1211 block_count,StoreIC_Megamorphic,5,0 block_count,StoreIC_Megamorphic,6,1211 -block_count,StoreIC_Megamorphic,7,1136 -block_count,StoreIC_Megamorphic,8,1111 -block_count,StoreIC_Megamorphic,9,24 -block_count,StoreIC_Megamorphic,10,74 -block_count,StoreIC_Megamorphic,11,99 -block_count,StoreIC_Megamorphic,12,98 -block_count,StoreIC_Megamorphic,13,96 +block_count,StoreIC_Megamorphic,7,1127 +block_count,StoreIC_Megamorphic,8,1072 +block_count,StoreIC_Megamorphic,9,54 +block_count,StoreIC_Megamorphic,10,84 +block_count,StoreIC_Megamorphic,11,139 +block_count,StoreIC_Megamorphic,12,138 +block_count,StoreIC_Megamorphic,13,136 block_count,StoreIC_Megamorphic,14,1 block_count,StoreIC_Megamorphic,15,0 -block_count,StoreIC_Megamorphic,16,1208 +block_count,StoreIC_Megamorphic,16,1209 block_count,StoreIC_Megamorphic,17,516 block_count,StoreIC_Megamorphic,18,1 block_count,StoreIC_Megamorphic,19,1 @@ -27141,18 +27100,18 @@ block_count,StoreIC_Megamorphic,157,0 block_count,StoreIC_Megamorphic,158,514 block_count,StoreIC_Megamorphic,159,514 -block_count,StoreIC_Megamorphic,160,343 -block_count,StoreIC_Megamorphic,161,343 -block_count,StoreIC_Megamorphic,162,343 +block_count,StoreIC_Megamorphic,160,344 +block_count,StoreIC_Megamorphic,161,344 +block_count,StoreIC_Megamorphic,162,344 block_count,StoreIC_Megamorphic,163,0 -block_count,StoreIC_Megamorphic,164,343 +block_count,StoreIC_Megamorphic,164,344 block_count,StoreIC_Megamorphic,165,0 -block_count,StoreIC_Megamorphic,166,343 -block_count,StoreIC_Megamorphic,167,343 +block_count,StoreIC_Megamorphic,166,344 +block_count,StoreIC_Megamorphic,167,344 block_count,StoreIC_Megamorphic,168,0 block_count,StoreIC_Megamorphic,169,0 block_count,StoreIC_Megamorphic,170,0 -block_count,StoreIC_Megamorphic,171,343 +block_count,StoreIC_Megamorphic,171,344 block_count,StoreIC_Megamorphic,172,208 block_count,StoreIC_Megamorphic,173,208 block_count,StoreIC_Megamorphic,174,0 @@ -27173,7 +27132,7 @@ block_count,StoreIC_Megamorphic,189,135 block_count,StoreIC_Megamorphic,190,0 block_count,StoreIC_Megamorphic,191,135 -block_count,StoreIC_Megamorphic,192,343 +block_count,StoreIC_Megamorphic,192,344 block_count,StoreIC_Megamorphic,193,26 block_count,StoreIC_Megamorphic,194,0 block_count,StoreIC_Megamorphic,195,0 @@ -27218,8 +27177,8 @@ block_count,StoreIC_Megamorphic,234,11 block_count,StoreIC_Megamorphic,235,14 block_count,StoreIC_Megamorphic,236,26 -block_count,StoreIC_Megamorphic,237,316 -block_count,StoreIC_Megamorphic,238,316 +block_count,StoreIC_Megamorphic,237,317 +block_count,StoreIC_Megamorphic,238,317 block_count,StoreIC_Megamorphic,239,0 block_count,StoreIC_Megamorphic,240,0 block_count,StoreIC_Megamorphic,241,0 @@ -27272,9 +27231,9 @@ block_count,StoreIC_Megamorphic,288,0 block_count,StoreIC_Megamorphic,289,0 block_count,StoreIC_Megamorphic,290,0 -block_count,StoreIC_Megamorphic,291,691 -block_count,StoreIC_Megamorphic,292,691 -block_count,StoreIC_Megamorphic,293,691 +block_count,StoreIC_Megamorphic,291,692 +block_count,StoreIC_Megamorphic,292,692 +block_count,StoreIC_Megamorphic,293,692 block_count,StoreIC_Megamorphic,294,5 block_count,StoreIC_Megamorphic,295,5 block_count,StoreIC_Megamorphic,296,5 @@ -27317,13 +27276,13 @@ block_count,StoreIC_Megamorphic,333,0 block_count,StoreIC_Megamorphic,334,0 block_count,StoreIC_Megamorphic,335,0 -block_count,StoreIC_Megamorphic,336,292 +block_count,StoreIC_Megamorphic,336,293 block_count,StoreIC_Megamorphic,337,0 -block_count,StoreIC_Megamorphic,338,292 +block_count,StoreIC_Megamorphic,338,293 block_count,StoreIC_Megamorphic,339,2 block_count,StoreIC_Megamorphic,340,290 -block_count,StoreIC_Megamorphic,341,292 -block_count,StoreIC_Megamorphic,342,292 +block_count,StoreIC_Megamorphic,341,293 +block_count,StoreIC_Megamorphic,342,293 block_count,StoreIC_Megamorphic,343,0 block_count,StoreIC_Megamorphic,344,0 block_count,StoreIC_Megamorphic,345,0 @@ -27356,13 +27315,13 @@ block_count,StoreICTrampoline_Megamorphic,1,573 block_count,StoreICTrampoline_Megamorphic,2,0 block_count,StoreICTrampoline_Megamorphic,3,573 -block_count,StoreICBaseline,0,278 -block_count,DefineNamedOwnIC,0,40 -block_count,DefineNamedOwnIC,1,40 +block_count,StoreICBaseline,0,277 +block_count,DefineNamedOwnIC,0,41 +block_count,DefineNamedOwnIC,1,41 block_count,DefineNamedOwnIC,2,0 -block_count,DefineNamedOwnIC,3,40 -block_count,DefineNamedOwnIC,4,40 -block_count,DefineNamedOwnIC,5,36 +block_count,DefineNamedOwnIC,3,41 +block_count,DefineNamedOwnIC,4,41 +block_count,DefineNamedOwnIC,5,37 block_count,DefineNamedOwnIC,6,0 block_count,DefineNamedOwnIC,7,0 block_count,DefineNamedOwnIC,8,0 @@ -27387,8 +27346,8 @@ block_count,DefineNamedOwnIC,27,0 block_count,DefineNamedOwnIC,28,0 block_count,DefineNamedOwnIC,29,0 -block_count,DefineNamedOwnIC,30,36 -block_count,DefineNamedOwnIC,31,36 +block_count,DefineNamedOwnIC,30,37 +block_count,DefineNamedOwnIC,31,37 block_count,DefineNamedOwnIC,32,0 block_count,DefineNamedOwnIC,33,0 block_count,DefineNamedOwnIC,34,0 @@ -27633,7 +27592,7 @@ block_count,DefineNamedOwnIC,273,0 block_count,DefineNamedOwnIC,274,0 block_count,DefineNamedOwnIC,275,0 -block_count,DefineNamedOwnIC,276,36 +block_count,DefineNamedOwnIC,276,37 block_count,DefineNamedOwnIC,277,0 block_count,DefineNamedOwnIC,278,0 block_count,DefineNamedOwnIC,279,0 @@ -27653,9 +27612,9 @@ block_count,DefineNamedOwnIC,293,0 block_count,DefineNamedOwnIC,294,0 block_count,DefineNamedOwnIC,295,0 -block_count,DefineNamedOwnIC,296,36 -block_count,DefineNamedOwnIC,297,36 -block_count,DefineNamedOwnIC,298,36 +block_count,DefineNamedOwnIC,296,37 +block_count,DefineNamedOwnIC,297,37 +block_count,DefineNamedOwnIC,298,37 block_count,DefineNamedOwnIC,299,0 block_count,DefineNamedOwnIC,300,0 block_count,DefineNamedOwnIC,301,0 @@ -27687,7 +27646,7 @@ block_count,DefineNamedOwnIC,327,4 block_count,DefineNamedOwnIC,328,0 block_count,DefineNamedOwnIC,329,4 -block_count,DefineNamedOwnIC,330,23 +block_count,DefineNamedOwnIC,330,24 block_count,DefineNamedOwnIC,331,0 block_count,DefineNamedOwnIC,332,28 block_count,DefineNamedOwnIC,333,0 @@ -27731,16 +27690,16 @@ block_count,DefineNamedOwnIC,371,3 block_count,DefineNamedOwnIC,372,0 block_count,DefineNamedOwnIC,373,0 -block_count,DefineNamedOwnICBaseline,0,35 -block_count,KeyedStoreIC,0,199 -block_count,KeyedStoreIC,1,199 +block_count,DefineNamedOwnICBaseline,0,36 +block_count,KeyedStoreIC,0,194 +block_count,KeyedStoreIC,1,194 block_count,KeyedStoreIC,2,0 -block_count,KeyedStoreIC,3,199 -block_count,KeyedStoreIC,4,199 -block_count,KeyedStoreIC,5,197 -block_count,KeyedStoreIC,6,16 +block_count,KeyedStoreIC,3,194 +block_count,KeyedStoreIC,4,194 +block_count,KeyedStoreIC,5,192 +block_count,KeyedStoreIC,6,17 block_count,KeyedStoreIC,7,0 -block_count,KeyedStoreIC,8,16 +block_count,KeyedStoreIC,8,17 block_count,KeyedStoreIC,9,10 block_count,KeyedStoreIC,10,1 block_count,KeyedStoreIC,11,0 @@ -27757,23 +27716,23 @@ block_count,KeyedStoreIC,22,5 block_count,KeyedStoreIC,23,0 block_count,KeyedStoreIC,24,6 -block_count,KeyedStoreIC,25,180 -block_count,KeyedStoreIC,26,188 -block_count,KeyedStoreIC,27,187 -block_count,KeyedStoreIC,28,186 -block_count,KeyedStoreIC,29,31 -block_count,KeyedStoreIC,30,31 +block_count,KeyedStoreIC,25,175 +block_count,KeyedStoreIC,26,183 +block_count,KeyedStoreIC,27,182 +block_count,KeyedStoreIC,28,181 +block_count,KeyedStoreIC,29,30 +block_count,KeyedStoreIC,30,30 block_count,KeyedStoreIC,31,0 -block_count,KeyedStoreIC,32,31 +block_count,KeyedStoreIC,32,30 block_count,KeyedStoreIC,33,0 -block_count,KeyedStoreIC,34,31 -block_count,KeyedStoreIC,35,31 +block_count,KeyedStoreIC,34,30 +block_count,KeyedStoreIC,35,30 block_count,KeyedStoreIC,36,0 block_count,KeyedStoreIC,37,0 block_count,KeyedStoreIC,38,0 block_count,KeyedStoreIC,39,0 block_count,KeyedStoreIC,40,0 -block_count,KeyedStoreIC,41,30 +block_count,KeyedStoreIC,41,29 block_count,KeyedStoreIC,42,0 block_count,KeyedStoreIC,43,0 block_count,KeyedStoreIC,44,0 @@ -27936,7 +27895,7 @@ block_count,KeyedStoreIC,201,0 block_count,KeyedStoreIC,202,0 block_count,KeyedStoreIC,203,0 -block_count,KeyedStoreIC,204,155 +block_count,KeyedStoreIC,204,151 block_count,KeyedStoreIC,205,0 block_count,KeyedStoreIC,206,0 block_count,KeyedStoreIC,207,0 @@ -28175,18 +28134,18 @@ block_count,KeyedStoreIC,440,0 block_count,KeyedStoreIC,441,0 block_count,KeyedStoreIC,442,1 -block_count,KeyedStoreIC,443,10 +block_count,KeyedStoreIC,443,11 block_count,KeyedStoreIC,444,0 block_count,KeyedStoreIC,445,0 block_count,KeyedStoreICTrampoline,0,0 block_count,KeyedStoreICTrampoline,1,0 block_count,KeyedStoreICTrampoline,2,0 block_count,KeyedStoreICTrampoline,3,0 -block_count,KeyedStoreICTrampoline_Megamorphic,0,223 -block_count,KeyedStoreICTrampoline_Megamorphic,1,223 +block_count,KeyedStoreICTrampoline_Megamorphic,0,285 +block_count,KeyedStoreICTrampoline_Megamorphic,1,285 block_count,KeyedStoreICTrampoline_Megamorphic,2,0 -block_count,KeyedStoreICTrampoline_Megamorphic,3,223 -block_count,KeyedStoreICBaseline,0,186 +block_count,KeyedStoreICTrampoline_Megamorphic,3,285 +block_count,KeyedStoreICBaseline,0,182 block_count,DefineKeyedOwnIC,0,2 block_count,DefineKeyedOwnIC,1,2 block_count,DefineKeyedOwnIC,2,0 @@ -28629,12 +28588,12 @@ block_count,DefineKeyedOwnIC,439,0 block_count,DefineKeyedOwnIC,440,2 block_count,DefineKeyedOwnIC,441,2 -block_count,StoreInArrayLiteralIC,0,19 -block_count,StoreInArrayLiteralIC,1,19 +block_count,StoreInArrayLiteralIC,0,20 +block_count,StoreInArrayLiteralIC,1,20 block_count,StoreInArrayLiteralIC,2,0 -block_count,StoreInArrayLiteralIC,3,19 -block_count,StoreInArrayLiteralIC,4,19 -block_count,StoreInArrayLiteralIC,5,18 +block_count,StoreInArrayLiteralIC,3,20 +block_count,StoreInArrayLiteralIC,4,20 +block_count,StoreInArrayLiteralIC,5,19 block_count,StoreInArrayLiteralIC,6,1 block_count,StoreInArrayLiteralIC,7,0 block_count,StoreInArrayLiteralIC,8,1 @@ -28647,25 +28606,25 @@ block_count,StoreInArrayLiteralIC,15,1 block_count,StoreInArrayLiteralIC,16,0 block_count,StoreInArrayLiteralIC,17,1 -block_count,StoreInArrayLiteralIC,18,17 -block_count,StoreInArrayLiteralIC,19,18 -block_count,StoreInArrayLiteralIC,20,18 +block_count,StoreInArrayLiteralIC,18,18 +block_count,StoreInArrayLiteralIC,19,19 +block_count,StoreInArrayLiteralIC,20,19 block_count,StoreInArrayLiteralIC,21,0 block_count,StoreInArrayLiteralIC,22,0 block_count,StoreInArrayLiteralIC,23,0 block_count,StoreInArrayLiteralIC,24,0 block_count,StoreInArrayLiteralIC,25,0 -block_count,StoreInArrayLiteralIC,26,18 +block_count,StoreInArrayLiteralIC,26,19 block_count,StoreInArrayLiteralIC,27,0 block_count,StoreInArrayLiteralIC,28,0 block_count,StoreInArrayLiteralIC,29,0 block_count,StoreInArrayLiteralIC,30,0 -block_count,StoreInArrayLiteralICBaseline,0,17 -block_count,LoadGlobalIC,0,1086 -block_count,LoadGlobalIC,1,1086 -block_count,LoadGlobalIC,2,1023 -block_count,LoadGlobalIC,3,1023 -block_count,LoadGlobalIC,4,1023 +block_count,StoreInArrayLiteralICBaseline,0,18 +block_count,LoadGlobalIC,0,1078 +block_count,LoadGlobalIC,1,1078 +block_count,LoadGlobalIC,2,1015 +block_count,LoadGlobalIC,3,1015 +block_count,LoadGlobalIC,4,1015 block_count,LoadGlobalIC,5,0 block_count,LoadGlobalIC,6,0 block_count,LoadGlobalIC,7,0 @@ -29092,11 +29051,11 @@ block_count,LoadGlobalICInsideTypeof,210,0 block_count,LoadGlobalICInsideTypeof,211,0 block_count,LoadGlobalICInsideTypeof,212,0 -block_count,LoadGlobalICTrampoline,0,661 -block_count,LoadGlobalICTrampoline,1,661 +block_count,LoadGlobalICTrampoline,0,663 +block_count,LoadGlobalICTrampoline,1,663 block_count,LoadGlobalICTrampoline,2,0 -block_count,LoadGlobalICTrampoline,3,661 -block_count,LoadGlobalICBaseline,0,367 +block_count,LoadGlobalICTrampoline,3,663 +block_count,LoadGlobalICBaseline,0,365 block_count,LoadGlobalICInsideTypeofBaseline,0,0 block_count,LookupGlobalICTrampoline,0,2 block_count,LookupGlobalICTrampoline,1,2 @@ -29456,7 +29415,7 @@ block_count,KeyedHasIC_Megamorphic,32,630 block_count,KeyedHasIC_Megamorphic,33,2491 block_count,KeyedHasIC_Megamorphic,34,2491 -block_count,KeyedHasIC_Megamorphic,35,2489 +block_count,KeyedHasIC_Megamorphic,35,2488 block_count,KeyedHasIC_Megamorphic,36,2383 block_count,KeyedHasIC_Megamorphic,37,626 block_count,KeyedHasIC_Megamorphic,38,626 @@ -29490,8 +29449,8 @@ block_count,KeyedHasIC_Megamorphic,66,1328 block_count,KeyedHasIC_Megamorphic,67,6588 block_count,KeyedHasIC_Megamorphic,68,6586 -block_count,KeyedHasIC_Megamorphic,69,6584 -block_count,KeyedHasIC_Megamorphic,70,5260 +block_count,KeyedHasIC_Megamorphic,69,6583 +block_count,KeyedHasIC_Megamorphic,70,5259 block_count,KeyedHasIC_Megamorphic,71,1323 block_count,KeyedHasIC_Megamorphic,72,2 block_count,KeyedHasIC_Megamorphic,73,2 @@ -29539,8 +29498,8 @@ block_count,KeyedHasIC_Megamorphic,115,0 block_count,KeyedHasIC_Megamorphic,116,0 block_count,KeyedHasIC_Megamorphic,117,0 -block_count,KeyedHasIC_Megamorphic,118,2485 -block_count,KeyedHasIC_Megamorphic,119,2485 +block_count,KeyedHasIC_Megamorphic,118,2484 +block_count,KeyedHasIC_Megamorphic,119,2484 block_count,KeyedHasIC_Megamorphic,120,0 block_count,KeyedHasIC_Megamorphic,121,0 block_count,KeyedHasIC_Megamorphic,122,0 @@ -29577,12 +29536,12 @@ block_count,KeyedHasIC_Megamorphic,153,0 block_count,KeyedHasIC_Megamorphic,154,0 block_count,KeyedHasIC_Megamorphic,155,0 -block_count,KeyedHasIC_Megamorphic,156,2485 +block_count,KeyedHasIC_Megamorphic,156,2484 block_count,KeyedHasIC_Megamorphic,157,4 block_count,KeyedHasIC_Megamorphic,158,4 block_count,KeyedHasIC_Megamorphic,159,0 block_count,KeyedHasIC_Megamorphic,160,2480 -block_count,KeyedHasIC_Megamorphic,161,2485 +block_count,KeyedHasIC_Megamorphic,161,2484 block_count,KeyedHasIC_Megamorphic,162,1861 block_count,KeyedHasIC_Megamorphic,163,623 block_count,KeyedHasIC_Megamorphic,164,1 @@ -29952,7 +29911,7 @@ block_count,IterableToListConvertHoles,6,35 block_count,IterableToListConvertHoles,7,35 block_count,IterableToListConvertHoles,8,35 -block_count,FindOrderedHashMapEntry,0,347 +block_count,FindOrderedHashMapEntry,0,344 block_count,FindOrderedHashMapEntry,1,340 block_count,FindOrderedHashMapEntry,2,114 block_count,FindOrderedHashMapEntry,3,114 @@ -29969,9 +29928,9 @@ block_count,FindOrderedHashMapEntry,14,50 block_count,FindOrderedHashMapEntry,15,55 block_count,FindOrderedHashMapEntry,16,114 -block_count,FindOrderedHashMapEntry,17,150 -block_count,FindOrderedHashMapEntry,18,56 -block_count,FindOrderedHashMapEntry,19,35 +block_count,FindOrderedHashMapEntry,17,130 +block_count,FindOrderedHashMapEntry,18,36 +block_count,FindOrderedHashMapEntry,19,15 block_count,FindOrderedHashMapEntry,20,20 block_count,FindOrderedHashMapEntry,21,93 block_count,FindOrderedHashMapEntry,22,0 @@ -30022,20 +29981,20 @@ block_count,FindOrderedHashMapEntry,67,0 block_count,FindOrderedHashMapEntry,68,56 block_count,FindOrderedHashMapEntry,69,36 -block_count,FindOrderedHashMapEntry,70,7 -block_count,FindOrderedHashMapEntry,71,19 -block_count,FindOrderedHashMapEntry,72,13 -block_count,FindOrderedHashMapEntry,73,12 +block_count,FindOrderedHashMapEntry,70,4 +block_count,FindOrderedHashMapEntry,71,11 +block_count,FindOrderedHashMapEntry,72,7 +block_count,FindOrderedHashMapEntry,73,7 block_count,FindOrderedHashMapEntry,74,1 block_count,FindOrderedHashMapEntry,75,0 block_count,FindOrderedHashMapEntry,76,0 block_count,FindOrderedHashMapEntry,77,0 block_count,FindOrderedHashMapEntry,78,1 -block_count,FindOrderedHashMapEntry,79,10 -block_count,FindOrderedHashMapEntry,80,12 +block_count,FindOrderedHashMapEntry,79,5 +block_count,FindOrderedHashMapEntry,80,7 block_count,FindOrderedHashMapEntry,81,0 block_count,FindOrderedHashMapEntry,82,0 -block_count,FindOrderedHashMapEntry,83,6 +block_count,FindOrderedHashMapEntry,83,3 block_count,MapConstructor,0,67 block_count,MapConstructor,1,0 block_count,MapConstructor,2,67 @@ -30444,8 +30403,8 @@ block_count,MapPrototypeSet,28,40 block_count,MapPrototypeSet,29,40 block_count,MapPrototypeSet,30,68 -block_count,MapPrototypeSet,31,38 -block_count,MapPrototypeSet,32,28 +block_count,MapPrototypeSet,31,37 +block_count,MapPrototypeSet,32,27 block_count,MapPrototypeSet,33,9 block_count,MapPrototypeSet,34,30 block_count,MapPrototypeSet,35,0 @@ -30617,14 +30576,14 @@ block_count,MapPrototypeDelete,96,0 block_count,MapPrototypeDelete,97,0 block_count,MapPrototypeDelete,98,0 -block_count,MapPrototypeGet,0,21 +block_count,MapPrototypeGet,0,18 block_count,MapPrototypeGet,1,0 -block_count,MapPrototypeGet,2,21 -block_count,MapPrototypeGet,3,21 -block_count,MapPrototypeGet,4,21 +block_count,MapPrototypeGet,2,18 +block_count,MapPrototypeGet,3,18 +block_count,MapPrototypeGet,4,18 block_count,MapPrototypeGet,5,0 -block_count,MapPrototypeGet,6,21 -block_count,MapPrototypeGet,7,15 +block_count,MapPrototypeGet,6,18 +block_count,MapPrototypeGet,7,12 block_count,MapPrototypeGet,8,6 block_count,MapPrototypeGet,9,0 block_count,MapPrototypeGet,10,6 @@ -30811,26 +30770,26 @@ block_count,MapIteratorToList,54,0 block_count,MapIteratorToList,55,0 block_count,MapIteratorToList,56,0 -block_count,Add_Baseline,0,199 -block_count,Add_Baseline,1,111 +block_count,Add_Baseline,0,205 +block_count,Add_Baseline,1,109 block_count,Add_Baseline,2,2 -block_count,Add_Baseline,3,2 +block_count,Add_Baseline,3,1 block_count,Add_Baseline,4,0 -block_count,Add_Baseline,5,109 -block_count,Add_Baseline,6,109 +block_count,Add_Baseline,5,107 +block_count,Add_Baseline,6,107 block_count,Add_Baseline,7,0 -block_count,Add_Baseline,8,108 -block_count,Add_Baseline,9,109 +block_count,Add_Baseline,8,107 +block_count,Add_Baseline,9,107 block_count,Add_Baseline,10,0 -block_count,Add_Baseline,11,88 -block_count,Add_Baseline,12,54 -block_count,Add_Baseline,13,47 -block_count,Add_Baseline,14,47 +block_count,Add_Baseline,11,96 +block_count,Add_Baseline,12,59 +block_count,Add_Baseline,13,53 +block_count,Add_Baseline,14,53 block_count,Add_Baseline,15,0 block_count,Add_Baseline,16,6 -block_count,Add_Baseline,17,34 -block_count,Add_Baseline,18,34 -block_count,Add_Baseline,19,32 +block_count,Add_Baseline,17,36 +block_count,Add_Baseline,18,36 +block_count,Add_Baseline,19,34 block_count,Add_Baseline,20,0 block_count,Add_Baseline,21,0 block_count,Add_Baseline,22,0 @@ -30885,7 +30844,7 @@ block_count,Add_Baseline,71,0 block_count,Add_Baseline,72,0 block_count,Add_Baseline,73,0 -block_count,Add_Baseline,74,32 +block_count,Add_Baseline,74,34 block_count,Add_Baseline,75,2 block_count,Add_Baseline,76,2 block_count,Add_Baseline,77,0 @@ -30894,10 +30853,10 @@ block_count,Add_Baseline,80,0 block_count,Add_Baseline,81,0 block_count,Add_Baseline,82,0 -block_count,Add_Baseline,83,29 +block_count,Add_Baseline,83,31 block_count,Add_Baseline,84,0 -block_count,Add_Baseline,85,29 -block_count,Add_Baseline,86,29 +block_count,Add_Baseline,85,31 +block_count,Add_Baseline,86,31 block_count,Add_Baseline,87,2 block_count,Add_Baseline,88,0 block_count,Add_Baseline,89,0 @@ -30913,19 +30872,19 @@ block_count,Add_Baseline,99,0 block_count,Add_Baseline,100,5 block_count,Add_Baseline,101,5 -block_count,Add_Baseline,102,56 +block_count,Add_Baseline,102,61 block_count,Add_Baseline,103,0 -block_count,Add_Baseline,104,56 -block_count,Add_Baseline,105,56 +block_count,Add_Baseline,104,61 +block_count,Add_Baseline,105,61 block_count,Add_Baseline,106,0 -block_count,Add_Baseline,107,56 -block_count,Add_Baseline,108,56 -block_count,AddSmi_Baseline,0,217 -block_count,AddSmi_Baseline,1,217 -block_count,AddSmi_Baseline,2,217 +block_count,Add_Baseline,107,61 +block_count,Add_Baseline,108,61 +block_count,AddSmi_Baseline,0,218 +block_count,AddSmi_Baseline,1,218 +block_count,AddSmi_Baseline,2,218 block_count,AddSmi_Baseline,3,0 -block_count,AddSmi_Baseline,4,216 -block_count,AddSmi_Baseline,5,217 +block_count,AddSmi_Baseline,4,218 +block_count,AddSmi_Baseline,5,218 block_count,AddSmi_Baseline,6,0 block_count,AddSmi_Baseline,7,0 block_count,AddSmi_Baseline,8,0 @@ -31020,23 +30979,23 @@ block_count,AddSmi_Baseline,97,0 block_count,AddSmi_Baseline,98,0 block_count,AddSmi_Baseline,99,0 -block_count,Subtract_Baseline,0,64 -block_count,Subtract_Baseline,1,32 +block_count,Subtract_Baseline,0,63 +block_count,Subtract_Baseline,1,31 block_count,Subtract_Baseline,2,2 block_count,Subtract_Baseline,3,2 block_count,Subtract_Baseline,4,0 -block_count,Subtract_Baseline,5,30 -block_count,Subtract_Baseline,6,30 +block_count,Subtract_Baseline,5,29 +block_count,Subtract_Baseline,6,29 block_count,Subtract_Baseline,7,0 block_count,Subtract_Baseline,8,0 block_count,Subtract_Baseline,9,0 block_count,Subtract_Baseline,10,0 -block_count,Subtract_Baseline,11,30 +block_count,Subtract_Baseline,11,29 block_count,Subtract_Baseline,12,0 -block_count,Subtract_Baseline,13,30 -block_count,Subtract_Baseline,14,30 -block_count,Subtract_Baseline,15,32 -block_count,Subtract_Baseline,16,32 +block_count,Subtract_Baseline,13,29 +block_count,Subtract_Baseline,14,29 +block_count,Subtract_Baseline,15,31 +block_count,Subtract_Baseline,16,31 block_count,Subtract_Baseline,17,30 block_count,Subtract_Baseline,18,30 block_count,Subtract_Baseline,19,0 @@ -31111,14 +31070,14 @@ block_count,Subtract_Baseline,88,0 block_count,Subtract_Baseline,89,0 block_count,Subtract_Baseline,90,0 -block_count,Subtract_Baseline,91,34 +block_count,Subtract_Baseline,91,33 block_count,Subtract_Baseline,92,0 -block_count,Subtract_Baseline,93,34 -block_count,Subtract_Baseline,94,34 +block_count,Subtract_Baseline,93,33 +block_count,Subtract_Baseline,94,33 block_count,Subtract_Baseline,95,0 -block_count,Subtract_Baseline,96,34 -block_count,Subtract_Baseline,97,34 -block_count,SubtractSmi_Baseline,0,21 +block_count,Subtract_Baseline,96,33 +block_count,Subtract_Baseline,97,33 +block_count,SubtractSmi_Baseline,0,20 block_count,SubtractSmi_Baseline,1,17 block_count,SubtractSmi_Baseline,2,17 block_count,SubtractSmi_Baseline,3,0 @@ -31137,10 +31096,10 @@ block_count,SubtractSmi_Baseline,16,0 block_count,SubtractSmi_Baseline,17,3 block_count,SubtractSmi_Baseline,18,3 -block_count,Multiply_Baseline,0,84 -block_count,Multiply_Baseline,1,10 -block_count,Multiply_Baseline,2,5 -block_count,Multiply_Baseline,3,5 +block_count,Multiply_Baseline,0,92 +block_count,Multiply_Baseline,1,14 +block_count,Multiply_Baseline,2,10 +block_count,Multiply_Baseline,3,10 block_count,Multiply_Baseline,4,0 block_count,Multiply_Baseline,5,4 block_count,Multiply_Baseline,6,4 @@ -31165,10 +31124,10 @@ block_count,Multiply_Baseline,25,0 block_count,Multiply_Baseline,26,4 block_count,Multiply_Baseline,27,4 -block_count,Multiply_Baseline,28,73 -block_count,Multiply_Baseline,29,73 -block_count,Multiply_Baseline,30,68 -block_count,Multiply_Baseline,31,68 +block_count,Multiply_Baseline,28,77 +block_count,Multiply_Baseline,29,77 +block_count,Multiply_Baseline,30,73 +block_count,Multiply_Baseline,31,73 block_count,Multiply_Baseline,32,0 block_count,Multiply_Baseline,33,4 block_count,Multiply_Baseline,34,0 @@ -31243,14 +31202,14 @@ block_count,Multiply_Baseline,103,0 block_count,Multiply_Baseline,104,0 block_count,Multiply_Baseline,105,0 -block_count,Multiply_Baseline,106,79 +block_count,Multiply_Baseline,106,87 block_count,Multiply_Baseline,107,0 -block_count,Multiply_Baseline,108,79 -block_count,Multiply_Baseline,109,79 +block_count,Multiply_Baseline,108,87 +block_count,Multiply_Baseline,109,87 block_count,Multiply_Baseline,110,0 -block_count,Multiply_Baseline,111,79 -block_count,Multiply_Baseline,112,79 -block_count,MultiplySmi_Baseline,0,6 +block_count,Multiply_Baseline,111,87 +block_count,Multiply_Baseline,112,87 +block_count,MultiplySmi_Baseline,0,5 block_count,MultiplySmi_Baseline,1,4 block_count,MultiplySmi_Baseline,2,4 block_count,MultiplySmi_Baseline,3,3 @@ -31260,8 +31219,8 @@ block_count,MultiplySmi_Baseline,7,0 block_count,MultiplySmi_Baseline,8,0 block_count,MultiplySmi_Baseline,9,3 -block_count,MultiplySmi_Baseline,10,1 -block_count,MultiplySmi_Baseline,11,1 +block_count,MultiplySmi_Baseline,10,0 +block_count,MultiplySmi_Baseline,11,0 block_count,MultiplySmi_Baseline,12,0 block_count,MultiplySmi_Baseline,13,0 block_count,MultiplySmi_Baseline,14,0 @@ -31360,7 +31319,7 @@ block_count,Divide_Baseline,4,0 block_count,Divide_Baseline,5,1 block_count,Divide_Baseline,6,1 -block_count,Divide_Baseline,7,1 +block_count,Divide_Baseline,7,0 block_count,Divide_Baseline,8,0 block_count,Divide_Baseline,9,0 block_count,Divide_Baseline,10,0 @@ -31462,14 +31421,14 @@ block_count,Divide_Baseline,106,0 block_count,Divide_Baseline,107,0 block_count,Divide_Baseline,108,0 -block_count,Divide_Baseline,109,5 +block_count,Divide_Baseline,109,4 block_count,Divide_Baseline,110,0 -block_count,Divide_Baseline,111,5 -block_count,Divide_Baseline,112,5 +block_count,Divide_Baseline,111,4 +block_count,Divide_Baseline,112,4 block_count,Divide_Baseline,113,0 -block_count,Divide_Baseline,114,5 -block_count,Divide_Baseline,115,5 -block_count,DivideSmi_Baseline,0,2 +block_count,Divide_Baseline,114,4 +block_count,Divide_Baseline,115,4 +block_count,DivideSmi_Baseline,0,1 block_count,DivideSmi_Baseline,1,1 block_count,DivideSmi_Baseline,2,1 block_count,DivideSmi_Baseline,3,1 @@ -31861,9 +31820,9 @@ block_count,BitwiseAnd_Baseline,92,0 block_count,BitwiseAnd_Baseline,93,0 block_count,BitwiseAnd_Baseline,94,0 -block_count,BitwiseAnd_Baseline,95,0 +block_count,BitwiseAnd_Baseline,95,1 block_count,BitwiseAnd_Baseline,96,11 -block_count,BitwiseAnd_Baseline,97,9 +block_count,BitwiseAnd_Baseline,97,10 block_count,BitwiseAnd_Baseline,98,1 block_count,BitwiseAnd_Baseline,99,1 block_count,BitwiseAnd_Baseline,100,0 @@ -31897,7 +31856,7 @@ block_count,BitwiseAnd_Baseline,128,0 block_count,BitwiseAnd_Baseline,129,11 block_count,BitwiseAnd_Baseline,130,11 -block_count,BitwiseAndSmi_Baseline,0,30 +block_count,BitwiseAndSmi_Baseline,0,31 block_count,BitwiseAndSmi_Baseline,1,1 block_count,BitwiseAndSmi_Baseline,2,1 block_count,BitwiseAndSmi_Baseline,3,0 @@ -31917,7 +31876,7 @@ block_count,BitwiseAndSmi_Baseline,17,0 block_count,BitwiseAndSmi_Baseline,18,0 block_count,BitwiseAndSmi_Baseline,19,0 -block_count,BitwiseAndSmi_Baseline,20,1 +block_count,BitwiseAndSmi_Baseline,20,0 block_count,BitwiseAndSmi_Baseline,21,1 block_count,BitwiseAndSmi_Baseline,22,1 block_count,BitwiseAndSmi_Baseline,23,0 @@ -31928,14 +31887,14 @@ block_count,BitwiseAndSmi_Baseline,28,0 block_count,BitwiseAndSmi_Baseline,29,1 block_count,BitwiseAndSmi_Baseline,30,1 -block_count,BitwiseAndSmi_Baseline,31,28 -block_count,BitwiseAndSmi_Baseline,32,30 +block_count,BitwiseAndSmi_Baseline,31,29 +block_count,BitwiseAndSmi_Baseline,32,31 block_count,BitwiseAndSmi_Baseline,33,0 -block_count,BitwiseAndSmi_Baseline,34,30 -block_count,BitwiseOr_Baseline,0,22 -block_count,BitwiseOr_Baseline,1,19 -block_count,BitwiseOr_Baseline,2,2 -block_count,BitwiseOr_Baseline,3,2 +block_count,BitwiseAndSmi_Baseline,34,31 +block_count,BitwiseOr_Baseline,0,23 +block_count,BitwiseOr_Baseline,1,20 +block_count,BitwiseOr_Baseline,2,3 +block_count,BitwiseOr_Baseline,3,3 block_count,BitwiseOr_Baseline,4,0 block_count,BitwiseOr_Baseline,5,0 block_count,BitwiseOr_Baseline,6,0 @@ -32027,9 +31986,9 @@ block_count,BitwiseOr_Baseline,92,0 block_count,BitwiseOr_Baseline,93,0 block_count,BitwiseOr_Baseline,94,0 -block_count,BitwiseOr_Baseline,95,2 -block_count,BitwiseOr_Baseline,96,22 -block_count,BitwiseOr_Baseline,97,20 +block_count,BitwiseOr_Baseline,95,3 +block_count,BitwiseOr_Baseline,96,23 +block_count,BitwiseOr_Baseline,97,21 block_count,BitwiseOr_Baseline,98,2 block_count,BitwiseOr_Baseline,99,2 block_count,BitwiseOr_Baseline,100,0 @@ -32050,20 +32009,20 @@ block_count,BitwiseOr_Baseline,115,0 block_count,BitwiseOr_Baseline,116,0 block_count,BitwiseOr_Baseline,117,2 -block_count,BitwiseOr_Baseline,118,22 +block_count,BitwiseOr_Baseline,118,23 block_count,BitwiseOr_Baseline,119,18 -block_count,BitwiseOr_Baseline,120,3 +block_count,BitwiseOr_Baseline,120,4 block_count,BitwiseOr_Baseline,121,0 -block_count,BitwiseOr_Baseline,122,3 -block_count,BitwiseOr_Baseline,123,3 -block_count,BitwiseOr_Baseline,124,22 -block_count,BitwiseOr_Baseline,125,3 +block_count,BitwiseOr_Baseline,122,4 +block_count,BitwiseOr_Baseline,123,4 +block_count,BitwiseOr_Baseline,124,23 +block_count,BitwiseOr_Baseline,125,4 block_count,BitwiseOr_Baseline,126,18 -block_count,BitwiseOr_Baseline,127,22 +block_count,BitwiseOr_Baseline,127,23 block_count,BitwiseOr_Baseline,128,0 -block_count,BitwiseOr_Baseline,129,22 -block_count,BitwiseOr_Baseline,130,22 -block_count,BitwiseOrSmi_Baseline,0,161 +block_count,BitwiseOr_Baseline,129,23 +block_count,BitwiseOr_Baseline,130,23 +block_count,BitwiseOrSmi_Baseline,0,160 block_count,BitwiseOrSmi_Baseline,1,1 block_count,BitwiseOrSmi_Baseline,2,1 block_count,BitwiseOrSmi_Baseline,3,0 @@ -32095,13 +32054,13 @@ block_count,BitwiseOrSmi_Baseline,29,0 block_count,BitwiseOrSmi_Baseline,30,1 block_count,BitwiseOrSmi_Baseline,31,159 -block_count,BitwiseOrSmi_Baseline,32,161 +block_count,BitwiseOrSmi_Baseline,32,160 block_count,BitwiseOrSmi_Baseline,33,0 -block_count,BitwiseOrSmi_Baseline,34,161 -block_count,BitwiseXor_Baseline,0,9 +block_count,BitwiseOrSmi_Baseline,34,160 +block_count,BitwiseXor_Baseline,0,8 block_count,BitwiseXor_Baseline,1,4 -block_count,BitwiseXor_Baseline,2,4 -block_count,BitwiseXor_Baseline,3,4 +block_count,BitwiseXor_Baseline,2,3 +block_count,BitwiseXor_Baseline,3,3 block_count,BitwiseXor_Baseline,4,0 block_count,BitwiseXor_Baseline,5,0 block_count,BitwiseXor_Baseline,6,0 @@ -32193,11 +32152,11 @@ block_count,BitwiseXor_Baseline,92,0 block_count,BitwiseXor_Baseline,93,0 block_count,BitwiseXor_Baseline,94,0 -block_count,BitwiseXor_Baseline,95,4 -block_count,BitwiseXor_Baseline,96,9 -block_count,BitwiseXor_Baseline,97,4 -block_count,BitwiseXor_Baseline,98,5 -block_count,BitwiseXor_Baseline,99,5 +block_count,BitwiseXor_Baseline,95,3 +block_count,BitwiseXor_Baseline,96,8 +block_count,BitwiseXor_Baseline,97,3 +block_count,BitwiseXor_Baseline,98,4 +block_count,BitwiseXor_Baseline,99,4 block_count,BitwiseXor_Baseline,100,0 block_count,BitwiseXor_Baseline,101,0 block_count,BitwiseXor_Baseline,102,0 @@ -32215,20 +32174,20 @@ block_count,BitwiseXor_Baseline,114,0 block_count,BitwiseXor_Baseline,115,0 block_count,BitwiseXor_Baseline,116,0 -block_count,BitwiseXor_Baseline,117,5 -block_count,BitwiseXor_Baseline,118,9 +block_count,BitwiseXor_Baseline,117,4 +block_count,BitwiseXor_Baseline,118,8 block_count,BitwiseXor_Baseline,119,5 block_count,BitwiseXor_Baseline,120,3 block_count,BitwiseXor_Baseline,121,0 block_count,BitwiseXor_Baseline,122,3 block_count,BitwiseXor_Baseline,123,3 -block_count,BitwiseXor_Baseline,124,9 +block_count,BitwiseXor_Baseline,124,8 block_count,BitwiseXor_Baseline,125,3 block_count,BitwiseXor_Baseline,126,5 -block_count,BitwiseXor_Baseline,127,9 +block_count,BitwiseXor_Baseline,127,8 block_count,BitwiseXor_Baseline,128,0 -block_count,BitwiseXor_Baseline,129,9 -block_count,BitwiseXor_Baseline,130,9 +block_count,BitwiseXor_Baseline,129,8 +block_count,BitwiseXor_Baseline,130,8 block_count,BitwiseXorSmi_Baseline,0,0 block_count,BitwiseXorSmi_Baseline,1,0 block_count,BitwiseXorSmi_Baseline,2,0 @@ -32374,16 +32333,16 @@ block_count,ShiftLeftSmi_Baseline,28,0 block_count,ShiftLeftSmi_Baseline,29,0 block_count,ShiftLeftSmi_Baseline,30,1 -block_count,ShiftLeftSmi_Baseline,31,27 -block_count,ShiftLeftSmi_Baseline,32,26 +block_count,ShiftLeftSmi_Baseline,31,26 +block_count,ShiftLeftSmi_Baseline,32,25 block_count,ShiftLeftSmi_Baseline,33,0 block_count,ShiftLeftSmi_Baseline,34,0 block_count,ShiftLeftSmi_Baseline,35,0 block_count,ShiftLeftSmi_Baseline,36,0 -block_count,ShiftLeftSmi_Baseline,37,27 +block_count,ShiftLeftSmi_Baseline,37,26 block_count,ShiftLeftSmi_Baseline,38,0 -block_count,ShiftLeftSmi_Baseline,39,26 -block_count,ShiftLeftSmi_Baseline,40,27 +block_count,ShiftLeftSmi_Baseline,39,25 +block_count,ShiftLeftSmi_Baseline,40,26 block_count,ShiftLeftSmi_Baseline,41,28 block_count,ShiftLeftSmi_Baseline,42,0 block_count,ShiftLeftSmi_Baseline,43,28 @@ -32466,7 +32425,7 @@ block_count,ShiftRight_Baseline,76,0 block_count,ShiftRight_Baseline,77,1 block_count,ShiftRight_Baseline,78,1 -block_count,ShiftRightSmi_Baseline,0,102 +block_count,ShiftRightSmi_Baseline,0,103 block_count,ShiftRightSmi_Baseline,1,1 block_count,ShiftRightSmi_Baseline,2,1 block_count,ShiftRightSmi_Baseline,3,0 @@ -32498,9 +32457,9 @@ block_count,ShiftRightSmi_Baseline,29,1 block_count,ShiftRightSmi_Baseline,30,1 block_count,ShiftRightSmi_Baseline,31,101 -block_count,ShiftRightSmi_Baseline,32,102 +block_count,ShiftRightSmi_Baseline,32,103 block_count,ShiftRightSmi_Baseline,33,0 -block_count,ShiftRightSmi_Baseline,34,102 +block_count,ShiftRightSmi_Baseline,34,103 block_count,ShiftRightLogical_Baseline,0,0 block_count,ShiftRightLogical_Baseline,1,0 block_count,ShiftRightLogical_Baseline,2,0 @@ -32632,14 +32591,14 @@ block_count,Add_WithFeedback,8,0 block_count,Add_WithFeedback,9,0 block_count,Add_WithFeedback,10,0 -block_count,Add_WithFeedback,11,37 +block_count,Add_WithFeedback,11,38 block_count,Add_WithFeedback,12,0 block_count,Add_WithFeedback,13,0 block_count,Add_WithFeedback,14,0 block_count,Add_WithFeedback,15,0 block_count,Add_WithFeedback,16,0 -block_count,Add_WithFeedback,17,37 -block_count,Add_WithFeedback,18,37 +block_count,Add_WithFeedback,17,38 +block_count,Add_WithFeedback,18,38 block_count,Add_WithFeedback,19,28 block_count,Add_WithFeedback,20,0 block_count,Add_WithFeedback,21,0 @@ -32695,7 +32654,7 @@ block_count,Add_WithFeedback,71,0 block_count,Add_WithFeedback,72,0 block_count,Add_WithFeedback,73,0 -block_count,Add_WithFeedback,74,27 +block_count,Add_WithFeedback,74,28 block_count,Add_WithFeedback,75,26 block_count,Add_WithFeedback,76,26 block_count,Add_WithFeedback,77,0 @@ -33163,7 +33122,7 @@ block_count,Equal_Baseline,0,156 block_count,Equal_Baseline,1,158 block_count,Equal_Baseline,2,127 -block_count,Equal_Baseline,3,28 +block_count,Equal_Baseline,3,27 block_count,Equal_Baseline,4,26 block_count,Equal_Baseline,5,11 block_count,Equal_Baseline,6,11 @@ -33267,10 +33226,10 @@ block_count,Equal_Baseline,104,0 block_count,Equal_Baseline,105,15 block_count,Equal_Baseline,106,0 -block_count,Equal_Baseline,107,15 +block_count,Equal_Baseline,107,14 block_count,Equal_Baseline,108,15 block_count,Equal_Baseline,109,2 -block_count,Equal_Baseline,110,13 +block_count,Equal_Baseline,110,12 block_count,Equal_Baseline,111,15 block_count,Equal_Baseline,112,1 block_count,Equal_Baseline,113,1 @@ -33311,7 +33270,7 @@ block_count,Equal_Baseline,148,2 block_count,Equal_Baseline,149,0 block_count,Equal_Baseline,150,30 -block_count,Equal_Baseline,151,7 +block_count,Equal_Baseline,151,6 block_count,Equal_Baseline,152,6 block_count,Equal_Baseline,153,4 block_count,Equal_Baseline,154,1 @@ -33337,28 +33296,28 @@ block_count,Equal_Baseline,174,0 block_count,Equal_Baseline,175,0 block_count,Equal_Baseline,176,0 -block_count,Equal_Baseline,177,23 +block_count,Equal_Baseline,177,24 block_count,Equal_Baseline,178,31 block_count,Equal_Baseline,179,109 block_count,Equal_Baseline,180,156 block_count,Equal_Baseline,181,0 block_count,Equal_Baseline,182,156 -block_count,StrictEqual_Baseline,0,218 -block_count,StrictEqual_Baseline,1,185 -block_count,StrictEqual_Baseline,2,132 -block_count,StrictEqual_Baseline,3,131 -block_count,StrictEqual_Baseline,4,131 -block_count,StrictEqual_Baseline,5,59 -block_count,StrictEqual_Baseline,6,59 -block_count,StrictEqual_Baseline,7,24 -block_count,StrictEqual_Baseline,8,23 -block_count,StrictEqual_Baseline,9,18 +block_count,StrictEqual_Baseline,0,226 +block_count,StrictEqual_Baseline,1,192 +block_count,StrictEqual_Baseline,2,142 +block_count,StrictEqual_Baseline,3,142 +block_count,StrictEqual_Baseline,4,141 +block_count,StrictEqual_Baseline,5,58 +block_count,StrictEqual_Baseline,6,58 +block_count,StrictEqual_Baseline,7,23 +block_count,StrictEqual_Baseline,8,22 +block_count,StrictEqual_Baseline,9,17 block_count,StrictEqual_Baseline,10,0 -block_count,StrictEqual_Baseline,11,18 +block_count,StrictEqual_Baseline,11,17 block_count,StrictEqual_Baseline,12,0 -block_count,StrictEqual_Baseline,13,18 +block_count,StrictEqual_Baseline,13,17 block_count,StrictEqual_Baseline,14,5 -block_count,StrictEqual_Baseline,15,2 +block_count,StrictEqual_Baseline,15,1 block_count,StrictEqual_Baseline,16,3 block_count,StrictEqual_Baseline,17,1 block_count,StrictEqual_Baseline,18,34 @@ -33398,17 +33357,17 @@ block_count,StrictEqual_Baseline,52,0 block_count,StrictEqual_Baseline,53,0 block_count,StrictEqual_Baseline,54,0 -block_count,StrictEqual_Baseline,55,71 +block_count,StrictEqual_Baseline,55,83 block_count,StrictEqual_Baseline,56,0 -block_count,StrictEqual_Baseline,57,71 -block_count,StrictEqual_Baseline,58,17 -block_count,StrictEqual_Baseline,59,53 -block_count,StrictEqual_Baseline,60,71 +block_count,StrictEqual_Baseline,57,82 +block_count,StrictEqual_Baseline,58,26 +block_count,StrictEqual_Baseline,59,56 +block_count,StrictEqual_Baseline,60,82 block_count,StrictEqual_Baseline,61,0 -block_count,StrictEqual_Baseline,62,71 -block_count,StrictEqual_Baseline,63,71 -block_count,StrictEqual_Baseline,64,48 -block_count,StrictEqual_Baseline,65,22 +block_count,StrictEqual_Baseline,62,82 +block_count,StrictEqual_Baseline,63,82 +block_count,StrictEqual_Baseline,64,59 +block_count,StrictEqual_Baseline,65,23 block_count,StrictEqual_Baseline,66,0 block_count,StrictEqual_Baseline,67,0 block_count,StrictEqual_Baseline,68,0 @@ -33419,13 +33378,13 @@ block_count,StrictEqual_Baseline,73,0 block_count,StrictEqual_Baseline,74,0 block_count,StrictEqual_Baseline,75,0 -block_count,StrictEqual_Baseline,76,53 +block_count,StrictEqual_Baseline,76,50 block_count,StrictEqual_Baseline,77,0 block_count,StrictEqual_Baseline,78,0 block_count,StrictEqual_Baseline,79,0 block_count,StrictEqual_Baseline,80,0 block_count,StrictEqual_Baseline,81,0 -block_count,StrictEqual_Baseline,82,52 +block_count,StrictEqual_Baseline,82,50 block_count,StrictEqual_Baseline,83,5 block_count,StrictEqual_Baseline,84,33 block_count,StrictEqual_Baseline,85,17 @@ -33455,14 +33414,14 @@ block_count,StrictEqual_Baseline,109,0 block_count,StrictEqual_Baseline,110,0 block_count,StrictEqual_Baseline,111,16 -block_count,StrictEqual_Baseline,112,113 +block_count,StrictEqual_Baseline,112,110 block_count,StrictEqual_Baseline,113,33 -block_count,StrictEqual_Baseline,114,218 +block_count,StrictEqual_Baseline,114,226 block_count,StrictEqual_Baseline,115,0 -block_count,StrictEqual_Baseline,116,218 -block_count,LessThan_Baseline,0,155 -block_count,LessThan_Baseline,1,155 -block_count,LessThan_Baseline,2,11 +block_count,StrictEqual_Baseline,116,226 +block_count,LessThan_Baseline,0,148 +block_count,LessThan_Baseline,1,148 +block_count,LessThan_Baseline,2,10 block_count,LessThan_Baseline,3,3 block_count,LessThan_Baseline,4,0 block_count,LessThan_Baseline,5,0 @@ -33555,7 +33514,7 @@ block_count,LessThan_Baseline,92,0 block_count,LessThan_Baseline,93,0 block_count,LessThan_Baseline,94,0 -block_count,LessThan_Baseline,95,3 +block_count,LessThan_Baseline,95,2 block_count,LessThan_Baseline,96,0 block_count,LessThan_Baseline,97,0 block_count,LessThan_Baseline,98,0 @@ -33565,7 +33524,7 @@ block_count,LessThan_Baseline,102,0 block_count,LessThan_Baseline,103,0 block_count,LessThan_Baseline,104,0 -block_count,LessThan_Baseline,105,3 +block_count,LessThan_Baseline,105,2 block_count,LessThan_Baseline,106,7 block_count,LessThan_Baseline,107,0 block_count,LessThan_Baseline,108,0 @@ -33576,8 +33535,8 @@ block_count,LessThan_Baseline,113,0 block_count,LessThan_Baseline,114,0 block_count,LessThan_Baseline,115,0 -block_count,LessThan_Baseline,116,7 -block_count,LessThan_Baseline,117,144 +block_count,LessThan_Baseline,116,6 +block_count,LessThan_Baseline,117,138 block_count,LessThan_Baseline,118,0 block_count,LessThan_Baseline,119,0 block_count,LessThan_Baseline,120,0 @@ -33589,24 +33548,24 @@ block_count,LessThan_Baseline,126,0 block_count,LessThan_Baseline,127,0 block_count,LessThan_Baseline,128,0 -block_count,LessThan_Baseline,129,143 -block_count,LessThan_Baseline,130,44 -block_count,LessThan_Baseline,131,99 +block_count,LessThan_Baseline,129,137 +block_count,LessThan_Baseline,130,42 +block_count,LessThan_Baseline,131,94 block_count,LessThan_Baseline,132,0 block_count,LessThan_Baseline,133,0 block_count,LessThan_Baseline,134,0 block_count,LessThan_Baseline,135,0 block_count,LessThan_Baseline,136,0 -block_count,LessThan_Baseline,137,11 -block_count,LessThan_Baseline,138,8 -block_count,LessThan_Baseline,139,3 -block_count,LessThan_Baseline,140,52 -block_count,LessThan_Baseline,141,102 -block_count,LessThan_Baseline,142,155 +block_count,LessThan_Baseline,137,10 +block_count,LessThan_Baseline,138,7 +block_count,LessThan_Baseline,139,2 +block_count,LessThan_Baseline,140,50 +block_count,LessThan_Baseline,141,97 +block_count,LessThan_Baseline,142,148 block_count,LessThan_Baseline,143,0 -block_count,LessThan_Baseline,144,155 -block_count,GreaterThan_Baseline,0,46 -block_count,GreaterThan_Baseline,1,46 +block_count,LessThan_Baseline,144,148 +block_count,GreaterThan_Baseline,0,44 +block_count,GreaterThan_Baseline,1,45 block_count,GreaterThan_Baseline,2,3 block_count,GreaterThan_Baseline,3,1 block_count,GreaterThan_Baseline,4,0 @@ -33722,7 +33681,7 @@ block_count,GreaterThan_Baseline,114,0 block_count,GreaterThan_Baseline,115,0 block_count,GreaterThan_Baseline,116,1 -block_count,GreaterThan_Baseline,117,42 +block_count,GreaterThan_Baseline,117,41 block_count,GreaterThan_Baseline,118,0 block_count,GreaterThan_Baseline,119,0 block_count,GreaterThan_Baseline,120,0 @@ -33734,9 +33693,9 @@ block_count,GreaterThan_Baseline,126,0 block_count,GreaterThan_Baseline,127,0 block_count,GreaterThan_Baseline,128,0 -block_count,GreaterThan_Baseline,129,42 -block_count,GreaterThan_Baseline,130,25 -block_count,GreaterThan_Baseline,131,17 +block_count,GreaterThan_Baseline,129,41 +block_count,GreaterThan_Baseline,130,24 +block_count,GreaterThan_Baseline,131,16 block_count,GreaterThan_Baseline,132,0 block_count,GreaterThan_Baseline,133,0 block_count,GreaterThan_Baseline,134,0 @@ -33745,11 +33704,11 @@ block_count,GreaterThan_Baseline,137,3 block_count,GreaterThan_Baseline,138,2 block_count,GreaterThan_Baseline,139,1 -block_count,GreaterThan_Baseline,140,27 +block_count,GreaterThan_Baseline,140,26 block_count,GreaterThan_Baseline,141,18 -block_count,GreaterThan_Baseline,142,46 +block_count,GreaterThan_Baseline,142,44 block_count,GreaterThan_Baseline,143,0 -block_count,GreaterThan_Baseline,144,46 +block_count,GreaterThan_Baseline,144,44 block_count,LessThanOrEqual_Baseline,0,22 block_count,LessThanOrEqual_Baseline,1,22 block_count,LessThanOrEqual_Baseline,2,3 @@ -33881,7 +33840,7 @@ block_count,LessThanOrEqual_Baseline,128,0 block_count,LessThanOrEqual_Baseline,129,17 block_count,LessThanOrEqual_Baseline,130,1 -block_count,LessThanOrEqual_Baseline,131,16 +block_count,LessThanOrEqual_Baseline,131,15 block_count,LessThanOrEqual_Baseline,132,0 block_count,LessThanOrEqual_Baseline,133,0 block_count,LessThanOrEqual_Baseline,134,0 @@ -33895,9 +33854,9 @@ block_count,LessThanOrEqual_Baseline,142,22 block_count,LessThanOrEqual_Baseline,143,0 block_count,LessThanOrEqual_Baseline,144,22 -block_count,GreaterThanOrEqual_Baseline,0,44 -block_count,GreaterThanOrEqual_Baseline,1,44 -block_count,GreaterThanOrEqual_Baseline,2,5 +block_count,GreaterThanOrEqual_Baseline,0,43 +block_count,GreaterThanOrEqual_Baseline,1,43 +block_count,GreaterThanOrEqual_Baseline,2,4 block_count,GreaterThanOrEqual_Baseline,3,3 block_count,GreaterThanOrEqual_Baseline,4,0 block_count,GreaterThanOrEqual_Baseline,5,0 @@ -34012,7 +33971,7 @@ block_count,GreaterThanOrEqual_Baseline,114,0 block_count,GreaterThanOrEqual_Baseline,115,0 block_count,GreaterThanOrEqual_Baseline,116,1 -block_count,GreaterThanOrEqual_Baseline,117,39 +block_count,GreaterThanOrEqual_Baseline,117,38 block_count,GreaterThanOrEqual_Baseline,118,0 block_count,GreaterThanOrEqual_Baseline,119,0 block_count,GreaterThanOrEqual_Baseline,120,0 @@ -34024,8 +33983,8 @@ block_count,GreaterThanOrEqual_Baseline,126,0 block_count,GreaterThanOrEqual_Baseline,127,0 block_count,GreaterThanOrEqual_Baseline,128,0 -block_count,GreaterThanOrEqual_Baseline,129,39 -block_count,GreaterThanOrEqual_Baseline,130,24 +block_count,GreaterThanOrEqual_Baseline,129,38 +block_count,GreaterThanOrEqual_Baseline,130,23 block_count,GreaterThanOrEqual_Baseline,131,14 block_count,GreaterThanOrEqual_Baseline,132,0 block_count,GreaterThanOrEqual_Baseline,133,0 @@ -34035,21 +33994,21 @@ block_count,GreaterThanOrEqual_Baseline,137,4 block_count,GreaterThanOrEqual_Baseline,138,1 block_count,GreaterThanOrEqual_Baseline,139,2 -block_count,GreaterThanOrEqual_Baseline,140,26 +block_count,GreaterThanOrEqual_Baseline,140,25 block_count,GreaterThanOrEqual_Baseline,141,17 -block_count,GreaterThanOrEqual_Baseline,142,44 +block_count,GreaterThanOrEqual_Baseline,142,43 block_count,GreaterThanOrEqual_Baseline,143,0 -block_count,GreaterThanOrEqual_Baseline,144,44 +block_count,GreaterThanOrEqual_Baseline,144,43 block_count,Equal_WithFeedback,0,13 -block_count,Equal_WithFeedback,1,16 -block_count,Equal_WithFeedback,2,10 +block_count,Equal_WithFeedback,1,15 +block_count,Equal_WithFeedback,2,9 block_count,Equal_WithFeedback,3,8 block_count,Equal_WithFeedback,4,8 block_count,Equal_WithFeedback,5,7 block_count,Equal_WithFeedback,6,7 block_count,Equal_WithFeedback,7,6 -block_count,Equal_WithFeedback,8,6 -block_count,Equal_WithFeedback,9,6 +block_count,Equal_WithFeedback,8,5 +block_count,Equal_WithFeedback,9,5 block_count,Equal_WithFeedback,10,1 block_count,Equal_WithFeedback,11,0 block_count,Equal_WithFeedback,12,0 @@ -34190,7 +34149,7 @@ block_count,Equal_WithFeedback,147,0 block_count,Equal_WithFeedback,148,0 block_count,Equal_WithFeedback,149,0 -block_count,Equal_WithFeedback,150,6 +block_count,Equal_WithFeedback,150,5 block_count,Equal_WithFeedback,151,5 block_count,Equal_WithFeedback,152,5 block_count,Equal_WithFeedback,153,5 @@ -34218,12 +34177,12 @@ block_count,Equal_WithFeedback,175,0 block_count,Equal_WithFeedback,176,0 block_count,Equal_WithFeedback,177,0 -block_count,Equal_WithFeedback,178,6 +block_count,Equal_WithFeedback,178,5 block_count,Equal_WithFeedback,179,7 block_count,Equal_WithFeedback,180,13 block_count,Equal_WithFeedback,181,0 block_count,Equal_WithFeedback,182,13 -block_count,StrictEqual_WithFeedback,0,100 +block_count,StrictEqual_WithFeedback,0,99 block_count,StrictEqual_WithFeedback,1,88 block_count,StrictEqual_WithFeedback,2,80 block_count,StrictEqual_WithFeedback,3,80 @@ -34241,8 +34200,8 @@ block_count,StrictEqual_WithFeedback,15,6 block_count,StrictEqual_WithFeedback,16,6 block_count,StrictEqual_WithFeedback,17,0 -block_count,StrictEqual_WithFeedback,18,2 -block_count,StrictEqual_WithFeedback,19,2 +block_count,StrictEqual_WithFeedback,18,3 +block_count,StrictEqual_WithFeedback,19,3 block_count,StrictEqual_WithFeedback,20,0 block_count,StrictEqual_WithFeedback,21,0 block_count,StrictEqual_WithFeedback,22,0 @@ -34299,7 +34258,7 @@ block_count,StrictEqual_WithFeedback,73,0 block_count,StrictEqual_WithFeedback,74,0 block_count,StrictEqual_WithFeedback,75,0 -block_count,StrictEqual_WithFeedback,76,8 +block_count,StrictEqual_WithFeedback,76,7 block_count,StrictEqual_WithFeedback,77,0 block_count,StrictEqual_WithFeedback,78,0 block_count,StrictEqual_WithFeedback,79,0 @@ -34323,7 +34282,7 @@ block_count,StrictEqual_WithFeedback,97,0 block_count,StrictEqual_WithFeedback,98,0 block_count,StrictEqual_WithFeedback,99,0 -block_count,StrictEqual_WithFeedback,100,1 +block_count,StrictEqual_WithFeedback,100,0 block_count,StrictEqual_WithFeedback,101,0 block_count,StrictEqual_WithFeedback,102,0 block_count,StrictEqual_WithFeedback,103,2 @@ -34335,13 +34294,13 @@ block_count,StrictEqual_WithFeedback,109,0 block_count,StrictEqual_WithFeedback,110,0 block_count,StrictEqual_WithFeedback,111,1 -block_count,StrictEqual_WithFeedback,112,27 +block_count,StrictEqual_WithFeedback,112,26 block_count,StrictEqual_WithFeedback,113,11 -block_count,StrictEqual_WithFeedback,114,100 +block_count,StrictEqual_WithFeedback,114,99 block_count,StrictEqual_WithFeedback,115,0 -block_count,StrictEqual_WithFeedback,116,100 +block_count,StrictEqual_WithFeedback,116,99 block_count,LessThan_WithFeedback,0,2 -block_count,LessThan_WithFeedback,1,3 +block_count,LessThan_WithFeedback,1,2 block_count,LessThan_WithFeedback,2,1 block_count,LessThan_WithFeedback,3,1 block_count,LessThan_WithFeedback,4,0 @@ -34836,8 +34795,8 @@ block_count,Decrement_Baseline,23,16 block_count,Decrement_Baseline,24,0 block_count,Decrement_Baseline,25,16 -block_count,Increment_Baseline,0,106 -block_count,Increment_Baseline,1,106 +block_count,Increment_Baseline,0,103 +block_count,Increment_Baseline,1,103 block_count,Increment_Baseline,2,0 block_count,Increment_Baseline,3,0 block_count,Increment_Baseline,4,0 @@ -34852,16 +34811,16 @@ block_count,Increment_Baseline,13,0 block_count,Increment_Baseline,14,0 block_count,Increment_Baseline,15,0 -block_count,Increment_Baseline,16,106 -block_count,Increment_Baseline,17,106 +block_count,Increment_Baseline,16,102 +block_count,Increment_Baseline,17,102 block_count,Increment_Baseline,18,0 block_count,Increment_Baseline,19,0 block_count,Increment_Baseline,20,0 block_count,Increment_Baseline,21,0 block_count,Increment_Baseline,22,0 -block_count,Increment_Baseline,23,106 +block_count,Increment_Baseline,23,103 block_count,Increment_Baseline,24,0 -block_count,Increment_Baseline,25,106 +block_count,Increment_Baseline,25,102 block_count,Negate_Baseline,0,6 block_count,Negate_Baseline,1,6 block_count,Negate_Baseline,2,5 @@ -35836,8 +35795,8 @@ block_count,ObjectPrototypeHasOwnProperty,37,0 block_count,ObjectPrototypeHasOwnProperty,38,41 block_count,ObjectPrototypeHasOwnProperty,39,0 -block_count,ObjectPrototypeHasOwnProperty,40,170 -block_count,ObjectPrototypeHasOwnProperty,41,170 +block_count,ObjectPrototypeHasOwnProperty,40,169 +block_count,ObjectPrototypeHasOwnProperty,41,169 block_count,ObjectPrototypeHasOwnProperty,42,133 block_count,ObjectPrototypeHasOwnProperty,43,129 block_count,ObjectPrototypeHasOwnProperty,44,0 @@ -36060,36 +36019,36 @@ block_count,ObjectToString,84,0 block_count,ObjectToString,85,151 block_count,ObjectToString,86,55 -block_count,OrdinaryHasInstance,0,84 -block_count,OrdinaryHasInstance,1,84 -block_count,OrdinaryHasInstance,2,84 +block_count,OrdinaryHasInstance,0,85 +block_count,OrdinaryHasInstance,1,85 +block_count,OrdinaryHasInstance,2,85 block_count,OrdinaryHasInstance,3,0 -block_count,OrdinaryHasInstance,4,84 +block_count,OrdinaryHasInstance,4,85 block_count,OrdinaryHasInstance,5,0 block_count,OrdinaryHasInstance,6,0 block_count,OrdinaryHasInstance,7,0 -block_count,OrdinaryHasInstance,8,84 -block_count,OrdinaryHasInstance,9,84 -block_count,OrdinaryHasInstance,10,84 +block_count,OrdinaryHasInstance,8,85 +block_count,OrdinaryHasInstance,9,85 +block_count,OrdinaryHasInstance,10,85 block_count,OrdinaryHasInstance,11,3 block_count,OrdinaryHasInstance,12,3 block_count,OrdinaryHasInstance,13,0 -block_count,OrdinaryHasInstance,14,80 -block_count,OrdinaryHasInstance,15,84 -block_count,OrdinaryHasInstance,16,261 -block_count,OrdinaryHasInstance,17,228 -block_count,OrdinaryHasInstance,18,32 -block_count,OrdinaryHasInstance,19,32 -block_count,OrdinaryHasInstance,20,32 +block_count,OrdinaryHasInstance,14,82 +block_count,OrdinaryHasInstance,15,85 +block_count,OrdinaryHasInstance,16,263 +block_count,OrdinaryHasInstance,17,229 +block_count,OrdinaryHasInstance,18,34 +block_count,OrdinaryHasInstance,19,34 +block_count,OrdinaryHasInstance,20,34 block_count,OrdinaryHasInstance,21,0 block_count,OrdinaryHasInstance,22,0 block_count,OrdinaryHasInstance,23,0 -block_count,OrdinaryHasInstance,24,261 -block_count,OrdinaryHasInstance,25,192 -block_count,OrdinaryHasInstance,26,176 +block_count,OrdinaryHasInstance,24,263 +block_count,OrdinaryHasInstance,25,193 +block_count,OrdinaryHasInstance,26,177 block_count,OrdinaryHasInstance,27,15 -block_count,OrdinaryHasInstance,28,68 -block_count,OrdinaryHasInstance,29,84 +block_count,OrdinaryHasInstance,28,69 +block_count,OrdinaryHasInstance,29,85 block_count,OrdinaryHasInstance,30,0 block_count,OrdinaryHasInstance,31,0 block_count,OrdinaryHasInstance,32,0 @@ -36186,8 +36145,8 @@ block_count,InstanceOf_WithFeedback,54,0 block_count,InstanceOf_WithFeedback,55,0 block_count,InstanceOf_WithFeedback,56,3 -block_count,InstanceOf_Baseline,0,42 -block_count,InstanceOf_Baseline,1,42 +block_count,InstanceOf_Baseline,0,41 +block_count,InstanceOf_Baseline,1,41 block_count,InstanceOf_Baseline,2,0 block_count,InstanceOf_Baseline,3,0 block_count,InstanceOf_Baseline,4,0 @@ -36208,12 +36167,12 @@ block_count,InstanceOf_Baseline,19,0 block_count,InstanceOf_Baseline,20,41 block_count,InstanceOf_Baseline,21,0 -block_count,InstanceOf_Baseline,22,42 -block_count,InstanceOf_Baseline,23,42 +block_count,InstanceOf_Baseline,22,41 +block_count,InstanceOf_Baseline,23,41 block_count,InstanceOf_Baseline,24,0 -block_count,InstanceOf_Baseline,25,42 +block_count,InstanceOf_Baseline,25,41 block_count,InstanceOf_Baseline,26,0 -block_count,InstanceOf_Baseline,27,42 +block_count,InstanceOf_Baseline,27,41 block_count,InstanceOf_Baseline,28,0 block_count,InstanceOf_Baseline,29,0 block_count,InstanceOf_Baseline,30,0 @@ -36242,7 +36201,7 @@ block_count,InstanceOf_Baseline,53,0 block_count,InstanceOf_Baseline,54,0 block_count,InstanceOf_Baseline,55,0 -block_count,InstanceOf_Baseline,56,42 +block_count,InstanceOf_Baseline,56,41 block_count,InstanceOf_Baseline,57,0 block_count,InstanceOf_Baseline,58,0 block_count,ForInEnumerate,0,52 @@ -37427,9 +37386,9 @@ block_count,SetPrototypeAdd,27,43 block_count,SetPrototypeAdd,28,62 block_count,SetPrototypeAdd,29,62 -block_count,SetPrototypeAdd,30,87 -block_count,SetPrototypeAdd,31,26 -block_count,SetPrototypeAdd,32,25 +block_count,SetPrototypeAdd,30,88 +block_count,SetPrototypeAdd,31,27 +block_count,SetPrototypeAdd,32,26 block_count,SetPrototypeAdd,33,1 block_count,SetPrototypeAdd,34,60 block_count,SetPrototypeAdd,35,0 @@ -37752,10 +37711,10 @@ block_count,SetOrSetIteratorToList,54,0 block_count,SetOrSetIteratorToList,55,0 block_count,SetOrSetIteratorToList,56,0 -block_count,StringFromCharCode,0,14 +block_count,StringFromCharCode,0,15 block_count,StringFromCharCode,1,0 -block_count,StringFromCharCode,2,14 -block_count,StringFromCharCode,3,14 +block_count,StringFromCharCode,2,15 +block_count,StringFromCharCode,3,15 block_count,StringFromCharCode,4,7 block_count,StringFromCharCode,5,7 block_count,StringFromCharCode,6,7 @@ -37782,7 +37741,7 @@ block_count,StringFromCharCode,27,0 block_count,StringFromCharCode,28,767 block_count,StringFromCharCode,29,767 -block_count,StringFromCharCode,30,760 +block_count,StringFromCharCode,30,759 block_count,StringFromCharCode,31,7 block_count,StringFromCharCode,32,0 block_count,StringFromCharCode,33,0 @@ -37826,8 +37785,8 @@ block_count,StringFromCharCode,71,0 block_count,StringFromCharCode,72,0 block_count,StringFromCharCode,73,0 -block_count,StringFromCharCode,74,7 -block_count,StringFromCharCode,75,4 +block_count,StringFromCharCode,74,8 +block_count,StringFromCharCode,75,6 block_count,StringFromCharCode,76,2 block_count,StringFromCharCode,77,2 block_count,StringFromCharCode,78,1 @@ -37837,12 +37796,12 @@ block_count,StringFromCharCode,82,0 block_count,StringFromCharCode,83,1 block_count,StringFromCharCode,84,0 -block_count,StringFromCharCode,85,7 +block_count,StringFromCharCode,85,8 block_count,StringFromCharCode,86,0 block_count,StringFromCharCode,87,0 block_count,StringFromCharCode,88,0 block_count,StringFromCharCode,89,0 -block_count,StringFromCharCode,90,6 +block_count,StringFromCharCode,90,8 block_count,StringPrototypeReplace,0,215 block_count,StringPrototypeReplace,1,0 block_count,StringPrototypeReplace,2,215 @@ -38165,16 +38124,16 @@ block_count,TypedArrayPrototypeByteLength,10,0 block_count,TypedArrayPrototypeByteLength,11,0 block_count,TypedArrayPrototypeByteLength,12,0 -block_count,TypedArrayPrototypeLength,0,37 +block_count,TypedArrayPrototypeLength,0,32 block_count,TypedArrayPrototypeLength,1,0 -block_count,TypedArrayPrototypeLength,2,37 -block_count,TypedArrayPrototypeLength,3,37 -block_count,TypedArrayPrototypeLength,4,37 +block_count,TypedArrayPrototypeLength,2,32 +block_count,TypedArrayPrototypeLength,3,32 +block_count,TypedArrayPrototypeLength,4,32 block_count,TypedArrayPrototypeLength,5,0 -block_count,TypedArrayPrototypeLength,6,37 -block_count,TypedArrayPrototypeLength,7,37 -block_count,TypedArrayPrototypeLength,8,37 -block_count,TypedArrayPrototypeLength,9,37 +block_count,TypedArrayPrototypeLength,6,32 +block_count,TypedArrayPrototypeLength,7,32 +block_count,TypedArrayPrototypeLength,8,32 +block_count,TypedArrayPrototypeLength,9,32 block_count,TypedArrayPrototypeLength,10,0 block_count,TypedArrayPrototypeLength,11,0 block_count,TypedArrayPrototypeLength,12,0 @@ -38210,8 +38169,8 @@ block_count,TypedArrayPrototypeLength,42,0 block_count,TypedArrayPrototypeLength,43,0 block_count,TypedArrayPrototypeLength,44,0 -block_count,TypedArrayPrototypeLength,45,37 -block_count,TypedArrayPrototypeLength,46,37 +block_count,TypedArrayPrototypeLength,45,32 +block_count,TypedArrayPrototypeLength,46,32 block_count,TypedArrayPrototypeToStringTag,0,0 block_count,TypedArrayPrototypeToStringTag,1,0 block_count,TypedArrayPrototypeToStringTag,2,0 @@ -38941,9 +38900,9 @@ block_count,WeakMapLookupHashIndex,27,64 block_count,WeakMapLookupHashIndex,28,1 block_count,WeakMapLookupHashIndex,29,64 -block_count,WeakMapLookupHashIndex,30,96 -block_count,WeakMapLookupHashIndex,31,96 -block_count,WeakMapLookupHashIndex,32,31 +block_count,WeakMapLookupHashIndex,30,90 +block_count,WeakMapLookupHashIndex,31,90 +block_count,WeakMapLookupHashIndex,32,26 block_count,WeakMapLookupHashIndex,33,64 block_count,WeakMapLookupHashIndex,34,0 block_count,WeakMapGet,0,33 @@ -39484,7 +39443,7 @@ block_count,StringAdd_CheckNone,9,0 block_count,StringAdd_CheckNone,10,7385 block_count,StringAdd_CheckNone,11,2 -block_count,StringAdd_CheckNone,12,7382 +block_count,StringAdd_CheckNone,12,7383 block_count,StringAdd_CheckNone,13,7385 block_count,StringAdd_CheckNone,14,0 block_count,StringAdd_CheckNone,15,7384 @@ -39545,7 +39504,7 @@ block_count,StringAdd_CheckNone,70,1432 block_count,StringAdd_CheckNone,71,750 block_count,StringAdd_CheckNone,72,1309 -block_count,StringAdd_CheckNone,73,559 +block_count,StringAdd_CheckNone,73,558 block_count,StringAdd_CheckNone,74,750 block_count,StringAdd_CheckNone,75,2183 block_count,StringAdd_CheckNone,76,461 @@ -39601,9 +39560,9 @@ block_count,SubString,6,161 block_count,SubString,7,114 block_count,SubString,8,6 -block_count,SubString,9,108 -block_count,SubString,10,47 -block_count,SubString,11,47 +block_count,SubString,9,107 +block_count,SubString,10,46 +block_count,SubString,11,46 block_count,SubString,12,0 block_count,SubString,13,161 block_count,SubString,14,0 @@ -39865,11 +39824,11 @@ block_count,GetProperty,28,0 block_count,GetProperty,29,0 block_count,GetProperty,30,0 -block_count,GetProperty,31,90 +block_count,GetProperty,31,89 block_count,GetProperty,32,636 block_count,GetProperty,33,1579 block_count,GetProperty,34,1579 -block_count,GetProperty,35,1579 +block_count,GetProperty,35,1578 block_count,GetProperty,36,1559 block_count,GetProperty,37,272 block_count,GetProperty,38,272 @@ -39901,11 +39860,11 @@ block_count,GetProperty,64,1286 block_count,GetProperty,65,284 block_count,GetProperty,66,1001 -block_count,GetProperty,67,2522 -block_count,GetProperty,68,2229 +block_count,GetProperty,67,2521 +block_count,GetProperty,68,2228 block_count,GetProperty,69,2122 block_count,GetProperty,70,1520 -block_count,GetProperty,71,602 +block_count,GetProperty,71,601 block_count,GetProperty,72,106 block_count,GetProperty,73,293 block_count,GetProperty,74,886 @@ -39969,7 +39928,7 @@ block_count,GetProperty,132,0 block_count,GetProperty,133,0 block_count,GetProperty,134,0 -block_count,GetProperty,135,952 +block_count,GetProperty,135,951 block_count,GetProperty,136,950 block_count,GetProperty,137,1 block_count,GetProperty,138,0 @@ -40007,7 +39966,7 @@ block_count,GetProperty,170,0 block_count,GetProperty,171,0 block_count,GetProperty,172,0 -block_count,GetProperty,173,952 +block_count,GetProperty,173,951 block_count,GetProperty,174,943 block_count,GetProperty,175,8 block_count,GetProperty,176,627 @@ -45155,47 +45114,47 @@ block_count,ArrayMap,55,23 block_count,ArrayMap,56,23 block_count,ArrayMap,57,7 -block_count,ArrayMap,58,15 -block_count,ArrayMap,59,15 -block_count,ArrayMap,60,15 +block_count,ArrayMap,58,16 +block_count,ArrayMap,59,16 +block_count,ArrayMap,60,16 block_count,ArrayMap,61,0 -block_count,ArrayMap,62,15 +block_count,ArrayMap,62,16 block_count,ArrayMap,63,0 block_count,ArrayMap,64,0 -block_count,ArrayMap,65,15 +block_count,ArrayMap,65,16 block_count,ArrayMap,66,0 -block_count,ArrayMap,67,15 +block_count,ArrayMap,67,16 block_count,ArrayMap,68,13 block_count,ArrayMap,69,2 block_count,ArrayMap,70,10 block_count,ArrayMap,71,8 block_count,ArrayMap,72,2 -block_count,ArrayMap,73,15 +block_count,ArrayMap,73,16 block_count,ArrayMap,74,2 block_count,ArrayMap,75,13 -block_count,ArrayMap,76,15 +block_count,ArrayMap,76,16 block_count,ArrayMap,77,0 block_count,ArrayMap,78,23 -block_count,ArrayMap,79,58 -block_count,ArrayMap,80,34 -block_count,ArrayMap,81,34 -block_count,ArrayMap,82,34 +block_count,ArrayMap,79,59 +block_count,ArrayMap,80,35 +block_count,ArrayMap,81,35 +block_count,ArrayMap,82,35 block_count,ArrayMap,83,0 block_count,ArrayMap,84,0 block_count,ArrayMap,85,0 -block_count,ArrayMap,86,34 +block_count,ArrayMap,86,35 block_count,ArrayMap,87,0 -block_count,ArrayMap,88,34 -block_count,ArrayMap,89,34 +block_count,ArrayMap,88,35 +block_count,ArrayMap,89,35 block_count,ArrayMap,90,0 block_count,ArrayMap,91,0 block_count,ArrayMap,92,0 block_count,ArrayMap,93,0 -block_count,ArrayMap,94,34 -block_count,ArrayMap,95,34 -block_count,ArrayMap,96,34 -block_count,ArrayMap,97,34 -block_count,ArrayMap,98,34 +block_count,ArrayMap,94,35 +block_count,ArrayMap,95,35 +block_count,ArrayMap,96,35 +block_count,ArrayMap,97,35 +block_count,ArrayMap,98,35 block_count,ArrayMap,99,0 block_count,ArrayMap,100,0 block_count,ArrayMap,101,0 @@ -45209,21 +45168,21 @@ block_count,ArrayMap,109,0 block_count,ArrayMap,110,0 block_count,ArrayMap,111,0 -block_count,ArrayMap,112,34 -block_count,ArrayMap,113,16 -block_count,ArrayMap,114,16 +block_count,ArrayMap,112,35 +block_count,ArrayMap,113,17 +block_count,ArrayMap,114,17 block_count,ArrayMap,115,0 -block_count,ArrayMap,116,17 +block_count,ArrayMap,116,18 block_count,ArrayMap,117,0 block_count,ArrayMap,118,0 block_count,ArrayMap,119,0 block_count,ArrayMap,120,17 block_count,ArrayMap,121,17 block_count,ArrayMap,122,0 -block_count,ArrayMap,123,17 -block_count,ArrayMap,124,34 +block_count,ArrayMap,123,18 +block_count,ArrayMap,124,35 block_count,ArrayMap,125,0 -block_count,ArrayMap,126,34 +block_count,ArrayMap,126,35 block_count,ArrayMap,127,0 block_count,ArrayMap,128,0 block_count,ArrayMap,129,0 @@ -46811,10 +46770,10 @@ block_count,ArrayPrototypeSplice,515,0 block_count,ArrayPrototypeSplice,516,2 block_count,ArrayPrototypeSplice,517,556 -block_count,ArrayPrototypeSplice,518,554 +block_count,ArrayPrototypeSplice,518,553 block_count,ArrayPrototypeSplice,519,191 block_count,ArrayPrototypeSplice,520,362 -block_count,ArrayPrototypeSplice,521,554 +block_count,ArrayPrototypeSplice,521,553 block_count,ArrayPrototypeSplice,522,2 block_count,ArrayPrototypeSplice,523,0 block_count,ArrayPrototypeSplice,524,0 @@ -46842,8 +46801,8 @@ block_count,ArrayPrototypeSplice,546,0 block_count,ArrayPrototypeSplice,547,0 block_count,ArrayPrototypeSplice,548,0 -block_count,ArrayPrototypeSplice,549,6 -block_count,ArrayPrototypeSplice,550,6 +block_count,ArrayPrototypeSplice,549,0 +block_count,ArrayPrototypeSplice,550,0 block_count,ArrayPrototypeSplice,551,0 block_count,ArrayPrototypeSplice,552,0 block_count,ArrayPrototypeSplice,553,0 @@ -47568,32 +47527,32 @@ block_count,StringPrototypeCharAt,44,0 block_count,StringPrototypeCharAt,45,111 block_count,StringPrototypeCharAt,46,2 -block_count,StringPrototypeCharCodeAt,0,63 +block_count,StringPrototypeCharCodeAt,0,61 block_count,StringPrototypeCharCodeAt,1,0 -block_count,StringPrototypeCharCodeAt,2,63 -block_count,StringPrototypeCharCodeAt,3,63 -block_count,StringPrototypeCharCodeAt,4,63 +block_count,StringPrototypeCharCodeAt,2,61 +block_count,StringPrototypeCharCodeAt,3,61 +block_count,StringPrototypeCharCodeAt,4,61 block_count,StringPrototypeCharCodeAt,5,0 block_count,StringPrototypeCharCodeAt,6,0 block_count,StringPrototypeCharCodeAt,7,0 -block_count,StringPrototypeCharCodeAt,8,63 +block_count,StringPrototypeCharCodeAt,8,61 block_count,StringPrototypeCharCodeAt,9,0 -block_count,StringPrototypeCharCodeAt,10,63 -block_count,StringPrototypeCharCodeAt,11,63 +block_count,StringPrototypeCharCodeAt,10,61 +block_count,StringPrototypeCharCodeAt,11,61 block_count,StringPrototypeCharCodeAt,12,0 -block_count,StringPrototypeCharCodeAt,13,63 -block_count,StringPrototypeCharCodeAt,14,63 -block_count,StringPrototypeCharCodeAt,15,63 -block_count,StringPrototypeCharCodeAt,16,111 -block_count,StringPrototypeCharCodeAt,17,48 -block_count,StringPrototypeCharCodeAt,18,48 +block_count,StringPrototypeCharCodeAt,13,61 +block_count,StringPrototypeCharCodeAt,14,61 +block_count,StringPrototypeCharCodeAt,15,61 +block_count,StringPrototypeCharCodeAt,16,109 +block_count,StringPrototypeCharCodeAt,17,47 +block_count,StringPrototypeCharCodeAt,18,47 block_count,StringPrototypeCharCodeAt,19,0 block_count,StringPrototypeCharCodeAt,20,0 block_count,StringPrototypeCharCodeAt,21,0 -block_count,StringPrototypeCharCodeAt,22,48 -block_count,StringPrototypeCharCodeAt,23,48 +block_count,StringPrototypeCharCodeAt,22,47 +block_count,StringPrototypeCharCodeAt,23,47 block_count,StringPrototypeCharCodeAt,24,0 -block_count,StringPrototypeCharCodeAt,25,48 +block_count,StringPrototypeCharCodeAt,25,47 block_count,StringPrototypeCharCodeAt,26,0 block_count,StringPrototypeCharCodeAt,27,0 block_count,StringPrototypeCharCodeAt,28,0 @@ -47604,10 +47563,10 @@ block_count,StringPrototypeCharCodeAt,33,0 block_count,StringPrototypeCharCodeAt,34,0 block_count,StringPrototypeCharCodeAt,35,0 -block_count,StringPrototypeCharCodeAt,36,63 -block_count,StringPrototypeCharCodeAt,37,63 +block_count,StringPrototypeCharCodeAt,36,61 +block_count,StringPrototypeCharCodeAt,37,61 block_count,StringPrototypeCharCodeAt,38,8 -block_count,StringPrototypeCharCodeAt,39,54 +block_count,StringPrototypeCharCodeAt,39,53 block_count,StringPrototypeCharCodeAt,40,0 block_count,StringPrototypeCodePointAt,0,0 block_count,StringPrototypeCodePointAt,1,0 @@ -48187,7 +48146,7 @@ block_count,StringCharAt,28,0 block_count,StringCharAt,29,0 block_count,StringCharAt,30,8 -block_count,FastNewClosureBaseline,0,31 +block_count,FastNewClosureBaseline,0,32 block_count,FastNewFunctionContextFunction,0,60 block_count,FastNewFunctionContextFunction,1,60 block_count,FastNewFunctionContextFunction,2,0 @@ -48224,15 +48183,15 @@ block_count,CreateShallowArrayLiteral,3,9 block_count,CreateShallowArrayLiteral,4,9 block_count,CreateShallowArrayLiteral,5,8 -block_count,CreateShallowArrayLiteral,6,5 -block_count,CreateShallowArrayLiteral,7,5 -block_count,CreateShallowArrayLiteral,8,5 +block_count,CreateShallowArrayLiteral,6,6 +block_count,CreateShallowArrayLiteral,7,6 +block_count,CreateShallowArrayLiteral,8,6 block_count,CreateShallowArrayLiteral,9,0 -block_count,CreateShallowArrayLiteral,10,5 +block_count,CreateShallowArrayLiteral,10,6 block_count,CreateShallowArrayLiteral,11,0 block_count,CreateShallowArrayLiteral,12,0 -block_count,CreateShallowArrayLiteral,13,5 -block_count,CreateShallowArrayLiteral,14,5 +block_count,CreateShallowArrayLiteral,13,6 +block_count,CreateShallowArrayLiteral,14,6 block_count,CreateShallowArrayLiteral,15,0 block_count,CreateShallowArrayLiteral,16,0 block_count,CreateShallowArrayLiteral,17,0 @@ -48242,7 +48201,7 @@ block_count,CreateShallowArrayLiteral,21,0 block_count,CreateShallowArrayLiteral,22,0 block_count,CreateShallowArrayLiteral,23,0 -block_count,CreateShallowArrayLiteral,24,5 +block_count,CreateShallowArrayLiteral,24,6 block_count,CreateShallowArrayLiteral,25,0 block_count,CreateShallowArrayLiteral,26,0 block_count,CreateShallowArrayLiteral,27,0 @@ -48254,8 +48213,8 @@ block_count,CreateShallowArrayLiteral,33,0 block_count,CreateShallowArrayLiteral,34,0 block_count,CreateShallowArrayLiteral,35,0 -block_count,CreateShallowArrayLiteral,36,5 -block_count,CreateShallowArrayLiteral,37,5 +block_count,CreateShallowArrayLiteral,36,6 +block_count,CreateShallowArrayLiteral,37,6 block_count,CreateShallowArrayLiteral,38,0 block_count,CreateShallowArrayLiteral,39,2 block_count,CreateShallowArrayLiteral,40,8 @@ -48307,14 +48266,14 @@ block_count,CreateShallowObjectLiteral,0,17 block_count,CreateShallowObjectLiteral,1,17 block_count,CreateShallowObjectLiteral,2,0 -block_count,CreateShallowObjectLiteral,3,16 -block_count,CreateShallowObjectLiteral,4,16 -block_count,CreateShallowObjectLiteral,5,16 -block_count,CreateShallowObjectLiteral,6,16 +block_count,CreateShallowObjectLiteral,3,17 +block_count,CreateShallowObjectLiteral,4,17 +block_count,CreateShallowObjectLiteral,5,17 +block_count,CreateShallowObjectLiteral,6,17 block_count,CreateShallowObjectLiteral,7,0 -block_count,CreateShallowObjectLiteral,8,16 +block_count,CreateShallowObjectLiteral,8,17 block_count,CreateShallowObjectLiteral,9,0 -block_count,CreateShallowObjectLiteral,10,16 +block_count,CreateShallowObjectLiteral,10,17 block_count,CreateShallowObjectLiteral,11,0 block_count,CreateShallowObjectLiteral,12,0 block_count,CreateShallowObjectLiteral,13,0 @@ -48356,7 +48315,7 @@ block_count,CreateShallowObjectLiteral,49,0 block_count,CreateShallowObjectLiteral,50,0 block_count,CreateShallowObjectLiteral,51,0 -block_count,CreateShallowObjectLiteral,52,16 +block_count,CreateShallowObjectLiteral,52,17 block_count,CreateShallowObjectLiteral,53,0 block_count,CreateShallowObjectLiteral,54,0 block_count,CreateShallowObjectLiteral,55,0 @@ -48418,17 +48377,17 @@ block_count,CreateShallowObjectLiteral,111,0 block_count,CreateShallowObjectLiteral,112,0 block_count,CreateShallowObjectLiteral,113,0 -block_count,CreateShallowObjectLiteral,114,16 -block_count,CreateShallowObjectLiteral,115,16 -block_count,CreateShallowObjectLiteral,116,16 +block_count,CreateShallowObjectLiteral,114,17 +block_count,CreateShallowObjectLiteral,115,17 +block_count,CreateShallowObjectLiteral,116,17 block_count,CreateShallowObjectLiteral,117,0 -block_count,CreateShallowObjectLiteral,118,16 +block_count,CreateShallowObjectLiteral,118,17 block_count,CreateShallowObjectLiteral,119,0 block_count,CreateShallowObjectLiteral,120,0 -block_count,CreateShallowObjectLiteral,121,16 -block_count,CreateShallowObjectLiteral,122,16 -block_count,CreateShallowObjectLiteral,123,45 -block_count,CreateShallowObjectLiteral,124,39 +block_count,CreateShallowObjectLiteral,121,17 +block_count,CreateShallowObjectLiteral,122,17 +block_count,CreateShallowObjectLiteral,123,46 +block_count,CreateShallowObjectLiteral,124,40 block_count,CreateShallowObjectLiteral,125,0 block_count,CreateShallowObjectLiteral,126,0 block_count,CreateShallowObjectLiteral,127,0 @@ -48455,10 +48414,10 @@ block_count,CreateShallowObjectLiteral,148,0 block_count,CreateShallowObjectLiteral,149,0 block_count,CreateShallowObjectLiteral,150,0 -block_count,CreateShallowObjectLiteral,151,39 +block_count,CreateShallowObjectLiteral,151,40 block_count,CreateShallowObjectLiteral,152,6 -block_count,CreateShallowObjectLiteral,153,45 -block_count,CreateShallowObjectLiteral,154,28 +block_count,CreateShallowObjectLiteral,153,46 +block_count,CreateShallowObjectLiteral,154,29 block_count,CreateShallowObjectLiteral,155,16 block_count,CreateShallowObjectLiteral,156,0 block_count,CreateShallowObjectLiteral,157,0 @@ -48600,7 +48559,7 @@ block_count,ToNumeric,1,0 block_count,ToNumeric,2,14 block_count,ToNumeric,3,14 -block_count,NumberToString,0,1322 +block_count,NumberToString,0,1321 block_count,NumberToString,1,41 block_count,NumberToString,2,41 block_count,NumberToString,3,0 @@ -48690,12 +48649,12 @@ block_count,ToBoolean,17,0 block_count,ToBoolean,18,0 block_count,ToBooleanForBaselineJump,0,480 -block_count,ToBooleanForBaselineJump,1,448 -block_count,ToBooleanForBaselineJump,2,172 +block_count,ToBooleanForBaselineJump,1,450 +block_count,ToBooleanForBaselineJump,2,171 block_count,ToBooleanForBaselineJump,3,78 block_count,ToBooleanForBaselineJump,4,78 -block_count,ToBooleanForBaselineJump,5,78 -block_count,ToBooleanForBaselineJump,6,78 +block_count,ToBooleanForBaselineJump,5,77 +block_count,ToBooleanForBaselineJump,6,77 block_count,ToBooleanForBaselineJump,7,0 block_count,ToBooleanForBaselineJump,8,0 block_count,ToBooleanForBaselineJump,9,0 @@ -48703,11 +48662,11 @@ block_count,ToBooleanForBaselineJump,11,0 block_count,ToBooleanForBaselineJump,12,0 block_count,ToBooleanForBaselineJump,13,0 -block_count,ToBooleanForBaselineJump,14,94 -block_count,ToBooleanForBaselineJump,15,276 -block_count,ToBooleanForBaselineJump,16,31 -block_count,ToBooleanForBaselineJump,17,18 -block_count,ToBooleanForBaselineJump,18,13 +block_count,ToBooleanForBaselineJump,14,93 +block_count,ToBooleanForBaselineJump,15,278 +block_count,ToBooleanForBaselineJump,16,29 +block_count,ToBooleanForBaselineJump,17,16 +block_count,ToBooleanForBaselineJump,18,12 block_count,ToLength,0,2 block_count,ToLength,1,2 block_count,ToLength,2,0 @@ -49469,7 +49428,7 @@ block_count,FunctionPrototypeHasInstance,14,2 block_count,FunctionPrototypeHasInstance,15,2 block_count,FunctionPrototypeHasInstance,16,0 -block_count,FunctionPrototypeHasInstance,17,50 +block_count,FunctionPrototypeHasInstance,17,49 block_count,FunctionPrototypeHasInstance,18,52 block_count,FunctionPrototypeHasInstance,19,181 block_count,FunctionPrototypeHasInstance,20,178 @@ -49567,8 +49526,8 @@ block_count,GetIteratorWithFeedback,1,0 block_count,GetIteratorWithFeedback,2,0 block_count,GetIteratorBaseline,0,13 -block_count,CallIteratorWithFeedback,0,14 -block_count,CallIteratorWithFeedback,1,14 +block_count,CallIteratorWithFeedback,0,13 +block_count,CallIteratorWithFeedback,1,13 block_count,CallIteratorWithFeedback,2,0 block_count,CallIteratorWithFeedback,3,0 block_count,CallIteratorWithFeedback,4,0 @@ -49633,15 +49592,15 @@ block_count,CallIteratorWithFeedback,63,0 block_count,CallIteratorWithFeedback,64,0 block_count,CallIteratorWithFeedback,65,0 -block_count,CallIteratorWithFeedback,66,14 +block_count,CallIteratorWithFeedback,66,13 block_count,CallIteratorWithFeedback,67,0 -block_count,CallIteratorWithFeedback,68,14 -block_count,CallIteratorWithFeedback,69,14 +block_count,CallIteratorWithFeedback,68,13 +block_count,CallIteratorWithFeedback,69,13 block_count,CallIteratorWithFeedback,70,0 -block_count,CallIteratorWithFeedback,71,14 -block_count,CallIteratorWithFeedback,72,14 +block_count,CallIteratorWithFeedback,71,13 +block_count,CallIteratorWithFeedback,72,13 block_count,CallIteratorWithFeedback,73,0 -block_count,CallIteratorWithFeedback,74,14 +block_count,CallIteratorWithFeedback,74,13 block_count,MathAbs,0,0 block_count,MathAbs,1,0 block_count,MathAbs,2,0 @@ -49812,26 +49771,26 @@ block_count,MathMax,1,0 block_count,MathMax,2,4 block_count,MathMax,3,4 -block_count,MathMax,4,13 -block_count,MathMax,5,9 -block_count,MathMax,6,9 +block_count,MathMax,4,12 +block_count,MathMax,5,8 +block_count,MathMax,6,8 block_count,MathMax,7,0 -block_count,MathMax,8,9 -block_count,MathMax,9,9 +block_count,MathMax,8,8 +block_count,MathMax,9,8 block_count,MathMax,10,1 block_count,MathMax,11,1 block_count,MathMax,12,0 block_count,MathMax,13,7 -block_count,MathMax,14,9 +block_count,MathMax,14,8 block_count,MathMax,15,4 block_count,MathMax,16,1 -block_count,MathMax,17,3 +block_count,MathMax,17,2 block_count,MathMax,18,2 block_count,MathMax,19,0 block_count,MathMax,20,0 block_count,MathMax,21,0 -block_count,MathMax,22,3 -block_count,MathMax,23,3 +block_count,MathMax,22,2 +block_count,MathMax,23,2 block_count,MathMax,24,0 block_count,MathMax,25,1 block_count,MathMax,26,0 @@ -50100,16 +50059,16 @@ block_count,MathSqrt,1,0 block_count,MathSqrt,2,9 block_count,MathSqrt,3,9 -block_count,MathSqrt,4,7 -block_count,MathSqrt,5,7 +block_count,MathSqrt,4,6 +block_count,MathSqrt,5,6 block_count,MathSqrt,6,0 -block_count,MathSqrt,7,7 +block_count,MathSqrt,7,6 block_count,MathSqrt,8,2 block_count,MathSqrt,9,9 -block_count,MathSqrt,10,7 +block_count,MathSqrt,10,6 block_count,MathSqrt,11,2 block_count,MathSqrt,12,9 -block_count,MathSqrt,13,7 +block_count,MathSqrt,13,6 block_count,MathSqrt,14,2 block_count,MathSqrt,15,1 block_count,MathSqrt,16,0 @@ -50118,10 +50077,10 @@ block_count,MathSqrt,19,2 block_count,MathSqrt,20,2 block_count,MathSqrt,21,0 -block_count,MathSqrt,22,7 +block_count,MathSqrt,22,6 block_count,MathSqrt,23,0 -block_count,MathSqrt,24,7 -block_count,MathSqrt,25,7 +block_count,MathSqrt,24,6 +block_count,MathSqrt,25,6 block_count,MathTan,0,0 block_count,MathTan,1,0 block_count,MathTan,2,0 @@ -50444,9 +50403,9 @@ block_count,ParseInt,28,5 block_count,ParseInt,29,3 block_count,ParseInt,30,63 -block_count,NumberParseInt,0,7 +block_count,NumberParseInt,0,6 block_count,NumberParseInt,1,0 -block_count,NumberParseInt,2,7 +block_count,NumberParseInt,2,6 block_count,Add,0,43 block_count,Add,1,44 block_count,Add,2,1 @@ -50816,8 +50775,8 @@ block_count,LessThan,73,549 block_count,LessThan,74,116 block_count,GreaterThan,0,582 -block_count,GreaterThan,1,1009 -block_count,GreaterThan,2,993 +block_count,GreaterThan,1,1010 +block_count,GreaterThan,2,994 block_count,GreaterThan,3,903 block_count,GreaterThan,4,14 block_count,GreaterThan,5,14 @@ -51075,12 +51034,12 @@ block_count,Equal,112,2 block_count,Equal,113,39 block_count,StrictEqual,0,1254 -block_count,StrictEqual,1,1110 +block_count,StrictEqual,1,1111 block_count,StrictEqual,2,1086 block_count,StrictEqual,3,1044 block_count,StrictEqual,4,1020 -block_count,StrictEqual,5,158 -block_count,StrictEqual,6,158 +block_count,StrictEqual,5,157 +block_count,StrictEqual,6,157 block_count,StrictEqual,7,0 block_count,StrictEqual,8,0 block_count,StrictEqual,9,0 @@ -51113,7 +51072,7 @@ block_count,StrictEqual,36,0 block_count,StrictEqual,37,862 block_count,StrictEqual,38,43 -block_count,StrictEqual,39,818 +block_count,StrictEqual,39,819 block_count,StrictEqual,40,457 block_count,StrictEqual,41,361 block_count,StrictEqual,42,23 @@ -51132,7 +51091,7 @@ block_count,StrictEqual,55,0 block_count,StrictEqual,56,0 block_count,StrictEqual,57,0 -block_count,StrictEqual,58,23 +block_count,StrictEqual,58,24 block_count,StrictEqual,59,143 block_count,StrictEqual,60,141 block_count,StrictEqual,61,141 @@ -52574,12 +52533,12 @@ block_count,RegExpPrototypeExec,33,0 block_count,RegExpPrototypeExec,34,312 block_count,RegExpPrototypeExec,35,322 -block_count,RegExpPrototypeExec,36,11 -block_count,RegExpPrototypeExec,37,11 +block_count,RegExpPrototypeExec,36,10 +block_count,RegExpPrototypeExec,37,10 block_count,RegExpPrototypeExec,38,7 block_count,RegExpPrototypeExec,39,0 block_count,RegExpPrototypeExec,40,7 -block_count,RegExpPrototypeExec,41,3 +block_count,RegExpPrototypeExec,41,2 block_count,RegExpPrototypeExec,42,2 block_count,RegExpPrototypeExec,43,0 block_count,RegExpPrototypeExec,44,10 @@ -53454,7 +53413,7 @@ block_count,RegExpReplace,93,40 block_count,RegExpReplace,94,625 block_count,RegExpReplace,95,625 -block_count,RegExpReplace,96,607 +block_count,RegExpReplace,96,606 block_count,RegExpReplace,97,18 block_count,RegExpReplace,98,0 block_count,RegExpReplace,99,18 @@ -54202,31 +54161,31 @@ block_count,RegExpSplit,357,0 block_count,RegExpSplit,358,0 block_count,RegExpSplit,359,0 -block_count,RegExpPrototypeTest,0,100 +block_count,RegExpPrototypeTest,0,101 block_count,RegExpPrototypeTest,1,0 -block_count,RegExpPrototypeTest,2,100 -block_count,RegExpPrototypeTest,3,100 -block_count,RegExpPrototypeTest,4,100 -block_count,RegExpPrototypeTest,5,100 -block_count,RegExpPrototypeTest,6,100 +block_count,RegExpPrototypeTest,2,101 +block_count,RegExpPrototypeTest,3,101 +block_count,RegExpPrototypeTest,4,101 +block_count,RegExpPrototypeTest,5,101 +block_count,RegExpPrototypeTest,6,101 block_count,RegExpPrototypeTest,7,34 block_count,RegExpPrototypeTest,8,66 block_count,RegExpPrototypeTest,9,0 block_count,RegExpPrototypeTest,10,34 -block_count,RegExpPrototypeTest,11,100 -block_count,RegExpPrototypeTest,12,100 +block_count,RegExpPrototypeTest,11,101 +block_count,RegExpPrototypeTest,12,101 block_count,RegExpPrototypeTest,13,0 -block_count,RegExpPrototypeTest,14,100 +block_count,RegExpPrototypeTest,14,101 block_count,RegExpPrototypeTest,15,0 -block_count,RegExpPrototypeTest,16,100 +block_count,RegExpPrototypeTest,16,101 block_count,RegExpPrototypeTest,17,0 -block_count,RegExpPrototypeTest,18,100 +block_count,RegExpPrototypeTest,18,101 block_count,RegExpPrototypeTest,19,0 -block_count,RegExpPrototypeTest,20,100 +block_count,RegExpPrototypeTest,20,101 block_count,RegExpPrototypeTest,21,0 -block_count,RegExpPrototypeTest,22,100 +block_count,RegExpPrototypeTest,22,101 block_count,RegExpPrototypeTest,23,0 -block_count,RegExpPrototypeTest,24,100 +block_count,RegExpPrototypeTest,24,101 block_count,RegExpPrototypeTest,25,0 block_count,RegExpPrototypeTest,26,0 block_count,RegExpPrototypeTest,27,0 @@ -54255,25 +54214,25 @@ block_count,RegExpPrototypeTest,50,0 block_count,RegExpPrototypeTest,51,0 block_count,RegExpPrototypeTest,52,0 -block_count,RegExpPrototypeTest,53,100 -block_count,RegExpPrototypeTest,54,100 +block_count,RegExpPrototypeTest,53,101 +block_count,RegExpPrototypeTest,54,101 block_count,RegExpPrototypeTest,55,0 block_count,RegExpPrototypeTest,56,0 block_count,RegExpPrototypeTest,57,0 block_count,RegExpPrototypeTest,58,0 block_count,RegExpPrototypeTest,59,0 block_count,RegExpPrototypeTest,60,0 -block_count,RegExpPrototypeTest,61,100 +block_count,RegExpPrototypeTest,61,101 block_count,RegExpPrototypeTest,62,0 -block_count,RegExpPrototypeTest,63,100 -block_count,RegExpPrototypeTest,64,100 -block_count,RegExpPrototypeTest,65,100 +block_count,RegExpPrototypeTest,63,101 +block_count,RegExpPrototypeTest,64,101 +block_count,RegExpPrototypeTest,65,101 block_count,RegExpPrototypeTest,66,0 block_count,RegExpPrototypeTest,67,99 block_count,RegExpPrototypeTest,68,1 block_count,RegExpPrototypeTest,69,0 block_count,RegExpPrototypeTest,70,99 -block_count,RegExpPrototypeTest,71,114 +block_count,RegExpPrototypeTest,71,115 block_count,RegExpPrototypeTest,72,49 block_count,RegExpPrototypeTest,73,49 block_count,RegExpPrototypeTest,74,15 @@ -54325,10 +54284,10 @@ block_count,RegExpPrototypeTest,120,0 block_count,RegExpPrototypeTest,121,0 block_count,RegExpPrototypeTest,122,53 -block_count,RegExpPrototypeTest,123,100 +block_count,RegExpPrototypeTest,123,101 block_count,RegExpPrototypeTest,124,65 block_count,RegExpPrototypeTest,125,35 -block_count,RegExpPrototypeTest,126,100 +block_count,RegExpPrototypeTest,126,101 block_count,RegExpPrototypeTest,127,87 block_count,RegExpPrototypeTest,128,87 block_count,RegExpPrototypeTest,129,0 @@ -54349,10 +54308,10 @@ block_count,RegExpPrototypeTestFast,11,377 block_count,RegExpPrototypeTestFast,12,377 block_count,RegExpPrototypeTestFast,13,0 -block_count,RegExpPrototypeTestFast,14,373 +block_count,RegExpPrototypeTestFast,14,372 block_count,RegExpPrototypeTestFast,15,4 block_count,RegExpPrototypeTestFast,16,0 -block_count,RegExpPrototypeTestFast,17,373 +block_count,RegExpPrototypeTestFast,17,372 block_count,RegExpPrototypeTestFast,18,479 block_count,RegExpPrototypeTestFast,19,106 block_count,RegExpPrototypeTestFast,20,106 @@ -54366,24 +54325,24 @@ block_count,RegExpPrototypeTestFast,28,0 block_count,RegExpPrototypeTestFast,29,0 block_count,RegExpPrototypeTestFast,30,0 -block_count,RegExpPrototypeTestFast,31,373 -block_count,RegExpPrototypeTestFast,32,373 +block_count,RegExpPrototypeTestFast,31,372 +block_count,RegExpPrototypeTestFast,32,372 block_count,RegExpPrototypeTestFast,33,0 block_count,RegExpPrototypeTestFast,34,0 block_count,RegExpPrototypeTestFast,35,0 -block_count,RegExpPrototypeTestFast,36,373 -block_count,RegExpPrototypeTestFast,37,373 +block_count,RegExpPrototypeTestFast,36,372 +block_count,RegExpPrototypeTestFast,37,372 block_count,RegExpPrototypeTestFast,38,0 -block_count,RegExpPrototypeTestFast,39,373 -block_count,RegExpPrototypeTestFast,40,373 -block_count,RegExpPrototypeTestFast,41,373 -block_count,RegExpPrototypeTestFast,42,263 +block_count,RegExpPrototypeTestFast,39,372 +block_count,RegExpPrototypeTestFast,40,372 +block_count,RegExpPrototypeTestFast,41,372 +block_count,RegExpPrototypeTestFast,42,262 block_count,RegExpPrototypeTestFast,43,0 block_count,RegExpPrototypeTestFast,44,0 block_count,RegExpPrototypeTestFast,45,0 block_count,RegExpPrototypeTestFast,46,0 block_count,RegExpPrototypeTestFast,47,0 -block_count,RegExpPrototypeTestFast,48,263 +block_count,RegExpPrototypeTestFast,48,262 block_count,RegExpPrototypeTestFast,49,110 block_count,RegExpPrototypeTestFast,50,110 block_count,RegExpPrototypeTestFast,51,0 @@ -54404,15 +54363,15 @@ block_count,RegExpPrototypeTestFast,66,0 block_count,RegExpPrototypeTestFast,67,0 block_count,RegExpPrototypeTestFast,68,0 -block_count,RegExpPrototypeTestFast,69,263 +block_count,RegExpPrototypeTestFast,69,262 block_count,RegExpPrototypeTestFast,70,377 -block_count,RegExpPrototypeTestFast,71,373 +block_count,RegExpPrototypeTestFast,71,372 block_count,RegExpPrototypeTestFast,72,4 block_count,RegExpPrototypeTestFast,73,377 -block_count,RegExpPrototypeTestFast,74,263 -block_count,RegExpPrototypeTestFast,75,263 +block_count,RegExpPrototypeTestFast,74,262 +block_count,RegExpPrototypeTestFast,75,262 block_count,RegExpPrototypeTestFast,76,0 -block_count,RegExpPrototypeTestFast,77,263 +block_count,RegExpPrototypeTestFast,77,262 block_count,RegExpPrototypeTestFast,78,114 block_count,RegExpPrototypeTestFast,79,114 block_count,RegExpPrototypeGlobalGetter,0,0 @@ -55517,7 +55476,7 @@ block_count,StringPrototypeSlice,174,6 block_count,StringPrototypeSlice,175,5 block_count,StringPrototypeSlice,176,5 -block_count,StringPrototypeSlice,177,4 +block_count,StringPrototypeSlice,177,3 block_count,StringPrototypeSlice,178,1 block_count,StringPrototypeSlice,179,5 block_count,StringPrototypeSlice,180,7 @@ -55614,15 +55573,15 @@ block_count,StringPrototypeSlice,271,0 block_count,StringPrototypeSlice,272,6 block_count,StringPrototypeSlice,273,10 -block_count,StringPrototypeSlice,274,3 -block_count,StringPrototypeSlice,275,3 +block_count,StringPrototypeSlice,274,4 +block_count,StringPrototypeSlice,275,4 block_count,StringPrototypeSlice,276,0 block_count,StringPrototypeSlice,277,0 block_count,StringPrototypeSlice,278,0 block_count,StringPrototypeSlice,279,3 block_count,StringPrototypeSlice,280,3 block_count,StringPrototypeSlice,281,0 -block_count,StringPrototypeSlice,282,3 +block_count,StringPrototypeSlice,282,4 block_count,StringPrototypeSlice,283,0 block_count,StringPrototypeSlice,284,0 block_count,StringPrototypeSlice,285,0 @@ -55633,8 +55592,8 @@ block_count,StringPrototypeSlice,290,0 block_count,StringPrototypeSlice,291,0 block_count,StringPrototypeSlice,292,0 -block_count,StringPrototypeSlice,293,6 -block_count,StringPrototypeSlice,294,6 +block_count,StringPrototypeSlice,293,5 +block_count,StringPrototypeSlice,294,5 block_count,StringPrototypeSlice,295,0 block_count,StringPrototypeSlice,296,5 block_count,StringPrototypeSlice,297,6 @@ -55917,26 +55876,26 @@ block_count,StringPrototypeStartsWith,264,0 block_count,StringPrototypeStartsWith,265,0 block_count,StringPrototypeStartsWith,266,0 -block_count,StringPrototypeSubstr,0,1 +block_count,StringPrototypeSubstr,0,2 block_count,StringPrototypeSubstr,1,0 -block_count,StringPrototypeSubstr,2,1 -block_count,StringPrototypeSubstr,3,1 -block_count,StringPrototypeSubstr,4,1 +block_count,StringPrototypeSubstr,2,2 +block_count,StringPrototypeSubstr,3,2 +block_count,StringPrototypeSubstr,4,2 block_count,StringPrototypeSubstr,5,0 block_count,StringPrototypeSubstr,6,0 block_count,StringPrototypeSubstr,7,0 -block_count,StringPrototypeSubstr,8,1 +block_count,StringPrototypeSubstr,8,2 block_count,StringPrototypeSubstr,9,0 -block_count,StringPrototypeSubstr,10,1 -block_count,StringPrototypeSubstr,11,1 +block_count,StringPrototypeSubstr,10,2 +block_count,StringPrototypeSubstr,11,2 block_count,StringPrototypeSubstr,12,0 -block_count,StringPrototypeSubstr,13,1 +block_count,StringPrototypeSubstr,13,2 block_count,StringPrototypeSubstr,14,0 -block_count,StringPrototypeSubstr,15,1 -block_count,StringPrototypeSubstr,16,1 +block_count,StringPrototypeSubstr,15,2 +block_count,StringPrototypeSubstr,16,2 block_count,StringPrototypeSubstr,17,0 -block_count,StringPrototypeSubstr,18,1 -block_count,StringPrototypeSubstr,19,1 +block_count,StringPrototypeSubstr,18,2 +block_count,StringPrototypeSubstr,19,2 block_count,StringPrototypeSubstr,20,1 block_count,StringPrototypeSubstr,21,0 block_count,StringPrototypeSubstr,22,1 @@ -55952,12 +55911,12 @@ block_count,StringPrototypeSubstr,32,0 block_count,StringPrototypeSubstr,33,0 block_count,StringPrototypeSubstr,34,0 -block_count,StringPrototypeSubstr,35,1 -block_count,StringPrototypeSubstr,36,1 -block_count,StringPrototypeSubstr,37,1 +block_count,StringPrototypeSubstr,35,2 +block_count,StringPrototypeSubstr,36,2 +block_count,StringPrototypeSubstr,37,2 block_count,StringPrototypeSubstr,38,1 block_count,StringPrototypeSubstr,39,0 -block_count,StringPrototypeSubstr,40,1 +block_count,StringPrototypeSubstr,40,2 block_count,StringPrototypeSubstr,41,0 block_count,StringPrototypeSubstr,42,1 block_count,StringPrototypeSubstr,43,1 @@ -55974,8 +55933,8 @@ block_count,StringPrototypeSubstr,54,0 block_count,StringPrototypeSubstr,55,0 block_count,StringPrototypeSubstr,56,1 -block_count,StringPrototypeSubstr,57,1 -block_count,StringPrototypeSubstr,58,1 +block_count,StringPrototypeSubstr,57,2 +block_count,StringPrototypeSubstr,58,2 block_count,StringPrototypeSubstr,59,1 block_count,StringPrototypeSubstr,60,1 block_count,StringPrototypeSubstr,61,1 @@ -57888,7 +57847,7 @@ block_count,CreateTypedArray,669,16 block_count,CreateTypedArray,670,0 block_count,CreateTypedArray,671,16 -block_count,CreateTypedArray,672,101 +block_count,CreateTypedArray,672,100 block_count,CreateTypedArray,673,84 block_count,CreateTypedArray,674,16 block_count,CreateTypedArray,675,16 @@ -58968,9 +58927,9 @@ block_count,FastNewSloppyArguments,93,0 block_count,FastNewSloppyArguments,94,1 block_count,FastNewSloppyArguments,95,1 -block_count,FastNewStrictArguments,0,1 -block_count,FastNewStrictArguments,1,1 -block_count,FastNewStrictArguments,2,1 +block_count,FastNewStrictArguments,0,2 +block_count,FastNewStrictArguments,1,2 +block_count,FastNewStrictArguments,2,2 block_count,FastNewStrictArguments,3,1 block_count,FastNewStrictArguments,4,1 block_count,FastNewStrictArguments,5,1 @@ -58981,7 +58940,7 @@ block_count,FastNewStrictArguments,10,0 block_count,FastNewStrictArguments,11,0 block_count,FastNewStrictArguments,12,1 -block_count,FastNewStrictArguments,13,4 +block_count,FastNewStrictArguments,13,5 block_count,FastNewStrictArguments,14,3 block_count,FastNewStrictArguments,15,3 block_count,FastNewStrictArguments,16,3 @@ -58993,12 +58952,12 @@ block_count,FastNewStrictArguments,22,0 block_count,FastNewStrictArguments,23,0 block_count,FastNewStrictArguments,24,0 -block_count,FastNewStrictArguments,25,1 +block_count,FastNewStrictArguments,25,2 block_count,FastNewStrictArguments,26,0 -block_count,FastNewStrictArguments,27,1 +block_count,FastNewStrictArguments,27,2 block_count,FastNewStrictArguments,28,0 -block_count,FastNewStrictArguments,29,1 -block_count,FastNewStrictArguments,30,1 +block_count,FastNewStrictArguments,29,2 +block_count,FastNewStrictArguments,30,2 block_count,FastNewRestArguments,0,0 block_count,FastNewRestArguments,1,0 block_count,FastNewRestArguments,2,0 @@ -61093,13 +61052,13 @@ block_count,StringToLowerCaseIntl,38,0 block_count,StringToLowerCaseIntl,39,0 block_count,StringToLowerCaseIntl,40,0 -block_count,WideHandler,0,55 +block_count,WideHandler,0,54 block_count,ExtraWideHandler,0,9 -block_count,LdarHandler,0,76 -block_count,LdaZeroHandler,0,9 -block_count,LdaZeroHandler,1,6 +block_count,LdarHandler,0,74 +block_count,LdaZeroHandler,0,10 +block_count,LdaZeroHandler,1,7 block_count,LdaZeroHandler,2,2 -block_count,LdaSmiHandler,0,11 +block_count,LdaSmiHandler,0,10 block_count,LdaSmiHandler,1,7 block_count,LdaSmiHandler,2,3 block_count,LdaUndefinedHandler,0,7 @@ -61115,7 +61074,7 @@ block_count,LdaFalseHandler,0,2 block_count,LdaConstantHandler,0,12 block_count,LdaConstantHandler,1,5 -block_count,LdaConstantHandler,2,7 +block_count,LdaConstantHandler,2,6 block_count,LdaContextSlotHandler,0,0 block_count,LdaContextSlotHandler,1,0 block_count,LdaContextSlotHandler,2,0 @@ -61142,18 +61101,18 @@ block_count,LdaImmutableContextSlotHandler,10,6 block_count,LdaImmutableContextSlotHandler,11,1 block_count,LdaImmutableContextSlotHandler,12,4 -block_count,LdaCurrentContextSlotHandler,0,6 +block_count,LdaCurrentContextSlotHandler,0,5 block_count,LdaCurrentContextSlotHandler,1,0 -block_count,LdaCurrentContextSlotHandler,2,6 +block_count,LdaCurrentContextSlotHandler,2,5 block_count,LdaCurrentContextSlotHandler,3,2 block_count,LdaCurrentContextSlotHandler,4,3 block_count,LdaImmutableCurrentContextSlotHandler,0,17 block_count,LdaImmutableCurrentContextSlotHandler,1,0 block_count,LdaImmutableCurrentContextSlotHandler,2,17 -block_count,LdaImmutableCurrentContextSlotHandler,3,4 +block_count,LdaImmutableCurrentContextSlotHandler,3,3 block_count,LdaImmutableCurrentContextSlotHandler,4,13 -block_count,StarHandler,0,18 -block_count,MovHandler,0,17 +block_count,StarHandler,0,17 +block_count,MovHandler,0,16 block_count,PushContextHandler,0,1 block_count,PopContextHandler,0,0 block_count,TestReferenceEqualHandler,0,0 @@ -61226,13 +61185,13 @@ block_count,TestTypeOfHandler,48,0 block_count,TestTypeOfHandler,49,0 block_count,TestTypeOfHandler,50,0 -block_count,LdaGlobalHandler,0,22 -block_count,LdaGlobalHandler,1,13 -block_count,LdaGlobalHandler,2,13 -block_count,LdaGlobalHandler,3,13 -block_count,LdaGlobalHandler,4,13 -block_count,LdaGlobalHandler,5,4 -block_count,LdaGlobalHandler,6,9 +block_count,LdaGlobalHandler,0,20 +block_count,LdaGlobalHandler,1,12 +block_count,LdaGlobalHandler,2,11 +block_count,LdaGlobalHandler,3,11 +block_count,LdaGlobalHandler,4,11 +block_count,LdaGlobalHandler,5,3 +block_count,LdaGlobalHandler,6,7 block_count,LdaGlobalHandler,7,0 block_count,LdaGlobalHandler,8,0 block_count,LdaGlobalHandler,9,0 @@ -62405,11 +62364,11 @@ block_count,StaLookupSlotHandler,3,0 block_count,StaLookupSlotHandler,4,0 block_count,StaLookupSlotHandler,5,0 -block_count,GetNamedPropertyHandler,0,67 -block_count,GetNamedPropertyHandler,1,42 -block_count,GetNamedPropertyHandler,2,42 +block_count,GetNamedPropertyHandler,0,65 +block_count,GetNamedPropertyHandler,1,41 +block_count,GetNamedPropertyHandler,2,41 block_count,GetNamedPropertyHandler,3,0 -block_count,GetNamedPropertyHandler,4,42 +block_count,GetNamedPropertyHandler,4,41 block_count,GetNamedPropertyHandler,5,5 block_count,GetNamedPropertyHandler,6,0 block_count,GetNamedPropertyHandler,7,5 @@ -62420,8 +62379,8 @@ block_count,GetNamedPropertyHandler,12,2 block_count,GetNamedPropertyHandler,13,0 block_count,GetNamedPropertyHandler,14,2 -block_count,GetNamedPropertyHandler,15,37 -block_count,GetNamedPropertyHandler,16,40 +block_count,GetNamedPropertyHandler,15,36 +block_count,GetNamedPropertyHandler,16,38 block_count,GetNamedPropertyHandler,17,13 block_count,GetNamedPropertyHandler,18,13 block_count,GetNamedPropertyHandler,19,12 @@ -62503,11 +62462,11 @@ block_count,GetNamedPropertyHandler,95,0 block_count,GetNamedPropertyHandler,96,2 block_count,GetNamedPropertyHandler,97,0 -block_count,GetNamedPropertyHandler,98,10 +block_count,GetNamedPropertyHandler,98,9 block_count,GetNamedPropertyHandler,99,12 block_count,GetNamedPropertyHandler,100,12 -block_count,GetNamedPropertyHandler,101,12 -block_count,GetNamedPropertyHandler,102,12 +block_count,GetNamedPropertyHandler,101,11 +block_count,GetNamedPropertyHandler,102,11 block_count,GetNamedPropertyHandler,103,0 block_count,GetNamedPropertyHandler,104,0 block_count,GetNamedPropertyHandler,105,12 @@ -62516,9 +62475,9 @@ block_count,GetNamedPropertyHandler,108,0 block_count,GetNamedPropertyHandler,109,0 block_count,GetNamedPropertyHandler,110,0 -block_count,GetNamedPropertyHandler,111,26 -block_count,GetNamedPropertyHandler,112,38 -block_count,GetNamedPropertyHandler,113,13 +block_count,GetNamedPropertyHandler,111,25 +block_count,GetNamedPropertyHandler,112,37 +block_count,GetNamedPropertyHandler,113,12 block_count,GetNamedPropertyHandler,114,2 block_count,GetNamedPropertyHandler,115,2 block_count,GetNamedPropertyHandler,116,1 @@ -62652,13 +62611,13 @@ block_count,GetNamedPropertyHandler,244,0 block_count,GetNamedPropertyHandler,245,0 block_count,GetNamedPropertyHandler,246,0 -block_count,GetNamedPropertyHandler,247,10 +block_count,GetNamedPropertyHandler,247,9 block_count,GetNamedPropertyHandler,248,25 block_count,GetNamedPropertyHandler,249,25 block_count,GetNamedPropertyHandler,250,4 block_count,GetNamedPropertyHandler,251,20 block_count,GetNamedPropertyHandler,252,25 -block_count,GetNamedPropertyHandler,253,24 +block_count,GetNamedPropertyHandler,253,23 block_count,GetNamedPropertyHandler,254,1 block_count,GetNamedPropertyHandler,255,1 block_count,GetNamedPropertyHandler,256,1 @@ -62706,26 +62665,26 @@ block_count,GetNamedPropertyHandler,298,1 block_count,GetNamedPropertyHandler,299,0 block_count,GetNamedPropertyHandler,300,24 -block_count,GetNamedPropertyHandler,301,67 +block_count,GetNamedPropertyHandler,301,65 block_count,GetNamedPropertyHandler,302,18 -block_count,GetNamedPropertyHandler,303,48 +block_count,GetNamedPropertyHandler,303,47 block_count,GetNamedPropertyFromSuperHandler,0,0 -block_count,GetKeyedPropertyHandler,0,18 +block_count,GetKeyedPropertyHandler,0,17 block_count,GetKeyedPropertyHandler,1,8 block_count,GetKeyedPropertyHandler,2,9 block_count,GetEnumeratedKeyedPropertyHandler,0,1 -block_count,SetNamedPropertyHandler,0,9 +block_count,SetNamedPropertyHandler,0,10 block_count,DefineNamedOwnPropertyHandler,0,2 -block_count,SetKeyedPropertyHandler,0,11 +block_count,SetKeyedPropertyHandler,0,10 block_count,DefineKeyedOwnPropertyHandler,0,0 block_count,StaInArrayLiteralHandler,0,1 block_count,DefineKeyedOwnPropertyInLiteralHandler,0,0 -block_count,AddHandler,0,10 -block_count,AddHandler,1,4 +block_count,AddHandler,0,9 +block_count,AddHandler,1,3 block_count,AddHandler,2,0 block_count,AddHandler,3,0 block_count,AddHandler,4,0 -block_count,AddHandler,5,4 +block_count,AddHandler,5,3 block_count,AddHandler,6,3 block_count,AddHandler,7,3 block_count,AddHandler,8,0 @@ -62735,8 +62694,8 @@ block_count,AddHandler,12,0 block_count,AddHandler,13,6 block_count,AddHandler,14,3 -block_count,AddHandler,15,3 -block_count,AddHandler,16,3 +block_count,AddHandler,15,2 +block_count,AddHandler,16,2 block_count,AddHandler,17,0 block_count,AddHandler,18,0 block_count,AddHandler,19,3 @@ -62837,16 +62796,16 @@ block_count,AddHandler,114,0 block_count,AddHandler,115,0 block_count,AddHandler,116,3 -block_count,AddHandler,117,3 +block_count,AddHandler,117,2 block_count,AddHandler,118,0 -block_count,AddHandler,119,3 +block_count,AddHandler,119,2 block_count,AddHandler,120,0 block_count,AddHandler,121,3 block_count,AddHandler,122,0 block_count,AddHandler,123,3 block_count,AddHandler,124,3 -block_count,AddHandler,125,10 -block_count,AddHandler,126,6 +block_count,AddHandler,125,9 +block_count,AddHandler,126,5 block_count,AddHandler,127,4 block_count,SubHandler,0,1 block_count,SubHandler,1,0 @@ -62949,15 +62908,15 @@ block_count,SubHandler,98,0 block_count,SubHandler,99,0 block_count,SubHandler,100,0 -block_count,SubHandler,101,1 +block_count,SubHandler,101,0 block_count,SubHandler,102,0 block_count,SubHandler,103,0 block_count,SubHandler,104,0 block_count,SubHandler,105,0 -block_count,SubHandler,106,1 +block_count,SubHandler,106,0 block_count,SubHandler,107,0 -block_count,SubHandler,108,1 -block_count,SubHandler,109,1 +block_count,SubHandler,108,0 +block_count,SubHandler,109,0 block_count,SubHandler,110,1 block_count,SubHandler,111,0 block_count,SubHandler,112,0 @@ -64127,14 +64086,14 @@ block_count,ShiftRightLogicalHandler,86,0 block_count,ShiftRightLogicalHandler,87,0 block_count,ShiftRightLogicalHandler,88,0 -block_count,AddSmiHandler,0,5 -block_count,AddSmiHandler,1,5 -block_count,AddSmiHandler,2,5 -block_count,AddSmiHandler,3,4 +block_count,AddSmiHandler,0,4 +block_count,AddSmiHandler,1,4 +block_count,AddSmiHandler,2,4 +block_count,AddSmiHandler,3,3 block_count,AddSmiHandler,4,0 -block_count,AddSmiHandler,5,4 +block_count,AddSmiHandler,5,3 block_count,AddSmiHandler,6,0 -block_count,AddSmiHandler,7,5 +block_count,AddSmiHandler,7,4 block_count,AddSmiHandler,8,0 block_count,AddSmiHandler,9,0 block_count,AddSmiHandler,10,0 @@ -64156,22 +64115,22 @@ block_count,AddSmiHandler,26,0 block_count,AddSmiHandler,27,0 block_count,AddSmiHandler,28,0 -block_count,AddSmiHandler,29,5 +block_count,AddSmiHandler,29,4 block_count,AddSmiHandler,30,3 block_count,AddSmiHandler,31,1 block_count,SubSmiHandler,0,1 -block_count,SubSmiHandler,1,1 -block_count,SubSmiHandler,2,1 +block_count,SubSmiHandler,1,0 +block_count,SubSmiHandler,2,0 block_count,SubSmiHandler,3,0 block_count,SubSmiHandler,4,0 block_count,SubSmiHandler,5,0 block_count,SubSmiHandler,6,0 -block_count,SubSmiHandler,7,1 +block_count,SubSmiHandler,7,0 block_count,SubSmiHandler,8,0 block_count,SubSmiHandler,9,0 block_count,SubSmiHandler,10,0 block_count,SubSmiHandler,11,0 -block_count,SubSmiHandler,12,1 +block_count,SubSmiHandler,12,0 block_count,SubSmiHandler,13,0 block_count,SubSmiHandler,14,0 block_count,SubSmiHandler,15,0 @@ -64503,14 +64462,14 @@ block_count,ShiftLeftSmiHandler,33,0 block_count,ShiftLeftSmiHandler,34,0 block_count,ShiftLeftSmiHandler,35,1 -block_count,ShiftLeftSmiHandler,36,1 +block_count,ShiftLeftSmiHandler,36,0 block_count,ShiftLeftSmiHandler,37,0 block_count,ShiftLeftSmiHandler,38,0 block_count,ShiftLeftSmiHandler,39,0 block_count,ShiftLeftSmiHandler,40,0 block_count,ShiftLeftSmiHandler,41,1 block_count,ShiftLeftSmiHandler,42,0 -block_count,ShiftLeftSmiHandler,43,1 +block_count,ShiftLeftSmiHandler,43,0 block_count,ShiftLeftSmiHandler,44,1 block_count,ShiftLeftSmiHandler,45,1 block_count,ShiftLeftSmiHandler,46,1 @@ -64611,8 +64570,8 @@ block_count,ShiftRightLogicalSmiHandler,48,0 block_count,ShiftRightLogicalSmiHandler,49,0 block_count,ShiftRightLogicalSmiHandler,50,0 -block_count,IncHandler,0,11 -block_count,IncHandler,1,11 +block_count,IncHandler,0,10 +block_count,IncHandler,1,10 block_count,IncHandler,2,0 block_count,IncHandler,3,0 block_count,IncHandler,4,0 @@ -64629,21 +64588,21 @@ block_count,IncHandler,15,0 block_count,IncHandler,16,0 block_count,IncHandler,17,0 -block_count,IncHandler,18,11 -block_count,IncHandler,19,11 +block_count,IncHandler,18,10 +block_count,IncHandler,19,10 block_count,IncHandler,20,0 block_count,IncHandler,21,0 block_count,IncHandler,22,0 block_count,IncHandler,23,0 block_count,IncHandler,24,0 -block_count,IncHandler,25,11 -block_count,IncHandler,26,10 +block_count,IncHandler,25,10 +block_count,IncHandler,26,9 block_count,IncHandler,27,0 -block_count,IncHandler,28,10 +block_count,IncHandler,28,9 block_count,IncHandler,29,0 -block_count,IncHandler,30,11 +block_count,IncHandler,30,10 block_count,IncHandler,31,1 -block_count,IncHandler,32,10 +block_count,IncHandler,32,9 block_count,DecHandler,0,2 block_count,DecHandler,1,2 block_count,DecHandler,2,0 @@ -64932,8 +64891,8 @@ block_count,CallAnyReceiverHandler,66,0 block_count,CallAnyReceiverHandler,67,0 block_count,CallAnyReceiverHandler,68,0 -block_count,CallPropertyHandler,0,2 -block_count,CallPropertyHandler,1,1 +block_count,CallPropertyHandler,0,1 +block_count,CallPropertyHandler,1,0 block_count,CallPropertyHandler,2,0 block_count,CallPropertyHandler,3,0 block_count,CallPropertyHandler,4,0 @@ -64998,9 +64957,9 @@ block_count,CallPropertyHandler,63,0 block_count,CallPropertyHandler,64,0 block_count,CallPropertyHandler,65,0 -block_count,CallPropertyHandler,66,1 +block_count,CallPropertyHandler,66,0 block_count,CallPropertyHandler,67,0 -block_count,CallPropertyHandler,68,2 +block_count,CallPropertyHandler,68,1 block_count,CallProperty0Handler,0,4 block_count,CallProperty0Handler,1,3 block_count,CallProperty0Handler,2,0 @@ -65416,7 +65375,7 @@ block_count,CallUndefinedReceiver1Handler,67,2 block_count,CallUndefinedReceiver1Handler,68,4 block_count,CallUndefinedReceiver2Handler,0,3 -block_count,CallUndefinedReceiver2Handler,1,2 +block_count,CallUndefinedReceiver2Handler,1,1 block_count,CallUndefinedReceiver2Handler,2,0 block_count,CallUndefinedReceiver2Handler,3,0 block_count,CallUndefinedReceiver2Handler,4,0 @@ -65840,21 +65799,21 @@ block_count,TestEqualHandler,94,0 block_count,TestEqualHandler,95,0 block_count,TestEqualHandler,96,0 -block_count,TestEqualHandler,97,1 +block_count,TestEqualHandler,97,0 block_count,TestEqualHandler,98,0 -block_count,TestEqualHandler,99,1 +block_count,TestEqualHandler,99,0 block_count,TestEqualHandler,100,0 block_count,TestEqualHandler,101,0 block_count,TestEqualHandler,102,0 block_count,TestEqualHandler,103,0 block_count,TestEqualHandler,104,0 -block_count,TestEqualHandler,105,1 +block_count,TestEqualHandler,105,0 block_count,TestEqualHandler,106,0 -block_count,TestEqualHandler,107,1 -block_count,TestEqualHandler,108,1 +block_count,TestEqualHandler,107,0 +block_count,TestEqualHandler,108,0 block_count,TestEqualHandler,109,0 -block_count,TestEqualHandler,110,1 -block_count,TestEqualHandler,111,1 +block_count,TestEqualHandler,110,0 +block_count,TestEqualHandler,111,0 block_count,TestEqualHandler,112,0 block_count,TestEqualHandler,113,0 block_count,TestEqualHandler,114,2 @@ -65877,7 +65836,7 @@ block_count,TestEqualHandler,131,0 block_count,TestEqualHandler,132,0 block_count,TestEqualHandler,133,0 -block_count,TestEqualHandler,134,2 +block_count,TestEqualHandler,134,1 block_count,TestEqualHandler,135,0 block_count,TestEqualHandler,136,0 block_count,TestEqualHandler,137,0 @@ -66055,16 +66014,16 @@ block_count,TestEqualStrictHandler,121,0 block_count,TestEqualStrictHandler,122,0 block_count,TestEqualStrictHandler,123,0 -block_count,TestEqualStrictHandler,124,3 +block_count,TestEqualStrictHandler,124,2 block_count,TestEqualStrictHandler,125,0 block_count,TestEqualStrictHandler,126,6 -block_count,TestEqualStrictHandler,127,5 +block_count,TestEqualStrictHandler,127,4 block_count,TestEqualStrictHandler,128,0 -block_count,TestEqualStrictHandler,129,5 +block_count,TestEqualStrictHandler,129,4 block_count,TestEqualStrictHandler,130,1 block_count,TestEqualStrictHandler,131,6 -block_count,TestLessThanHandler,0,10 -block_count,TestLessThanHandler,1,10 +block_count,TestLessThanHandler,0,9 +block_count,TestLessThanHandler,1,9 block_count,TestLessThanHandler,2,0 block_count,TestLessThanHandler,3,0 block_count,TestLessThanHandler,4,0 @@ -66207,12 +66166,12 @@ block_count,TestLessThanHandler,141,0 block_count,TestLessThanHandler,142,1 block_count,TestLessThanHandler,143,8 -block_count,TestLessThanHandler,144,10 -block_count,TestLessThanHandler,145,9 +block_count,TestLessThanHandler,144,9 +block_count,TestLessThanHandler,145,8 block_count,TestLessThanHandler,146,0 block_count,TestLessThanHandler,147,8 block_count,TestLessThanHandler,148,0 -block_count,TestLessThanHandler,149,10 +block_count,TestLessThanHandler,149,9 block_count,TestGreaterThanHandler,0,2 block_count,TestGreaterThanHandler,1,2 block_count,TestGreaterThanHandler,2,0 @@ -66744,9 +66703,9 @@ block_count,ToNumericHandler,5,0 block_count,ToNumericHandler,6,3 block_count,ToNumericHandler,7,3 -block_count,ToNumericHandler,8,3 +block_count,ToNumericHandler,8,2 block_count,ToNumericHandler,9,0 -block_count,ToNumericHandler,10,3 +block_count,ToNumericHandler,10,2 block_count,ToNumericHandler,11,0 block_count,ToNumericHandler,12,3 block_count,ToObjectHandler,0,0 @@ -67313,15 +67272,15 @@ block_count,JumpLoopHandler,32,0 block_count,JumpLoopHandler,33,0 block_count,JumpLoopHandler,34,0 -block_count,JumpLoopHandler,35,11 -block_count,JumpLoopHandler,36,11 +block_count,JumpLoopHandler,35,10 +block_count,JumpLoopHandler,36,10 block_count,JumpLoopHandler,37,0 -block_count,JumpLoopHandler,38,11 -block_count,JumpLoopHandler,39,11 +block_count,JumpLoopHandler,38,10 +block_count,JumpLoopHandler,39,10 block_count,JumpLoopHandler,40,0 -block_count,JumpLoopHandler,41,11 -block_count,JumpLoopHandler,42,11 -block_count,JumpLoopHandler,43,11 +block_count,JumpLoopHandler,41,10 +block_count,JumpLoopHandler,42,10 +block_count,JumpLoopHandler,43,10 block_count,JumpLoopHandler,44,0 block_count,JumpLoopHandler,45,0 block_count,JumpLoopHandler,46,0 @@ -67335,11 +67294,11 @@ block_count,JumpLoopHandler,54,0 block_count,JumpLoopHandler,55,0 block_count,JumpLoopHandler,56,0 -block_count,JumpLoopHandler,57,12 +block_count,JumpLoopHandler,57,11 block_count,JumpLoopHandler,58,0 -block_count,JumpLoopHandler,59,12 -block_count,JumpLoopHandler,60,12 -block_count,JumpHandler,0,4 +block_count,JumpLoopHandler,59,11 +block_count,JumpLoopHandler,60,11 +block_count,JumpHandler,0,3 block_count,JumpConstantHandler,0,0 block_count,JumpIfUndefinedConstantHandler,0,0 block_count,JumpIfUndefinedConstantHandler,1,0 @@ -67446,7 +67405,7 @@ block_count,JumpIfTrueHandler,0,5 block_count,JumpIfTrueHandler,1,4 block_count,JumpIfTrueHandler,2,1 -block_count,JumpIfFalseHandler,0,21 +block_count,JumpIfFalseHandler,0,20 block_count,JumpIfFalseHandler,1,12 block_count,JumpIfFalseHandler,2,8 block_count,JumpIfNullHandler,0,0 @@ -67552,7 +67511,7 @@ block_count,SetPendingMessageHandler,0,0 block_count,ThrowHandler,0,2 block_count,ReThrowHandler,0,0 -block_count,ReturnHandler,0,18 +block_count,ReturnHandler,0,17 block_count,ReturnHandler,1,0 block_count,ReturnHandler,2,17 block_count,ThrowReferenceErrorIfHoleHandler,0,1 @@ -67591,7 +67550,7 @@ block_count,ResumeGeneratorHandler,6,0 block_count,ResumeGeneratorHandler,7,0 block_count,GetIteratorHandler,0,0 -block_count,ShortStarHandler,0,48 +block_count,ShortStarHandler,0,47 block_count,LdarWideHandler,0,0 block_count,LdaSmiWideHandler,0,6 block_count,LdaConstantWideHandler,0,1 @@ -72690,7 +72649,6 @@ builtin_hash,RecordWriteSaveFP,916602188 builtin_hash,RecordWriteIgnoreFP,916602188 builtin_hash,EphemeronKeyBarrierSaveFP,5707399 -builtin_hash,IndirectPointerBarrierIgnoreFP,-437345525 builtin_hash,AdaptorWithBuiltinExitFrame0,338091353 builtin_hash,AdaptorWithBuiltinExitFrame1,-349616847 builtin_hash,AdaptorWithBuiltinExitFrame2,-349616847 diff -Nru chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/x64.profile chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x64.profile --- chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/x64.profile 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x64.profile 2025-01-27 17:37:37.000000000 +0000 @@ -11,12 +11,11 @@ block_hint,RecordWriteSaveFP,57,47,0 block_hint,RecordWriteSaveFP,49,48,1 block_hint,RecordWriteSaveFP,51,52,1 +block_hint,RecordWriteIgnoreFP,12,1,0 block_hint,RecordWriteIgnoreFP,2,3,0 block_hint,RecordWriteIgnoreFP,5,4,1 block_hint,RecordWriteIgnoreFP,9,6,0 block_hint,RecordWriteIgnoreFP,8,7,0 -block_hint,RecordWriteIgnoreFP,13,25,0 -block_hint,RecordWriteIgnoreFP,15,16,1 block_hint,RecordWriteIgnoreFP,28,27,0 block_hint,RecordWriteIgnoreFP,57,47,0 block_hint,RecordWriteIgnoreFP,49,48,1 @@ -126,6 +125,7 @@ block_hint,ConstructWithSpread_WithFeedback,107,76,1 block_hint,ConstructForwardAllArgs_Baseline,42,2,1 block_hint,ConstructForwardAllArgs_WithFeedback,42,2,1 +block_hint,Construct_Baseline,43,2,1 block_hint,Construct_Baseline,4,5,0 block_hint,Construct_Baseline,6,15,1 block_hint,Construct_Baseline,7,14,1 @@ -150,6 +150,7 @@ block_hint,FastNewObject,4,78,1 block_hint,FastNewObject,5,77,1 block_hint,FastNewObject,7,6,0 +block_hint,FastNewObject,34,37,0 block_hint,FastNewObject,36,35,0 block_hint,FastNewObject,52,40,0 block_hint,FastNewObject,54,53,0 @@ -369,6 +370,7 @@ block_hint,KeyedStoreIC_Megamorphic,288,287,0 block_hint,KeyedStoreIC_Megamorphic,290,291,1 block_hint,KeyedStoreIC_Megamorphic,297,296,1 +block_hint,KeyedStoreIC_Megamorphic,317,316,1 block_hint,KeyedStoreIC_Megamorphic,687,615,1 block_hint,KeyedStoreIC_Megamorphic,686,685,1 block_hint,KeyedStoreIC_Megamorphic,701,695,0 @@ -426,7 +428,6 @@ block_hint,KeyedStoreIC_Megamorphic,1228,1222,0 block_hint,KeyedStoreIC_Megamorphic,1226,1223,0 block_hint,KeyedStoreIC_Megamorphic,1224,1225,1 -block_hint,KeyedStoreIC_Megamorphic,1298,1301,0 block_hint,KeyedStoreIC_Megamorphic,1310,1387,0 block_hint,KeyedStoreIC_Megamorphic,1321,1385,0 block_hint,KeyedStoreIC_Megamorphic,1384,1351,1 @@ -872,6 +873,7 @@ block_hint,ArrayConstructorImpl,21,14,0 block_hint,ArrayConstructorImpl,19,16,0 block_hint,ArrayConstructorImpl,18,17,1 +block_hint,ArrayConstructorImpl,35,26,0 block_hint,ArrayConstructorImpl,33,28,0 block_hint,ArrayConstructorImpl,41,38,0 block_hint,ArrayConstructorImpl,40,39,1 @@ -1600,7 +1602,6 @@ block_hint,StoreIC,380,379,0 block_hint,StoreIC_Megamorphic,1,2,1 block_hint,StoreIC_Megamorphic,5,4,0 -block_hint,StoreIC_Megamorphic,8,9,1 block_hint,StoreIC_Megamorphic,12,15,1 block_hint,StoreIC_Megamorphic,13,14,1 block_hint,StoreIC_Megamorphic,17,268,1 @@ -1700,6 +1701,7 @@ block_hint,KeyedStoreIC,33,30,0 block_hint,KeyedStoreIC,32,31,1 block_hint,KeyedStoreIC,35,42,1 +block_hint,KeyedStoreIC,41,36,1 block_hint,KeyedStoreIC,40,37,0 block_hint,KeyedStoreIC,39,38,0 block_hint,KeyedStoreIC,297,207,0 @@ -1999,7 +2001,6 @@ block_hint,MultiplySmi_Baseline,20,21,1 block_hint,MultiplySmi_Baseline,27,35,1 block_hint,MultiplySmi_Baseline,29,28,0 -block_hint,Divide_Baseline,3,4,1 block_hint,Divide_Baseline,19,6,0 block_hint,Divide_Baseline,10,9,0 block_hint,Divide_Baseline,13,12,0 @@ -2011,7 +2012,6 @@ block_hint,Divide_Baseline,110,109,0 block_hint,Divide_Baseline,114,113,1 block_hint,DivideSmi_Baseline,15,2,0 -block_hint,DivideSmi_Baseline,4,3,0 block_hint,DivideSmi_Baseline,9,8,0 block_hint,DivideSmi_Baseline,32,31,0 block_hint,Modulus_Baseline,26,1,0 @@ -2035,6 +2035,8 @@ block_hint,BitwiseAndSmi_Baseline,23,22,0 block_hint,BitwiseAndSmi_Baseline,35,34,0 block_hint,BitwiseOr_Baseline,97,4,1 +block_hint,BitwiseOr_Baseline,17,5,0 +block_hint,BitwiseOr_Baseline,13,6,1 block_hint,BitwiseOr_Baseline,95,94,1 block_hint,BitwiseOr_Baseline,100,99,0 block_hint,BitwiseOr_Baseline,119,102,1 @@ -2057,7 +2059,6 @@ block_hint,BitwiseXorSmi_Baseline,12,5,1 block_hint,BitwiseXorSmi_Baseline,14,15,1 block_hint,BitwiseXorSmi_Baseline,35,34,0 -block_hint,ShiftLeft_Baseline,2,1,0 block_hint,ShiftLeft_Baseline,46,45,0 block_hint,ShiftLeftSmi_Baseline,20,3,1 block_hint,ShiftLeftSmi_Baseline,34,33,0 @@ -2099,7 +2100,6 @@ block_hint,BitwiseOr_WithFeedback,128,129,0 block_hint,Equal_Baseline,92,6,0 block_hint,Equal_Baseline,19,9,0 -block_hint,Equal_Baseline,18,10,1 block_hint,Equal_Baseline,17,16,0 block_hint,Equal_Baseline,69,68,1 block_hint,Equal_Baseline,78,71,0 @@ -2114,6 +2114,7 @@ block_hint,Equal_Baseline,130,131,0 block_hint,Equal_Baseline,136,137,0 block_hint,Equal_Baseline,174,152,0 +block_hint,Equal_Baseline,166,155,1 block_hint,Equal_Baseline,157,156,0 block_hint,Equal_Baseline,168,167,1 block_hint,Equal_Baseline,171,172,0 @@ -2212,7 +2213,6 @@ block_hint,LessThan_WithFeedback,37,30,1 block_hint,LessThan_WithFeedback,101,97,0 block_hint,LessThan_WithFeedback,112,108,0 -block_hint,LessThan_WithFeedback,118,129,0 block_hint,LessThan_WithFeedback,128,119,1 block_hint,LessThan_WithFeedback,131,130,1 block_hint,LessThan_WithFeedback,144,143,1 @@ -3979,6 +3979,7 @@ block_hint,Equal,94,89,0 block_hint,Equal,93,90,0 block_hint,Equal,91,92,1 +block_hint,Equal,95,96,0 block_hint,Equal,104,103,0 block_hint,Equal,108,107,0 block_hint,StrictEqual,2,52,1 @@ -4357,6 +4358,7 @@ block_hint,RegExpPrototypeTest,24,23,1 block_hint,RegExpPrototypeTest,53,28,1 block_hint,RegExpPrototypeTest,82,74,0 +block_hint,RegExpPrototypeTest,78,75,0 block_hint,RegExpPrototypeTest,84,83,1 block_hint,RegExpPrototypeTest,87,90,0 block_hint,RegExpPrototypeTest,88,89,0 @@ -4942,6 +4944,8 @@ block_hint,MergeAt,68,73,1 block_hint,MergeAt,69,72,1 block_hint,MergeAt,71,70,0 +block_hint,MergeAt,82,79,0 +block_hint,MergeAt,80,81,0 block_hint,MergeAt,86,85,1 block_hint,MergeAt,88,115,1 block_hint,MergeAt,94,114,1 @@ -5190,6 +5194,7 @@ block_hint,GetNamedPropertyHandler,96,85,1 block_hint,GetNamedPropertyHandler,100,106,1 block_hint,GetNamedPropertyHandler,103,102,0 +block_hint,GetNamedPropertyHandler,110,109,0 block_hint,GetNamedPropertyHandler,190,191,1 block_hint,GetNamedPropertyHandler,199,193,0 block_hint,GetNamedPropertyHandler,198,195,0 @@ -5311,6 +5316,7 @@ block_hint,DecHandler,2,18,0 block_hint,DecHandler,20,19,0 block_hint,DecHandler,30,27,1 +block_hint,DecHandler,29,28,0 block_hint,DecHandler,33,32,0 block_hint,NegateHandler,17,3,1 block_hint,NegateHandler,33,30,1 @@ -5417,7 +5423,6 @@ block_hint,TestEqualHandler,4,112,1 block_hint,TestEqualHandler,19,9,0 block_hint,TestEqualHandler,91,80,1 -block_hint,TestEqualHandler,93,94,0 block_hint,TestEqualHandler,99,98,1 block_hint,TestEqualHandler,109,110,0 block_hint,TestEqualHandler,115,134,0 @@ -5517,11 +5522,18 @@ block_hint,CreateRestParameterHandler,38,2,0 block_hint,CreateRestParameterHandler,4,3,1 block_hint,CreateRestParameterHandler,7,6,1 +block_hint,CreateRestParameterHandler,31,12,0 +block_hint,CreateRestParameterHandler,30,13,0 +block_hint,CreateRestParameterHandler,29,14,0 +block_hint,CreateRestParameterHandler,15,18,1 +block_hint,CreateRestParameterHandler,17,16,1 block_hint,CreateRestParameterHandler,27,23,0 block_hint,CreateRestParameterHandler,25,24,0 block_hint,JumpLoopHandler,10,7,1 block_hint,JumpLoopHandler,12,16,1 +block_hint,JumpLoopHandler,13,14,0 block_hint,JumpLoopHandler,18,21,1 +block_hint,JumpLoopHandler,20,19,0 block_hint,JumpLoopHandler,27,23,0 block_hint,JumpLoopHandler,25,24,1 block_hint,JumpLoopHandler,36,40,1 @@ -5559,15 +5571,10 @@ block_hint,LdaImmutableCurrentContextSlotWideHandler,2,1,1 block_hint,LdaGlobalWideHandler,223,1,0 block_hint,LdaGlobalWideHandler,2,218,0 -block_hint,LdaGlobalWideHandler,5,4,0 block_hint,StaCurrentContextSlotWideHandler,2,1,1 block_hint,GetNamedPropertyWideHandler,305,1,0 block_hint,GetNamedPropertyWideHandler,2,3,1 block_hint,GetNamedPropertyWideHandler,108,18,0 -block_hint,GetNamedPropertyWideHandler,23,20,0 -block_hint,GetNamedPropertyWideHandler,22,21,1 -block_hint,GetNamedPropertyWideHandler,100,106,1 -block_hint,GetNamedPropertyWideHandler,103,102,0 block_hint,GetNamedPropertyWideHandler,259,249,0 block_hint,GetNamedPropertyWideHandler,302,301,0 block_hint,AddWideHandler,2,5,0 @@ -5576,6 +5583,7 @@ block_hint,AddWideHandler,21,101,1 block_hint,AddWideHandler,82,79,1 block_hint,AddWideHandler,126,125,0 +block_hint,MulWideHandler,30,27,1 block_hint,MulWideHandler,33,38,1 block_hint,MulWideHandler,123,122,1 block_hint,AddSmiWideHandler,9,1,0 @@ -5608,6 +5616,7 @@ block_hint,IncWideHandler,20,19,0 block_hint,IncWideHandler,30,27,1 block_hint,CallProperty1WideHandler,1,67,0 +block_hint,CallUndefinedReceiverWideHandler,1,67,0 block_hint,CallUndefinedReceiver0WideHandler,1,67,0 block_hint,CallUndefinedReceiver1WideHandler,1,67,0 block_hint,ConstructWideHandler,1,46,0 @@ -5616,7 +5625,6 @@ block_hint,TestEqualWideHandler,115,134,0 block_hint,TestEqualWideHandler,153,179,0 block_hint,TestEqualWideHandler,185,184,1 -block_hint,TestLessThanWideHandler,118,129,0 block_hint,TestGreaterThanWideHandler,118,129,0 block_hint,CreateRegExpLiteralWideHandler,10,1,1 block_hint,CreateRegExpLiteralWideHandler,9,8,1 @@ -5630,6 +5638,7 @@ block_hint,CreateClosureWideHandler,2,1,1 block_hint,CreateFunctionContextWideHandler,14,15,1 block_hint,JumpLoopWideHandler,3,4,0 +block_hint,JumpLoopWideHandler,35,6,1 block_hint,JumpLoopWideHandler,36,40,1 block_hint,JumpLoopWideHandler,37,38,0 block_hint,JumpLoopWideHandler,42,56,1 @@ -5651,16 +5660,16 @@ block_hint,BitwiseAndSmiExtraWideHandler,27,26,0 block_hint,BitwiseAndSmiExtraWideHandler,41,38,1 block_hint,CallUndefinedReceiver1ExtraWideHandler,1,67,0 -builtin_count,RecordWriteSaveFP,2647 -builtin_count,RecordWriteIgnoreFP,35 +builtin_count,RecordWriteSaveFP,2636 +builtin_count,RecordWriteIgnoreFP,34 builtin_count,EphemeronKeyBarrierSaveFP,0 builtin_count,IndirectPointerBarrierIgnoreFP,0 builtin_count,AdaptorWithBuiltinExitFrame0,104 builtin_count,AdaptorWithBuiltinExitFrame1,3 builtin_count,AdaptorWithBuiltinExitFrame2,0 builtin_count,AdaptorWithBuiltinExitFrame3,7 -builtin_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,141 -builtin_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,595 +builtin_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,140 +builtin_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,591 builtin_count,Call_ReceiverIsAny_Baseline_Compact,2 builtin_count,CallProxy,0 builtin_count,CallWithSpread,23 @@ -5672,9 +5681,9 @@ builtin_count,ConstructWithSpread_WithFeedback,0 builtin_count,ConstructForwardAllArgs_Baseline,0 builtin_count,ConstructForwardAllArgs_WithFeedback,1 -builtin_count,Construct_Baseline,54 +builtin_count,Construct_Baseline,53 builtin_count,Construct_WithFeedback,39 -builtin_count,FastNewObject,295 +builtin_count,FastNewObject,310 builtin_count,FastNewClosure,168 builtin_count,StringEqual,665 builtin_count,StringGreaterThan,0 @@ -5696,12 +5705,12 @@ builtin_count,GrowFastSmiOrObjectElements,308 builtin_count,ToNumber,0 builtin_count,ToNumber_Baseline,0 -builtin_count,ToNumeric_Baseline,27 +builtin_count,ToNumeric_Baseline,26 builtin_count,ToNumberConvertBigInt,2 builtin_count,Typeof,27 builtin_count,Typeof_Baseline,0 builtin_count,KeyedLoadIC_PolymorphicName,1 -builtin_count,KeyedStoreIC_Megamorphic,302 +builtin_count,KeyedStoreIC_Megamorphic,365 builtin_count,DefineKeyedOwnIC_Megamorphic,2 builtin_count,LoadGlobalIC_NoFeedback,14 builtin_count,LoadIC_FunctionPrototype,181 @@ -5711,8 +5720,8 @@ builtin_count,StoreIC_NoFeedback,5 builtin_count,DefineNamedOwnIC_NoFeedback,3 builtin_count,KeyedLoadIC_SloppyArguments,1 -builtin_count,StoreFastElementIC_InBounds,181 -builtin_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,18 +builtin_count,StoreFastElementIC_InBounds,183 +builtin_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,19 builtin_count,StoreFastElementIC_NoTransitionHandleCOW,0 builtin_count,ElementsTransitionAndStore_InBounds,0 builtin_count,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,0 @@ -5733,7 +5742,7 @@ builtin_count,ArrayNoArgumentConstructor_Holey_DisableAllocationSites,0 builtin_count,ArrayNoArgumentConstructor_PackedDouble_DisableAllocationSites,0 builtin_count,ArraySingleArgumentConstructor_HoleySmi_DontOverride,0 -builtin_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,97 +builtin_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,98 builtin_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,2 builtin_count,ArraySingleArgumentConstructor_HoleyDouble_DisableAllocationSites,1 builtin_count,ArrayIncludesSmi,0 @@ -5754,7 +5763,7 @@ builtin_count,ArrayPrototypeEntries,0 builtin_count,ArrayPrototypeKeys,0 builtin_count,ArrayPrototypeValues,18 -builtin_count,ArrayIteratorPrototypeNext,92 +builtin_count,ArrayIteratorPrototypeNext,91 builtin_count,AsyncFunctionEnter,0 builtin_count,AsyncFunctionResolve,0 builtin_count,AsyncFunctionAwait,4 @@ -5779,42 +5788,42 @@ builtin_count,CallIteratorWithFeedbackLazyDeoptContinuation,0 builtin_count,GlobalIsFinite,0 builtin_count,GlobalIsNaN,0 -builtin_count,LoadIC,2800 -builtin_count,LoadIC_Megamorphic,8810 +builtin_count,LoadIC,2801 +builtin_count,LoadIC_Megamorphic,8813 builtin_count,LoadIC_Noninlined,2 builtin_count,LoadICTrampoline,270 -builtin_count,LoadICBaseline,2245 -builtin_count,LoadICTrampoline_Megamorphic,5544 +builtin_count,LoadICBaseline,2247 +builtin_count,LoadICTrampoline_Megamorphic,5543 builtin_count,LoadSuperIC,2 builtin_count,LoadSuperICBaseline,2 -builtin_count,KeyedLoadIC,327 +builtin_count,KeyedLoadIC,325 builtin_count,EnumeratedKeyedLoadIC,4 builtin_count,KeyedLoadIC_Megamorphic,2107 builtin_count,KeyedLoadICTrampoline,1 -builtin_count,KeyedLoadICBaseline,306 +builtin_count,KeyedLoadICBaseline,304 builtin_count,EnumeratedKeyedLoadICBaseline,2 -builtin_count,KeyedLoadICTrampoline_Megamorphic,724 -builtin_count,StoreGlobalIC,479 +builtin_count,KeyedLoadICTrampoline_Megamorphic,722 +builtin_count,StoreGlobalIC,531 builtin_count,StoreGlobalICTrampoline,144 builtin_count,StoreGlobalICBaseline,1 -builtin_count,StoreIC,331 -builtin_count,StoreIC_Megamorphic,1210 +builtin_count,StoreIC,334 +builtin_count,StoreIC_Megamorphic,1211 builtin_count,StoreICTrampoline,23 builtin_count,StoreICTrampoline_Megamorphic,574 -builtin_count,StoreICBaseline,277 +builtin_count,StoreICBaseline,279 builtin_count,DefineNamedOwnIC,42 -builtin_count,DefineNamedOwnICBaseline,38 -builtin_count,KeyedStoreIC,196 +builtin_count,DefineNamedOwnICBaseline,37 +builtin_count,KeyedStoreIC,199 builtin_count,KeyedStoreICTrampoline,0 -builtin_count,KeyedStoreICTrampoline_Megamorphic,222 -builtin_count,KeyedStoreICBaseline,182 +builtin_count,KeyedStoreICTrampoline_Megamorphic,284 +builtin_count,KeyedStoreICBaseline,186 builtin_count,DefineKeyedOwnIC,2 builtin_count,StoreInArrayLiteralIC,19 builtin_count,StoreInArrayLiteralICBaseline,17 -builtin_count,LoadGlobalIC,1397 +builtin_count,LoadGlobalIC,1372 builtin_count,LoadGlobalICInsideTypeof,0 -builtin_count,LoadGlobalICTrampoline,988 -builtin_count,LoadGlobalICBaseline,366 +builtin_count,LoadGlobalICTrampoline,971 +builtin_count,LoadGlobalICBaseline,363 builtin_count,LoadGlobalICInsideTypeofBaseline,0 builtin_count,LookupGlobalICTrampoline,2 builtin_count,LookupGlobalICBaseline,1 @@ -5839,19 +5848,19 @@ builtin_count,MapPrototypeValues,0 builtin_count,MapIteratorPrototypeNext,11 builtin_count,MapIteratorToList,0 -builtin_count,Add_Baseline,199 -builtin_count,AddSmi_Baseline,217 -builtin_count,Subtract_Baseline,63 +builtin_count,Add_Baseline,200 +builtin_count,AddSmi_Baseline,219 +builtin_count,Subtract_Baseline,61 builtin_count,SubtractSmi_Baseline,20 -builtin_count,Multiply_Baseline,85 +builtin_count,Multiply_Baseline,92 builtin_count,MultiplySmi_Baseline,5 -builtin_count,Divide_Baseline,6 +builtin_count,Divide_Baseline,5 builtin_count,DivideSmi_Baseline,1 builtin_count,Modulus_Baseline,1 builtin_count,ModulusSmi_Baseline,1 builtin_count,Exponentiate_Baseline,0 builtin_count,BitwiseAnd_Baseline,11 -builtin_count,BitwiseAndSmi_Baseline,28 +builtin_count,BitwiseAndSmi_Baseline,30 builtin_count,BitwiseOr_Baseline,22 builtin_count,BitwiseOrSmi_Baseline,160 builtin_count,BitwiseXor_Baseline,8 @@ -5859,28 +5868,28 @@ builtin_count,ShiftLeft_Baseline,1 builtin_count,ShiftLeftSmi_Baseline,27 builtin_count,ShiftRight_Baseline,1 -builtin_count,ShiftRightSmi_Baseline,102 +builtin_count,ShiftRightSmi_Baseline,103 builtin_count,ShiftRightLogical_Baseline,0 builtin_count,ShiftRightLogicalSmi_Baseline,3 -builtin_count,Add_WithFeedback,38 +builtin_count,Add_WithFeedback,39 builtin_count,Subtract_WithFeedback,0 builtin_count,Divide_WithFeedback,0 builtin_count,Modulus_WithFeedback,0 builtin_count,BitwiseOr_WithFeedback,0 builtin_count,Equal_Baseline,153 -builtin_count,StrictEqual_Baseline,214 -builtin_count,LessThan_Baseline,145 +builtin_count,StrictEqual_Baseline,213 +builtin_count,LessThan_Baseline,146 builtin_count,GreaterThan_Baseline,43 builtin_count,LessThanOrEqual_Baseline,20 -builtin_count,GreaterThanOrEqual_Baseline,43 +builtin_count,GreaterThanOrEqual_Baseline,42 builtin_count,Equal_WithFeedback,9 -builtin_count,StrictEqual_WithFeedback,103 +builtin_count,StrictEqual_WithFeedback,104 builtin_count,LessThan_WithFeedback,2 builtin_count,GreaterThan_WithFeedback,1 builtin_count,GreaterThanOrEqual_WithFeedback,0 builtin_count,BitwiseNot_Baseline,1 builtin_count,Decrement_Baseline,15 -builtin_count,Increment_Baseline,100 +builtin_count,Increment_Baseline,101 builtin_count,Negate_Baseline,6 builtin_count,ObjectAssign,1 builtin_count,ObjectCreate,6 @@ -5891,7 +5900,7 @@ builtin_count,ObjectKeys,13 builtin_count,ObjectPrototypeHasOwnProperty,212 builtin_count,ObjectToString,55 -builtin_count,OrdinaryHasInstance,90 +builtin_count,OrdinaryHasInstance,91 builtin_count,InstanceOf,6 builtin_count,InstanceOf_WithFeedback,3 builtin_count,InstanceOf_Baseline,41 @@ -5955,7 +5964,7 @@ builtin_count,ArrayForEachLoopContinuation,0 builtin_count,ArrayForEach,1 builtin_count,ArrayFrom,0 -builtin_count,ArrayIsArray,7 +builtin_count,ArrayIsArray,6 builtin_count,LoadJoinElement_FastSmiOrObjectElements_0,646 builtin_count,LoadJoinElement_FastDoubleElements_0,90 builtin_count,JoinStackPush,0 @@ -5965,7 +5974,7 @@ builtin_count,ArrayPrototypeLastIndexOf,1 builtin_count,ArrayMapLoopLazyDeoptContinuation,0 builtin_count,ArrayMapLoopContinuation,0 -builtin_count,ArrayMap,24 +builtin_count,ArrayMap,23 builtin_count,ArrayReduceLoopLazyDeoptContinuation,0 builtin_count,ArrayReduceLoopContinuation,0 builtin_count,ArrayReduce,1 @@ -5981,7 +5990,7 @@ builtin_count,FastCreateDataProperty,0 builtin_count,BooleanConstructor,0 builtin_count,BooleanPrototypeToString,0 -builtin_count,ToString,64 +builtin_count,ToString,65 builtin_count,StringPrototypeToString,16 builtin_count,StringPrototypeCharAt,112 builtin_count,StringPrototypeCharCodeAt,61 @@ -5989,11 +5998,11 @@ builtin_count,StringPrototypeConcat,0 builtin_count,StringConstructor,28 builtin_count,StringAddConvertLeft,15 -builtin_count,StringAddConvertRight,178 +builtin_count,StringAddConvertRight,179 builtin_count,StringCharAt,8 builtin_count,FastNewClosureBaseline,31 builtin_count,FastNewFunctionContextFunction,60 -builtin_count,CreateRegExpLiteral,11 +builtin_count,CreateRegExpLiteral,10 builtin_count,CreateShallowArrayLiteral,9 builtin_count,CreateEmptyArrayLiteral,14 builtin_count,CreateShallowObjectLiteral,17 @@ -6004,9 +6013,9 @@ builtin_count,NonNumberToNumber,4 builtin_count,NonNumberToNumeric,885 builtin_count,ToNumeric,14 -builtin_count,NumberToString,1322 +builtin_count,NumberToString,1321 builtin_count,ToBoolean,19 -builtin_count,ToBooleanForBaselineJump,476 +builtin_count,ToBooleanForBaselineJump,472 builtin_count,ToLength,2 builtin_count,ToName,42 builtin_count,ToObject,215 @@ -6024,7 +6033,7 @@ builtin_count,FastFunctionPrototypeBind,5 builtin_count,ForInNext,31 builtin_count,GetIteratorWithFeedback,0 -builtin_count,GetIteratorBaseline,14 +builtin_count,GetIteratorBaseline,13 builtin_count,CallIteratorWithFeedback,14 builtin_count,MathAbs,0 builtin_count,MathCeil,0 @@ -6042,7 +6051,7 @@ builtin_count,MathLog,0 builtin_count,MathSin,0 builtin_count,MathSign,0 -builtin_count,MathSqrt,8 +builtin_count,MathSqrt,9 builtin_count,MathTan,0 builtin_count,MathTanh,0 builtin_count,MathRandom,278 @@ -6052,13 +6061,13 @@ builtin_count,NumberParseFloat,10 builtin_count,ParseInt,118 builtin_count,NumberParseInt,6 -builtin_count,Add,42 +builtin_count,Add,43 builtin_count,Subtract,0 builtin_count,Multiply,0 builtin_count,Divide,0 builtin_count,Modulus,0 builtin_count,BitwiseOr,3 -builtin_count,LessThan,671 +builtin_count,LessThan,669 builtin_count,GreaterThan,582 builtin_count,GreaterThanOrEqual,3 builtin_count,Equal,44 @@ -6162,10 +6171,10 @@ builtin_count,CanUseSameAccessor_FastObjectElements_0,33 builtin_count,StringPrototypeToLowerCaseIntl,3 builtin_count,StringToLowerCaseIntl,129 -builtin_count,WideHandler,55 +builtin_count,WideHandler,54 builtin_count,ExtraWideHandler,9 -builtin_count,LdarHandler,76 -builtin_count,LdaZeroHandler,9 +builtin_count,LdarHandler,77 +builtin_count,LdaZeroHandler,10 builtin_count,LdaSmiHandler,11 builtin_count,LdaUndefinedHandler,7 builtin_count,LdaNullHandler,1 @@ -6173,7 +6182,7 @@ builtin_count,LdaTrueHandler,1 builtin_count,LdaFalseHandler,2 builtin_count,LdaConstantHandler,12 -builtin_count,LdaContextSlotHandler,0 +builtin_count,LdaContextSlotHandler,1 builtin_count,LdaImmutableContextSlotHandler,6 builtin_count,LdaCurrentContextSlotHandler,5 builtin_count,LdaImmutableCurrentContextSlotHandler,18 @@ -6196,7 +6205,7 @@ builtin_count,LdaLookupGlobalSlotHandler,0 builtin_count,LdaLookupGlobalSlotInsideTypeofHandler,0 builtin_count,StaLookupSlotHandler,0 -builtin_count,GetNamedPropertyHandler,66 +builtin_count,GetNamedPropertyHandler,67 builtin_count,GetNamedPropertyFromSuperHandler,0 builtin_count,GetKeyedPropertyHandler,18 builtin_count,GetEnumeratedKeyedPropertyHandler,1 @@ -6230,7 +6239,7 @@ builtin_count,ShiftRightSmiHandler,2 builtin_count,ShiftRightLogicalSmiHandler,0 builtin_count,IncHandler,10 -builtin_count,DecHandler,2 +builtin_count,DecHandler,3 builtin_count,NegateHandler,0 builtin_count,BitwiseNotHandler,0 builtin_count,ToBooleanLogicalNotHandler,0 @@ -6241,7 +6250,7 @@ builtin_count,FindNonDefaultConstructorOrConstructHandler,0 builtin_count,CallAnyReceiverHandler,0 builtin_count,CallPropertyHandler,1 -builtin_count,CallProperty0Handler,4 +builtin_count,CallProperty0Handler,5 builtin_count,CallProperty1Handler,11 builtin_count,CallProperty2Handler,3 builtin_count,CallUndefinedReceiverHandler,1 @@ -6282,7 +6291,7 @@ builtin_count,CreateMappedArgumentsHandler,0 builtin_count,CreateUnmappedArgumentsHandler,0 builtin_count,CreateRestParameterHandler,0 -builtin_count,JumpLoopHandler,12 +builtin_count,JumpLoopHandler,13 builtin_count,JumpHandler,4 builtin_count,JumpConstantHandler,0 builtin_count,JumpIfUndefinedConstantHandler,0 @@ -6296,7 +6305,7 @@ builtin_count,JumpIfToBooleanTrueHandler,5 builtin_count,JumpIfToBooleanFalseHandler,11 builtin_count,JumpIfTrueHandler,5 -builtin_count,JumpIfFalseHandler,20 +builtin_count,JumpIfFalseHandler,21 builtin_count,JumpIfNullHandler,0 builtin_count,JumpIfNotNullHandler,0 builtin_count,JumpIfUndefinedHandler,1 @@ -6321,7 +6330,7 @@ builtin_count,SuspendGeneratorHandler,0 builtin_count,ResumeGeneratorHandler,0 builtin_count,GetIteratorHandler,0 -builtin_count,ShortStarHandler,48 +builtin_count,ShortStarHandler,47 builtin_count,LdarWideHandler,0 builtin_count,LdaSmiWideHandler,6 builtin_count,LdaConstantWideHandler,1 @@ -6419,34 +6428,34 @@ builtin_count,CallUndefinedReceiverExtraWideHandler,0 builtin_count,CallUndefinedReceiver1ExtraWideHandler,4 builtin_count,CallUndefinedReceiver2ExtraWideHandler,0 -block_count,RecordWriteSaveFP,0,2647 -block_count,RecordWriteSaveFP,1,2590 +block_count,RecordWriteSaveFP,0,2636 +block_count,RecordWriteSaveFP,1,2588 block_count,RecordWriteSaveFP,2,0 -block_count,RecordWriteSaveFP,3,2590 +block_count,RecordWriteSaveFP,3,2588 block_count,RecordWriteSaveFP,4,0 -block_count,RecordWriteSaveFP,5,2590 -block_count,RecordWriteSaveFP,6,2589 -block_count,RecordWriteSaveFP,7,2587 +block_count,RecordWriteSaveFP,5,2588 +block_count,RecordWriteSaveFP,6,2588 +block_count,RecordWriteSaveFP,7,2585 block_count,RecordWriteSaveFP,8,2 block_count,RecordWriteSaveFP,9,0 block_count,RecordWriteSaveFP,10,2 -block_count,RecordWriteSaveFP,11,2590 -block_count,RecordWriteSaveFP,12,57 -block_count,RecordWriteSaveFP,13,37 -block_count,RecordWriteSaveFP,14,35 -block_count,RecordWriteSaveFP,15,35 +block_count,RecordWriteSaveFP,11,2588 +block_count,RecordWriteSaveFP,12,48 +block_count,RecordWriteSaveFP,13,34 +block_count,RecordWriteSaveFP,14,32 +block_count,RecordWriteSaveFP,15,32 block_count,RecordWriteSaveFP,16,0 -block_count,RecordWriteSaveFP,17,2 +block_count,RecordWriteSaveFP,17,1 block_count,RecordWriteSaveFP,18,0 -block_count,RecordWriteSaveFP,19,2 -block_count,RecordWriteSaveFP,20,2 -block_count,RecordWriteSaveFP,21,2 +block_count,RecordWriteSaveFP,19,1 +block_count,RecordWriteSaveFP,20,1 +block_count,RecordWriteSaveFP,21,1 block_count,RecordWriteSaveFP,22,0 block_count,RecordWriteSaveFP,23,0 block_count,RecordWriteSaveFP,24,0 -block_count,RecordWriteSaveFP,25,19 -block_count,RecordWriteSaveFP,26,57 -block_count,RecordWriteSaveFP,27,57 +block_count,RecordWriteSaveFP,25,14 +block_count,RecordWriteSaveFP,26,48 +block_count,RecordWriteSaveFP,27,48 block_count,RecordWriteSaveFP,28,0 block_count,RecordWriteSaveFP,29,0 block_count,RecordWriteSaveFP,30,0 @@ -6465,17 +6474,17 @@ block_count,RecordWriteSaveFP,43,0 block_count,RecordWriteSaveFP,44,0 block_count,RecordWriteSaveFP,45,0 -block_count,RecordWriteSaveFP,46,57 -block_count,RecordWriteSaveFP,47,57 +block_count,RecordWriteSaveFP,46,48 +block_count,RecordWriteSaveFP,47,48 block_count,RecordWriteSaveFP,48,0 -block_count,RecordWriteSaveFP,49,57 -block_count,RecordWriteSaveFP,50,54 -block_count,RecordWriteSaveFP,51,54 +block_count,RecordWriteSaveFP,49,48 +block_count,RecordWriteSaveFP,50,46 +block_count,RecordWriteSaveFP,51,46 block_count,RecordWriteSaveFP,52,0 block_count,RecordWriteSaveFP,53,0 block_count,RecordWriteSaveFP,54,0 -block_count,RecordWriteSaveFP,55,3 -block_count,RecordWriteSaveFP,56,3 +block_count,RecordWriteSaveFP,55,1 +block_count,RecordWriteSaveFP,56,1 block_count,RecordWriteSaveFP,57,0 block_count,RecordWriteSaveFP,58,0 block_count,RecordWriteSaveFP,59,0 @@ -6483,20 +6492,20 @@ block_count,RecordWriteSaveFP,61,0 block_count,RecordWriteSaveFP,62,0 block_count,RecordWriteSaveFP,63,0 -block_count,RecordWriteSaveFP,64,57 -block_count,RecordWriteIgnoreFP,0,35 +block_count,RecordWriteSaveFP,64,48 +block_count,RecordWriteIgnoreFP,0,34 block_count,RecordWriteIgnoreFP,1,33 block_count,RecordWriteIgnoreFP,2,0 block_count,RecordWriteIgnoreFP,3,33 block_count,RecordWriteIgnoreFP,4,0 block_count,RecordWriteIgnoreFP,5,33 block_count,RecordWriteIgnoreFP,6,33 -block_count,RecordWriteIgnoreFP,7,32 +block_count,RecordWriteIgnoreFP,7,33 block_count,RecordWriteIgnoreFP,8,0 block_count,RecordWriteIgnoreFP,9,0 block_count,RecordWriteIgnoreFP,10,0 block_count,RecordWriteIgnoreFP,11,33 -block_count,RecordWriteIgnoreFP,12,2 +block_count,RecordWriteIgnoreFP,12,0 block_count,RecordWriteIgnoreFP,13,0 block_count,RecordWriteIgnoreFP,14,0 block_count,RecordWriteIgnoreFP,15,0 @@ -6509,9 +6518,9 @@ block_count,RecordWriteIgnoreFP,22,0 block_count,RecordWriteIgnoreFP,23,0 block_count,RecordWriteIgnoreFP,24,0 -block_count,RecordWriteIgnoreFP,25,2 -block_count,RecordWriteIgnoreFP,26,2 -block_count,RecordWriteIgnoreFP,27,2 +block_count,RecordWriteIgnoreFP,25,0 +block_count,RecordWriteIgnoreFP,26,0 +block_count,RecordWriteIgnoreFP,27,0 block_count,RecordWriteIgnoreFP,28,0 block_count,RecordWriteIgnoreFP,29,0 block_count,RecordWriteIgnoreFP,30,0 @@ -6530,12 +6539,12 @@ block_count,RecordWriteIgnoreFP,43,0 block_count,RecordWriteIgnoreFP,44,0 block_count,RecordWriteIgnoreFP,45,0 -block_count,RecordWriteIgnoreFP,46,2 -block_count,RecordWriteIgnoreFP,47,2 +block_count,RecordWriteIgnoreFP,46,0 +block_count,RecordWriteIgnoreFP,47,0 block_count,RecordWriteIgnoreFP,48,0 -block_count,RecordWriteIgnoreFP,49,2 -block_count,RecordWriteIgnoreFP,50,2 -block_count,RecordWriteIgnoreFP,51,2 +block_count,RecordWriteIgnoreFP,49,0 +block_count,RecordWriteIgnoreFP,50,0 +block_count,RecordWriteIgnoreFP,51,0 block_count,RecordWriteIgnoreFP,52,0 block_count,RecordWriteIgnoreFP,53,0 block_count,RecordWriteIgnoreFP,54,0 @@ -6548,7 +6557,7 @@ block_count,RecordWriteIgnoreFP,61,0 block_count,RecordWriteIgnoreFP,62,0 block_count,RecordWriteIgnoreFP,63,0 -block_count,RecordWriteIgnoreFP,64,2 +block_count,RecordWriteIgnoreFP,64,0 block_count,EphemeronKeyBarrierSaveFP,0,0 block_count,IndirectPointerBarrierIgnoreFP,0,0 block_count,AdaptorWithBuiltinExitFrame0,0,104 @@ -6564,16 +6573,16 @@ block_count,AdaptorWithBuiltinExitFrame3,1,6 block_count,AdaptorWithBuiltinExitFrame3,2,1 block_count,AdaptorWithBuiltinExitFrame3,3,7 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,0,141 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,141 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,2,43 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,3,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,4,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,5,38 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,0,140 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,140 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,2,42 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,3,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,4,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,5,37 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,6,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,7,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,8,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,9,38 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,7,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,8,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,9,37 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,10,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,11,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,12,0 @@ -6591,15 +6600,15 @@ block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,24,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,25,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,26,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,27,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,28,38 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,29,38 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,27,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,28,37 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,29,37 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,30,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,31,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,32,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,33,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,34,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,35,38 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,35,37 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,36,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,37,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,38,0 @@ -6630,11 +6639,11 @@ block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,63,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,64,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,65,5 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,66,98 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,66,97 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,67,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,68,141 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,0,595 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1,595 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,68,140 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,0,591 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1,591 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,2,32 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,3,13 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,4,12 @@ -6699,9 +6708,9 @@ block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,63,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,64,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,65,18 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,66,563 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,66,558 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,67,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,68,595 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,68,591 block_count,Call_ReceiverIsAny_Baseline_Compact,0,2 block_count,Call_ReceiverIsAny_Baseline_Compact,1,2 block_count,Call_ReceiverIsAny_Baseline_Compact,2,0 @@ -7482,8 +7491,8 @@ block_count,ConstructForwardAllArgs_WithFeedback,41,0 block_count,ConstructForwardAllArgs_WithFeedback,42,1 block_count,ConstructForwardAllArgs_WithFeedback,43,1 -block_count,Construct_Baseline,0,54 -block_count,Construct_Baseline,1,3 +block_count,Construct_Baseline,0,53 +block_count,Construct_Baseline,1,2 block_count,Construct_Baseline,2,1 block_count,Construct_Baseline,3,1 block_count,Construct_Baseline,4,0 @@ -7525,8 +7534,8 @@ block_count,Construct_Baseline,40,0 block_count,Construct_Baseline,41,1 block_count,Construct_Baseline,42,1 -block_count,Construct_Baseline,43,51 -block_count,Construct_Baseline,44,53 +block_count,Construct_Baseline,43,50 +block_count,Construct_Baseline,44,52 block_count,Construct_WithFeedback,0,39 block_count,Construct_WithFeedback,1,39 block_count,Construct_WithFeedback,2,9 @@ -7571,16 +7580,16 @@ block_count,Construct_WithFeedback,41,0 block_count,Construct_WithFeedback,42,3 block_count,Construct_WithFeedback,43,5 -block_count,Construct_WithFeedback,44,29 +block_count,Construct_WithFeedback,44,30 block_count,Construct_WithFeedback,45,0 block_count,Construct_WithFeedback,46,35 -block_count,FastNewObject,0,295 +block_count,FastNewObject,0,310 block_count,FastNewObject,1,0 -block_count,FastNewObject,2,295 -block_count,FastNewObject,3,295 -block_count,FastNewObject,4,292 -block_count,FastNewObject,5,292 -block_count,FastNewObject,6,292 +block_count,FastNewObject,2,310 +block_count,FastNewObject,3,310 +block_count,FastNewObject,4,307 +block_count,FastNewObject,5,307 +block_count,FastNewObject,6,307 block_count,FastNewObject,7,0 block_count,FastNewObject,8,0 block_count,FastNewObject,9,0 @@ -7606,25 +7615,25 @@ block_count,FastNewObject,29,0 block_count,FastNewObject,30,0 block_count,FastNewObject,31,0 -block_count,FastNewObject,32,292 -block_count,FastNewObject,33,292 +block_count,FastNewObject,32,307 +block_count,FastNewObject,33,307 block_count,FastNewObject,34,0 -block_count,FastNewObject,35,292 +block_count,FastNewObject,35,307 block_count,FastNewObject,36,0 block_count,FastNewObject,37,0 -block_count,FastNewObject,38,292 -block_count,FastNewObject,39,292 +block_count,FastNewObject,38,307 +block_count,FastNewObject,39,307 block_count,FastNewObject,40,1 -block_count,FastNewObject,41,290 +block_count,FastNewObject,41,306 block_count,FastNewObject,42,40 -block_count,FastNewObject,43,250 -block_count,FastNewObject,44,399 -block_count,FastNewObject,45,149 -block_count,FastNewObject,46,250 -block_count,FastNewObject,47,290 -block_count,FastNewObject,48,205 +block_count,FastNewObject,43,265 +block_count,FastNewObject,44,442 +block_count,FastNewObject,45,176 +block_count,FastNewObject,46,265 +block_count,FastNewObject,47,306 +block_count,FastNewObject,48,220 block_count,FastNewObject,49,85 -block_count,FastNewObject,50,292 +block_count,FastNewObject,50,307 block_count,FastNewObject,51,0 block_count,FastNewObject,52,0 block_count,FastNewObject,53,0 @@ -7668,7 +7677,7 @@ block_count,FastNewClosure,11,0 block_count,FastNewClosure,12,0 block_count,FastNewClosure,13,168 -block_count,FastNewClosure,14,61 +block_count,FastNewClosure,14,60 block_count,FastNewClosure,15,107 block_count,FastNewClosure,16,107 block_count,FastNewClosure,17,0 @@ -7679,12 +7688,12 @@ block_count,FastNewClosure,22,0 block_count,FastNewClosure,23,107 block_count,FastNewClosure,24,168 -block_count,FastNewClosure,25,61 +block_count,FastNewClosure,25,60 block_count,FastNewClosure,26,107 block_count,StringEqual,0,665 block_count,StringEqual,1,677 block_count,StringEqual,2,266 -block_count,StringEqual,3,17 +block_count,StringEqual,3,16 block_count,StringEqual,4,15 block_count,StringEqual,5,7 block_count,StringEqual,6,3 @@ -7699,7 +7708,7 @@ block_count,StringEqual,15,3 block_count,StringEqual,16,0 block_count,StringEqual,17,6 -block_count,StringEqual,18,2 +block_count,StringEqual,18,1 block_count,StringEqual,19,6 block_count,StringEqual,20,6 block_count,StringEqual,21,3 @@ -7805,7 +7814,7 @@ block_count,StringEqual,121,0 block_count,StringEqual,122,0 block_count,StringEqual,123,0 -block_count,StringEqual,124,411 +block_count,StringEqual,124,410 block_count,StringGreaterThan,0,0 block_count,StringGreaterThan,1,0 block_count,StringGreaterThan,2,0 @@ -7855,7 +7864,7 @@ block_count,StringGreaterThan,46,0 block_count,StringGreaterThanOrEqual,0,4 block_count,StringGreaterThanOrEqual,1,4 -block_count,StringGreaterThanOrEqual,2,0 +block_count,StringGreaterThanOrEqual,2,1 block_count,StringGreaterThanOrEqual,3,0 block_count,StringGreaterThanOrEqual,4,0 block_count,StringGreaterThanOrEqual,5,0 @@ -7881,23 +7890,23 @@ block_count,StringGreaterThanOrEqual,25,0 block_count,StringGreaterThanOrEqual,26,0 block_count,StringGreaterThanOrEqual,27,0 -block_count,StringGreaterThanOrEqual,28,0 +block_count,StringGreaterThanOrEqual,28,1 block_count,StringGreaterThanOrEqual,29,0 -block_count,StringGreaterThanOrEqual,30,0 -block_count,StringGreaterThanOrEqual,31,0 -block_count,StringGreaterThanOrEqual,32,0 +block_count,StringGreaterThanOrEqual,30,1 +block_count,StringGreaterThanOrEqual,31,1 +block_count,StringGreaterThanOrEqual,32,1 block_count,StringGreaterThanOrEqual,33,0 block_count,StringGreaterThanOrEqual,34,0 block_count,StringGreaterThanOrEqual,35,0 block_count,StringGreaterThanOrEqual,36,0 block_count,StringGreaterThanOrEqual,37,0 block_count,StringGreaterThanOrEqual,38,0 -block_count,StringGreaterThanOrEqual,39,0 -block_count,StringGreaterThanOrEqual,40,0 -block_count,StringGreaterThanOrEqual,41,0 -block_count,StringGreaterThanOrEqual,42,0 +block_count,StringGreaterThanOrEqual,39,1 +block_count,StringGreaterThanOrEqual,40,1 +block_count,StringGreaterThanOrEqual,41,1 +block_count,StringGreaterThanOrEqual,42,1 block_count,StringGreaterThanOrEqual,43,0 -block_count,StringGreaterThanOrEqual,44,0 +block_count,StringGreaterThanOrEqual,44,1 block_count,StringGreaterThanOrEqual,45,0 block_count,StringGreaterThanOrEqual,46,0 block_count,StringGreaterThanOrEqual,47,0 @@ -8076,29 +8085,29 @@ block_count,StringSubstring,0,489 block_count,StringSubstring,1,479 block_count,StringSubstring,2,479 -block_count,StringSubstring,3,388 -block_count,StringSubstring,4,594 -block_count,StringSubstring,5,205 -block_count,StringSubstring,6,205 +block_count,StringSubstring,3,389 +block_count,StringSubstring,4,595 +block_count,StringSubstring,5,206 +block_count,StringSubstring,6,206 block_count,StringSubstring,7,160 block_count,StringSubstring,8,5 -block_count,StringSubstring,9,154 +block_count,StringSubstring,9,155 block_count,StringSubstring,10,45 block_count,StringSubstring,11,45 block_count,StringSubstring,12,0 -block_count,StringSubstring,13,205 +block_count,StringSubstring,13,206 block_count,StringSubstring,14,0 -block_count,StringSubstring,15,388 -block_count,StringSubstring,16,388 +block_count,StringSubstring,15,389 +block_count,StringSubstring,16,389 block_count,StringSubstring,17,172 block_count,StringSubstring,18,4 block_count,StringSubstring,19,0 block_count,StringSubstring,20,4 block_count,StringSubstring,21,4 -block_count,StringSubstring,22,167 +block_count,StringSubstring,22,168 block_count,StringSubstring,23,0 -block_count,StringSubstring,24,167 -block_count,StringSubstring,25,167 +block_count,StringSubstring,24,168 +block_count,StringSubstring,25,168 block_count,StringSubstring,26,216 block_count,StringSubstring,27,216 block_count,StringSubstring,28,32 @@ -8453,7 +8462,7 @@ block_count,GrowFastDoubleElements,21,334 block_count,GrowFastDoubleElements,22,143 block_count,GrowFastDoubleElements,23,4265 -block_count,GrowFastDoubleElements,24,4265 +block_count,GrowFastDoubleElements,24,4264 block_count,GrowFastDoubleElements,25,0 block_count,GrowFastDoubleElements,26,4265 block_count,GrowFastDoubleElements,27,4122 @@ -8477,7 +8486,7 @@ block_count,GrowFastSmiOrObjectElements,11,308 block_count,GrowFastSmiOrObjectElements,12,0 block_count,GrowFastSmiOrObjectElements,13,308 -block_count,GrowFastSmiOrObjectElements,14,4050 +block_count,GrowFastSmiOrObjectElements,14,4051 block_count,GrowFastSmiOrObjectElements,15,3742 block_count,GrowFastSmiOrObjectElements,16,308 block_count,GrowFastSmiOrObjectElements,17,308 @@ -8485,8 +8494,8 @@ block_count,GrowFastSmiOrObjectElements,19,292 block_count,GrowFastSmiOrObjectElements,20,308 block_count,GrowFastSmiOrObjectElements,21,42 -block_count,GrowFastSmiOrObjectElements,22,6193 -block_count,GrowFastSmiOrObjectElements,23,6151 +block_count,GrowFastSmiOrObjectElements,22,6192 +block_count,GrowFastSmiOrObjectElements,23,6150 block_count,GrowFastSmiOrObjectElements,24,42 block_count,GrowFastSmiOrObjectElements,25,266 block_count,GrowFastSmiOrObjectElements,26,0 @@ -8539,7 +8548,7 @@ block_count,ToNumber_Baseline,22,0 block_count,ToNumber_Baseline,23,0 block_count,ToNumber_Baseline,24,0 -block_count,ToNumeric_Baseline,0,27 +block_count,ToNumeric_Baseline,0,26 block_count,ToNumeric_Baseline,1,0 block_count,ToNumeric_Baseline,2,0 block_count,ToNumeric_Baseline,3,0 @@ -8567,10 +8576,10 @@ block_count,ToNumeric_Baseline,25,0 block_count,ToNumeric_Baseline,26,0 block_count,ToNumeric_Baseline,27,0 -block_count,ToNumeric_Baseline,28,27 -block_count,ToNumeric_Baseline,29,27 +block_count,ToNumeric_Baseline,28,26 +block_count,ToNumeric_Baseline,29,26 block_count,ToNumeric_Baseline,30,0 -block_count,ToNumeric_Baseline,31,27 +block_count,ToNumeric_Baseline,31,26 block_count,ToNumberConvertBigInt,0,2 block_count,ToNumberConvertBigInt,1,2 block_count,ToNumberConvertBigInt,2,0 @@ -8964,9 +8973,9 @@ block_count,KeyedLoadIC_PolymorphicName,287,0 block_count,KeyedLoadIC_PolymorphicName,288,0 block_count,KeyedLoadIC_PolymorphicName,289,0 -block_count,KeyedStoreIC_Megamorphic,0,302 -block_count,KeyedStoreIC_Megamorphic,1,302 -block_count,KeyedStoreIC_Megamorphic,2,302 +block_count,KeyedStoreIC_Megamorphic,0,365 +block_count,KeyedStoreIC_Megamorphic,1,365 +block_count,KeyedStoreIC_Megamorphic,2,365 block_count,KeyedStoreIC_Megamorphic,3,265 block_count,KeyedStoreIC_Megamorphic,4,265 block_count,KeyedStoreIC_Megamorphic,5,0 @@ -9145,14 +9154,14 @@ block_count,KeyedStoreIC_Megamorphic,178,10 block_count,KeyedStoreIC_Megamorphic,179,0 block_count,KeyedStoreIC_Megamorphic,180,10 -block_count,KeyedStoreIC_Megamorphic,181,86 -block_count,KeyedStoreIC_Megamorphic,182,86 +block_count,KeyedStoreIC_Megamorphic,181,87 +block_count,KeyedStoreIC_Megamorphic,182,87 block_count,KeyedStoreIC_Megamorphic,183,0 -block_count,KeyedStoreIC_Megamorphic,184,86 +block_count,KeyedStoreIC_Megamorphic,184,87 block_count,KeyedStoreIC_Megamorphic,185,37 -block_count,KeyedStoreIC_Megamorphic,186,48 -block_count,KeyedStoreIC_Megamorphic,187,86 -block_count,KeyedStoreIC_Megamorphic,188,76 +block_count,KeyedStoreIC_Megamorphic,186,50 +block_count,KeyedStoreIC_Megamorphic,187,87 +block_count,KeyedStoreIC_Megamorphic,188,77 block_count,KeyedStoreIC_Megamorphic,189,10 block_count,KeyedStoreIC_Megamorphic,190,10 block_count,KeyedStoreIC_Megamorphic,191,10 @@ -9216,7 +9225,7 @@ block_count,KeyedStoreIC_Megamorphic,249,7 block_count,KeyedStoreIC_Megamorphic,250,0 block_count,KeyedStoreIC_Megamorphic,251,7 -block_count,KeyedStoreIC_Megamorphic,252,41 +block_count,KeyedStoreIC_Megamorphic,252,40 block_count,KeyedStoreIC_Megamorphic,253,0 block_count,KeyedStoreIC_Megamorphic,254,0 block_count,KeyedStoreIC_Megamorphic,255,0 @@ -9879,9 +9888,9 @@ block_count,KeyedStoreIC_Megamorphic,912,0 block_count,KeyedStoreIC_Megamorphic,913,0 block_count,KeyedStoreIC_Megamorphic,914,0 -block_count,KeyedStoreIC_Megamorphic,915,36 -block_count,KeyedStoreIC_Megamorphic,916,37 -block_count,KeyedStoreIC_Megamorphic,917,82 +block_count,KeyedStoreIC_Megamorphic,915,99 +block_count,KeyedStoreIC_Megamorphic,916,100 +block_count,KeyedStoreIC_Megamorphic,917,145 block_count,KeyedStoreIC_Megamorphic,918,1 block_count,KeyedStoreIC_Megamorphic,919,0 block_count,KeyedStoreIC_Megamorphic,920,0 @@ -9905,13 +9914,13 @@ block_count,KeyedStoreIC_Megamorphic,938,0 block_count,KeyedStoreIC_Megamorphic,939,0 block_count,KeyedStoreIC_Megamorphic,940,0 -block_count,KeyedStoreIC_Megamorphic,941,81 +block_count,KeyedStoreIC_Megamorphic,941,144 block_count,KeyedStoreIC_Megamorphic,942,7 block_count,KeyedStoreIC_Megamorphic,943,1 block_count,KeyedStoreIC_Megamorphic,944,6 -block_count,KeyedStoreIC_Megamorphic,945,73 -block_count,KeyedStoreIC_Megamorphic,946,31 -block_count,KeyedStoreIC_Megamorphic,947,31 +block_count,KeyedStoreIC_Megamorphic,945,136 +block_count,KeyedStoreIC_Megamorphic,946,94 +block_count,KeyedStoreIC_Megamorphic,947,94 block_count,KeyedStoreIC_Megamorphic,948,0 block_count,KeyedStoreIC_Megamorphic,949,0 block_count,KeyedStoreIC_Megamorphic,950,0 @@ -10173,22 +10182,22 @@ block_count,KeyedStoreIC_Megamorphic,1206,0 block_count,KeyedStoreIC_Megamorphic,1207,0 block_count,KeyedStoreIC_Megamorphic,1208,0 -block_count,KeyedStoreIC_Megamorphic,1209,31 -block_count,KeyedStoreIC_Megamorphic,1210,31 -block_count,KeyedStoreIC_Megamorphic,1211,31 -block_count,KeyedStoreIC_Megamorphic,1212,31 -block_count,KeyedStoreIC_Megamorphic,1213,94 -block_count,KeyedStoreIC_Megamorphic,1214,63 -block_count,KeyedStoreIC_Megamorphic,1215,63 +block_count,KeyedStoreIC_Megamorphic,1209,94 +block_count,KeyedStoreIC_Megamorphic,1210,94 +block_count,KeyedStoreIC_Megamorphic,1211,94 +block_count,KeyedStoreIC_Megamorphic,1212,94 +block_count,KeyedStoreIC_Megamorphic,1213,283 +block_count,KeyedStoreIC_Megamorphic,1214,189 +block_count,KeyedStoreIC_Megamorphic,1215,189 block_count,KeyedStoreIC_Megamorphic,1216,0 block_count,KeyedStoreIC_Megamorphic,1217,0 block_count,KeyedStoreIC_Megamorphic,1218,0 -block_count,KeyedStoreIC_Megamorphic,1219,63 -block_count,KeyedStoreIC_Megamorphic,1220,63 +block_count,KeyedStoreIC_Megamorphic,1219,189 +block_count,KeyedStoreIC_Megamorphic,1220,189 block_count,KeyedStoreIC_Megamorphic,1221,0 -block_count,KeyedStoreIC_Megamorphic,1222,31 -block_count,KeyedStoreIC_Megamorphic,1223,31 -block_count,KeyedStoreIC_Megamorphic,1224,31 +block_count,KeyedStoreIC_Megamorphic,1222,94 +block_count,KeyedStoreIC_Megamorphic,1223,94 +block_count,KeyedStoreIC_Megamorphic,1224,94 block_count,KeyedStoreIC_Megamorphic,1225,0 block_count,KeyedStoreIC_Megamorphic,1226,0 block_count,KeyedStoreIC_Megamorphic,1227,0 @@ -10347,7 +10356,7 @@ block_count,KeyedStoreIC_Megamorphic,1380,0 block_count,KeyedStoreIC_Megamorphic,1381,0 block_count,KeyedStoreIC_Megamorphic,1382,0 -block_count,KeyedStoreIC_Megamorphic,1383,42 +block_count,KeyedStoreIC_Megamorphic,1383,41 block_count,KeyedStoreIC_Megamorphic,1384,48 block_count,KeyedStoreIC_Megamorphic,1385,48 block_count,KeyedStoreIC_Megamorphic,1386,6 @@ -12650,7 +12659,7 @@ block_count,KeyedLoadIC_SloppyArguments,20,0 block_count,KeyedLoadIC_SloppyArguments,21,0 block_count,KeyedLoadIC_SloppyArguments,22,0 -block_count,StoreFastElementIC_InBounds,0,181 +block_count,StoreFastElementIC_InBounds,0,183 block_count,StoreFastElementIC_InBounds,1,0 block_count,StoreFastElementIC_InBounds,2,3 block_count,StoreFastElementIC_InBounds,3,3 @@ -12914,7 +12923,7 @@ block_count,StoreFastElementIC_InBounds,261,12 block_count,StoreFastElementIC_InBounds,262,0 block_count,StoreFastElementIC_InBounds,263,0 -block_count,StoreFastElementIC_InBounds,264,3 +block_count,StoreFastElementIC_InBounds,264,2 block_count,StoreFastElementIC_InBounds,265,0 block_count,StoreFastElementIC_InBounds,266,0 block_count,StoreFastElementIC_InBounds,267,0 @@ -12922,20 +12931,20 @@ block_count,StoreFastElementIC_InBounds,269,0 block_count,StoreFastElementIC_InBounds,270,0 block_count,StoreFastElementIC_InBounds,271,0 -block_count,StoreFastElementIC_InBounds,272,3 -block_count,StoreFastElementIC_InBounds,273,3 -block_count,StoreFastElementIC_InBounds,274,3 +block_count,StoreFastElementIC_InBounds,272,2 +block_count,StoreFastElementIC_InBounds,273,2 +block_count,StoreFastElementIC_InBounds,274,2 block_count,StoreFastElementIC_InBounds,275,0 block_count,StoreFastElementIC_InBounds,276,0 block_count,StoreFastElementIC_InBounds,277,0 block_count,StoreFastElementIC_InBounds,278,0 block_count,StoreFastElementIC_InBounds,279,0 block_count,StoreFastElementIC_InBounds,280,0 -block_count,StoreFastElementIC_InBounds,281,3 -block_count,StoreFastElementIC_InBounds,282,3 -block_count,StoreFastElementIC_InBounds,283,3 +block_count,StoreFastElementIC_InBounds,281,2 +block_count,StoreFastElementIC_InBounds,282,2 +block_count,StoreFastElementIC_InBounds,283,2 block_count,StoreFastElementIC_InBounds,284,0 -block_count,StoreFastElementIC_InBounds,285,3 +block_count,StoreFastElementIC_InBounds,285,2 block_count,StoreFastElementIC_InBounds,286,0 block_count,StoreFastElementIC_InBounds,287,0 block_count,StoreFastElementIC_InBounds,288,0 @@ -13096,7 +13105,7 @@ block_count,StoreFastElementIC_InBounds,443,0 block_count,StoreFastElementIC_InBounds,444,0 block_count,StoreFastElementIC_InBounds,445,0 -block_count,StoreFastElementIC_InBounds,446,21 +block_count,StoreFastElementIC_InBounds,446,24 block_count,StoreFastElementIC_InBounds,447,0 block_count,StoreFastElementIC_InBounds,448,0 block_count,StoreFastElementIC_InBounds,449,0 @@ -13104,20 +13113,20 @@ block_count,StoreFastElementIC_InBounds,451,0 block_count,StoreFastElementIC_InBounds,452,0 block_count,StoreFastElementIC_InBounds,453,0 -block_count,StoreFastElementIC_InBounds,454,21 -block_count,StoreFastElementIC_InBounds,455,21 -block_count,StoreFastElementIC_InBounds,456,21 -block_count,StoreFastElementIC_InBounds,457,17 -block_count,StoreFastElementIC_InBounds,458,17 +block_count,StoreFastElementIC_InBounds,454,24 +block_count,StoreFastElementIC_InBounds,455,24 +block_count,StoreFastElementIC_InBounds,456,24 +block_count,StoreFastElementIC_InBounds,457,19 +block_count,StoreFastElementIC_InBounds,458,19 block_count,StoreFastElementIC_InBounds,459,0 block_count,StoreFastElementIC_InBounds,460,0 block_count,StoreFastElementIC_InBounds,461,0 -block_count,StoreFastElementIC_InBounds,462,17 -block_count,StoreFastElementIC_InBounds,463,4 -block_count,StoreFastElementIC_InBounds,464,21 -block_count,StoreFastElementIC_InBounds,465,21 +block_count,StoreFastElementIC_InBounds,462,19 +block_count,StoreFastElementIC_InBounds,463,5 +block_count,StoreFastElementIC_InBounds,464,24 +block_count,StoreFastElementIC_InBounds,465,24 block_count,StoreFastElementIC_InBounds,466,0 -block_count,StoreFastElementIC_InBounds,467,21 +block_count,StoreFastElementIC_InBounds,467,24 block_count,StoreFastElementIC_InBounds,468,0 block_count,StoreFastElementIC_InBounds,469,0 block_count,StoreFastElementIC_InBounds,470,0 @@ -13997,7 +14006,7 @@ block_count,StoreFastElementIC_InBounds,1344,0 block_count,StoreFastElementIC_InBounds,1345,0 block_count,StoreFastElementIC_InBounds,1346,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,0,18 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,0,19 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,1,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,2,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,3,0 @@ -14096,7 +14105,7 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,96,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,97,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,98,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,99,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,99,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,100,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,101,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,102,0 @@ -14104,13 +14113,13 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,104,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,105,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,106,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,107,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,108,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,107,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,108,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,109,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,110,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,110,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,111,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,112,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,113,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,112,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,113,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,114,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,115,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,116,0 @@ -14160,8 +14169,8 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,160,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,161,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,162,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,163,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,164,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,163,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,164,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,165,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,166,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,167,0 @@ -14190,10 +14199,10 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,190,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,191,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,192,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,193,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,193,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,194,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,195,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,196,14 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,195,0 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,196,15 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,197,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,198,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,199,0 @@ -14201,15 +14210,15 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,201,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,202,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,203,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,204,14 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,205,14 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,204,15 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,205,15 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,206,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,207,14 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,208,14 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,207,15 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,208,15 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,209,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,210,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,211,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,212,13 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,212,14 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,213,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,214,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,215,1 @@ -14225,15 +14234,15 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,225,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,226,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,227,14 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,228,12 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,228,13 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,229,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,230,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,231,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,232,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,233,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,234,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,235,11 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,236,10 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,235,12 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,236,11 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,237,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,238,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,239,1 @@ -14251,12 +14260,12 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,251,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,252,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,253,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,254,11 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,255,13 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,254,12 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,255,14 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,256,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,257,13 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,258,14 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,259,14 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,257,14 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,258,15 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,259,15 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,260,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,261,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,262,0 @@ -14285,9 +14294,9 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,285,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,286,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,287,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,288,14 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,288,15 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,289,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,290,14 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,290,15 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,291,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,292,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,293,0 @@ -19538,16 +19547,16 @@ block_count,ArrayConstructorImpl,2,6 block_count,ArrayConstructorImpl,3,5 block_count,ArrayConstructorImpl,4,1 -block_count,ArrayConstructorImpl,5,4 +block_count,ArrayConstructorImpl,5,3 block_count,ArrayConstructorImpl,6,0 block_count,ArrayConstructorImpl,7,0 block_count,ArrayConstructorImpl,8,0 -block_count,ArrayConstructorImpl,9,4 -block_count,ArrayConstructorImpl,10,4 +block_count,ArrayConstructorImpl,9,3 +block_count,ArrayConstructorImpl,10,3 block_count,ArrayConstructorImpl,11,0 -block_count,ArrayConstructorImpl,12,4 -block_count,ArrayConstructorImpl,13,4 -block_count,ArrayConstructorImpl,14,4 +block_count,ArrayConstructorImpl,12,3 +block_count,ArrayConstructorImpl,13,3 +block_count,ArrayConstructorImpl,14,3 block_count,ArrayConstructorImpl,15,2 block_count,ArrayConstructorImpl,16,2 block_count,ArrayConstructorImpl,17,0 @@ -19570,10 +19579,10 @@ block_count,ArrayConstructorImpl,34,0 block_count,ArrayConstructorImpl,35,0 block_count,ArrayConstructorImpl,36,0 -block_count,ArrayConstructorImpl,37,97 -block_count,ArrayConstructorImpl,38,97 +block_count,ArrayConstructorImpl,37,98 +block_count,ArrayConstructorImpl,38,98 block_count,ArrayConstructorImpl,39,0 -block_count,ArrayConstructorImpl,40,97 +block_count,ArrayConstructorImpl,40,98 block_count,ArrayConstructorImpl,41,0 block_count,ArrayConstructorImpl,42,113 block_count,ArrayConstructorImpl,43,114 @@ -19659,13 +19668,13 @@ block_count,ArraySingleArgumentConstructor_HoleySmi_DontOverride,43,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DontOverride,44,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DontOverride,45,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,0,97 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,0,98 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,1,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,2,97 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,2,98 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,3,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,4,97 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,5,97 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,6,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,4,98 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,5,98 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,6,51 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,7,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,8,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,9,0 @@ -19680,25 +19689,25 @@ block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,18,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,19,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,20,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,21,50 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,22,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,21,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,22,51 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,23,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,24,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,24,51 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,25,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,26,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,27,50 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,28,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,27,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,28,51 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,29,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,30,50 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,31,32 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,30,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,31,33 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,32,18 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,33,23 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,34,5 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,35,18 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,36,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,36,51 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,37,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,38,50 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,39,50 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,39,51 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,40,46 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,41,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,42,46 @@ -19709,9 +19718,9 @@ block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,1,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,2,2 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,3,0 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,4,2 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,5,2 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,6,2 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,4,1 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,5,1 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,6,1 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,7,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,8,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,9,0 @@ -19726,25 +19735,25 @@ block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,18,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,19,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,20,0 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,21,2 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,22,2 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,21,1 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,22,1 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,23,0 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,24,2 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,24,1 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,25,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,26,0 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,27,2 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,28,2 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,27,1 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,28,1 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,29,0 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,30,2 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,30,1 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,31,1 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,32,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,33,34 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,34,34 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,35,0 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,36,2 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,36,1 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,37,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,38,1 -block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,39,2 +block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,39,1 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,40,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,41,0 block_count,ArraySingleArgumentConstructor_Holey_DisableAllocationSites,42,0 @@ -20485,8 +20494,8 @@ block_count,ArrayIndexOf,22,0 block_count,ArrayIndexOf,23,28 block_count,ArrayIndexOf,24,28 -block_count,ArrayIndexOf,25,28 -block_count,ArrayIndexOf,26,28 +block_count,ArrayIndexOf,25,27 +block_count,ArrayIndexOf,26,27 block_count,ArrayIndexOf,27,0 block_count,ArrayIndexOf,28,0 block_count,ArrayIndexOf,29,0 @@ -20494,7 +20503,7 @@ block_count,ArrayIndexOf,31,0 block_count,ArrayIndexOf,32,0 block_count,ArrayIndexOf,33,0 -block_count,ArrayIndexOf,34,28 +block_count,ArrayIndexOf,34,27 block_count,ArrayIndexOf,35,0 block_count,ArrayIndexOf,36,0 block_count,ArrayIndexOf,37,0 @@ -20579,7 +20588,7 @@ block_count,ArrayPrototypePush,31,0 block_count,ArrayPrototypePush,32,0 block_count,ArrayPrototypePush,33,7 -block_count,ArrayPrototypePush,34,7 +block_count,ArrayPrototypePush,34,6 block_count,ArrayPrototypePush,35,0 block_count,ArrayPrototypePush,36,0 block_count,ArrayPrototypePush,37,0 @@ -20697,7 +20706,7 @@ block_count,ArrayPrototypePush,149,19 block_count,ArrayPrototypePush,150,1 block_count,ArrayPrototypePush,151,255 -block_count,ArrayPrototypePush,152,254 +block_count,ArrayPrototypePush,152,253 block_count,ArrayPrototypePush,153,1 block_count,ArrayPrototypePush,154,18 block_count,ArrayPrototypePush,155,19 @@ -20705,8 +20714,8 @@ block_count,ArrayPrototypePush,157,0 block_count,ArrayPrototypePush,158,275 block_count,ArrayPrototypePush,159,275 -block_count,ArrayPrototypePush,160,291 -block_count,ArrayPrototypePush,161,291 +block_count,ArrayPrototypePush,160,290 +block_count,ArrayPrototypePush,161,290 block_count,ArrayPrototypePush,162,15 block_count,ArrayPrototypePush,163,275 block_count,ArrayPrototypePush,164,0 @@ -21018,8 +21027,8 @@ block_count,ExtractFastJSArray,28,0 block_count,ExtractFastJSArray,29,0 block_count,ExtractFastJSArray,30,0 -block_count,ExtractFastJSArray,31,2 -block_count,ExtractFastJSArray,32,2 +block_count,ExtractFastJSArray,31,1 +block_count,ExtractFastJSArray,32,1 block_count,ExtractFastJSArray,33,0 block_count,ExtractFastJSArray,34,0 block_count,ExtractFastJSArray,35,0 @@ -21282,7 +21291,7 @@ block_count,CreateObjectFromSlowBoilerplateHelper,79,0 block_count,CreateObjectFromSlowBoilerplateHelper,80,44 block_count,CreateObjectFromSlowBoilerplateHelper,81,44 -block_count,CreateObjectFromSlowBoilerplateHelper,82,93 +block_count,CreateObjectFromSlowBoilerplateHelper,82,94 block_count,CreateObjectFromSlowBoilerplateHelper,83,93 block_count,CreateObjectFromSlowBoilerplateHelper,84,41 block_count,CreateObjectFromSlowBoilerplateHelper,85,0 @@ -21311,7 +21320,7 @@ block_count,CreateObjectFromSlowBoilerplateHelper,108,0 block_count,CreateObjectFromSlowBoilerplateHelper,109,52 block_count,CreateObjectFromSlowBoilerplateHelper,110,0 -block_count,CreateObjectFromSlowBoilerplateHelper,111,52 +block_count,CreateObjectFromSlowBoilerplateHelper,111,53 block_count,CreateObjectFromSlowBoilerplateHelper,112,49 block_count,CreateObjectFromSlowBoilerplateHelper,113,3 block_count,CreateObjectFromSlowBoilerplateHelper,114,0 @@ -21472,13 +21481,13 @@ block_count,ArrayPrototypeValues,12,0 block_count,ArrayPrototypeValues,13,18 block_count,ArrayPrototypeValues,14,18 -block_count,ArrayIteratorPrototypeNext,0,92 +block_count,ArrayIteratorPrototypeNext,0,91 block_count,ArrayIteratorPrototypeNext,1,0 -block_count,ArrayIteratorPrototypeNext,2,92 -block_count,ArrayIteratorPrototypeNext,3,92 -block_count,ArrayIteratorPrototypeNext,4,92 +block_count,ArrayIteratorPrototypeNext,2,91 +block_count,ArrayIteratorPrototypeNext,3,91 +block_count,ArrayIteratorPrototypeNext,4,91 block_count,ArrayIteratorPrototypeNext,5,0 -block_count,ArrayIteratorPrototypeNext,6,92 +block_count,ArrayIteratorPrototypeNext,6,91 block_count,ArrayIteratorPrototypeNext,7,2 block_count,ArrayIteratorPrototypeNext,8,2 block_count,ArrayIteratorPrototypeNext,9,0 @@ -21648,14 +21657,14 @@ block_count,ArrayIteratorPrototypeNext,173,89 block_count,ArrayIteratorPrototypeNext,174,89 block_count,ArrayIteratorPrototypeNext,175,24 -block_count,ArrayIteratorPrototypeNext,176,65 -block_count,ArrayIteratorPrototypeNext,177,65 +block_count,ArrayIteratorPrototypeNext,176,64 +block_count,ArrayIteratorPrototypeNext,177,64 block_count,ArrayIteratorPrototypeNext,178,0 block_count,ArrayIteratorPrototypeNext,179,0 block_count,ArrayIteratorPrototypeNext,180,0 block_count,ArrayIteratorPrototypeNext,181,0 -block_count,ArrayIteratorPrototypeNext,182,65 -block_count,ArrayIteratorPrototypeNext,183,65 +block_count,ArrayIteratorPrototypeNext,182,64 +block_count,ArrayIteratorPrototypeNext,183,64 block_count,ArrayIteratorPrototypeNext,184,0 block_count,ArrayIteratorPrototypeNext,185,0 block_count,ArrayIteratorPrototypeNext,186,0 @@ -21702,7 +21711,7 @@ block_count,ArrayIteratorPrototypeNext,227,0 block_count,ArrayIteratorPrototypeNext,228,0 block_count,ArrayIteratorPrototypeNext,229,0 -block_count,ArrayIteratorPrototypeNext,230,65 +block_count,ArrayIteratorPrototypeNext,230,64 block_count,ArrayIteratorPrototypeNext,231,0 block_count,ArrayIteratorPrototypeNext,232,0 block_count,ArrayIteratorPrototypeNext,233,0 @@ -21728,12 +21737,12 @@ block_count,ArrayIteratorPrototypeNext,253,0 block_count,ArrayIteratorPrototypeNext,254,0 block_count,ArrayIteratorPrototypeNext,255,66 -block_count,ArrayIteratorPrototypeNext,256,92 +block_count,ArrayIteratorPrototypeNext,256,91 block_count,ArrayIteratorPrototypeNext,257,0 -block_count,ArrayIteratorPrototypeNext,258,92 +block_count,ArrayIteratorPrototypeNext,258,91 block_count,ArrayIteratorPrototypeNext,259,0 -block_count,ArrayIteratorPrototypeNext,260,92 -block_count,ArrayIteratorPrototypeNext,261,92 +block_count,ArrayIteratorPrototypeNext,260,91 +block_count,ArrayIteratorPrototypeNext,261,91 block_count,AsyncFunctionEnter,0,0 block_count,AsyncFunctionEnter,1,0 block_count,AsyncFunctionEnter,2,0 @@ -22106,14 +22115,14 @@ block_count,SuspendGeneratorBaseline,9,0 block_count,SuspendGeneratorBaseline,10,1 block_count,SuspendGeneratorBaseline,11,1 -block_count,SuspendGeneratorBaseline,12,14 +block_count,SuspendGeneratorBaseline,12,15 block_count,SuspendGeneratorBaseline,13,13 block_count,SuspendGeneratorBaseline,14,1 block_count,ResumeGeneratorBaseline,0,1 block_count,ResumeGeneratorBaseline,1,0 block_count,ResumeGeneratorBaseline,2,1 block_count,ResumeGeneratorBaseline,3,1 -block_count,ResumeGeneratorBaseline,4,14 +block_count,ResumeGeneratorBaseline,4,15 block_count,ResumeGeneratorBaseline,5,13 block_count,ResumeGeneratorBaseline,6,1 block_count,CallIteratorWithFeedbackLazyDeoptContinuation,0,0 @@ -22142,15 +22151,15 @@ block_count,GlobalIsNaN,8,0 block_count,GlobalIsNaN,9,0 block_count,GlobalIsNaN,10,0 -block_count,LoadIC,0,2800 -block_count,LoadIC,1,2799 +block_count,LoadIC,0,2801 +block_count,LoadIC,1,2800 block_count,LoadIC,2,0 -block_count,LoadIC,3,2800 -block_count,LoadIC,4,2800 -block_count,LoadIC,5,824 +block_count,LoadIC,3,2801 +block_count,LoadIC,4,2801 +block_count,LoadIC,5,819 block_count,LoadIC,6,0 -block_count,LoadIC,7,823 -block_count,LoadIC,8,143 +block_count,LoadIC,7,819 +block_count,LoadIC,8,150 block_count,LoadIC,9,1 block_count,LoadIC,10,1 block_count,LoadIC,11,0 @@ -22164,35 +22173,35 @@ block_count,LoadIC,19,0 block_count,LoadIC,20,0 block_count,LoadIC,21,0 -block_count,LoadIC,22,141 -block_count,LoadIC,23,141 +block_count,LoadIC,22,148 +block_count,LoadIC,23,148 block_count,LoadIC,24,0 -block_count,LoadIC,25,141 -block_count,LoadIC,26,121 -block_count,LoadIC,27,120 +block_count,LoadIC,25,148 +block_count,LoadIC,26,125 +block_count,LoadIC,27,125 block_count,LoadIC,28,0 -block_count,LoadIC,29,20 -block_count,LoadIC,30,21 -block_count,LoadIC,31,20 -block_count,LoadIC,32,20 +block_count,LoadIC,29,22 +block_count,LoadIC,30,23 +block_count,LoadIC,31,22 +block_count,LoadIC,32,22 block_count,LoadIC,33,0 block_count,LoadIC,34,1 -block_count,LoadIC,35,680 -block_count,LoadIC,36,1105 -block_count,LoadIC,37,425 -block_count,LoadIC,38,425 +block_count,LoadIC,35,669 +block_count,LoadIC,36,1072 +block_count,LoadIC,37,403 +block_count,LoadIC,38,403 block_count,LoadIC,39,0 -block_count,LoadIC,40,680 -block_count,LoadIC,41,1976 +block_count,LoadIC,40,668 +block_count,LoadIC,41,1981 block_count,LoadIC,42,2797 -block_count,LoadIC,43,901 -block_count,LoadIC,44,896 -block_count,LoadIC,45,687 -block_count,LoadIC,46,686 +block_count,LoadIC,43,904 +block_count,LoadIC,44,900 +block_count,LoadIC,45,691 +block_count,LoadIC,46,690 block_count,LoadIC,47,0 -block_count,LoadIC,48,686 +block_count,LoadIC,48,690 block_count,LoadIC,49,0 -block_count,LoadIC,50,687 +block_count,LoadIC,50,691 block_count,LoadIC,51,73 block_count,LoadIC,52,32 block_count,LoadIC,53,32 @@ -22265,26 +22274,26 @@ block_count,LoadIC,120,0 block_count,LoadIC,121,40 block_count,LoadIC,122,0 -block_count,LoadIC,123,613 -block_count,LoadIC,124,685 -block_count,LoadIC,125,685 -block_count,LoadIC,126,635 -block_count,LoadIC,127,635 +block_count,LoadIC,123,617 +block_count,LoadIC,124,689 +block_count,LoadIC,125,689 +block_count,LoadIC,126,641 +block_count,LoadIC,127,641 block_count,LoadIC,128,0 -block_count,LoadIC,129,49 -block_count,LoadIC,130,685 +block_count,LoadIC,129,47 +block_count,LoadIC,130,689 block_count,LoadIC,131,0 block_count,LoadIC,132,209 block_count,LoadIC,133,4 block_count,LoadIC,134,4 block_count,LoadIC,135,0 -block_count,LoadIC,136,1895 -block_count,LoadIC,137,2580 -block_count,LoadIC,138,920 -block_count,LoadIC,139,379 -block_count,LoadIC,140,329 -block_count,LoadIC,141,119 -block_count,LoadIC,142,24 +block_count,LoadIC,136,1892 +block_count,LoadIC,137,2582 +block_count,LoadIC,138,924 +block_count,LoadIC,139,387 +block_count,LoadIC,140,339 +block_count,LoadIC,141,129 +block_count,LoadIC,142,25 block_count,LoadIC,143,2 block_count,LoadIC,144,2 block_count,LoadIC,145,2 @@ -22352,8 +22361,8 @@ block_count,LoadIC,207,0 block_count,LoadIC,208,0 block_count,LoadIC,209,0 -block_count,LoadIC,210,22 -block_count,LoadIC,211,94 +block_count,LoadIC,210,23 +block_count,LoadIC,211,103 block_count,LoadIC,212,210 block_count,LoadIC,213,210 block_count,LoadIC,214,0 @@ -22410,20 +22419,20 @@ block_count,LoadIC,265,0 block_count,LoadIC,266,0 block_count,LoadIC,267,210 -block_count,LoadIC,268,49 -block_count,LoadIC,269,540 -block_count,LoadIC,270,1660 -block_count,LoadIC,271,1660 +block_count,LoadIC,268,47 +block_count,LoadIC,269,537 +block_count,LoadIC,270,1657 +block_count,LoadIC,271,1657 block_count,LoadIC,272,447 -block_count,LoadIC,273,1213 -block_count,LoadIC,274,1660 -block_count,LoadIC,275,1569 -block_count,LoadIC,276,91 -block_count,LoadIC,277,91 -block_count,LoadIC,278,91 +block_count,LoadIC,273,1210 +block_count,LoadIC,274,1657 +block_count,LoadIC,275,1568 +block_count,LoadIC,276,89 +block_count,LoadIC,277,89 +block_count,LoadIC,278,89 block_count,LoadIC,279,0 -block_count,LoadIC,280,91 -block_count,LoadIC,281,91 +block_count,LoadIC,280,89 +block_count,LoadIC,281,89 block_count,LoadIC,282,0 block_count,LoadIC,283,0 block_count,LoadIC,284,0 @@ -22466,31 +22475,31 @@ block_count,LoadIC,321,0 block_count,LoadIC,322,0 block_count,LoadIC,323,3 -block_count,LoadIC_Megamorphic,0,8810 -block_count,LoadIC_Megamorphic,1,8809 +block_count,LoadIC_Megamorphic,0,8813 +block_count,LoadIC_Megamorphic,1,8811 block_count,LoadIC_Megamorphic,2,1 -block_count,LoadIC_Megamorphic,3,8810 -block_count,LoadIC_Megamorphic,4,8810 +block_count,LoadIC_Megamorphic,3,8813 +block_count,LoadIC_Megamorphic,4,8813 block_count,LoadIC_Megamorphic,5,0 -block_count,LoadIC_Megamorphic,6,8810 -block_count,LoadIC_Megamorphic,7,7452 -block_count,LoadIC_Megamorphic,8,7382 -block_count,LoadIC_Megamorphic,9,69 -block_count,LoadIC_Megamorphic,10,1358 -block_count,LoadIC_Megamorphic,11,1427 -block_count,LoadIC_Megamorphic,12,1413 -block_count,LoadIC_Megamorphic,13,1410 +block_count,LoadIC_Megamorphic,6,8813 +block_count,LoadIC_Megamorphic,7,7551 +block_count,LoadIC_Megamorphic,8,7494 +block_count,LoadIC_Megamorphic,9,57 +block_count,LoadIC_Megamorphic,10,1261 +block_count,LoadIC_Megamorphic,11,1318 +block_count,LoadIC_Megamorphic,12,1304 +block_count,LoadIC_Megamorphic,13,1301 block_count,LoadIC_Megamorphic,14,2 block_count,LoadIC_Megamorphic,15,14 -block_count,LoadIC_Megamorphic,16,8793 -block_count,LoadIC_Megamorphic,17,3217 -block_count,LoadIC_Megamorphic,18,3217 -block_count,LoadIC_Megamorphic,19,3206 -block_count,LoadIC_Megamorphic,20,3206 +block_count,LoadIC_Megamorphic,16,8795 +block_count,LoadIC_Megamorphic,17,3219 +block_count,LoadIC_Megamorphic,18,3219 +block_count,LoadIC_Megamorphic,19,3208 +block_count,LoadIC_Megamorphic,20,3208 block_count,LoadIC_Megamorphic,21,0 -block_count,LoadIC_Megamorphic,22,3206 +block_count,LoadIC_Megamorphic,22,3208 block_count,LoadIC_Megamorphic,23,0 -block_count,LoadIC_Megamorphic,24,3206 +block_count,LoadIC_Megamorphic,24,3208 block_count,LoadIC_Megamorphic,25,7 block_count,LoadIC_Megamorphic,26,4 block_count,LoadIC_Megamorphic,27,4 @@ -22563,23 +22572,23 @@ block_count,LoadIC_Megamorphic,94,0 block_count,LoadIC_Megamorphic,95,3 block_count,LoadIC_Megamorphic,96,0 -block_count,LoadIC_Megamorphic,97,3199 -block_count,LoadIC_Megamorphic,98,3206 -block_count,LoadIC_Megamorphic,99,3204 -block_count,LoadIC_Megamorphic,100,2522 -block_count,LoadIC_Megamorphic,101,2522 +block_count,LoadIC_Megamorphic,97,3201 +block_count,LoadIC_Megamorphic,98,3208 +block_count,LoadIC_Megamorphic,99,3207 +block_count,LoadIC_Megamorphic,100,2523 +block_count,LoadIC_Megamorphic,101,2523 block_count,LoadIC_Megamorphic,102,0 -block_count,LoadIC_Megamorphic,103,682 -block_count,LoadIC_Megamorphic,104,3204 +block_count,LoadIC_Megamorphic,103,684 +block_count,LoadIC_Megamorphic,104,3207 block_count,LoadIC_Megamorphic,105,1 block_count,LoadIC_Megamorphic,106,10 block_count,LoadIC_Megamorphic,107,0 block_count,LoadIC_Megamorphic,108,0 block_count,LoadIC_Megamorphic,109,0 block_count,LoadIC_Megamorphic,110,5576 -block_count,LoadIC_Megamorphic,111,8781 -block_count,LoadIC_Megamorphic,112,3825 -block_count,LoadIC_Megamorphic,113,2009 +block_count,LoadIC_Megamorphic,111,8783 +block_count,LoadIC_Megamorphic,112,3828 +block_count,LoadIC_Megamorphic,113,2010 block_count,LoadIC_Megamorphic,114,1326 block_count,LoadIC_Megamorphic,115,1321 block_count,LoadIC_Megamorphic,116,618 @@ -22708,14 +22717,14 @@ block_count,LoadIC_Megamorphic,239,0 block_count,LoadIC_Megamorphic,240,0 block_count,LoadIC_Megamorphic,241,5 -block_count,LoadIC_Megamorphic,242,682 -block_count,LoadIC_Megamorphic,243,1816 +block_count,LoadIC_Megamorphic,242,684 +block_count,LoadIC_Megamorphic,243,1817 block_count,LoadIC_Megamorphic,244,4955 block_count,LoadIC_Megamorphic,245,4955 block_count,LoadIC_Megamorphic,246,261 -block_count,LoadIC_Megamorphic,247,4693 +block_count,LoadIC_Megamorphic,247,4694 block_count,LoadIC_Megamorphic,248,4955 -block_count,LoadIC_Megamorphic,249,4935 +block_count,LoadIC_Megamorphic,249,4936 block_count,LoadIC_Megamorphic,250,19 block_count,LoadIC_Megamorphic,251,19 block_count,LoadIC_Megamorphic,252,19 @@ -22875,7 +22884,7 @@ block_count,LoadIC_Noninlined,108,0 block_count,LoadIC_Noninlined,109,0 block_count,LoadIC_Noninlined,110,0 -block_count,LoadIC_Noninlined,111,1 +block_count,LoadIC_Noninlined,111,0 block_count,LoadIC_Noninlined,112,1 block_count,LoadIC_Noninlined,113,1 block_count,LoadIC_Noninlined,114,0 @@ -23080,11 +23089,11 @@ block_count,LoadICTrampoline,1,270 block_count,LoadICTrampoline,2,0 block_count,LoadICTrampoline,3,270 -block_count,LoadICBaseline,0,2245 -block_count,LoadICTrampoline_Megamorphic,0,5544 -block_count,LoadICTrampoline_Megamorphic,1,5544 +block_count,LoadICBaseline,0,2247 +block_count,LoadICTrampoline_Megamorphic,0,5543 +block_count,LoadICTrampoline_Megamorphic,1,5543 block_count,LoadICTrampoline_Megamorphic,2,0 -block_count,LoadICTrampoline_Megamorphic,3,5544 +block_count,LoadICTrampoline_Megamorphic,3,5543 block_count,LoadSuperIC,0,2 block_count,LoadSuperIC,1,2 block_count,LoadSuperIC,2,2 @@ -23681,15 +23690,15 @@ block_count,LoadSuperIC,593,0 block_count,LoadSuperIC,594,0 block_count,LoadSuperICBaseline,0,2 -block_count,KeyedLoadIC,0,327 -block_count,KeyedLoadIC,1,327 +block_count,KeyedLoadIC,0,325 +block_count,KeyedLoadIC,1,325 block_count,KeyedLoadIC,2,0 -block_count,KeyedLoadIC,3,327 -block_count,KeyedLoadIC,4,327 -block_count,KeyedLoadIC,5,324 -block_count,KeyedLoadIC,6,44 +block_count,KeyedLoadIC,3,325 +block_count,KeyedLoadIC,4,325 +block_count,KeyedLoadIC,5,323 +block_count,KeyedLoadIC,6,43 block_count,KeyedLoadIC,7,0 -block_count,KeyedLoadIC,8,44 +block_count,KeyedLoadIC,8,43 block_count,KeyedLoadIC,9,24 block_count,KeyedLoadIC,10,1 block_count,KeyedLoadIC,11,1 @@ -23732,13 +23741,13 @@ block_count,KeyedLoadIC,48,0 block_count,KeyedLoadIC,49,22 block_count,KeyedLoadIC,50,19 -block_count,KeyedLoadIC,51,33 -block_count,KeyedLoadIC,52,13 -block_count,KeyedLoadIC,53,13 +block_count,KeyedLoadIC,51,31 +block_count,KeyedLoadIC,52,12 +block_count,KeyedLoadIC,53,12 block_count,KeyedLoadIC,54,0 block_count,KeyedLoadIC,55,19 -block_count,KeyedLoadIC,56,280 -block_count,KeyedLoadIC,57,300 +block_count,KeyedLoadIC,56,279 +block_count,KeyedLoadIC,57,299 block_count,KeyedLoadIC,58,1 block_count,KeyedLoadIC,59,1 block_count,KeyedLoadIC,60,0 @@ -23832,8 +23841,8 @@ block_count,KeyedLoadIC,148,0 block_count,KeyedLoadIC,149,0 block_count,KeyedLoadIC,150,0 -block_count,KeyedLoadIC,151,298 -block_count,KeyedLoadIC,152,298 +block_count,KeyedLoadIC,151,297 +block_count,KeyedLoadIC,152,297 block_count,KeyedLoadIC,153,2 block_count,KeyedLoadIC,154,0 block_count,KeyedLoadIC,155,0 @@ -24063,15 +24072,15 @@ block_count,KeyedLoadIC,379,2 block_count,KeyedLoadIC,380,2 block_count,KeyedLoadIC,381,3 -block_count,KeyedLoadIC,382,0 -block_count,KeyedLoadIC,383,0 +block_count,KeyedLoadIC,382,1 +block_count,KeyedLoadIC,383,1 block_count,KeyedLoadIC,384,0 block_count,KeyedLoadIC,385,0 block_count,KeyedLoadIC,386,0 block_count,KeyedLoadIC,387,0 block_count,KeyedLoadIC,388,0 block_count,KeyedLoadIC,389,0 -block_count,KeyedLoadIC,390,0 +block_count,KeyedLoadIC,390,1 block_count,KeyedLoadIC,391,0 block_count,KeyedLoadIC,392,0 block_count,KeyedLoadIC,393,0 @@ -24099,7 +24108,7 @@ block_count,KeyedLoadIC,415,0 block_count,KeyedLoadIC,416,0 block_count,KeyedLoadIC,417,0 -block_count,KeyedLoadIC,418,296 +block_count,KeyedLoadIC,418,294 block_count,KeyedLoadIC,419,0 block_count,KeyedLoadIC,420,0 block_count,KeyedLoadIC,421,0 @@ -24112,40 +24121,40 @@ block_count,KeyedLoadIC,428,0 block_count,KeyedLoadIC,429,0 block_count,KeyedLoadIC,430,0 -block_count,KeyedLoadIC,431,295 -block_count,KeyedLoadIC,432,295 -block_count,KeyedLoadIC,433,296 -block_count,KeyedLoadIC,434,177 +block_count,KeyedLoadIC,431,294 +block_count,KeyedLoadIC,432,294 +block_count,KeyedLoadIC,433,294 +block_count,KeyedLoadIC,434,176 block_count,KeyedLoadIC,435,4 -block_count,KeyedLoadIC,436,173 -block_count,KeyedLoadIC,437,177 +block_count,KeyedLoadIC,436,172 +block_count,KeyedLoadIC,437,176 block_count,KeyedLoadIC,438,0 block_count,KeyedLoadIC,439,176 block_count,KeyedLoadIC,440,0 block_count,KeyedLoadIC,441,9 -block_count,KeyedLoadIC,442,99 +block_count,KeyedLoadIC,442,100 block_count,KeyedLoadIC,443,0 block_count,KeyedLoadIC,444,0 block_count,KeyedLoadIC,445,0 block_count,KeyedLoadIC,446,0 -block_count,KeyedLoadIC,447,108 -block_count,KeyedLoadIC,448,6 -block_count,KeyedLoadIC,449,33 +block_count,KeyedLoadIC,447,110 +block_count,KeyedLoadIC,448,5 +block_count,KeyedLoadIC,449,32 block_count,KeyedLoadIC,450,0 block_count,KeyedLoadIC,451,0 block_count,KeyedLoadIC,452,0 -block_count,KeyedLoadIC,453,39 -block_count,KeyedLoadIC,454,38 +block_count,KeyedLoadIC,453,38 +block_count,KeyedLoadIC,454,36 block_count,KeyedLoadIC,455,1 block_count,KeyedLoadIC,456,15 block_count,KeyedLoadIC,457,0 block_count,KeyedLoadIC,458,15 block_count,KeyedLoadIC,459,15 -block_count,KeyedLoadIC,460,12 -block_count,KeyedLoadIC,461,12 +block_count,KeyedLoadIC,460,11 +block_count,KeyedLoadIC,461,11 block_count,KeyedLoadIC,462,0 -block_count,KeyedLoadIC,463,12 -block_count,KeyedLoadIC,464,12 +block_count,KeyedLoadIC,463,11 +block_count,KeyedLoadIC,464,11 block_count,KeyedLoadIC,465,0 block_count,KeyedLoadIC,466,118 block_count,KeyedLoadIC,467,118 @@ -24181,7 +24190,7 @@ block_count,KeyedLoadIC,497,0 block_count,KeyedLoadIC,498,3 block_count,KeyedLoadIC,499,0 -block_count,KeyedLoadIC,500,0 +block_count,KeyedLoadIC,500,1 block_count,KeyedLoadIC,501,82 block_count,KeyedLoadIC,502,17 block_count,KeyedLoadIC,503,0 @@ -24236,8 +24245,8 @@ block_count,KeyedLoadIC,552,0 block_count,KeyedLoadIC,553,0 block_count,KeyedLoadIC,554,0 -block_count,KeyedLoadIC,555,0 -block_count,KeyedLoadIC,556,0 +block_count,KeyedLoadIC,555,1 +block_count,KeyedLoadIC,556,1 block_count,KeyedLoadIC,557,0 block_count,KeyedLoadIC,558,0 block_count,KeyedLoadIC,559,0 @@ -24344,8 +24353,8 @@ block_count,EnumeratedKeyedLoadIC,26,0 block_count,EnumeratedKeyedLoadIC,27,0 block_count,EnumeratedKeyedLoadIC,28,0 -block_count,EnumeratedKeyedLoadIC,29,1 -block_count,EnumeratedKeyedLoadIC,30,1 +block_count,EnumeratedKeyedLoadIC,29,2 +block_count,EnumeratedKeyedLoadIC,30,2 block_count,EnumeratedKeyedLoadIC,31,1 block_count,EnumeratedKeyedLoadIC,32,1 block_count,EnumeratedKeyedLoadIC,33,0 @@ -24990,16 +24999,16 @@ block_count,KeyedLoadIC_Megamorphic,12,42 block_count,KeyedLoadIC_Megamorphic,13,37 block_count,KeyedLoadIC_Megamorphic,14,4 -block_count,KeyedLoadIC_Megamorphic,15,1778 -block_count,KeyedLoadIC_Megamorphic,16,1778 +block_count,KeyedLoadIC_Megamorphic,15,1777 +block_count,KeyedLoadIC_Megamorphic,16,1777 block_count,KeyedLoadIC_Megamorphic,17,1692 block_count,KeyedLoadIC_Megamorphic,18,1692 -block_count,KeyedLoadIC_Megamorphic,19,1630 +block_count,KeyedLoadIC_Megamorphic,19,1629 block_count,KeyedLoadIC_Megamorphic,20,0 block_count,KeyedLoadIC_Megamorphic,21,0 block_count,KeyedLoadIC_Megamorphic,22,0 -block_count,KeyedLoadIC_Megamorphic,23,1630 -block_count,KeyedLoadIC_Megamorphic,24,891 +block_count,KeyedLoadIC_Megamorphic,23,1629 +block_count,KeyedLoadIC_Megamorphic,24,890 block_count,KeyedLoadIC_Megamorphic,25,739 block_count,KeyedLoadIC_Megamorphic,26,62 block_count,KeyedLoadIC_Megamorphic,27,0 @@ -25360,11 +25369,11 @@ block_count,KeyedLoadIC_Megamorphic,382,0 block_count,KeyedLoadIC_Megamorphic,383,336 block_count,KeyedLoadIC_Megamorphic,384,8 -block_count,KeyedLoadIC_Megamorphic,385,328 -block_count,KeyedLoadIC_Megamorphic,386,886 +block_count,KeyedLoadIC_Megamorphic,385,327 +block_count,KeyedLoadIC_Megamorphic,386,885 block_count,KeyedLoadIC_Megamorphic,387,759 -block_count,KeyedLoadIC_Megamorphic,388,639 -block_count,KeyedLoadIC_Megamorphic,389,558 +block_count,KeyedLoadIC_Megamorphic,388,638 +block_count,KeyedLoadIC_Megamorphic,389,557 block_count,KeyedLoadIC_Megamorphic,390,80 block_count,KeyedLoadIC_Megamorphic,391,120 block_count,KeyedLoadIC_Megamorphic,392,126 @@ -25389,17 +25398,17 @@ block_count,KeyedLoadIC_Megamorphic,411,303 block_count,KeyedLoadIC_Megamorphic,412,21 block_count,KeyedLoadIC_Megamorphic,413,99 -block_count,KeyedLoadIC_Megamorphic,414,99 -block_count,KeyedLoadIC_Megamorphic,415,99 +block_count,KeyedLoadIC_Megamorphic,414,98 +block_count,KeyedLoadIC_Megamorphic,415,98 block_count,KeyedLoadIC_Megamorphic,416,0 -block_count,KeyedLoadIC_Megamorphic,417,99 -block_count,KeyedLoadIC_Megamorphic,418,74 -block_count,KeyedLoadIC_Megamorphic,419,74 +block_count,KeyedLoadIC_Megamorphic,417,98 +block_count,KeyedLoadIC_Megamorphic,418,72 +block_count,KeyedLoadIC_Megamorphic,419,72 block_count,KeyedLoadIC_Megamorphic,420,0 -block_count,KeyedLoadIC_Megamorphic,421,24 -block_count,KeyedLoadIC_Megamorphic,422,24 -block_count,KeyedLoadIC_Megamorphic,423,10 -block_count,KeyedLoadIC_Megamorphic,424,10 +block_count,KeyedLoadIC_Megamorphic,421,26 +block_count,KeyedLoadIC_Megamorphic,422,26 +block_count,KeyedLoadIC_Megamorphic,423,12 +block_count,KeyedLoadIC_Megamorphic,424,12 block_count,KeyedLoadIC_Megamorphic,425,0 block_count,KeyedLoadIC_Megamorphic,426,14 block_count,KeyedLoadIC_Megamorphic,427,84 @@ -25918,10 +25927,10 @@ block_count,KeyedLoadIC_Megamorphic,940,362 block_count,KeyedLoadIC_Megamorphic,941,352 block_count,KeyedLoadIC_Megamorphic,942,66 -block_count,KeyedLoadIC_Megamorphic,943,286 +block_count,KeyedLoadIC_Megamorphic,943,285 block_count,KeyedLoadIC_Megamorphic,944,352 block_count,KeyedLoadIC_Megamorphic,945,8 -block_count,KeyedLoadIC_Megamorphic,946,344 +block_count,KeyedLoadIC_Megamorphic,946,343 block_count,KeyedLoadIC_Megamorphic,947,0 block_count,KeyedLoadIC_Megamorphic,948,0 block_count,KeyedLoadIC_Megamorphic,949,280 @@ -26117,18 +26126,18 @@ block_count,KeyedLoadICTrampoline,1,1 block_count,KeyedLoadICTrampoline,2,0 block_count,KeyedLoadICTrampoline,3,1 -block_count,KeyedLoadICBaseline,0,306 +block_count,KeyedLoadICBaseline,0,304 block_count,EnumeratedKeyedLoadICBaseline,0,2 -block_count,KeyedLoadICTrampoline_Megamorphic,0,724 -block_count,KeyedLoadICTrampoline_Megamorphic,1,724 +block_count,KeyedLoadICTrampoline_Megamorphic,0,722 +block_count,KeyedLoadICTrampoline_Megamorphic,1,722 block_count,KeyedLoadICTrampoline_Megamorphic,2,0 -block_count,KeyedLoadICTrampoline_Megamorphic,3,724 -block_count,StoreGlobalIC,0,479 -block_count,StoreGlobalIC,1,479 -block_count,StoreGlobalIC,2,479 -block_count,StoreGlobalIC,3,479 -block_count,StoreGlobalIC,4,479 -block_count,StoreGlobalIC,5,479 +block_count,KeyedLoadICTrampoline_Megamorphic,3,722 +block_count,StoreGlobalIC,0,531 +block_count,StoreGlobalIC,1,531 +block_count,StoreGlobalIC,2,531 +block_count,StoreGlobalIC,3,531 +block_count,StoreGlobalIC,4,531 +block_count,StoreGlobalIC,5,531 block_count,StoreGlobalIC,6,1 block_count,StoreGlobalIC,7,0 block_count,StoreGlobalIC,8,0 @@ -26138,7 +26147,7 @@ block_count,StoreGlobalIC,12,1 block_count,StoreGlobalIC,13,0 block_count,StoreGlobalIC,14,1 -block_count,StoreGlobalIC,15,477 +block_count,StoreGlobalIC,15,529 block_count,StoreGlobalIC,16,0 block_count,StoreGlobalIC,17,0 block_count,StoreGlobalIC,18,0 @@ -26571,39 +26580,39 @@ block_count,StoreGlobalICTrampoline,2,0 block_count,StoreGlobalICTrampoline,3,144 block_count,StoreGlobalICBaseline,0,1 -block_count,StoreIC,0,331 -block_count,StoreIC,1,331 +block_count,StoreIC,0,334 +block_count,StoreIC,1,334 block_count,StoreIC,2,0 -block_count,StoreIC,3,331 -block_count,StoreIC,4,331 -block_count,StoreIC,5,325 -block_count,StoreIC,6,109 +block_count,StoreIC,3,334 +block_count,StoreIC,4,334 +block_count,StoreIC,5,328 +block_count,StoreIC,6,110 block_count,StoreIC,7,0 -block_count,StoreIC,8,109 +block_count,StoreIC,8,110 block_count,StoreIC,9,26 block_count,StoreIC,10,0 block_count,StoreIC,11,26 block_count,StoreIC,12,26 block_count,StoreIC,13,0 block_count,StoreIC,14,26 -block_count,StoreIC,15,24 -block_count,StoreIC,16,23 +block_count,StoreIC,15,25 +block_count,StoreIC,16,24 block_count,StoreIC,17,0 -block_count,StoreIC,18,2 -block_count,StoreIC,19,2 -block_count,StoreIC,20,2 -block_count,StoreIC,21,2 +block_count,StoreIC,18,0 +block_count,StoreIC,19,1 +block_count,StoreIC,20,0 +block_count,StoreIC,21,0 block_count,StoreIC,22,0 block_count,StoreIC,23,0 -block_count,StoreIC,24,82 -block_count,StoreIC,25,135 -block_count,StoreIC,26,52 -block_count,StoreIC,27,52 +block_count,StoreIC,24,84 +block_count,StoreIC,25,137 +block_count,StoreIC,26,53 +block_count,StoreIC,27,53 block_count,StoreIC,28,0 -block_count,StoreIC,29,82 -block_count,StoreIC,30,216 -block_count,StoreIC,31,325 -block_count,StoreIC,32,126 +block_count,StoreIC,29,84 +block_count,StoreIC,30,217 +block_count,StoreIC,31,327 +block_count,StoreIC,32,125 block_count,StoreIC,33,4 block_count,StoreIC,34,4 block_count,StoreIC,35,4 @@ -26744,8 +26753,8 @@ block_count,StoreIC,170,0 block_count,StoreIC,171,0 block_count,StoreIC,172,0 -block_count,StoreIC,173,121 -block_count,StoreIC,174,121 +block_count,StoreIC,173,120 +block_count,StoreIC,174,120 block_count,StoreIC,175,111 block_count,StoreIC,176,111 block_count,StoreIC,177,111 @@ -26758,10 +26767,10 @@ block_count,StoreIC,184,0 block_count,StoreIC,185,0 block_count,StoreIC,186,111 -block_count,StoreIC,187,95 +block_count,StoreIC,187,94 block_count,StoreIC,188,93 -block_count,StoreIC,189,3 -block_count,StoreIC,190,3 +block_count,StoreIC,189,2 +block_count,StoreIC,190,2 block_count,StoreIC,191,0 block_count,StoreIC,192,90 block_count,StoreIC,193,90 @@ -26779,7 +26788,7 @@ block_count,StoreIC,205,0 block_count,StoreIC,206,16 block_count,StoreIC,207,111 -block_count,StoreIC,208,22 +block_count,StoreIC,208,23 block_count,StoreIC,209,0 block_count,StoreIC,210,0 block_count,StoreIC,211,0 @@ -26788,43 +26797,43 @@ block_count,StoreIC,214,0 block_count,StoreIC,215,0 block_count,StoreIC,216,22 -block_count,StoreIC,217,22 -block_count,StoreIC,218,22 +block_count,StoreIC,217,23 +block_count,StoreIC,218,23 block_count,StoreIC,219,0 -block_count,StoreIC,220,22 -block_count,StoreIC,221,10 -block_count,StoreIC,222,10 +block_count,StoreIC,220,23 +block_count,StoreIC,221,11 +block_count,StoreIC,222,11 block_count,StoreIC,223,0 -block_count,StoreIC,224,10 +block_count,StoreIC,224,11 block_count,StoreIC,225,0 block_count,StoreIC,226,0 -block_count,StoreIC,227,10 +block_count,StoreIC,227,11 block_count,StoreIC,228,0 -block_count,StoreIC,229,10 +block_count,StoreIC,229,11 block_count,StoreIC,230,0 -block_count,StoreIC,231,10 -block_count,StoreIC,232,10 +block_count,StoreIC,231,11 +block_count,StoreIC,232,11 block_count,StoreIC,233,0 -block_count,StoreIC,234,10 -block_count,StoreIC,235,10 +block_count,StoreIC,234,11 +block_count,StoreIC,235,11 block_count,StoreIC,236,0 -block_count,StoreIC,237,10 -block_count,StoreIC,238,10 +block_count,StoreIC,237,11 +block_count,StoreIC,238,11 block_count,StoreIC,239,7 block_count,StoreIC,240,3 block_count,StoreIC,241,0 block_count,StoreIC,242,3 -block_count,StoreIC,243,7 +block_count,StoreIC,243,8 block_count,StoreIC,244,4 block_count,StoreIC,245,3 block_count,StoreIC,246,3 -block_count,StoreIC,247,0 +block_count,StoreIC,247,1 block_count,StoreIC,248,2 -block_count,StoreIC,249,10 -block_count,StoreIC,250,11 -block_count,StoreIC,251,22 +block_count,StoreIC,249,11 +block_count,StoreIC,250,12 +block_count,StoreIC,251,23 block_count,StoreIC,252,88 -block_count,StoreIC,253,87 +block_count,StoreIC,253,86 block_count,StoreIC,254,1 block_count,StoreIC,255,1 block_count,StoreIC,256,0 @@ -26852,7 +26861,7 @@ block_count,StoreIC,278,0 block_count,StoreIC,279,0 block_count,StoreIC,280,0 -block_count,StoreIC,281,198 +block_count,StoreIC,281,201 block_count,StoreIC,282,12 block_count,StoreIC,283,12 block_count,StoreIC,284,12 @@ -26877,9 +26886,9 @@ block_count,StoreIC,303,0 block_count,StoreIC,304,0 block_count,StoreIC,305,0 -block_count,StoreIC,306,186 -block_count,StoreIC,307,169 -block_count,StoreIC,308,169 +block_count,StoreIC,306,189 +block_count,StoreIC,307,172 +block_count,StoreIC,308,172 block_count,StoreIC,309,20 block_count,StoreIC,310,19 block_count,StoreIC,311,19 @@ -26905,30 +26914,30 @@ block_count,StoreIC,331,0 block_count,StoreIC,332,0 block_count,StoreIC,333,0 -block_count,StoreIC,334,80 -block_count,StoreIC,335,80 -block_count,StoreIC,336,80 +block_count,StoreIC,334,81 +block_count,StoreIC,335,81 +block_count,StoreIC,336,81 block_count,StoreIC,337,3 block_count,StoreIC,338,0 block_count,StoreIC,339,3 -block_count,StoreIC,340,76 +block_count,StoreIC,340,77 block_count,StoreIC,341,0 -block_count,StoreIC,342,80 +block_count,StoreIC,342,81 block_count,StoreIC,343,20 -block_count,StoreIC,344,59 -block_count,StoreIC,345,80 -block_count,StoreIC,346,80 +block_count,StoreIC,344,60 +block_count,StoreIC,345,81 +block_count,StoreIC,346,81 block_count,StoreIC,347,0 block_count,StoreIC,348,0 block_count,StoreIC,349,0 block_count,StoreIC,350,0 -block_count,StoreIC,351,66 +block_count,StoreIC,351,67 block_count,StoreIC,352,0 -block_count,StoreIC,353,66 +block_count,StoreIC,353,67 block_count,StoreIC,354,11 -block_count,StoreIC,355,54 -block_count,StoreIC,356,66 -block_count,StoreIC,357,66 +block_count,StoreIC,355,56 +block_count,StoreIC,356,67 +block_count,StoreIC,357,67 block_count,StoreIC,358,0 block_count,StoreIC,359,0 block_count,StoreIC,360,0 @@ -26955,24 +26964,24 @@ block_count,StoreIC,381,5 block_count,StoreIC,382,0 block_count,StoreIC,383,0 -block_count,StoreIC_Megamorphic,0,1210 -block_count,StoreIC_Megamorphic,1,1210 +block_count,StoreIC_Megamorphic,0,1211 +block_count,StoreIC_Megamorphic,1,1211 block_count,StoreIC_Megamorphic,2,0 -block_count,StoreIC_Megamorphic,3,1210 -block_count,StoreIC_Megamorphic,4,1210 +block_count,StoreIC_Megamorphic,3,1211 +block_count,StoreIC_Megamorphic,4,1211 block_count,StoreIC_Megamorphic,5,0 -block_count,StoreIC_Megamorphic,6,1210 -block_count,StoreIC_Megamorphic,7,1067 -block_count,StoreIC_Megamorphic,8,1043 -block_count,StoreIC_Megamorphic,9,23 -block_count,StoreIC_Megamorphic,10,143 -block_count,StoreIC_Megamorphic,11,166 -block_count,StoreIC_Megamorphic,12,165 -block_count,StoreIC_Megamorphic,13,164 +block_count,StoreIC_Megamorphic,6,1211 +block_count,StoreIC_Megamorphic,7,1123 +block_count,StoreIC_Megamorphic,8,1018 +block_count,StoreIC_Megamorphic,9,104 +block_count,StoreIC_Megamorphic,10,88 +block_count,StoreIC_Megamorphic,11,192 +block_count,StoreIC_Megamorphic,12,192 +block_count,StoreIC_Megamorphic,13,190 block_count,StoreIC_Megamorphic,14,1 block_count,StoreIC_Megamorphic,15,0 -block_count,StoreIC_Megamorphic,16,1208 -block_count,StoreIC_Megamorphic,17,515 +block_count,StoreIC_Megamorphic,16,1209 +block_count,StoreIC_Megamorphic,17,516 block_count,StoreIC_Megamorphic,18,1 block_count,StoreIC_Megamorphic,19,1 block_count,StoreIC_Megamorphic,20,1 @@ -27113,20 +27122,20 @@ block_count,StoreIC_Megamorphic,155,0 block_count,StoreIC_Megamorphic,156,0 block_count,StoreIC_Megamorphic,157,0 -block_count,StoreIC_Megamorphic,158,513 -block_count,StoreIC_Megamorphic,159,513 -block_count,StoreIC_Megamorphic,160,343 -block_count,StoreIC_Megamorphic,161,343 -block_count,StoreIC_Megamorphic,162,343 +block_count,StoreIC_Megamorphic,158,514 +block_count,StoreIC_Megamorphic,159,514 +block_count,StoreIC_Megamorphic,160,344 +block_count,StoreIC_Megamorphic,161,344 +block_count,StoreIC_Megamorphic,162,344 block_count,StoreIC_Megamorphic,163,0 -block_count,StoreIC_Megamorphic,164,343 +block_count,StoreIC_Megamorphic,164,344 block_count,StoreIC_Megamorphic,165,0 -block_count,StoreIC_Megamorphic,166,343 -block_count,StoreIC_Megamorphic,167,343 +block_count,StoreIC_Megamorphic,166,344 +block_count,StoreIC_Megamorphic,167,344 block_count,StoreIC_Megamorphic,168,0 block_count,StoreIC_Megamorphic,169,0 block_count,StoreIC_Megamorphic,170,0 -block_count,StoreIC_Megamorphic,171,343 +block_count,StoreIC_Megamorphic,171,344 block_count,StoreIC_Megamorphic,172,208 block_count,StoreIC_Megamorphic,173,208 block_count,StoreIC_Megamorphic,174,0 @@ -27144,10 +27153,10 @@ block_count,StoreIC_Megamorphic,186,0 block_count,StoreIC_Megamorphic,187,0 block_count,StoreIC_Megamorphic,188,0 -block_count,StoreIC_Megamorphic,189,134 +block_count,StoreIC_Megamorphic,189,135 block_count,StoreIC_Megamorphic,190,0 -block_count,StoreIC_Megamorphic,191,134 -block_count,StoreIC_Megamorphic,192,343 +block_count,StoreIC_Megamorphic,191,135 +block_count,StoreIC_Megamorphic,192,344 block_count,StoreIC_Megamorphic,193,26 block_count,StoreIC_Megamorphic,194,0 block_count,StoreIC_Megamorphic,195,0 @@ -27192,8 +27201,8 @@ block_count,StoreIC_Megamorphic,234,11 block_count,StoreIC_Megamorphic,235,14 block_count,StoreIC_Megamorphic,236,26 -block_count,StoreIC_Megamorphic,237,316 -block_count,StoreIC_Megamorphic,238,316 +block_count,StoreIC_Megamorphic,237,317 +block_count,StoreIC_Megamorphic,238,317 block_count,StoreIC_Megamorphic,239,0 block_count,StoreIC_Megamorphic,240,0 block_count,StoreIC_Megamorphic,241,0 @@ -27330,7 +27339,7 @@ block_count,StoreICTrampoline_Megamorphic,1,574 block_count,StoreICTrampoline_Megamorphic,2,0 block_count,StoreICTrampoline_Megamorphic,3,574 -block_count,StoreICBaseline,0,277 +block_count,StoreICBaseline,0,279 block_count,DefineNamedOwnIC,0,42 block_count,DefineNamedOwnIC,1,42 block_count,DefineNamedOwnIC,2,0 @@ -27361,8 +27370,8 @@ block_count,DefineNamedOwnIC,27,0 block_count,DefineNamedOwnIC,28,0 block_count,DefineNamedOwnIC,29,0 -block_count,DefineNamedOwnIC,30,38 -block_count,DefineNamedOwnIC,31,38 +block_count,DefineNamedOwnIC,30,37 +block_count,DefineNamedOwnIC,31,37 block_count,DefineNamedOwnIC,32,0 block_count,DefineNamedOwnIC,33,0 block_count,DefineNamedOwnIC,34,0 @@ -27607,7 +27616,7 @@ block_count,DefineNamedOwnIC,273,0 block_count,DefineNamedOwnIC,274,0 block_count,DefineNamedOwnIC,275,0 -block_count,DefineNamedOwnIC,276,38 +block_count,DefineNamedOwnIC,276,37 block_count,DefineNamedOwnIC,277,0 block_count,DefineNamedOwnIC,278,0 block_count,DefineNamedOwnIC,279,0 @@ -27627,9 +27636,9 @@ block_count,DefineNamedOwnIC,293,0 block_count,DefineNamedOwnIC,294,0 block_count,DefineNamedOwnIC,295,0 -block_count,DefineNamedOwnIC,296,38 -block_count,DefineNamedOwnIC,297,38 -block_count,DefineNamedOwnIC,298,38 +block_count,DefineNamedOwnIC,296,37 +block_count,DefineNamedOwnIC,297,37 +block_count,DefineNamedOwnIC,298,37 block_count,DefineNamedOwnIC,299,0 block_count,DefineNamedOwnIC,300,0 block_count,DefineNamedOwnIC,301,0 @@ -27655,19 +27664,19 @@ block_count,DefineNamedOwnIC,321,0 block_count,DefineNamedOwnIC,322,0 block_count,DefineNamedOwnIC,323,0 -block_count,DefineNamedOwnIC,324,30 -block_count,DefineNamedOwnIC,325,30 -block_count,DefineNamedOwnIC,326,30 +block_count,DefineNamedOwnIC,324,29 +block_count,DefineNamedOwnIC,325,29 +block_count,DefineNamedOwnIC,326,29 block_count,DefineNamedOwnIC,327,4 block_count,DefineNamedOwnIC,328,0 block_count,DefineNamedOwnIC,329,4 -block_count,DefineNamedOwnIC,330,25 +block_count,DefineNamedOwnIC,330,24 block_count,DefineNamedOwnIC,331,0 -block_count,DefineNamedOwnIC,332,30 +block_count,DefineNamedOwnIC,332,29 block_count,DefineNamedOwnIC,333,0 -block_count,DefineNamedOwnIC,334,30 -block_count,DefineNamedOwnIC,335,30 -block_count,DefineNamedOwnIC,336,30 +block_count,DefineNamedOwnIC,334,29 +block_count,DefineNamedOwnIC,335,29 +block_count,DefineNamedOwnIC,336,29 block_count,DefineNamedOwnIC,337,0 block_count,DefineNamedOwnIC,338,0 block_count,DefineNamedOwnIC,339,0 @@ -27705,17 +27714,17 @@ block_count,DefineNamedOwnIC,371,3 block_count,DefineNamedOwnIC,372,0 block_count,DefineNamedOwnIC,373,0 -block_count,DefineNamedOwnICBaseline,0,38 -block_count,KeyedStoreIC,0,196 -block_count,KeyedStoreIC,1,196 +block_count,DefineNamedOwnICBaseline,0,37 +block_count,KeyedStoreIC,0,199 +block_count,KeyedStoreIC,1,199 block_count,KeyedStoreIC,2,0 -block_count,KeyedStoreIC,3,196 -block_count,KeyedStoreIC,4,196 -block_count,KeyedStoreIC,5,194 +block_count,KeyedStoreIC,3,199 +block_count,KeyedStoreIC,4,199 +block_count,KeyedStoreIC,5,197 block_count,KeyedStoreIC,6,17 block_count,KeyedStoreIC,7,0 block_count,KeyedStoreIC,8,17 -block_count,KeyedStoreIC,9,10 +block_count,KeyedStoreIC,9,11 block_count,KeyedStoreIC,10,1 block_count,KeyedStoreIC,11,0 block_count,KeyedStoreIC,12,0 @@ -27724,17 +27733,17 @@ block_count,KeyedStoreIC,15,0 block_count,KeyedStoreIC,16,0 block_count,KeyedStoreIC,17,0 -block_count,KeyedStoreIC,18,9 +block_count,KeyedStoreIC,18,10 block_count,KeyedStoreIC,19,6 -block_count,KeyedStoreIC,20,11 +block_count,KeyedStoreIC,20,12 block_count,KeyedStoreIC,21,5 block_count,KeyedStoreIC,22,5 block_count,KeyedStoreIC,23,0 block_count,KeyedStoreIC,24,6 -block_count,KeyedStoreIC,25,176 -block_count,KeyedStoreIC,26,184 -block_count,KeyedStoreIC,27,182 -block_count,KeyedStoreIC,28,182 +block_count,KeyedStoreIC,25,179 +block_count,KeyedStoreIC,26,187 +block_count,KeyedStoreIC,27,186 +block_count,KeyedStoreIC,28,185 block_count,KeyedStoreIC,29,29 block_count,KeyedStoreIC,30,29 block_count,KeyedStoreIC,31,0 @@ -27910,7 +27919,7 @@ block_count,KeyedStoreIC,201,0 block_count,KeyedStoreIC,202,0 block_count,KeyedStoreIC,203,0 -block_count,KeyedStoreIC,204,152 +block_count,KeyedStoreIC,204,155 block_count,KeyedStoreIC,205,0 block_count,KeyedStoreIC,206,0 block_count,KeyedStoreIC,207,0 @@ -28149,18 +28158,18 @@ block_count,KeyedStoreIC,440,0 block_count,KeyedStoreIC,441,0 block_count,KeyedStoreIC,442,1 -block_count,KeyedStoreIC,443,11 +block_count,KeyedStoreIC,443,12 block_count,KeyedStoreIC,444,0 block_count,KeyedStoreIC,445,0 block_count,KeyedStoreICTrampoline,0,0 block_count,KeyedStoreICTrampoline,1,0 block_count,KeyedStoreICTrampoline,2,0 block_count,KeyedStoreICTrampoline,3,0 -block_count,KeyedStoreICTrampoline_Megamorphic,0,222 -block_count,KeyedStoreICTrampoline_Megamorphic,1,222 +block_count,KeyedStoreICTrampoline_Megamorphic,0,284 +block_count,KeyedStoreICTrampoline_Megamorphic,1,284 block_count,KeyedStoreICTrampoline_Megamorphic,2,0 -block_count,KeyedStoreICTrampoline_Megamorphic,3,222 -block_count,KeyedStoreICBaseline,0,182 +block_count,KeyedStoreICTrampoline_Megamorphic,3,284 +block_count,KeyedStoreICBaseline,0,186 block_count,DefineKeyedOwnIC,0,2 block_count,DefineKeyedOwnIC,1,2 block_count,DefineKeyedOwnIC,2,0 @@ -28635,11 +28644,11 @@ block_count,StoreInArrayLiteralIC,29,0 block_count,StoreInArrayLiteralIC,30,0 block_count,StoreInArrayLiteralICBaseline,0,17 -block_count,LoadGlobalIC,0,1397 -block_count,LoadGlobalIC,1,1397 -block_count,LoadGlobalIC,2,1334 -block_count,LoadGlobalIC,3,1334 -block_count,LoadGlobalIC,4,1334 +block_count,LoadGlobalIC,0,1372 +block_count,LoadGlobalIC,1,1372 +block_count,LoadGlobalIC,2,1309 +block_count,LoadGlobalIC,3,1309 +block_count,LoadGlobalIC,4,1309 block_count,LoadGlobalIC,5,0 block_count,LoadGlobalIC,6,0 block_count,LoadGlobalIC,7,0 @@ -28848,11 +28857,11 @@ block_count,LoadGlobalIC,210,0 block_count,LoadGlobalIC,211,0 block_count,LoadGlobalIC,212,0 -block_count,LoadGlobalIC,213,63 +block_count,LoadGlobalIC,213,62 block_count,LoadGlobalIC,214,0 -block_count,LoadGlobalIC,215,63 +block_count,LoadGlobalIC,215,62 block_count,LoadGlobalIC,216,0 -block_count,LoadGlobalIC,217,63 +block_count,LoadGlobalIC,217,62 block_count,LoadGlobalICInsideTypeof,0,0 block_count,LoadGlobalICInsideTypeof,1,0 block_count,LoadGlobalICInsideTypeof,2,0 @@ -29066,11 +29075,11 @@ block_count,LoadGlobalICInsideTypeof,210,0 block_count,LoadGlobalICInsideTypeof,211,0 block_count,LoadGlobalICInsideTypeof,212,0 -block_count,LoadGlobalICTrampoline,0,988 -block_count,LoadGlobalICTrampoline,1,988 +block_count,LoadGlobalICTrampoline,0,971 +block_count,LoadGlobalICTrampoline,1,971 block_count,LoadGlobalICTrampoline,2,0 -block_count,LoadGlobalICTrampoline,3,988 -block_count,LoadGlobalICBaseline,0,366 +block_count,LoadGlobalICTrampoline,3,971 +block_count,LoadGlobalICBaseline,0,363 block_count,LoadGlobalICInsideTypeofBaseline,0,0 block_count,LookupGlobalICTrampoline,0,2 block_count,LookupGlobalICTrampoline,1,2 @@ -29123,7 +29132,7 @@ block_count,KeyedHasIC,6,636 block_count,KeyedHasIC,7,0 block_count,KeyedHasIC,8,636 -block_count,KeyedHasIC,9,636 +block_count,KeyedHasIC,9,635 block_count,KeyedHasIC,10,3 block_count,KeyedHasIC,11,3 block_count,KeyedHasIC,12,0 @@ -29462,7 +29471,7 @@ block_count,KeyedHasIC_Megamorphic,64,1756 block_count,KeyedHasIC_Megamorphic,65,427 block_count,KeyedHasIC_Megamorphic,66,1328 -block_count,KeyedHasIC_Megamorphic,67,6588 +block_count,KeyedHasIC_Megamorphic,67,6587 block_count,KeyedHasIC_Megamorphic,68,6585 block_count,KeyedHasIC_Megamorphic,69,6583 block_count,KeyedHasIC_Megamorphic,70,5259 @@ -29943,9 +29952,9 @@ block_count,FindOrderedHashMapEntry,14,50 block_count,FindOrderedHashMapEntry,15,55 block_count,FindOrderedHashMapEntry,16,114 -block_count,FindOrderedHashMapEntry,17,235 -block_count,FindOrderedHashMapEntry,18,141 -block_count,FindOrderedHashMapEntry,19,120 +block_count,FindOrderedHashMapEntry,17,215 +block_count,FindOrderedHashMapEntry,18,121 +block_count,FindOrderedHashMapEntry,19,101 block_count,FindOrderedHashMapEntry,20,20 block_count,FindOrderedHashMapEntry,21,93 block_count,FindOrderedHashMapEntry,22,0 @@ -30417,9 +30426,9 @@ block_count,MapPrototypeSet,27,37 block_count,MapPrototypeSet,28,40 block_count,MapPrototypeSet,29,40 -block_count,MapPrototypeSet,30,68 +block_count,MapPrototypeSet,30,67 block_count,MapPrototypeSet,31,37 -block_count,MapPrototypeSet,32,28 +block_count,MapPrototypeSet,32,27 block_count,MapPrototypeSet,33,9 block_count,MapPrototypeSet,34,30 block_count,MapPrototypeSet,35,0 @@ -30785,26 +30794,26 @@ block_count,MapIteratorToList,54,0 block_count,MapIteratorToList,55,0 block_count,MapIteratorToList,56,0 -block_count,Add_Baseline,0,199 -block_count,Add_Baseline,1,109 -block_count,Add_Baseline,2,2 -block_count,Add_Baseline,3,2 +block_count,Add_Baseline,0,200 +block_count,Add_Baseline,1,108 +block_count,Add_Baseline,2,1 +block_count,Add_Baseline,3,1 block_count,Add_Baseline,4,0 -block_count,Add_Baseline,5,107 -block_count,Add_Baseline,6,107 +block_count,Add_Baseline,5,106 +block_count,Add_Baseline,6,106 block_count,Add_Baseline,7,0 -block_count,Add_Baseline,8,107 -block_count,Add_Baseline,9,107 +block_count,Add_Baseline,8,106 +block_count,Add_Baseline,9,106 block_count,Add_Baseline,10,0 -block_count,Add_Baseline,11,90 -block_count,Add_Baseline,12,55 -block_count,Add_Baseline,13,48 -block_count,Add_Baseline,14,48 +block_count,Add_Baseline,11,91 +block_count,Add_Baseline,12,57 +block_count,Add_Baseline,13,52 +block_count,Add_Baseline,14,52 block_count,Add_Baseline,15,0 -block_count,Add_Baseline,16,7 +block_count,Add_Baseline,16,5 block_count,Add_Baseline,17,34 block_count,Add_Baseline,18,34 -block_count,Add_Baseline,19,31 +block_count,Add_Baseline,19,32 block_count,Add_Baseline,20,0 block_count,Add_Baseline,21,0 block_count,Add_Baseline,22,0 @@ -30887,19 +30896,19 @@ block_count,Add_Baseline,99,0 block_count,Add_Baseline,100,5 block_count,Add_Baseline,101,5 -block_count,Add_Baseline,102,58 +block_count,Add_Baseline,102,59 block_count,Add_Baseline,103,0 -block_count,Add_Baseline,104,58 -block_count,Add_Baseline,105,58 +block_count,Add_Baseline,104,59 +block_count,Add_Baseline,105,59 block_count,Add_Baseline,106,0 -block_count,Add_Baseline,107,58 -block_count,Add_Baseline,108,58 -block_count,AddSmi_Baseline,0,217 -block_count,AddSmi_Baseline,1,216 -block_count,AddSmi_Baseline,2,216 +block_count,Add_Baseline,107,59 +block_count,Add_Baseline,108,59 +block_count,AddSmi_Baseline,0,219 +block_count,AddSmi_Baseline,1,218 +block_count,AddSmi_Baseline,2,218 block_count,AddSmi_Baseline,3,0 -block_count,AddSmi_Baseline,4,216 -block_count,AddSmi_Baseline,5,216 +block_count,AddSmi_Baseline,4,218 +block_count,AddSmi_Baseline,5,218 block_count,AddSmi_Baseline,6,0 block_count,AddSmi_Baseline,7,0 block_count,AddSmi_Baseline,8,0 @@ -30994,10 +31003,10 @@ block_count,AddSmi_Baseline,97,0 block_count,AddSmi_Baseline,98,0 block_count,AddSmi_Baseline,99,0 -block_count,Subtract_Baseline,0,63 -block_count,Subtract_Baseline,1,32 -block_count,Subtract_Baseline,2,2 -block_count,Subtract_Baseline,3,2 +block_count,Subtract_Baseline,0,61 +block_count,Subtract_Baseline,1,31 +block_count,Subtract_Baseline,2,1 +block_count,Subtract_Baseline,3,1 block_count,Subtract_Baseline,4,0 block_count,Subtract_Baseline,5,29 block_count,Subtract_Baseline,6,29 @@ -31009,10 +31018,10 @@ block_count,Subtract_Baseline,12,0 block_count,Subtract_Baseline,13,29 block_count,Subtract_Baseline,14,29 -block_count,Subtract_Baseline,15,31 -block_count,Subtract_Baseline,16,31 -block_count,Subtract_Baseline,17,30 -block_count,Subtract_Baseline,18,30 +block_count,Subtract_Baseline,15,29 +block_count,Subtract_Baseline,16,29 +block_count,Subtract_Baseline,17,28 +block_count,Subtract_Baseline,18,28 block_count,Subtract_Baseline,19,0 block_count,Subtract_Baseline,20,1 block_count,Subtract_Baseline,21,0 @@ -31085,13 +31094,13 @@ block_count,Subtract_Baseline,88,0 block_count,Subtract_Baseline,89,0 block_count,Subtract_Baseline,90,0 -block_count,Subtract_Baseline,91,33 +block_count,Subtract_Baseline,91,31 block_count,Subtract_Baseline,92,0 -block_count,Subtract_Baseline,93,33 -block_count,Subtract_Baseline,94,33 +block_count,Subtract_Baseline,93,31 +block_count,Subtract_Baseline,94,31 block_count,Subtract_Baseline,95,0 -block_count,Subtract_Baseline,96,33 -block_count,Subtract_Baseline,97,33 +block_count,Subtract_Baseline,96,31 +block_count,Subtract_Baseline,97,31 block_count,SubtractSmi_Baseline,0,20 block_count,SubtractSmi_Baseline,1,17 block_count,SubtractSmi_Baseline,2,17 @@ -31103,18 +31112,18 @@ block_count,SubtractSmi_Baseline,8,0 block_count,SubtractSmi_Baseline,9,17 block_count,SubtractSmi_Baseline,10,17 -block_count,SubtractSmi_Baseline,11,3 -block_count,SubtractSmi_Baseline,12,3 +block_count,SubtractSmi_Baseline,11,2 +block_count,SubtractSmi_Baseline,12,2 block_count,SubtractSmi_Baseline,13,0 -block_count,SubtractSmi_Baseline,14,3 -block_count,SubtractSmi_Baseline,15,3 +block_count,SubtractSmi_Baseline,14,2 +block_count,SubtractSmi_Baseline,15,2 block_count,SubtractSmi_Baseline,16,0 -block_count,SubtractSmi_Baseline,17,3 -block_count,SubtractSmi_Baseline,18,3 -block_count,Multiply_Baseline,0,85 -block_count,Multiply_Baseline,1,11 -block_count,Multiply_Baseline,2,6 -block_count,Multiply_Baseline,3,6 +block_count,SubtractSmi_Baseline,17,2 +block_count,SubtractSmi_Baseline,18,2 +block_count,Multiply_Baseline,0,92 +block_count,Multiply_Baseline,1,15 +block_count,Multiply_Baseline,2,10 +block_count,Multiply_Baseline,3,10 block_count,Multiply_Baseline,4,0 block_count,Multiply_Baseline,5,4 block_count,Multiply_Baseline,6,4 @@ -31139,10 +31148,10 @@ block_count,Multiply_Baseline,25,0 block_count,Multiply_Baseline,26,4 block_count,Multiply_Baseline,27,4 -block_count,Multiply_Baseline,28,74 -block_count,Multiply_Baseline,29,74 -block_count,Multiply_Baseline,30,69 -block_count,Multiply_Baseline,31,69 +block_count,Multiply_Baseline,28,76 +block_count,Multiply_Baseline,29,76 +block_count,Multiply_Baseline,30,72 +block_count,Multiply_Baseline,31,72 block_count,Multiply_Baseline,32,0 block_count,Multiply_Baseline,33,4 block_count,Multiply_Baseline,34,0 @@ -31217,13 +31226,13 @@ block_count,Multiply_Baseline,103,0 block_count,Multiply_Baseline,104,0 block_count,Multiply_Baseline,105,0 -block_count,Multiply_Baseline,106,80 +block_count,Multiply_Baseline,106,87 block_count,Multiply_Baseline,107,0 -block_count,Multiply_Baseline,108,80 -block_count,Multiply_Baseline,109,80 +block_count,Multiply_Baseline,108,87 +block_count,Multiply_Baseline,109,87 block_count,Multiply_Baseline,110,0 -block_count,Multiply_Baseline,111,80 -block_count,Multiply_Baseline,112,80 +block_count,Multiply_Baseline,111,87 +block_count,Multiply_Baseline,112,87 block_count,MultiplySmi_Baseline,0,5 block_count,MultiplySmi_Baseline,1,4 block_count,MultiplySmi_Baseline,2,4 @@ -31234,8 +31243,8 @@ block_count,MultiplySmi_Baseline,7,0 block_count,MultiplySmi_Baseline,8,0 block_count,MultiplySmi_Baseline,9,3 -block_count,MultiplySmi_Baseline,10,1 -block_count,MultiplySmi_Baseline,11,1 +block_count,MultiplySmi_Baseline,10,0 +block_count,MultiplySmi_Baseline,11,0 block_count,MultiplySmi_Baseline,12,0 block_count,MultiplySmi_Baseline,13,0 block_count,MultiplySmi_Baseline,14,0 @@ -31327,7 +31336,7 @@ block_count,MultiplySmi_Baseline,100,0 block_count,MultiplySmi_Baseline,101,0 block_count,MultiplySmi_Baseline,102,0 -block_count,Divide_Baseline,0,6 +block_count,Divide_Baseline,0,5 block_count,Divide_Baseline,1,2 block_count,Divide_Baseline,2,1 block_count,Divide_Baseline,3,1 @@ -31355,10 +31364,10 @@ block_count,Divide_Baseline,25,0 block_count,Divide_Baseline,26,1 block_count,Divide_Baseline,27,1 -block_count,Divide_Baseline,28,3 -block_count,Divide_Baseline,29,3 -block_count,Divide_Baseline,30,2 -block_count,Divide_Baseline,31,2 +block_count,Divide_Baseline,28,2 +block_count,Divide_Baseline,29,2 +block_count,Divide_Baseline,30,1 +block_count,Divide_Baseline,31,1 block_count,Divide_Baseline,32,0 block_count,Divide_Baseline,33,0 block_count,Divide_Baseline,34,0 @@ -31436,26 +31445,26 @@ block_count,Divide_Baseline,106,0 block_count,Divide_Baseline,107,0 block_count,Divide_Baseline,108,0 -block_count,Divide_Baseline,109,4 +block_count,Divide_Baseline,109,3 block_count,Divide_Baseline,110,0 -block_count,Divide_Baseline,111,4 -block_count,Divide_Baseline,112,4 +block_count,Divide_Baseline,111,3 +block_count,Divide_Baseline,112,3 block_count,Divide_Baseline,113,0 -block_count,Divide_Baseline,114,4 -block_count,Divide_Baseline,115,4 +block_count,Divide_Baseline,114,3 +block_count,Divide_Baseline,115,3 block_count,DivideSmi_Baseline,0,1 -block_count,DivideSmi_Baseline,1,1 -block_count,DivideSmi_Baseline,2,1 -block_count,DivideSmi_Baseline,3,1 +block_count,DivideSmi_Baseline,1,0 +block_count,DivideSmi_Baseline,2,0 +block_count,DivideSmi_Baseline,3,0 block_count,DivideSmi_Baseline,4,0 block_count,DivideSmi_Baseline,5,0 block_count,DivideSmi_Baseline,6,0 -block_count,DivideSmi_Baseline,7,1 -block_count,DivideSmi_Baseline,8,1 +block_count,DivideSmi_Baseline,7,0 +block_count,DivideSmi_Baseline,8,0 block_count,DivideSmi_Baseline,9,0 block_count,DivideSmi_Baseline,10,0 block_count,DivideSmi_Baseline,11,0 -block_count,DivideSmi_Baseline,12,1 +block_count,DivideSmi_Baseline,12,0 block_count,DivideSmi_Baseline,13,0 block_count,DivideSmi_Baseline,14,0 block_count,DivideSmi_Baseline,15,0 @@ -31463,10 +31472,10 @@ block_count,DivideSmi_Baseline,17,0 block_count,DivideSmi_Baseline,18,0 block_count,DivideSmi_Baseline,19,0 -block_count,DivideSmi_Baseline,20,1 +block_count,DivideSmi_Baseline,20,0 block_count,DivideSmi_Baseline,21,0 -block_count,DivideSmi_Baseline,22,1 -block_count,DivideSmi_Baseline,23,1 +block_count,DivideSmi_Baseline,22,0 +block_count,DivideSmi_Baseline,23,0 block_count,DivideSmi_Baseline,24,0 block_count,DivideSmi_Baseline,25,0 block_count,DivideSmi_Baseline,26,0 @@ -31871,7 +31880,7 @@ block_count,BitwiseAnd_Baseline,128,0 block_count,BitwiseAnd_Baseline,129,11 block_count,BitwiseAnd_Baseline,130,11 -block_count,BitwiseAndSmi_Baseline,0,28 +block_count,BitwiseAndSmi_Baseline,0,30 block_count,BitwiseAndSmi_Baseline,1,1 block_count,BitwiseAndSmi_Baseline,2,1 block_count,BitwiseAndSmi_Baseline,3,0 @@ -31902,10 +31911,10 @@ block_count,BitwiseAndSmi_Baseline,28,0 block_count,BitwiseAndSmi_Baseline,29,1 block_count,BitwiseAndSmi_Baseline,30,1 -block_count,BitwiseAndSmi_Baseline,31,27 -block_count,BitwiseAndSmi_Baseline,32,28 +block_count,BitwiseAndSmi_Baseline,31,29 +block_count,BitwiseAndSmi_Baseline,32,30 block_count,BitwiseAndSmi_Baseline,33,0 -block_count,BitwiseAndSmi_Baseline,34,28 +block_count,BitwiseAndSmi_Baseline,34,30 block_count,BitwiseOr_Baseline,0,22 block_count,BitwiseOr_Baseline,1,19 block_count,BitwiseOr_Baseline,2,2 @@ -32440,7 +32449,7 @@ block_count,ShiftRight_Baseline,76,0 block_count,ShiftRight_Baseline,77,1 block_count,ShiftRight_Baseline,78,1 -block_count,ShiftRightSmi_Baseline,0,102 +block_count,ShiftRightSmi_Baseline,0,103 block_count,ShiftRightSmi_Baseline,1,1 block_count,ShiftRightSmi_Baseline,2,1 block_count,ShiftRightSmi_Baseline,3,0 @@ -32471,10 +32480,10 @@ block_count,ShiftRightSmi_Baseline,28,0 block_count,ShiftRightSmi_Baseline,29,1 block_count,ShiftRightSmi_Baseline,30,1 -block_count,ShiftRightSmi_Baseline,31,100 -block_count,ShiftRightSmi_Baseline,32,102 +block_count,ShiftRightSmi_Baseline,31,102 +block_count,ShiftRightSmi_Baseline,32,103 block_count,ShiftRightSmi_Baseline,33,0 -block_count,ShiftRightSmi_Baseline,34,102 +block_count,ShiftRightSmi_Baseline,34,103 block_count,ShiftRightLogical_Baseline,0,0 block_count,ShiftRightLogical_Baseline,1,0 block_count,ShiftRightLogical_Baseline,2,0 @@ -32595,7 +32604,7 @@ block_count,ShiftRightLogicalSmi_Baseline,41,3 block_count,ShiftRightLogicalSmi_Baseline,42,0 block_count,ShiftRightLogicalSmi_Baseline,43,3 -block_count,Add_WithFeedback,0,38 +block_count,Add_WithFeedback,0,39 block_count,Add_WithFeedback,1,1 block_count,Add_WithFeedback,2,1 block_count,Add_WithFeedback,3,0 @@ -32606,14 +32615,14 @@ block_count,Add_WithFeedback,8,0 block_count,Add_WithFeedback,9,0 block_count,Add_WithFeedback,10,0 -block_count,Add_WithFeedback,11,37 +block_count,Add_WithFeedback,11,38 block_count,Add_WithFeedback,12,0 block_count,Add_WithFeedback,13,0 block_count,Add_WithFeedback,14,0 block_count,Add_WithFeedback,15,0 block_count,Add_WithFeedback,16,0 -block_count,Add_WithFeedback,17,37 -block_count,Add_WithFeedback,18,37 +block_count,Add_WithFeedback,17,38 +block_count,Add_WithFeedback,18,38 block_count,Add_WithFeedback,19,28 block_count,Add_WithFeedback,20,0 block_count,Add_WithFeedback,21,0 @@ -33135,8 +33144,8 @@ block_count,BitwiseOr_WithFeedback,129,0 block_count,BitwiseOr_WithFeedback,130,0 block_count,Equal_Baseline,0,153 -block_count,Equal_Baseline,1,155 -block_count,Equal_Baseline,2,124 +block_count,Equal_Baseline,1,154 +block_count,Equal_Baseline,2,123 block_count,Equal_Baseline,3,25 block_count,Equal_Baseline,4,24 block_count,Equal_Baseline,5,10 @@ -33231,7 +33240,7 @@ block_count,Equal_Baseline,94,0 block_count,Equal_Baseline,95,0 block_count,Equal_Baseline,96,0 -block_count,Equal_Baseline,97,14 +block_count,Equal_Baseline,97,13 block_count,Equal_Baseline,98,0 block_count,Equal_Baseline,99,13 block_count,Equal_Baseline,100,9 @@ -33248,8 +33257,8 @@ block_count,Equal_Baseline,111,13 block_count,Equal_Baseline,112,1 block_count,Equal_Baseline,113,1 -block_count,Equal_Baseline,114,99 -block_count,Equal_Baseline,115,2 +block_count,Equal_Baseline,114,97 +block_count,Equal_Baseline,115,1 block_count,Equal_Baseline,116,0 block_count,Equal_Baseline,117,0 block_count,Equal_Baseline,118,0 @@ -33268,7 +33277,7 @@ block_count,Equal_Baseline,131,0 block_count,Equal_Baseline,132,0 block_count,Equal_Baseline,133,1 -block_count,Equal_Baseline,134,97 +block_count,Equal_Baseline,134,96 block_count,Equal_Baseline,135,0 block_count,Equal_Baseline,136,0 block_count,Equal_Baseline,137,0 @@ -33284,11 +33293,11 @@ block_count,Equal_Baseline,147,2 block_count,Equal_Baseline,148,1 block_count,Equal_Baseline,149,0 -block_count,Equal_Baseline,150,30 -block_count,Equal_Baseline,151,6 -block_count,Equal_Baseline,152,6 -block_count,Equal_Baseline,153,4 -block_count,Equal_Baseline,154,1 +block_count,Equal_Baseline,150,31 +block_count,Equal_Baseline,151,7 +block_count,Equal_Baseline,152,7 +block_count,Equal_Baseline,153,5 +block_count,Equal_Baseline,154,2 block_count,Equal_Baseline,155,0 block_count,Equal_Baseline,156,0 block_count,Equal_Baseline,157,0 @@ -33300,9 +33309,9 @@ block_count,Equal_Baseline,163,0 block_count,Equal_Baseline,164,0 block_count,Equal_Baseline,165,0 -block_count,Equal_Baseline,166,1 +block_count,Equal_Baseline,166,2 block_count,Equal_Baseline,167,0 -block_count,Equal_Baseline,168,1 +block_count,Equal_Baseline,168,2 block_count,Equal_Baseline,169,2 block_count,Equal_Baseline,170,2 block_count,Equal_Baseline,171,0 @@ -33311,32 +33320,32 @@ block_count,Equal_Baseline,174,0 block_count,Equal_Baseline,175,0 block_count,Equal_Baseline,176,0 -block_count,Equal_Baseline,177,23 -block_count,Equal_Baseline,178,30 -block_count,Equal_Baseline,179,108 +block_count,Equal_Baseline,177,24 +block_count,Equal_Baseline,178,31 +block_count,Equal_Baseline,179,107 block_count,Equal_Baseline,180,153 block_count,Equal_Baseline,181,0 block_count,Equal_Baseline,182,153 -block_count,StrictEqual_Baseline,0,214 -block_count,StrictEqual_Baseline,1,181 +block_count,StrictEqual_Baseline,0,213 +block_count,StrictEqual_Baseline,1,180 block_count,StrictEqual_Baseline,2,128 block_count,StrictEqual_Baseline,3,128 block_count,StrictEqual_Baseline,4,128 block_count,StrictEqual_Baseline,5,59 block_count,StrictEqual_Baseline,6,59 -block_count,StrictEqual_Baseline,7,24 -block_count,StrictEqual_Baseline,8,23 -block_count,StrictEqual_Baseline,9,18 +block_count,StrictEqual_Baseline,7,23 +block_count,StrictEqual_Baseline,8,22 +block_count,StrictEqual_Baseline,9,17 block_count,StrictEqual_Baseline,10,0 -block_count,StrictEqual_Baseline,11,18 +block_count,StrictEqual_Baseline,11,17 block_count,StrictEqual_Baseline,12,0 -block_count,StrictEqual_Baseline,13,18 +block_count,StrictEqual_Baseline,13,17 block_count,StrictEqual_Baseline,14,5 block_count,StrictEqual_Baseline,15,2 block_count,StrictEqual_Baseline,16,3 block_count,StrictEqual_Baseline,17,1 -block_count,StrictEqual_Baseline,18,34 -block_count,StrictEqual_Baseline,19,34 +block_count,StrictEqual_Baseline,18,35 +block_count,StrictEqual_Baseline,19,35 block_count,StrictEqual_Baseline,20,0 block_count,StrictEqual_Baseline,21,0 block_count,StrictEqual_Baseline,22,0 @@ -33372,16 +33381,16 @@ block_count,StrictEqual_Baseline,52,0 block_count,StrictEqual_Baseline,53,0 block_count,StrictEqual_Baseline,54,0 -block_count,StrictEqual_Baseline,55,68 +block_count,StrictEqual_Baseline,55,69 block_count,StrictEqual_Baseline,56,0 block_count,StrictEqual_Baseline,57,68 block_count,StrictEqual_Baseline,58,16 -block_count,StrictEqual_Baseline,59,51 +block_count,StrictEqual_Baseline,59,52 block_count,StrictEqual_Baseline,60,68 block_count,StrictEqual_Baseline,61,0 -block_count,StrictEqual_Baseline,62,67 +block_count,StrictEqual_Baseline,62,68 block_count,StrictEqual_Baseline,63,68 -block_count,StrictEqual_Baseline,64,45 +block_count,StrictEqual_Baseline,64,46 block_count,StrictEqual_Baseline,65,22 block_count,StrictEqual_Baseline,66,0 block_count,StrictEqual_Baseline,67,0 @@ -33399,7 +33408,7 @@ block_count,StrictEqual_Baseline,79,0 block_count,StrictEqual_Baseline,80,0 block_count,StrictEqual_Baseline,81,0 -block_count,StrictEqual_Baseline,82,52 +block_count,StrictEqual_Baseline,82,51 block_count,StrictEqual_Baseline,83,5 block_count,StrictEqual_Baseline,84,33 block_count,StrictEqual_Baseline,85,17 @@ -33429,14 +33438,14 @@ block_count,StrictEqual_Baseline,109,0 block_count,StrictEqual_Baseline,110,0 block_count,StrictEqual_Baseline,111,15 -block_count,StrictEqual_Baseline,112,113 +block_count,StrictEqual_Baseline,112,111 block_count,StrictEqual_Baseline,113,33 -block_count,StrictEqual_Baseline,114,214 +block_count,StrictEqual_Baseline,114,213 block_count,StrictEqual_Baseline,115,0 -block_count,StrictEqual_Baseline,116,214 -block_count,LessThan_Baseline,0,145 -block_count,LessThan_Baseline,1,145 -block_count,LessThan_Baseline,2,10 +block_count,StrictEqual_Baseline,116,213 +block_count,LessThan_Baseline,0,146 +block_count,LessThan_Baseline,1,146 +block_count,LessThan_Baseline,2,9 block_count,LessThan_Baseline,3,3 block_count,LessThan_Baseline,4,0 block_count,LessThan_Baseline,5,0 @@ -33540,7 +33549,7 @@ block_count,LessThan_Baseline,103,0 block_count,LessThan_Baseline,104,0 block_count,LessThan_Baseline,105,2 -block_count,LessThan_Baseline,106,7 +block_count,LessThan_Baseline,106,6 block_count,LessThan_Baseline,107,0 block_count,LessThan_Baseline,108,0 block_count,LessThan_Baseline,109,0 @@ -33551,7 +33560,7 @@ block_count,LessThan_Baseline,114,0 block_count,LessThan_Baseline,115,0 block_count,LessThan_Baseline,116,6 -block_count,LessThan_Baseline,117,135 +block_count,LessThan_Baseline,117,137 block_count,LessThan_Baseline,118,0 block_count,LessThan_Baseline,119,0 block_count,LessThan_Baseline,120,0 @@ -33563,9 +33572,9 @@ block_count,LessThan_Baseline,126,0 block_count,LessThan_Baseline,127,0 block_count,LessThan_Baseline,128,0 -block_count,LessThan_Baseline,129,134 -block_count,LessThan_Baseline,130,41 -block_count,LessThan_Baseline,131,92 +block_count,LessThan_Baseline,129,136 +block_count,LessThan_Baseline,130,42 +block_count,LessThan_Baseline,131,93 block_count,LessThan_Baseline,132,0 block_count,LessThan_Baseline,133,0 block_count,LessThan_Baseline,134,0 @@ -33575,12 +33584,12 @@ block_count,LessThan_Baseline,138,7 block_count,LessThan_Baseline,139,2 block_count,LessThan_Baseline,140,49 -block_count,LessThan_Baseline,141,95 -block_count,LessThan_Baseline,142,145 +block_count,LessThan_Baseline,141,96 +block_count,LessThan_Baseline,142,146 block_count,LessThan_Baseline,143,0 -block_count,LessThan_Baseline,144,145 +block_count,LessThan_Baseline,144,146 block_count,GreaterThan_Baseline,0,43 -block_count,GreaterThan_Baseline,1,44 +block_count,GreaterThan_Baseline,1,43 block_count,GreaterThan_Baseline,2,3 block_count,GreaterThan_Baseline,3,1 block_count,GreaterThan_Baseline,4,0 @@ -33696,7 +33705,7 @@ block_count,GreaterThan_Baseline,114,0 block_count,GreaterThan_Baseline,115,0 block_count,GreaterThan_Baseline,116,1 -block_count,GreaterThan_Baseline,117,40 +block_count,GreaterThan_Baseline,117,39 block_count,GreaterThan_Baseline,118,0 block_count,GreaterThan_Baseline,119,0 block_count,GreaterThan_Baseline,120,0 @@ -33708,8 +33717,8 @@ block_count,GreaterThan_Baseline,126,0 block_count,GreaterThan_Baseline,127,0 block_count,GreaterThan_Baseline,128,0 -block_count,GreaterThan_Baseline,129,40 -block_count,GreaterThan_Baseline,130,23 +block_count,GreaterThan_Baseline,129,39 +block_count,GreaterThan_Baseline,130,22 block_count,GreaterThan_Baseline,131,16 block_count,GreaterThan_Baseline,132,0 block_count,GreaterThan_Baseline,133,0 @@ -33719,14 +33728,14 @@ block_count,GreaterThan_Baseline,137,3 block_count,GreaterThan_Baseline,138,2 block_count,GreaterThan_Baseline,139,1 -block_count,GreaterThan_Baseline,140,25 +block_count,GreaterThan_Baseline,140,24 block_count,GreaterThan_Baseline,141,18 block_count,GreaterThan_Baseline,142,43 block_count,GreaterThan_Baseline,143,0 block_count,GreaterThan_Baseline,144,43 block_count,LessThanOrEqual_Baseline,0,20 block_count,LessThanOrEqual_Baseline,1,20 -block_count,LessThanOrEqual_Baseline,2,3 +block_count,LessThanOrEqual_Baseline,2,2 block_count,LessThanOrEqual_Baseline,3,1 block_count,LessThanOrEqual_Baseline,4,0 block_count,LessThanOrEqual_Baseline,5,0 @@ -33819,7 +33828,7 @@ block_count,LessThanOrEqual_Baseline,92,0 block_count,LessThanOrEqual_Baseline,93,0 block_count,LessThanOrEqual_Baseline,94,0 -block_count,LessThanOrEqual_Baseline,95,1 +block_count,LessThanOrEqual_Baseline,95,0 block_count,LessThanOrEqual_Baseline,96,0 block_count,LessThanOrEqual_Baseline,97,0 block_count,LessThanOrEqual_Baseline,98,0 @@ -33829,7 +33838,7 @@ block_count,LessThanOrEqual_Baseline,102,0 block_count,LessThanOrEqual_Baseline,103,0 block_count,LessThanOrEqual_Baseline,104,0 -block_count,LessThanOrEqual_Baseline,105,1 +block_count,LessThanOrEqual_Baseline,105,0 block_count,LessThanOrEqual_Baseline,106,1 block_count,LessThanOrEqual_Baseline,107,0 block_count,LessThanOrEqual_Baseline,108,0 @@ -33841,7 +33850,7 @@ block_count,LessThanOrEqual_Baseline,114,0 block_count,LessThanOrEqual_Baseline,115,0 block_count,LessThanOrEqual_Baseline,116,1 -block_count,LessThanOrEqual_Baseline,117,17 +block_count,LessThanOrEqual_Baseline,117,18 block_count,LessThanOrEqual_Baseline,118,0 block_count,LessThanOrEqual_Baseline,119,0 block_count,LessThanOrEqual_Baseline,120,0 @@ -33853,26 +33862,26 @@ block_count,LessThanOrEqual_Baseline,126,0 block_count,LessThanOrEqual_Baseline,127,0 block_count,LessThanOrEqual_Baseline,128,0 -block_count,LessThanOrEqual_Baseline,129,16 +block_count,LessThanOrEqual_Baseline,129,17 block_count,LessThanOrEqual_Baseline,130,1 -block_count,LessThanOrEqual_Baseline,131,14 +block_count,LessThanOrEqual_Baseline,131,15 block_count,LessThanOrEqual_Baseline,132,0 block_count,LessThanOrEqual_Baseline,133,0 block_count,LessThanOrEqual_Baseline,134,0 block_count,LessThanOrEqual_Baseline,135,0 block_count,LessThanOrEqual_Baseline,136,0 -block_count,LessThanOrEqual_Baseline,137,3 -block_count,LessThanOrEqual_Baseline,138,1 -block_count,LessThanOrEqual_Baseline,139,2 -block_count,LessThanOrEqual_Baseline,140,3 +block_count,LessThanOrEqual_Baseline,137,2 +block_count,LessThanOrEqual_Baseline,138,0 +block_count,LessThanOrEqual_Baseline,139,1 +block_count,LessThanOrEqual_Baseline,140,2 block_count,LessThanOrEqual_Baseline,141,17 block_count,LessThanOrEqual_Baseline,142,20 block_count,LessThanOrEqual_Baseline,143,0 block_count,LessThanOrEqual_Baseline,144,20 -block_count,GreaterThanOrEqual_Baseline,0,43 -block_count,GreaterThanOrEqual_Baseline,1,43 -block_count,GreaterThanOrEqual_Baseline,2,5 -block_count,GreaterThanOrEqual_Baseline,3,3 +block_count,GreaterThanOrEqual_Baseline,0,42 +block_count,GreaterThanOrEqual_Baseline,1,42 +block_count,GreaterThanOrEqual_Baseline,2,4 +block_count,GreaterThanOrEqual_Baseline,3,2 block_count,GreaterThanOrEqual_Baseline,4,0 block_count,GreaterThanOrEqual_Baseline,5,0 block_count,GreaterThanOrEqual_Baseline,6,0 @@ -33964,7 +33973,7 @@ block_count,GreaterThanOrEqual_Baseline,92,0 block_count,GreaterThanOrEqual_Baseline,93,0 block_count,GreaterThanOrEqual_Baseline,94,0 -block_count,GreaterThanOrEqual_Baseline,95,3 +block_count,GreaterThanOrEqual_Baseline,95,2 block_count,GreaterThanOrEqual_Baseline,96,0 block_count,GreaterThanOrEqual_Baseline,97,0 block_count,GreaterThanOrEqual_Baseline,98,0 @@ -33974,7 +33983,7 @@ block_count,GreaterThanOrEqual_Baseline,102,0 block_count,GreaterThanOrEqual_Baseline,103,0 block_count,GreaterThanOrEqual_Baseline,104,0 -block_count,GreaterThanOrEqual_Baseline,105,3 +block_count,GreaterThanOrEqual_Baseline,105,2 block_count,GreaterThanOrEqual_Baseline,106,1 block_count,GreaterThanOrEqual_Baseline,107,0 block_count,GreaterThanOrEqual_Baseline,108,0 @@ -33986,7 +33995,7 @@ block_count,GreaterThanOrEqual_Baseline,114,0 block_count,GreaterThanOrEqual_Baseline,115,0 block_count,GreaterThanOrEqual_Baseline,116,1 -block_count,GreaterThanOrEqual_Baseline,117,38 +block_count,GreaterThanOrEqual_Baseline,117,37 block_count,GreaterThanOrEqual_Baseline,118,0 block_count,GreaterThanOrEqual_Baseline,119,0 block_count,GreaterThanOrEqual_Baseline,120,0 @@ -33998,7 +34007,7 @@ block_count,GreaterThanOrEqual_Baseline,126,0 block_count,GreaterThanOrEqual_Baseline,127,0 block_count,GreaterThanOrEqual_Baseline,128,0 -block_count,GreaterThanOrEqual_Baseline,129,38 +block_count,GreaterThanOrEqual_Baseline,129,37 block_count,GreaterThanOrEqual_Baseline,130,23 block_count,GreaterThanOrEqual_Baseline,131,14 block_count,GreaterThanOrEqual_Baseline,132,0 @@ -34006,14 +34015,14 @@ block_count,GreaterThanOrEqual_Baseline,134,0 block_count,GreaterThanOrEqual_Baseline,135,0 block_count,GreaterThanOrEqual_Baseline,136,0 -block_count,GreaterThanOrEqual_Baseline,137,5 -block_count,GreaterThanOrEqual_Baseline,138,2 +block_count,GreaterThanOrEqual_Baseline,137,4 +block_count,GreaterThanOrEqual_Baseline,138,1 block_count,GreaterThanOrEqual_Baseline,139,2 -block_count,GreaterThanOrEqual_Baseline,140,25 +block_count,GreaterThanOrEqual_Baseline,140,24 block_count,GreaterThanOrEqual_Baseline,141,17 -block_count,GreaterThanOrEqual_Baseline,142,43 +block_count,GreaterThanOrEqual_Baseline,142,42 block_count,GreaterThanOrEqual_Baseline,143,0 -block_count,GreaterThanOrEqual_Baseline,144,43 +block_count,GreaterThanOrEqual_Baseline,144,42 block_count,Equal_WithFeedback,0,9 block_count,Equal_WithFeedback,1,12 block_count,Equal_WithFeedback,2,8 @@ -34197,7 +34206,7 @@ block_count,Equal_WithFeedback,180,9 block_count,Equal_WithFeedback,181,0 block_count,Equal_WithFeedback,182,9 -block_count,StrictEqual_WithFeedback,0,103 +block_count,StrictEqual_WithFeedback,0,104 block_count,StrictEqual_WithFeedback,1,91 block_count,StrictEqual_WithFeedback,2,83 block_count,StrictEqual_WithFeedback,3,83 @@ -34206,11 +34215,11 @@ block_count,StrictEqual_WithFeedback,6,17 block_count,StrictEqual_WithFeedback,7,14 block_count,StrictEqual_WithFeedback,8,13 -block_count,StrictEqual_WithFeedback,9,1 +block_count,StrictEqual_WithFeedback,9,0 block_count,StrictEqual_WithFeedback,10,0 -block_count,StrictEqual_WithFeedback,11,1 +block_count,StrictEqual_WithFeedback,11,0 block_count,StrictEqual_WithFeedback,12,0 -block_count,StrictEqual_WithFeedback,13,1 +block_count,StrictEqual_WithFeedback,13,0 block_count,StrictEqual_WithFeedback,14,12 block_count,StrictEqual_WithFeedback,15,6 block_count,StrictEqual_WithFeedback,16,6 @@ -34279,9 +34288,9 @@ block_count,StrictEqual_WithFeedback,79,0 block_count,StrictEqual_WithFeedback,80,0 block_count,StrictEqual_WithFeedback,81,0 -block_count,StrictEqual_WithFeedback,82,6 +block_count,StrictEqual_WithFeedback,82,7 block_count,StrictEqual_WithFeedback,83,8 -block_count,StrictEqual_WithFeedback,84,12 +block_count,StrictEqual_WithFeedback,84,13 block_count,StrictEqual_WithFeedback,85,11 block_count,StrictEqual_WithFeedback,86,11 block_count,StrictEqual_WithFeedback,87,4 @@ -34310,10 +34319,10 @@ block_count,StrictEqual_WithFeedback,110,0 block_count,StrictEqual_WithFeedback,111,1 block_count,StrictEqual_WithFeedback,112,26 -block_count,StrictEqual_WithFeedback,113,12 -block_count,StrictEqual_WithFeedback,114,103 +block_count,StrictEqual_WithFeedback,113,13 +block_count,StrictEqual_WithFeedback,114,104 block_count,StrictEqual_WithFeedback,115,0 -block_count,StrictEqual_WithFeedback,116,103 +block_count,StrictEqual_WithFeedback,116,104 block_count,LessThan_WithFeedback,0,2 block_count,LessThan_WithFeedback,1,3 block_count,LessThan_WithFeedback,2,1 @@ -34409,7 +34418,7 @@ block_count,LessThan_WithFeedback,92,0 block_count,LessThan_WithFeedback,93,0 block_count,LessThan_WithFeedback,94,0 -block_count,LessThan_WithFeedback,95,1 +block_count,LessThan_WithFeedback,95,0 block_count,LessThan_WithFeedback,96,0 block_count,LessThan_WithFeedback,97,0 block_count,LessThan_WithFeedback,98,0 @@ -34810,8 +34819,8 @@ block_count,Decrement_Baseline,23,15 block_count,Decrement_Baseline,24,0 block_count,Decrement_Baseline,25,15 -block_count,Increment_Baseline,0,100 -block_count,Increment_Baseline,1,100 +block_count,Increment_Baseline,0,101 +block_count,Increment_Baseline,1,101 block_count,Increment_Baseline,2,0 block_count,Increment_Baseline,3,0 block_count,Increment_Baseline,4,0 @@ -34826,16 +34835,16 @@ block_count,Increment_Baseline,13,0 block_count,Increment_Baseline,14,0 block_count,Increment_Baseline,15,0 -block_count,Increment_Baseline,16,100 -block_count,Increment_Baseline,17,100 +block_count,Increment_Baseline,16,101 +block_count,Increment_Baseline,17,101 block_count,Increment_Baseline,18,0 block_count,Increment_Baseline,19,0 block_count,Increment_Baseline,20,0 block_count,Increment_Baseline,21,0 block_count,Increment_Baseline,22,0 -block_count,Increment_Baseline,23,100 +block_count,Increment_Baseline,23,101 block_count,Increment_Baseline,24,0 -block_count,Increment_Baseline,25,100 +block_count,Increment_Baseline,25,101 block_count,Negate_Baseline,0,6 block_count,Negate_Baseline,1,6 block_count,Negate_Baseline,2,5 @@ -35805,13 +35814,13 @@ block_count,ObjectPrototypeHasOwnProperty,32,0 block_count,ObjectPrototypeHasOwnProperty,33,0 block_count,ObjectPrototypeHasOwnProperty,34,0 -block_count,ObjectPrototypeHasOwnProperty,35,2 +block_count,ObjectPrototypeHasOwnProperty,35,3 block_count,ObjectPrototypeHasOwnProperty,36,2 block_count,ObjectPrototypeHasOwnProperty,37,0 block_count,ObjectPrototypeHasOwnProperty,38,41 block_count,ObjectPrototypeHasOwnProperty,39,0 -block_count,ObjectPrototypeHasOwnProperty,40,169 -block_count,ObjectPrototypeHasOwnProperty,41,169 +block_count,ObjectPrototypeHasOwnProperty,40,170 +block_count,ObjectPrototypeHasOwnProperty,41,170 block_count,ObjectPrototypeHasOwnProperty,42,133 block_count,ObjectPrototypeHasOwnProperty,43,129 block_count,ObjectPrototypeHasOwnProperty,44,0 @@ -36034,7 +36043,7 @@ block_count,ObjectToString,84,0 block_count,ObjectToString,85,151 block_count,ObjectToString,86,55 -block_count,OrdinaryHasInstance,0,90 +block_count,OrdinaryHasInstance,0,91 block_count,OrdinaryHasInstance,1,90 block_count,OrdinaryHasInstance,2,90 block_count,OrdinaryHasInstance,3,0 @@ -36050,16 +36059,16 @@ block_count,OrdinaryHasInstance,13,0 block_count,OrdinaryHasInstance,14,87 block_count,OrdinaryHasInstance,15,90 -block_count,OrdinaryHasInstance,16,269 -block_count,OrdinaryHasInstance,17,231 +block_count,OrdinaryHasInstance,16,270 +block_count,OrdinaryHasInstance,17,232 block_count,OrdinaryHasInstance,18,38 block_count,OrdinaryHasInstance,19,38 block_count,OrdinaryHasInstance,20,38 block_count,OrdinaryHasInstance,21,0 block_count,OrdinaryHasInstance,22,0 block_count,OrdinaryHasInstance,23,0 -block_count,OrdinaryHasInstance,24,269 -block_count,OrdinaryHasInstance,25,194 +block_count,OrdinaryHasInstance,24,270 +block_count,OrdinaryHasInstance,25,195 block_count,OrdinaryHasInstance,26,179 block_count,OrdinaryHasInstance,27,15 block_count,OrdinaryHasInstance,28,74 @@ -37402,7 +37411,7 @@ block_count,SetPrototypeAdd,28,62 block_count,SetPrototypeAdd,29,62 block_count,SetPrototypeAdd,30,88 -block_count,SetPrototypeAdd,31,28 +block_count,SetPrototypeAdd,31,27 block_count,SetPrototypeAdd,32,26 block_count,SetPrototypeAdd,33,1 block_count,SetPrototypeAdd,34,60 @@ -37800,8 +37809,8 @@ block_count,StringFromCharCode,71,0 block_count,StringFromCharCode,72,0 block_count,StringFromCharCode,73,0 -block_count,StringFromCharCode,74,7 -block_count,StringFromCharCode,75,5 +block_count,StringFromCharCode,74,6 +block_count,StringFromCharCode,75,4 block_count,StringFromCharCode,76,2 block_count,StringFromCharCode,77,2 block_count,StringFromCharCode,78,2 @@ -37811,7 +37820,7 @@ block_count,StringFromCharCode,82,0 block_count,StringFromCharCode,83,2 block_count,StringFromCharCode,84,0 -block_count,StringFromCharCode,85,7 +block_count,StringFromCharCode,85,6 block_count,StringFromCharCode,86,0 block_count,StringFromCharCode,87,0 block_count,StringFromCharCode,88,0 @@ -38915,9 +38924,9 @@ block_count,WeakMapLookupHashIndex,27,64 block_count,WeakMapLookupHashIndex,28,1 block_count,WeakMapLookupHashIndex,29,64 -block_count,WeakMapLookupHashIndex,30,94 -block_count,WeakMapLookupHashIndex,31,94 -block_count,WeakMapLookupHashIndex,32,29 +block_count,WeakMapLookupHashIndex,30,91 +block_count,WeakMapLookupHashIndex,31,91 +block_count,WeakMapLookupHashIndex,32,27 block_count,WeakMapLookupHashIndex,33,64 block_count,WeakMapLookupHashIndex,34,0 block_count,WeakMapGet,0,33 @@ -39451,7 +39460,7 @@ block_count,StringAdd_CheckNone,2,9578 block_count,StringAdd_CheckNone,3,9578 block_count,StringAdd_CheckNone,4,7385 -block_count,StringAdd_CheckNone,5,7381 +block_count,StringAdd_CheckNone,5,7382 block_count,StringAdd_CheckNone,6,3 block_count,StringAdd_CheckNone,7,7385 block_count,StringAdd_CheckNone,8,7385 @@ -39461,7 +39470,7 @@ block_count,StringAdd_CheckNone,12,7383 block_count,StringAdd_CheckNone,13,7385 block_count,StringAdd_CheckNone,14,0 -block_count,StringAdd_CheckNone,15,7384 +block_count,StringAdd_CheckNone,15,7385 block_count,StringAdd_CheckNone,16,7385 block_count,StringAdd_CheckNone,17,2192 block_count,StringAdd_CheckNone,18,2193 @@ -39512,7 +39521,7 @@ block_count,StringAdd_CheckNone,63,1451 block_count,StringAdd_CheckNone,64,2183 block_count,StringAdd_CheckNone,65,597 -block_count,StringAdd_CheckNone,66,1586 +block_count,StringAdd_CheckNone,66,1585 block_count,StringAdd_CheckNone,67,2183 block_count,StringAdd_CheckNone,68,0 block_count,StringAdd_CheckNone,69,2183 @@ -39875,8 +39884,8 @@ block_count,GetProperty,64,1285 block_count,GetProperty,65,284 block_count,GetProperty,66,1001 -block_count,GetProperty,67,2520 -block_count,GetProperty,68,2227 +block_count,GetProperty,67,2521 +block_count,GetProperty,68,2228 block_count,GetProperty,69,2121 block_count,GetProperty,70,1519 block_count,GetProperty,71,601 @@ -42418,7 +42427,7 @@ block_count,FindNonDefaultConstructorOrConstruct,7,8 block_count,FindNonDefaultConstructorOrConstruct,8,5 block_count,FindNonDefaultConstructorOrConstruct,9,1 -block_count,FindNonDefaultConstructorOrConstruct,10,4 +block_count,FindNonDefaultConstructorOrConstruct,10,3 block_count,FindNonDefaultConstructorOrConstruct,11,2 block_count,OrdinaryGetOwnPropertyDescriptor,0,0 block_count,OrdinaryGetOwnPropertyDescriptor,1,0 @@ -43538,10 +43547,10 @@ block_count,ArrayFrom,204,0 block_count,ArrayFrom,205,0 block_count,ArrayFrom,206,0 -block_count,ArrayIsArray,0,7 +block_count,ArrayIsArray,0,6 block_count,ArrayIsArray,1,0 -block_count,ArrayIsArray,2,7 -block_count,ArrayIsArray,3,7 +block_count,ArrayIsArray,2,6 +block_count,ArrayIsArray,3,6 block_count,ArrayIsArray,4,6 block_count,ArrayIsArray,5,3 block_count,ArrayIsArray,6,3 @@ -45068,19 +45077,19 @@ block_count,ArrayMapLoopContinuation,327,0 block_count,ArrayMapLoopContinuation,328,0 block_count,ArrayMapLoopContinuation,329,0 -block_count,ArrayMap,0,24 +block_count,ArrayMap,0,23 block_count,ArrayMap,1,0 -block_count,ArrayMap,2,24 -block_count,ArrayMap,3,24 -block_count,ArrayMap,4,24 -block_count,ArrayMap,5,24 +block_count,ArrayMap,2,23 +block_count,ArrayMap,3,23 +block_count,ArrayMap,4,23 +block_count,ArrayMap,5,23 block_count,ArrayMap,6,0 -block_count,ArrayMap,7,24 +block_count,ArrayMap,7,23 block_count,ArrayMap,8,0 block_count,ArrayMap,9,0 -block_count,ArrayMap,10,24 -block_count,ArrayMap,11,24 -block_count,ArrayMap,12,24 +block_count,ArrayMap,10,23 +block_count,ArrayMap,11,23 +block_count,ArrayMap,12,23 block_count,ArrayMap,13,0 block_count,ArrayMap,14,0 block_count,ArrayMap,15,0 @@ -45108,65 +45117,65 @@ block_count,ArrayMap,37,0 block_count,ArrayMap,38,0 block_count,ArrayMap,39,0 -block_count,ArrayMap,40,24 -block_count,ArrayMap,41,24 -block_count,ArrayMap,42,24 +block_count,ArrayMap,40,23 +block_count,ArrayMap,41,23 +block_count,ArrayMap,42,23 block_count,ArrayMap,43,0 -block_count,ArrayMap,44,24 +block_count,ArrayMap,44,23 block_count,ArrayMap,45,0 -block_count,ArrayMap,46,24 -block_count,ArrayMap,47,24 -block_count,ArrayMap,48,24 -block_count,ArrayMap,49,24 -block_count,ArrayMap,50,24 -block_count,ArrayMap,51,24 +block_count,ArrayMap,46,23 +block_count,ArrayMap,47,23 +block_count,ArrayMap,48,23 +block_count,ArrayMap,49,23 +block_count,ArrayMap,50,23 +block_count,ArrayMap,51,23 block_count,ArrayMap,52,0 -block_count,ArrayMap,53,24 -block_count,ArrayMap,54,24 -block_count,ArrayMap,55,24 -block_count,ArrayMap,56,24 -block_count,ArrayMap,57,8 -block_count,ArrayMap,58,16 -block_count,ArrayMap,59,16 -block_count,ArrayMap,60,16 +block_count,ArrayMap,53,23 +block_count,ArrayMap,54,23 +block_count,ArrayMap,55,23 +block_count,ArrayMap,56,23 +block_count,ArrayMap,57,7 +block_count,ArrayMap,58,15 +block_count,ArrayMap,59,15 +block_count,ArrayMap,60,15 block_count,ArrayMap,61,0 -block_count,ArrayMap,62,16 +block_count,ArrayMap,62,15 block_count,ArrayMap,63,0 block_count,ArrayMap,64,0 -block_count,ArrayMap,65,16 +block_count,ArrayMap,65,15 block_count,ArrayMap,66,0 -block_count,ArrayMap,67,16 +block_count,ArrayMap,67,15 block_count,ArrayMap,68,13 block_count,ArrayMap,69,2 block_count,ArrayMap,70,10 block_count,ArrayMap,71,8 block_count,ArrayMap,72,2 -block_count,ArrayMap,73,16 +block_count,ArrayMap,73,15 block_count,ArrayMap,74,2 block_count,ArrayMap,75,13 -block_count,ArrayMap,76,16 +block_count,ArrayMap,76,15 block_count,ArrayMap,77,0 -block_count,ArrayMap,78,24 -block_count,ArrayMap,79,60 -block_count,ArrayMap,80,35 -block_count,ArrayMap,81,35 -block_count,ArrayMap,82,35 +block_count,ArrayMap,78,23 +block_count,ArrayMap,79,58 +block_count,ArrayMap,80,34 +block_count,ArrayMap,81,34 +block_count,ArrayMap,82,34 block_count,ArrayMap,83,0 block_count,ArrayMap,84,0 block_count,ArrayMap,85,0 -block_count,ArrayMap,86,35 +block_count,ArrayMap,86,34 block_count,ArrayMap,87,0 -block_count,ArrayMap,88,35 -block_count,ArrayMap,89,35 +block_count,ArrayMap,88,34 +block_count,ArrayMap,89,34 block_count,ArrayMap,90,0 block_count,ArrayMap,91,0 block_count,ArrayMap,92,0 block_count,ArrayMap,93,0 -block_count,ArrayMap,94,35 -block_count,ArrayMap,95,35 -block_count,ArrayMap,96,35 -block_count,ArrayMap,97,35 -block_count,ArrayMap,98,35 +block_count,ArrayMap,94,34 +block_count,ArrayMap,95,34 +block_count,ArrayMap,96,34 +block_count,ArrayMap,97,34 +block_count,ArrayMap,98,34 block_count,ArrayMap,99,0 block_count,ArrayMap,100,0 block_count,ArrayMap,101,0 @@ -45180,21 +45189,21 @@ block_count,ArrayMap,109,0 block_count,ArrayMap,110,0 block_count,ArrayMap,111,0 -block_count,ArrayMap,112,35 -block_count,ArrayMap,113,17 -block_count,ArrayMap,114,17 +block_count,ArrayMap,112,34 +block_count,ArrayMap,113,16 +block_count,ArrayMap,114,16 block_count,ArrayMap,115,0 block_count,ArrayMap,116,18 block_count,ArrayMap,117,0 block_count,ArrayMap,118,0 block_count,ArrayMap,119,0 -block_count,ArrayMap,120,18 -block_count,ArrayMap,121,18 +block_count,ArrayMap,120,17 +block_count,ArrayMap,121,17 block_count,ArrayMap,122,0 block_count,ArrayMap,123,18 -block_count,ArrayMap,124,35 +block_count,ArrayMap,124,34 block_count,ArrayMap,125,0 -block_count,ArrayMap,126,35 +block_count,ArrayMap,126,34 block_count,ArrayMap,127,0 block_count,ArrayMap,128,0 block_count,ArrayMap,129,0 @@ -45262,15 +45271,15 @@ block_count,ArrayMap,191,0 block_count,ArrayMap,192,0 block_count,ArrayMap,193,0 -block_count,ArrayMap,194,24 +block_count,ArrayMap,194,23 block_count,ArrayMap,195,9 block_count,ArrayMap,196,14 block_count,ArrayMap,197,14 block_count,ArrayMap,198,0 block_count,ArrayMap,199,14 -block_count,ArrayMap,200,24 -block_count,ArrayMap,201,24 -block_count,ArrayMap,202,24 +block_count,ArrayMap,200,23 +block_count,ArrayMap,201,23 +block_count,ArrayMap,202,23 block_count,ArrayMap,203,0 block_count,ArrayMap,204,0 block_count,ArrayMap,205,0 @@ -45279,13 +45288,13 @@ block_count,ArrayMap,208,0 block_count,ArrayMap,209,0 block_count,ArrayMap,210,0 -block_count,ArrayMap,211,24 +block_count,ArrayMap,211,23 block_count,ArrayMap,212,0 -block_count,ArrayMap,213,24 -block_count,ArrayMap,214,24 +block_count,ArrayMap,213,23 +block_count,ArrayMap,214,23 block_count,ArrayMap,215,0 -block_count,ArrayMap,216,24 -block_count,ArrayMap,217,24 +block_count,ArrayMap,216,23 +block_count,ArrayMap,217,23 block_count,ArrayMap,218,0 block_count,ArrayMap,219,0 block_count,ArrayMap,220,0 @@ -47294,7 +47303,7 @@ block_count,BooleanPrototypeToString,7,0 block_count,BooleanPrototypeToString,8,0 block_count,BooleanPrototypeToString,9,0 -block_count,ToString,0,64 +block_count,ToString,0,65 block_count,ToString,1,99 block_count,ToString,2,87 block_count,ToString,3,70 @@ -47489,16 +47498,16 @@ block_count,StringPrototypeCharAt,13,112 block_count,StringPrototypeCharAt,14,112 block_count,StringPrototypeCharAt,15,110 -block_count,StringPrototypeCharAt,16,172 -block_count,StringPrototypeCharAt,17,62 -block_count,StringPrototypeCharAt,18,62 +block_count,StringPrototypeCharAt,16,173 +block_count,StringPrototypeCharAt,17,63 +block_count,StringPrototypeCharAt,18,63 block_count,StringPrototypeCharAt,19,58 block_count,StringPrototypeCharAt,20,0 block_count,StringPrototypeCharAt,21,58 block_count,StringPrototypeCharAt,22,4 block_count,StringPrototypeCharAt,23,4 block_count,StringPrototypeCharAt,24,0 -block_count,StringPrototypeCharAt,25,62 +block_count,StringPrototypeCharAt,25,63 block_count,StringPrototypeCharAt,26,0 block_count,StringPrototypeCharAt,27,0 block_count,StringPrototypeCharAt,28,0 @@ -47512,7 +47521,7 @@ block_count,StringPrototypeCharAt,36,110 block_count,StringPrototypeCharAt,37,110 block_count,StringPrototypeCharAt,38,13 -block_count,StringPrototypeCharAt,39,97 +block_count,StringPrototypeCharAt,39,96 block_count,StringPrototypeCharAt,40,110 block_count,StringPrototypeCharAt,41,0 block_count,StringPrototypeCharAt,42,0 @@ -47660,7 +47669,7 @@ block_count,StringConstructor,2,28 block_count,StringConstructor,3,28 block_count,StringConstructor,4,28 -block_count,StringConstructor,5,1 +block_count,StringConstructor,5,2 block_count,StringConstructor,6,26 block_count,StringConstructor,7,19 block_count,StringConstructor,8,0 @@ -47675,19 +47684,19 @@ block_count,StringConstructor,17,28 block_count,StringConstructor,18,0 block_count,StringConstructor,19,28 -block_count,StringConstructor,20,1 -block_count,StringConstructor,21,1 +block_count,StringConstructor,20,2 +block_count,StringConstructor,21,2 block_count,StringConstructor,22,0 -block_count,StringConstructor,23,1 +block_count,StringConstructor,23,2 block_count,StringConstructor,24,0 -block_count,StringConstructor,25,1 -block_count,StringConstructor,26,1 -block_count,StringConstructor,27,1 +block_count,StringConstructor,25,2 +block_count,StringConstructor,26,2 +block_count,StringConstructor,27,2 block_count,StringConstructor,28,0 block_count,StringConstructor,29,0 block_count,StringConstructor,30,0 -block_count,StringConstructor,31,1 -block_count,StringConstructor,32,1 +block_count,StringConstructor,31,2 +block_count,StringConstructor,32,2 block_count,StringConstructor,33,0 block_count,StringConstructor,34,0 block_count,StringConstructor,35,0 @@ -47713,25 +47722,25 @@ block_count,StringConstructor,55,0 block_count,StringConstructor,56,0 block_count,StringConstructor,57,0 -block_count,StringConstructor,58,1 -block_count,StringConstructor,59,1 +block_count,StringConstructor,58,2 +block_count,StringConstructor,59,2 block_count,StringConstructor,60,0 -block_count,StringConstructor,61,1 +block_count,StringConstructor,61,2 block_count,StringConstructor,62,0 block_count,StringConstructor,63,0 -block_count,StringConstructor,64,1 -block_count,StringConstructor,65,1 +block_count,StringConstructor,64,2 +block_count,StringConstructor,65,2 block_count,StringConstructor,66,0 -block_count,StringConstructor,67,1 -block_count,StringConstructor,68,1 +block_count,StringConstructor,67,2 +block_count,StringConstructor,68,2 block_count,StringConstructor,69,0 block_count,StringConstructor,70,0 block_count,StringConstructor,71,0 block_count,StringConstructor,72,0 -block_count,StringConstructor,73,1 +block_count,StringConstructor,73,2 block_count,StringConstructor,74,0 -block_count,StringConstructor,75,1 -block_count,StringConstructor,76,1 +block_count,StringConstructor,75,2 +block_count,StringConstructor,76,2 block_count,StringConstructor,77,0 block_count,StringConstructor,78,0 block_count,StringConstructor,79,0 @@ -47933,14 +47942,14 @@ block_count,StringAddConvertLeft,172,1 block_count,StringAddConvertLeft,173,0 block_count,StringAddConvertLeft,174,1 -block_count,StringAddConvertRight,0,178 +block_count,StringAddConvertRight,0,179 block_count,StringAddConvertRight,1,161 block_count,StringAddConvertRight,2,121 block_count,StringAddConvertRight,3,40 block_count,StringAddConvertRight,4,17 block_count,StringAddConvertRight,5,57 -block_count,StringAddConvertRight,6,178 -block_count,StringAddConvertRight,7,178 +block_count,StringAddConvertRight,6,179 +block_count,StringAddConvertRight,7,179 block_count,StringAddConvertRight,8,161 block_count,StringAddConvertRight,9,161 block_count,StringAddConvertRight,10,0 @@ -48059,7 +48068,7 @@ block_count,StringAddConvertRight,123,0 block_count,StringAddConvertRight,124,17 block_count,StringAddConvertRight,125,17 -block_count,StringAddConvertRight,126,16 +block_count,StringAddConvertRight,126,17 block_count,StringAddConvertRight,127,0 block_count,StringAddConvertRight,128,0 block_count,StringAddConvertRight,129,0 @@ -48159,15 +48168,15 @@ block_count,FastNewFunctionContextFunction,16,60 block_count,FastNewFunctionContextFunction,17,42 block_count,FastNewFunctionContextFunction,18,17 -block_count,CreateRegExpLiteral,0,11 -block_count,CreateRegExpLiteral,1,11 +block_count,CreateRegExpLiteral,0,10 +block_count,CreateRegExpLiteral,1,10 block_count,CreateRegExpLiteral,2,0 -block_count,CreateRegExpLiteral,3,11 +block_count,CreateRegExpLiteral,3,10 block_count,CreateRegExpLiteral,4,0 -block_count,CreateRegExpLiteral,5,11 -block_count,CreateRegExpLiteral,6,11 +block_count,CreateRegExpLiteral,5,10 +block_count,CreateRegExpLiteral,6,10 block_count,CreateRegExpLiteral,7,0 -block_count,CreateRegExpLiteral,8,11 +block_count,CreateRegExpLiteral,8,10 block_count,CreateRegExpLiteral,9,0 block_count,CreateRegExpLiteral,10,0 block_count,CreateShallowArrayLiteral,0,9 @@ -48380,7 +48389,7 @@ block_count,CreateShallowObjectLiteral,121,17 block_count,CreateShallowObjectLiteral,122,17 block_count,CreateShallowObjectLiteral,123,47 -block_count,CreateShallowObjectLiteral,124,41 +block_count,CreateShallowObjectLiteral,124,40 block_count,CreateShallowObjectLiteral,125,0 block_count,CreateShallowObjectLiteral,126,0 block_count,CreateShallowObjectLiteral,127,0 @@ -48394,23 +48403,23 @@ block_count,CreateShallowObjectLiteral,135,0 block_count,CreateShallowObjectLiteral,136,0 block_count,CreateShallowObjectLiteral,137,0 -block_count,CreateShallowObjectLiteral,138,1 -block_count,CreateShallowObjectLiteral,139,1 +block_count,CreateShallowObjectLiteral,138,0 +block_count,CreateShallowObjectLiteral,139,0 block_count,CreateShallowObjectLiteral,140,0 block_count,CreateShallowObjectLiteral,141,0 block_count,CreateShallowObjectLiteral,142,0 block_count,CreateShallowObjectLiteral,143,0 block_count,CreateShallowObjectLiteral,144,0 block_count,CreateShallowObjectLiteral,145,0 -block_count,CreateShallowObjectLiteral,146,1 +block_count,CreateShallowObjectLiteral,146,0 block_count,CreateShallowObjectLiteral,147,0 block_count,CreateShallowObjectLiteral,148,0 block_count,CreateShallowObjectLiteral,149,0 block_count,CreateShallowObjectLiteral,150,0 -block_count,CreateShallowObjectLiteral,151,41 +block_count,CreateShallowObjectLiteral,151,40 block_count,CreateShallowObjectLiteral,152,6 -block_count,CreateShallowObjectLiteral,153,47 -block_count,CreateShallowObjectLiteral,154,30 +block_count,CreateShallowObjectLiteral,153,46 +block_count,CreateShallowObjectLiteral,154,29 block_count,CreateShallowObjectLiteral,155,17 block_count,CreateShallowObjectLiteral,156,0 block_count,CreateShallowObjectLiteral,157,0 @@ -48552,7 +48561,7 @@ block_count,ToNumeric,1,0 block_count,ToNumeric,2,14 block_count,ToNumeric,3,14 -block_count,NumberToString,0,1322 +block_count,NumberToString,0,1321 block_count,NumberToString,1,41 block_count,NumberToString,2,41 block_count,NumberToString,3,0 @@ -48574,7 +48583,7 @@ block_count,NumberToString,19,5 block_count,NumberToString,20,1280 block_count,NumberToString,21,1280 -block_count,NumberToString,22,1280 +block_count,NumberToString,22,1279 block_count,NumberToString,23,0 block_count,NumberToString,24,0 block_count,NumberToString,25,0 @@ -48641,13 +48650,13 @@ block_count,ToBoolean,16,0 block_count,ToBoolean,17,0 block_count,ToBoolean,18,0 -block_count,ToBooleanForBaselineJump,0,476 -block_count,ToBooleanForBaselineJump,1,446 -block_count,ToBooleanForBaselineJump,2,171 -block_count,ToBooleanForBaselineJump,3,77 -block_count,ToBooleanForBaselineJump,4,77 -block_count,ToBooleanForBaselineJump,5,77 -block_count,ToBooleanForBaselineJump,6,77 +block_count,ToBooleanForBaselineJump,0,472 +block_count,ToBooleanForBaselineJump,1,443 +block_count,ToBooleanForBaselineJump,2,169 +block_count,ToBooleanForBaselineJump,3,76 +block_count,ToBooleanForBaselineJump,4,76 +block_count,ToBooleanForBaselineJump,5,76 +block_count,ToBooleanForBaselineJump,6,76 block_count,ToBooleanForBaselineJump,7,0 block_count,ToBooleanForBaselineJump,8,0 block_count,ToBooleanForBaselineJump,9,0 @@ -48655,9 +48664,9 @@ block_count,ToBooleanForBaselineJump,11,0 block_count,ToBooleanForBaselineJump,12,0 block_count,ToBooleanForBaselineJump,13,0 -block_count,ToBooleanForBaselineJump,14,93 -block_count,ToBooleanForBaselineJump,15,275 -block_count,ToBooleanForBaselineJump,16,29 +block_count,ToBooleanForBaselineJump,14,92 +block_count,ToBooleanForBaselineJump,15,274 +block_count,ToBooleanForBaselineJump,16,28 block_count,ToBooleanForBaselineJump,17,16 block_count,ToBooleanForBaselineJump,18,12 block_count,ToLength,0,2 @@ -49518,7 +49527,7 @@ block_count,GetIteratorWithFeedback,0,0 block_count,GetIteratorWithFeedback,1,0 block_count,GetIteratorWithFeedback,2,0 -block_count,GetIteratorBaseline,0,14 +block_count,GetIteratorBaseline,0,13 block_count,CallIteratorWithFeedback,0,14 block_count,CallIteratorWithFeedback,1,14 block_count,CallIteratorWithFeedback,2,0 @@ -49764,17 +49773,17 @@ block_count,MathMax,1,0 block_count,MathMax,2,4 block_count,MathMax,3,4 -block_count,MathMax,4,12 -block_count,MathMax,5,8 -block_count,MathMax,6,8 +block_count,MathMax,4,13 +block_count,MathMax,5,9 +block_count,MathMax,6,9 block_count,MathMax,7,0 -block_count,MathMax,8,8 -block_count,MathMax,9,8 +block_count,MathMax,8,9 +block_count,MathMax,9,9 block_count,MathMax,10,1 block_count,MathMax,11,1 block_count,MathMax,12,0 block_count,MathMax,13,7 -block_count,MathMax,14,8 +block_count,MathMax,14,9 block_count,MathMax,15,4 block_count,MathMax,16,1 block_count,MathMax,17,2 @@ -49793,7 +49802,7 @@ block_count,MathMin,1,0 block_count,MathMin,2,3 block_count,MathMin,3,3 -block_count,MathMin,4,10 +block_count,MathMin,4,9 block_count,MathMin,5,6 block_count,MathMin,6,6 block_count,MathMin,7,0 @@ -50048,19 +50057,19 @@ block_count,MathSign,13,0 block_count,MathSign,14,0 block_count,MathSign,15,0 -block_count,MathSqrt,0,8 +block_count,MathSqrt,0,9 block_count,MathSqrt,1,0 -block_count,MathSqrt,2,8 -block_count,MathSqrt,3,8 +block_count,MathSqrt,2,9 +block_count,MathSqrt,3,9 block_count,MathSqrt,4,6 block_count,MathSqrt,5,6 block_count,MathSqrt,6,0 block_count,MathSqrt,7,6 block_count,MathSqrt,8,2 -block_count,MathSqrt,9,8 +block_count,MathSqrt,9,9 block_count,MathSqrt,10,6 block_count,MathSqrt,11,2 -block_count,MathSqrt,12,8 +block_count,MathSqrt,12,9 block_count,MathSqrt,13,6 block_count,MathSqrt,14,2 block_count,MathSqrt,15,1 @@ -50399,8 +50408,8 @@ block_count,NumberParseInt,0,6 block_count,NumberParseInt,1,0 block_count,NumberParseInt,2,6 -block_count,Add,0,42 -block_count,Add,1,43 +block_count,Add,0,43 +block_count,Add,1,44 block_count,Add,2,1 block_count,Add,3,1 block_count,Add,4,1 @@ -50421,7 +50430,7 @@ block_count,Add,19,0 block_count,Add,20,0 block_count,Add,21,0 -block_count,Add,22,42 +block_count,Add,22,43 block_count,Add,23,0 block_count,Add,24,0 block_count,Add,25,0 @@ -50440,8 +50449,8 @@ block_count,Add,38,0 block_count,Add,39,0 block_count,Add,40,0 -block_count,Add,41,42 -block_count,Add,42,42 +block_count,Add,41,43 +block_count,Add,42,43 block_count,Add,43,1 block_count,Add,44,1 block_count,Add,45,1 @@ -50458,7 +50467,7 @@ block_count,Add,56,0 block_count,Add,57,0 block_count,Add,58,0 -block_count,Add,59,41 +block_count,Add,59,42 block_count,Add,60,0 block_count,Add,61,0 block_count,Add,62,0 @@ -50692,10 +50701,10 @@ block_count,BitwiseOr,32,0 block_count,BitwiseOr,33,0 block_count,BitwiseOr,34,3 -block_count,LessThan,0,671 -block_count,LessThan,1,1129 -block_count,LessThan,2,1100 -block_count,LessThan,3,1100 +block_count,LessThan,0,669 +block_count,LessThan,1,1127 +block_count,LessThan,2,1098 +block_count,LessThan,3,1098 block_count,LessThan,4,9 block_count,LessThan,5,9 block_count,LessThan,6,3 @@ -50742,11 +50751,11 @@ block_count,LessThan,47,0 block_count,LessThan,48,0 block_count,LessThan,49,0 -block_count,LessThan,50,1091 +block_count,LessThan,50,1089 block_count,LessThan,51,451 block_count,LessThan,52,451 block_count,LessThan,53,0 -block_count,LessThan,54,639 +block_count,LessThan,54,637 block_count,LessThan,55,0 block_count,LessThan,56,0 block_count,LessThan,57,0 @@ -50762,13 +50771,13 @@ block_count,LessThan,67,0 block_count,LessThan,68,0 block_count,LessThan,69,458 -block_count,LessThan,70,668 -block_count,LessThan,71,551 -block_count,LessThan,72,117 -block_count,LessThan,73,551 -block_count,LessThan,74,117 +block_count,LessThan,70,666 +block_count,LessThan,71,549 +block_count,LessThan,72,116 +block_count,LessThan,73,549 +block_count,LessThan,74,116 block_count,GreaterThan,0,582 -block_count,GreaterThan,1,1009 +block_count,GreaterThan,1,1010 block_count,GreaterThan,2,993 block_count,GreaterThan,3,903 block_count,GreaterThan,4,14 @@ -50915,7 +50924,7 @@ block_count,Equal,0,44 block_count,Equal,1,126 block_count,Equal,2,124 -block_count,Equal,3,71 +block_count,Equal,3,70 block_count,Equal,4,53 block_count,Equal,5,34 block_count,Equal,6,23 @@ -50996,7 +51005,7 @@ block_count,Equal,81,0 block_count,Equal,82,2 block_count,Equal,83,17 -block_count,Equal,84,35 +block_count,Equal,84,34 block_count,Equal,85,53 block_count,Equal,86,53 block_count,Equal,87,29 @@ -51027,12 +51036,12 @@ block_count,Equal,112,2 block_count,Equal,113,39 block_count,StrictEqual,0,1250 -block_count,StrictEqual,1,1107 +block_count,StrictEqual,1,1108 block_count,StrictEqual,2,1083 block_count,StrictEqual,3,1041 block_count,StrictEqual,4,1017 -block_count,StrictEqual,5,157 -block_count,StrictEqual,6,157 +block_count,StrictEqual,5,158 +block_count,StrictEqual,6,158 block_count,StrictEqual,7,0 block_count,StrictEqual,8,0 block_count,StrictEqual,9,0 @@ -51092,7 +51101,7 @@ block_count,StrictEqual,63,0 block_count,StrictEqual,64,0 block_count,StrictEqual,65,2 -block_count,StrictEqual,66,291 +block_count,StrictEqual,66,292 block_count,StrictEqual,67,142 block_count,CreateObjectWithoutProperties,0,6 block_count,CreateObjectWithoutProperties,1,6 @@ -53181,23 +53190,23 @@ block_count,RegExpMatchFast,389,0 block_count,RegExpMatchFast,390,169 block_count,RegExpMatchFast,391,75 -block_count,RegExpMatchFast,392,94 +block_count,RegExpMatchFast,392,93 block_count,RegExpMatchFast,393,102 block_count,RegExpMatchFast,394,8 -block_count,RegExpMatchFast,395,94 +block_count,RegExpMatchFast,395,93 block_count,RegExpMatchFast,396,169 block_count,RegExpMatchFast,397,91 block_count,RegExpMatchFast,398,77 block_count,RegExpMatchFast,399,169 -block_count,RegExpMatchFast,400,94 +block_count,RegExpMatchFast,400,93 block_count,RegExpMatchFast,401,113 block_count,RegExpMatchFast,402,101 block_count,RegExpMatchFast,403,12 block_count,RegExpMatchFast,404,113 block_count,RegExpMatchFast,405,19 -block_count,RegExpMatchFast,406,94 +block_count,RegExpMatchFast,406,93 block_count,RegExpMatchFast,407,0 -block_count,RegExpMatchFast,408,94 +block_count,RegExpMatchFast,408,93 block_count,RegExpMatchFast,409,0 block_count,RegExpMatchFast,410,0 block_count,RegExpMatchFast,411,0 @@ -53302,7 +53311,7 @@ block_count,RegExpMatchFast,510,0 block_count,RegExpMatchFast,511,0 block_count,RegExpMatchFast,512,0 -block_count,RegExpMatchFast,513,94 +block_count,RegExpMatchFast,513,93 block_count,RegExpMatchFast,514,75 block_count,RegExpMatchFast,515,169 block_count,RegExpMatchFast,516,169 @@ -54249,13 +54258,13 @@ block_count,RegExpPrototypeTest,92,66 block_count,RegExpPrototypeTest,93,66 block_count,RegExpPrototypeTest,94,66 -block_count,RegExpPrototypeTest,95,53 +block_count,RegExpPrototypeTest,95,54 block_count,RegExpPrototypeTest,96,0 block_count,RegExpPrototypeTest,97,0 block_count,RegExpPrototypeTest,98,0 block_count,RegExpPrototypeTest,99,0 block_count,RegExpPrototypeTest,100,0 -block_count,RegExpPrototypeTest,101,53 +block_count,RegExpPrototypeTest,101,54 block_count,RegExpPrototypeTest,102,12 block_count,RegExpPrototypeTest,103,12 block_count,RegExpPrototypeTest,104,0 @@ -54276,15 +54285,15 @@ block_count,RegExpPrototypeTest,119,34 block_count,RegExpPrototypeTest,120,0 block_count,RegExpPrototypeTest,121,0 -block_count,RegExpPrototypeTest,122,53 +block_count,RegExpPrototypeTest,122,54 block_count,RegExpPrototypeTest,123,101 block_count,RegExpPrototypeTest,124,66 block_count,RegExpPrototypeTest,125,35 block_count,RegExpPrototypeTest,126,101 -block_count,RegExpPrototypeTest,127,87 -block_count,RegExpPrototypeTest,128,87 +block_count,RegExpPrototypeTest,127,88 +block_count,RegExpPrototypeTest,128,88 block_count,RegExpPrototypeTest,129,0 -block_count,RegExpPrototypeTest,130,87 +block_count,RegExpPrototypeTest,130,88 block_count,RegExpPrototypeTest,131,13 block_count,RegExpPrototypeTest,132,13 block_count,RegExpPrototypeTestFast,0,376 @@ -54305,7 +54314,7 @@ block_count,RegExpPrototypeTestFast,15,4 block_count,RegExpPrototypeTestFast,16,0 block_count,RegExpPrototypeTestFast,17,372 -block_count,RegExpPrototypeTestFast,18,478 +block_count,RegExpPrototypeTestFast,18,477 block_count,RegExpPrototypeTestFast,19,105 block_count,RegExpPrototypeTestFast,20,105 block_count,RegExpPrototypeTestFast,21,105 @@ -54318,17 +54327,17 @@ block_count,RegExpPrototypeTestFast,28,0 block_count,RegExpPrototypeTestFast,29,0 block_count,RegExpPrototypeTestFast,30,0 -block_count,RegExpPrototypeTestFast,31,372 -block_count,RegExpPrototypeTestFast,32,372 +block_count,RegExpPrototypeTestFast,31,371 +block_count,RegExpPrototypeTestFast,32,371 block_count,RegExpPrototypeTestFast,33,0 block_count,RegExpPrototypeTestFast,34,0 block_count,RegExpPrototypeTestFast,35,0 block_count,RegExpPrototypeTestFast,36,371 block_count,RegExpPrototypeTestFast,37,371 block_count,RegExpPrototypeTestFast,38,0 -block_count,RegExpPrototypeTestFast,39,372 -block_count,RegExpPrototypeTestFast,40,372 -block_count,RegExpPrototypeTestFast,41,372 +block_count,RegExpPrototypeTestFast,39,371 +block_count,RegExpPrototypeTestFast,40,371 +block_count,RegExpPrototypeTestFast,41,371 block_count,RegExpPrototypeTestFast,42,262 block_count,RegExpPrototypeTestFast,43,0 block_count,RegExpPrototypeTestFast,44,0 @@ -54358,7 +54367,7 @@ block_count,RegExpPrototypeTestFast,68,0 block_count,RegExpPrototypeTestFast,69,262 block_count,RegExpPrototypeTestFast,70,376 -block_count,RegExpPrototypeTestFast,71,372 +block_count,RegExpPrototypeTestFast,71,371 block_count,RegExpPrototypeTestFast,72,4 block_count,RegExpPrototypeTestFast,73,376 block_count,RegExpPrototypeTestFast,74,262 @@ -55331,9 +55340,9 @@ block_count,StringPrototypeSlice,36,20 block_count,StringPrototypeSlice,37,20 block_count,StringPrototypeSlice,38,14 -block_count,StringPrototypeSlice,39,6 +block_count,StringPrototypeSlice,39,5 block_count,StringPrototypeSlice,40,20 -block_count,StringPrototypeSlice,41,6 +block_count,StringPrototypeSlice,41,5 block_count,StringPrototypeSlice,42,14 block_count,StringPrototypeSlice,43,14 block_count,StringPrototypeSlice,44,0 @@ -55357,32 +55366,32 @@ block_count,StringPrototypeSlice,62,14 block_count,StringPrototypeSlice,63,14 block_count,StringPrototypeSlice,64,20 -block_count,StringPrototypeSlice,65,19 -block_count,StringPrototypeSlice,66,18 -block_count,StringPrototypeSlice,67,18 +block_count,StringPrototypeSlice,65,18 +block_count,StringPrototypeSlice,66,17 +block_count,StringPrototypeSlice,67,17 block_count,StringPrototypeSlice,68,12 -block_count,StringPrototypeSlice,69,21 -block_count,StringPrototypeSlice,70,9 -block_count,StringPrototypeSlice,71,9 -block_count,StringPrototypeSlice,72,5 +block_count,StringPrototypeSlice,69,20 +block_count,StringPrototypeSlice,70,8 +block_count,StringPrototypeSlice,71,8 +block_count,StringPrototypeSlice,72,4 block_count,StringPrototypeSlice,73,0 -block_count,StringPrototypeSlice,74,5 +block_count,StringPrototypeSlice,74,4 block_count,StringPrototypeSlice,75,3 block_count,StringPrototypeSlice,76,3 block_count,StringPrototypeSlice,77,0 -block_count,StringPrototypeSlice,78,9 +block_count,StringPrototypeSlice,78,8 block_count,StringPrototypeSlice,79,0 block_count,StringPrototypeSlice,80,12 block_count,StringPrototypeSlice,81,12 -block_count,StringPrototypeSlice,82,5 +block_count,StringPrototypeSlice,82,4 block_count,StringPrototypeSlice,83,1 block_count,StringPrototypeSlice,84,0 block_count,StringPrototypeSlice,85,1 block_count,StringPrototypeSlice,86,1 -block_count,StringPrototypeSlice,87,4 +block_count,StringPrototypeSlice,87,3 block_count,StringPrototypeSlice,88,0 -block_count,StringPrototypeSlice,89,4 -block_count,StringPrototypeSlice,90,4 +block_count,StringPrototypeSlice,89,3 +block_count,StringPrototypeSlice,90,3 block_count,StringPrototypeSlice,91,7 block_count,StringPrototypeSlice,92,7 block_count,StringPrototypeSlice,93,1 @@ -55574,7 +55583,7 @@ block_count,StringPrototypeSlice,279,3 block_count,StringPrototypeSlice,280,3 block_count,StringPrototypeSlice,281,0 -block_count,StringPrototypeSlice,282,3 +block_count,StringPrototypeSlice,282,4 block_count,StringPrototypeSlice,283,0 block_count,StringPrototypeSlice,284,0 block_count,StringPrototypeSlice,285,0 @@ -58786,12 +58795,12 @@ block_count,NewStrictArgumentsElements,8,0 block_count,NewStrictArgumentsElements,9,0 block_count,NewStrictArgumentsElements,10,3 -block_count,NewStrictArgumentsElements,11,10 -block_count,NewStrictArgumentsElements,12,7 -block_count,NewStrictArgumentsElements,13,7 -block_count,NewStrictArgumentsElements,14,7 +block_count,NewStrictArgumentsElements,11,9 +block_count,NewStrictArgumentsElements,12,6 +block_count,NewStrictArgumentsElements,13,6 +block_count,NewStrictArgumentsElements,14,6 block_count,NewStrictArgumentsElements,15,0 -block_count,NewStrictArgumentsElements,16,7 +block_count,NewStrictArgumentsElements,16,6 block_count,NewStrictArgumentsElements,17,0 block_count,NewStrictArgumentsElements,18,3 block_count,NewStrictArgumentsElements,19,0 @@ -59222,7 +59231,7 @@ block_count,StringIndexOf,9,456 block_count,StringIndexOf,10,481 block_count,StringIndexOf,11,42 -block_count,StringIndexOf,12,24 +block_count,StringIndexOf,12,25 block_count,StringIndexOf,13,20 block_count,StringIndexOf,14,4 block_count,StringIndexOf,15,3 @@ -59259,7 +59268,7 @@ block_count,StringIndexOf,46,0 block_count,StringIndexOf,47,0 block_count,StringIndexOf,48,4 -block_count,StringIndexOf,49,24 +block_count,StringIndexOf,49,25 block_count,StringIndexOf,50,17 block_count,StringIndexOf,51,17 block_count,StringIndexOf,52,17 @@ -61045,10 +61054,10 @@ block_count,StringToLowerCaseIntl,38,0 block_count,StringToLowerCaseIntl,39,0 block_count,StringToLowerCaseIntl,40,0 -block_count,WideHandler,0,55 +block_count,WideHandler,0,54 block_count,ExtraWideHandler,0,9 -block_count,LdarHandler,0,76 -block_count,LdaZeroHandler,0,9 +block_count,LdarHandler,0,77 +block_count,LdaZeroHandler,0,10 block_count,LdaZeroHandler,1,7 block_count,LdaZeroHandler,2,2 block_count,LdaSmiHandler,0,11 @@ -61068,7 +61077,7 @@ block_count,LdaConstantHandler,0,12 block_count,LdaConstantHandler,1,5 block_count,LdaConstantHandler,2,7 -block_count,LdaContextSlotHandler,0,0 +block_count,LdaContextSlotHandler,0,1 block_count,LdaContextSlotHandler,1,0 block_count,LdaContextSlotHandler,2,0 block_count,LdaContextSlotHandler,3,0 @@ -61076,9 +61085,9 @@ block_count,LdaContextSlotHandler,5,0 block_count,LdaContextSlotHandler,6,0 block_count,LdaContextSlotHandler,7,0 -block_count,LdaContextSlotHandler,8,0 +block_count,LdaContextSlotHandler,8,1 block_count,LdaContextSlotHandler,9,0 -block_count,LdaContextSlotHandler,10,0 +block_count,LdaContextSlotHandler,10,1 block_count,LdaContextSlotHandler,11,0 block_count,LdaContextSlotHandler,12,0 block_count,LdaImmutableContextSlotHandler,0,6 @@ -61098,7 +61107,7 @@ block_count,LdaCurrentContextSlotHandler,1,0 block_count,LdaCurrentContextSlotHandler,2,5 block_count,LdaCurrentContextSlotHandler,3,2 -block_count,LdaCurrentContextSlotHandler,4,3 +block_count,LdaCurrentContextSlotHandler,4,2 block_count,LdaImmutableCurrentContextSlotHandler,0,18 block_count,LdaImmutableCurrentContextSlotHandler,1,0 block_count,LdaImmutableCurrentContextSlotHandler,2,18 @@ -61179,7 +61188,7 @@ block_count,TestTypeOfHandler,49,0 block_count,TestTypeOfHandler,50,0 block_count,LdaGlobalHandler,0,20 -block_count,LdaGlobalHandler,1,12 +block_count,LdaGlobalHandler,1,11 block_count,LdaGlobalHandler,2,11 block_count,LdaGlobalHandler,3,11 block_count,LdaGlobalHandler,4,11 @@ -62357,11 +62366,11 @@ block_count,StaLookupSlotHandler,3,0 block_count,StaLookupSlotHandler,4,0 block_count,StaLookupSlotHandler,5,0 -block_count,GetNamedPropertyHandler,0,66 -block_count,GetNamedPropertyHandler,1,41 -block_count,GetNamedPropertyHandler,2,41 +block_count,GetNamedPropertyHandler,0,67 +block_count,GetNamedPropertyHandler,1,42 +block_count,GetNamedPropertyHandler,2,42 block_count,GetNamedPropertyHandler,3,0 -block_count,GetNamedPropertyHandler,4,41 +block_count,GetNamedPropertyHandler,4,42 block_count,GetNamedPropertyHandler,5,5 block_count,GetNamedPropertyHandler,6,0 block_count,GetNamedPropertyHandler,7,5 @@ -62373,9 +62382,9 @@ block_count,GetNamedPropertyHandler,13,0 block_count,GetNamedPropertyHandler,14,2 block_count,GetNamedPropertyHandler,15,36 -block_count,GetNamedPropertyHandler,16,38 -block_count,GetNamedPropertyHandler,17,13 -block_count,GetNamedPropertyHandler,18,13 +block_count,GetNamedPropertyHandler,16,39 +block_count,GetNamedPropertyHandler,17,14 +block_count,GetNamedPropertyHandler,18,14 block_count,GetNamedPropertyHandler,19,12 block_count,GetNamedPropertyHandler,20,12 block_count,GetNamedPropertyHandler,21,0 @@ -62458,8 +62467,8 @@ block_count,GetNamedPropertyHandler,98,10 block_count,GetNamedPropertyHandler,99,12 block_count,GetNamedPropertyHandler,100,12 -block_count,GetNamedPropertyHandler,101,11 -block_count,GetNamedPropertyHandler,102,11 +block_count,GetNamedPropertyHandler,101,12 +block_count,GetNamedPropertyHandler,102,12 block_count,GetNamedPropertyHandler,103,0 block_count,GetNamedPropertyHandler,104,0 block_count,GetNamedPropertyHandler,105,12 @@ -62469,8 +62478,8 @@ block_count,GetNamedPropertyHandler,109,0 block_count,GetNamedPropertyHandler,110,0 block_count,GetNamedPropertyHandler,111,25 -block_count,GetNamedPropertyHandler,112,37 -block_count,GetNamedPropertyHandler,113,12 +block_count,GetNamedPropertyHandler,112,38 +block_count,GetNamedPropertyHandler,113,13 block_count,GetNamedPropertyHandler,114,2 block_count,GetNamedPropertyHandler,115,2 block_count,GetNamedPropertyHandler,116,1 @@ -62608,7 +62617,7 @@ block_count,GetNamedPropertyHandler,248,24 block_count,GetNamedPropertyHandler,249,24 block_count,GetNamedPropertyHandler,250,4 -block_count,GetNamedPropertyHandler,251,19 +block_count,GetNamedPropertyHandler,251,20 block_count,GetNamedPropertyHandler,252,24 block_count,GetNamedPropertyHandler,253,23 block_count,GetNamedPropertyHandler,254,1 @@ -62658,8 +62667,8 @@ block_count,GetNamedPropertyHandler,298,1 block_count,GetNamedPropertyHandler,299,0 block_count,GetNamedPropertyHandler,300,24 -block_count,GetNamedPropertyHandler,301,66 -block_count,GetNamedPropertyHandler,302,18 +block_count,GetNamedPropertyHandler,301,67 +block_count,GetNamedPropertyHandler,302,19 block_count,GetNamedPropertyHandler,303,47 block_count,GetNamedPropertyFromSuperHandler,0,0 block_count,GetKeyedPropertyHandler,0,18 @@ -62686,7 +62695,7 @@ block_count,AddHandler,11,3 block_count,AddHandler,12,0 block_count,AddHandler,13,6 -block_count,AddHandler,14,2 +block_count,AddHandler,14,3 block_count,AddHandler,15,2 block_count,AddHandler,16,2 block_count,AddHandler,17,0 @@ -64112,18 +64121,18 @@ block_count,AddSmiHandler,30,3 block_count,AddSmiHandler,31,1 block_count,SubSmiHandler,0,1 -block_count,SubSmiHandler,1,1 -block_count,SubSmiHandler,2,1 +block_count,SubSmiHandler,1,0 +block_count,SubSmiHandler,2,0 block_count,SubSmiHandler,3,0 block_count,SubSmiHandler,4,0 block_count,SubSmiHandler,5,0 block_count,SubSmiHandler,6,0 -block_count,SubSmiHandler,7,1 +block_count,SubSmiHandler,7,0 block_count,SubSmiHandler,8,0 block_count,SubSmiHandler,9,0 block_count,SubSmiHandler,10,0 block_count,SubSmiHandler,11,0 -block_count,SubSmiHandler,12,1 +block_count,SubSmiHandler,12,0 block_count,SubSmiHandler,13,0 block_count,SubSmiHandler,14,0 block_count,SubSmiHandler,15,0 @@ -64328,7 +64337,7 @@ block_count,BitwiseOrSmiHandler,32,0 block_count,BitwiseOrSmiHandler,33,0 block_count,BitwiseOrSmiHandler,34,0 -block_count,BitwiseOrSmiHandler,35,1 +block_count,BitwiseOrSmiHandler,35,0 block_count,BitwiseOrSmiHandler,36,1 block_count,BitwiseOrSmiHandler,37,0 block_count,BitwiseOrSmiHandler,38,0 @@ -64596,8 +64605,8 @@ block_count,IncHandler,30,10 block_count,IncHandler,31,1 block_count,IncHandler,32,9 -block_count,DecHandler,0,2 -block_count,DecHandler,1,2 +block_count,DecHandler,0,3 +block_count,DecHandler,1,3 block_count,DecHandler,2,0 block_count,DecHandler,3,0 block_count,DecHandler,4,0 @@ -64614,21 +64623,21 @@ block_count,DecHandler,15,0 block_count,DecHandler,16,0 block_count,DecHandler,17,0 -block_count,DecHandler,18,2 -block_count,DecHandler,19,2 +block_count,DecHandler,18,3 +block_count,DecHandler,19,3 block_count,DecHandler,20,0 block_count,DecHandler,21,0 block_count,DecHandler,22,0 block_count,DecHandler,23,0 block_count,DecHandler,24,0 -block_count,DecHandler,25,2 -block_count,DecHandler,26,2 +block_count,DecHandler,25,3 +block_count,DecHandler,26,3 block_count,DecHandler,27,0 -block_count,DecHandler,28,2 +block_count,DecHandler,28,3 block_count,DecHandler,29,0 -block_count,DecHandler,30,2 -block_count,DecHandler,31,0 -block_count,DecHandler,32,1 +block_count,DecHandler,30,3 +block_count,DecHandler,31,1 +block_count,DecHandler,32,2 block_count,NegateHandler,0,0 block_count,NegateHandler,1,0 block_count,NegateHandler,2,0 @@ -64953,7 +64962,7 @@ block_count,CallPropertyHandler,66,0 block_count,CallPropertyHandler,67,0 block_count,CallPropertyHandler,68,1 -block_count,CallProperty0Handler,0,4 +block_count,CallProperty0Handler,0,5 block_count,CallProperty0Handler,1,3 block_count,CallProperty0Handler,2,0 block_count,CallProperty0Handler,3,0 @@ -65019,9 +65028,9 @@ block_count,CallProperty0Handler,63,0 block_count,CallProperty0Handler,64,0 block_count,CallProperty0Handler,65,0 -block_count,CallProperty0Handler,66,2 +block_count,CallProperty0Handler,66,3 block_count,CallProperty0Handler,67,1 -block_count,CallProperty0Handler,68,4 +block_count,CallProperty0Handler,68,5 block_count,CallProperty1Handler,0,11 block_count,CallProperty1Handler,1,7 block_count,CallProperty1Handler,2,0 @@ -65697,7 +65706,7 @@ block_count,ConstructForwardAllArgsHandler,47,0 block_count,TestEqualHandler,0,4 block_count,TestEqualHandler,1,4 -block_count,TestEqualHandler,2,3 +block_count,TestEqualHandler,2,4 block_count,TestEqualHandler,3,1 block_count,TestEqualHandler,4,1 block_count,TestEqualHandler,5,0 @@ -65809,7 +65818,7 @@ block_count,TestEqualHandler,111,1 block_count,TestEqualHandler,112,0 block_count,TestEqualHandler,113,0 -block_count,TestEqualHandler,114,1 +block_count,TestEqualHandler,114,2 block_count,TestEqualHandler,115,0 block_count,TestEqualHandler,116,0 block_count,TestEqualHandler,117,0 @@ -65829,7 +65838,7 @@ block_count,TestEqualHandler,131,0 block_count,TestEqualHandler,132,0 block_count,TestEqualHandler,133,0 -block_count,TestEqualHandler,134,1 +block_count,TestEqualHandler,134,2 block_count,TestEqualHandler,135,0 block_count,TestEqualHandler,136,0 block_count,TestEqualHandler,137,0 @@ -65878,9 +65887,9 @@ block_count,TestEqualHandler,180,0 block_count,TestEqualHandler,181,2 block_count,TestEqualHandler,182,4 -block_count,TestEqualHandler,183,3 +block_count,TestEqualHandler,183,4 block_count,TestEqualHandler,184,0 -block_count,TestEqualHandler,185,3 +block_count,TestEqualHandler,185,4 block_count,TestEqualHandler,186,0 block_count,TestEqualHandler,187,4 block_count,TestEqualStrictHandler,0,6 @@ -66007,7 +66016,7 @@ block_count,TestEqualStrictHandler,121,0 block_count,TestEqualStrictHandler,122,0 block_count,TestEqualStrictHandler,123,0 -block_count,TestEqualStrictHandler,124,3 +block_count,TestEqualStrictHandler,124,2 block_count,TestEqualStrictHandler,125,0 block_count,TestEqualStrictHandler,126,6 block_count,TestEqualStrictHandler,127,4 @@ -66282,7 +66291,7 @@ block_count,TestGreaterThanHandler,114,0 block_count,TestGreaterThanHandler,115,0 block_count,TestGreaterThanHandler,116,0 -block_count,TestGreaterThanHandler,117,1 +block_count,TestGreaterThanHandler,117,2 block_count,TestGreaterThanHandler,118,0 block_count,TestGreaterThanHandler,119,0 block_count,TestGreaterThanHandler,120,0 @@ -66294,7 +66303,7 @@ block_count,TestGreaterThanHandler,126,0 block_count,TestGreaterThanHandler,127,0 block_count,TestGreaterThanHandler,128,0 -block_count,TestGreaterThanHandler,129,1 +block_count,TestGreaterThanHandler,129,2 block_count,TestGreaterThanHandler,130,0 block_count,TestGreaterThanHandler,131,1 block_count,TestGreaterThanHandler,132,0 @@ -66310,9 +66319,9 @@ block_count,TestGreaterThanHandler,142,0 block_count,TestGreaterThanHandler,143,1 block_count,TestGreaterThanHandler,144,2 -block_count,TestGreaterThanHandler,145,1 +block_count,TestGreaterThanHandler,145,2 block_count,TestGreaterThanHandler,146,0 -block_count,TestGreaterThanHandler,147,1 +block_count,TestGreaterThanHandler,147,2 block_count,TestGreaterThanHandler,148,0 block_count,TestGreaterThanHandler,149,2 block_count,TestLessThanOrEqualHandler,0,0 @@ -67230,7 +67239,7 @@ block_count,CreateRestParameterHandler,34,0 block_count,CreateRestParameterHandler,35,0 block_count,CreateRestParameterHandler,36,0 -block_count,JumpLoopHandler,0,12 +block_count,JumpLoopHandler,0,13 block_count,JumpLoopHandler,1,11 block_count,JumpLoopHandler,2,1 block_count,JumpLoopHandler,3,0 @@ -67398,9 +67407,9 @@ block_count,JumpIfTrueHandler,0,5 block_count,JumpIfTrueHandler,1,4 block_count,JumpIfTrueHandler,2,1 -block_count,JumpIfFalseHandler,0,20 +block_count,JumpIfFalseHandler,0,21 block_count,JumpIfFalseHandler,1,12 -block_count,JumpIfFalseHandler,2,8 +block_count,JumpIfFalseHandler,2,9 block_count,JumpIfNullHandler,0,0 block_count,JumpIfNullHandler,1,0 block_count,JumpIfNullHandler,2,0 @@ -67543,7 +67552,7 @@ block_count,ResumeGeneratorHandler,6,0 block_count,ResumeGeneratorHandler,7,0 block_count,GetIteratorHandler,0,0 -block_count,ShortStarHandler,0,48 +block_count,ShortStarHandler,0,47 block_count,LdarWideHandler,0,0 block_count,LdaSmiWideHandler,0,6 block_count,LdaConstantWideHandler,0,1 diff -Nru chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/x86-rl.profile chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x86-rl.profile --- chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/x86-rl.profile 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x86-rl.profile 2025-01-27 17:37:37.000000000 +0000 @@ -7,13 +7,12 @@ block_hint,RecordWriteSaveFP,24,23,0 block_hint,RecordWriteSaveFP,49,41,0 block_hint,RecordWriteSaveFP,44,43,0 +block_hint,RecordWriteIgnoreFP,10,1,0 block_hint,RecordWriteIgnoreFP,3,2,1 block_hint,RecordWriteIgnoreFP,4,7,1 block_hint,RecordWriteIgnoreFP,5,6,1 -block_hint,RecordWriteIgnoreFP,21,11,1 block_hint,RecordWriteIgnoreFP,24,23,0 block_hint,RecordWriteIgnoreFP,49,41,0 -block_hint,RecordWriteIgnoreFP,44,43,0 block_hint,AdaptorWithBuiltinExitFrame1,2,1,1 block_hint,AdaptorWithBuiltinExitFrame2,2,1,1 block_hint,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,67,1 @@ -361,6 +360,7 @@ block_hint,KeyedStoreIC_Megamorphic,286,285,0 block_hint,KeyedStoreIC_Megamorphic,288,289,1 block_hint,KeyedStoreIC_Megamorphic,295,294,1 +block_hint,KeyedStoreIC_Megamorphic,315,314,1 block_hint,KeyedStoreIC_Megamorphic,685,613,1 block_hint,KeyedStoreIC_Megamorphic,684,683,1 block_hint,KeyedStoreIC_Megamorphic,699,693,0 @@ -756,7 +756,6 @@ block_hint,ElementsTransitionAndStore_InBounds,626,625,0 block_hint,ElementsTransitionAndStore_InBounds,630,629,1 block_hint,ElementsTransitionAndStore_InBounds,633,632,0 -block_hint,ElementsTransitionAndStore_InBounds,635,634,0 block_hint,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,399,404,0 block_hint,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,401,400,1 block_hint,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,403,402,0 @@ -1097,6 +1096,7 @@ block_hint,ExtractFastJSArray,11,10,1 block_hint,ExtractFastJSArray,16,15,0 block_hint,ExtractFastJSArray,26,37,0 +block_hint,ExtractFastJSArray,32,33,1 block_hint,ExtractFastJSArray,47,46,0 block_hint,ExtractFastJSArray,68,67,1 block_hint,ExtractFastJSArray,72,71,0 @@ -1453,6 +1453,7 @@ block_hint,KeyedLoadIC_Megamorphic,43,46,0 block_hint,KeyedLoadIC_Megamorphic,48,47,1 block_hint,KeyedLoadIC_Megamorphic,61,56,1 +block_hint,KeyedLoadIC_Megamorphic,60,57,1 block_hint,KeyedLoadIC_Megamorphic,341,62,0 block_hint,KeyedLoadIC_Megamorphic,67,66,0 block_hint,KeyedLoadIC_Megamorphic,71,70,0 @@ -2094,7 +2095,6 @@ block_hint,ShiftRightLogicalSmi_Baseline,34,33,0 block_hint,Equal_Baseline,19,9,0 block_hint,Equal_Baseline,17,16,0 -block_hint,Equal_Baseline,42,41,1 block_hint,Equal_Baseline,51,44,0 block_hint,Equal_Baseline,50,45,0 block_hint,Equal_Baseline,49,46,0 @@ -2106,7 +2106,6 @@ block_hint,Equal_Baseline,93,97,1 block_hint,Equal_Baseline,103,104,0 block_hint,Equal_Baseline,109,110,0 -block_hint,Equal_Baseline,139,125,0 block_hint,Equal_Baseline,130,129,0 block_hint,Equal_Baseline,133,132,1 block_hint,Equal_Baseline,136,137,0 @@ -2673,10 +2672,12 @@ block_hint,StringAdd_CheckNone,12,11,1 block_hint,StringAdd_CheckNone,116,20,0 block_hint,StringAdd_CheckNone,21,45,0 +block_hint,StringAdd_CheckNone,35,22,1 block_hint,StringAdd_CheckNone,23,26,0 block_hint,StringAdd_CheckNone,25,24,1 block_hint,StringAdd_CheckNone,33,28,1 block_hint,StringAdd_CheckNone,29,32,0 +block_hint,StringAdd_CheckNone,40,39,1 block_hint,StringAdd_CheckNone,46,80,1 block_hint,StringAdd_CheckNone,55,48,0 block_hint,StringAdd_CheckNone,49,52,0 @@ -3906,6 +3907,7 @@ block_hint,Equal,27,8,0 block_hint,Equal,16,9,0 block_hint,Equal,12,11,0 +block_hint,Equal,28,31,0 block_hint,Equal,33,32,0 block_hint,Equal,42,37,0 block_hint,Equal,41,38,0 @@ -4838,10 +4840,17 @@ block_hint,MergeAt,68,73,1 block_hint,MergeAt,69,72,1 block_hint,MergeAt,71,70,0 +block_hint,MergeAt,82,79,0 +block_hint,MergeAt,80,81,0 block_hint,MergeAt,86,85,1 block_hint,MergeAt,88,115,1 block_hint,MergeAt,94,114,1 block_hint,MergeAt,95,113,1 +block_hint,MergeAt,112,96,0 +block_hint,MergeAt,97,111,1 +block_hint,MergeAt,105,110,1 +block_hint,MergeAt,106,109,1 +block_hint,MergeAt,107,108,1 block_hint,MergeAt,121,120,1 block_hint,MergeAt,123,122,1 block_hint,MergeAt,127,126,1 @@ -5048,6 +5057,7 @@ block_hint,TestTypeOfHandler,46,41,0 block_hint,TestTypeOfHandler,44,45,0 block_hint,LdaGlobalHandler,286,1,0 +block_hint,LdaGlobalHandler,2,279,1 block_hint,LdaGlobalHandler,8,3,0 block_hint,LdaGlobalHandler,7,4,0 block_hint,LdaGlobalHandler,275,9,1 @@ -5055,11 +5065,6 @@ block_hint,LdaGlobalHandler,283,282,0 block_hint,StaContextSlotHandler,10,9,1 block_hint,StaCurrentContextSlotHandler,2,1,1 -block_hint,StaCurrentScriptContextSlotHandler,1,101,1 -block_hint,StaCurrentScriptContextSlotHandler,3,2,1 -block_hint,StaCurrentScriptContextSlotHandler,4,99,1 -block_hint,StaCurrentScriptContextSlotHandler,6,97,1 -block_hint,StaCurrentScriptContextSlotHandler,8,7,1 block_hint,LdaLookupGlobalSlotHandler,2,250,1 block_hint,LdaLookupGlobalSlotHandler,4,3,1 block_hint,LdaLookupGlobalSlotHandler,5,8,1 @@ -5334,12 +5339,13 @@ block_hint,ConstructHandler,55,54,0 block_hint,TestEqualHandler,4,85,1 block_hint,TestEqualHandler,19,9,0 +block_hint,TestEqualHandler,42,41,1 block_hint,TestEqualHandler,66,67,0 block_hint,TestEqualHandler,72,71,1 block_hint,TestEqualHandler,79,80,0 block_hint,TestEqualHandler,88,107,0 +block_hint,TestEqualHandler,141,127,0 block_hint,TestEqualHandler,138,139,0 -block_hint,TestEqualHandler,143,142,1 block_hint,TestEqualHandler,150,149,1 block_hint,TestEqualStrictHandler,52,3,0 block_hint,TestEqualStrictHandler,4,51,1 @@ -5352,7 +5358,6 @@ block_hint,TestEqualStrictHandler,55,54,0 block_hint,TestEqualStrictHandler,85,71,0 block_hint,TestEqualStrictHandler,94,93,1 -block_hint,TestLessThanHandler,2,90,0 block_hint,TestLessThanHandler,49,5,0 block_hint,TestLessThanHandler,78,69,1 block_hint,TestLessThanHandler,85,81,0 @@ -5379,6 +5384,7 @@ block_hint,ToNumericHandler,11,8,0 block_hint,ToNumericHandler,10,9,1 block_hint,ToStringHandler,3,2,1 +block_hint,ToBooleanHandler,15,4,0 block_hint,CreateArrayLiteralHandler,4,3,1 block_hint,CreateArrayLiteralHandler,7,6,1 block_hint,CreateArrayLiteralHandler,8,72,1 @@ -5498,6 +5504,10 @@ block_hint,GetNamedPropertyWideHandler,318,1,0 block_hint,GetNamedPropertyWideHandler,2,3,1 block_hint,GetNamedPropertyWideHandler,108,18,0 +block_hint,GetNamedPropertyWideHandler,23,20,0 +block_hint,GetNamedPropertyWideHandler,22,21,1 +block_hint,GetNamedPropertyWideHandler,100,106,1 +block_hint,GetNamedPropertyWideHandler,103,102,0 block_hint,GetNamedPropertyWideHandler,259,249,0 block_hint,AddWideHandler,2,5,0 block_hint,AddWideHandler,12,6,0 @@ -5601,26 +5611,26 @@ block_hint,BitwiseAndSmiExtraWideHandler,27,26,0 block_hint,BitwiseAndSmiExtraWideHandler,41,38,1 block_hint,CallUndefinedReceiver1ExtraWideHandler,1,67,0 -builtin_count,RecordWriteSaveFP,2761 -builtin_count,RecordWriteIgnoreFP,4 +builtin_count,RecordWriteSaveFP,2758 +builtin_count,RecordWriteIgnoreFP,3 builtin_count,EphemeronKeyBarrierSaveFP,0 builtin_count,AdaptorWithBuiltinExitFrame0,101 builtin_count,AdaptorWithBuiltinExitFrame1,3 builtin_count,AdaptorWithBuiltinExitFrame2,0 builtin_count,AdaptorWithBuiltinExitFrame3,7 -builtin_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,331 -builtin_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1252 +builtin_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,333 +builtin_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1254 builtin_count,Call_ReceiverIsAny_Baseline_Compact,4 builtin_count,CallProxy,0 builtin_count,CallWithSpread,17 -builtin_count,CallWithSpread_Baseline,1 +builtin_count,CallWithSpread_Baseline,2 builtin_count,CallWithArrayLike,31 builtin_count,CallFunctionTemplate_Generic,0 builtin_count,ConstructWithSpread,0 builtin_count,ConstructWithSpread_Baseline,0 builtin_count,ConstructForwardAllArgs_Baseline,1 -builtin_count,Construct_Baseline,107 -builtin_count,FastNewObject,340 +builtin_count,Construct_Baseline,108 +builtin_count,FastNewObject,328 builtin_count,FastNewClosure,85 builtin_count,StringEqual,674 builtin_count,StringGreaterThan,0 @@ -5630,7 +5640,7 @@ builtin_count,StringCompare,3 builtin_count,StringSubstring,503 builtin_count,OrderedHashTableHealIndex,0 -builtin_count,CompileLazy,221 +builtin_count,CompileLazy,222 builtin_count,CompileLazyDeoptimizedCode,0 builtin_count,InstantiateAsmJs,0 builtin_count,HandleApiCallOrConstruct,0 @@ -5642,7 +5652,7 @@ builtin_count,GrowFastSmiOrObjectElements,306 builtin_count,ToNumber,0 builtin_count,ToNumber_Baseline,0 -builtin_count,ToNumeric_Baseline,82 +builtin_count,ToNumeric_Baseline,78 builtin_count,ToNumberConvertBigInt,2 builtin_count,Typeof,26 builtin_count,Typeof_Baseline,2 @@ -5657,7 +5667,7 @@ builtin_count,StoreIC_NoFeedback,5 builtin_count,DefineNamedOwnIC_NoFeedback,3 builtin_count,KeyedLoadIC_SloppyArguments,1 -builtin_count,StoreFastElementIC_InBounds,411 +builtin_count,StoreFastElementIC_InBounds,400 builtin_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,41 builtin_count,StoreFastElementIC_NoTransitionHandleCOW,0 builtin_count,ElementsTransitionAndStore_InBounds,1 @@ -5671,7 +5681,7 @@ builtin_count,SetDataProperties,1 builtin_count,ReturnReceiver,4 builtin_count,ArrayConstructor,1 -builtin_count,ArrayConstructorImpl,203 +builtin_count,ArrayConstructorImpl,217 builtin_count,ArrayNoArgumentConstructor_PackedSmi_DontOverride,0 builtin_count,ArrayNoArgumentConstructor_HoleySmi_DontOverride,0 builtin_count,ArrayNoArgumentConstructor_PackedSmi_DisableAllocationSites,0 @@ -5689,7 +5699,7 @@ builtin_count,ArrayIndexOfSmiOrObject,125 builtin_count,ArrayIndexOf,23 builtin_count,ArrayPrototypePop,11 -builtin_count,ArrayPrototypePush,299 +builtin_count,ArrayPrototypePush,302 builtin_count,CloneFastJSArray,171 builtin_count,CloneFastJSArrayFillingHoles,36 builtin_count,ExtractFastJSArray,179 @@ -5700,7 +5710,7 @@ builtin_count,ArrayPrototypeEntries,0 builtin_count,ArrayPrototypeKeys,0 builtin_count,ArrayPrototypeValues,29 -builtin_count,ArrayIteratorPrototypeNext,68 +builtin_count,ArrayIteratorPrototypeNext,69 builtin_count,AsyncFunctionEnter,0 builtin_count,AsyncFunctionResolve,0 builtin_count,AsyncFunctionAwait,4 @@ -5725,47 +5735,47 @@ builtin_count,CallIteratorWithFeedbackLazyDeoptContinuation,0 builtin_count,GlobalIsFinite,0 builtin_count,GlobalIsNaN,0 -builtin_count,LoadIC,4991 -builtin_count,LoadIC_Megamorphic,8676 +builtin_count,LoadIC,4986 +builtin_count,LoadIC_Megamorphic,8670 builtin_count,LoadIC_Noninlined,5 -builtin_count,LoadICTrampoline,302 -builtin_count,LoadICBaseline,4481 -builtin_count,LoadICTrampoline_Megamorphic,5303 +builtin_count,LoadICTrampoline,300 +builtin_count,LoadICBaseline,4478 +builtin_count,LoadICTrampoline_Megamorphic,5310 builtin_count,LoadSuperIC,4 builtin_count,LoadSuperICBaseline,4 -builtin_count,KeyedLoadIC,837 +builtin_count,KeyedLoadIC,825 builtin_count,EnumeratedKeyedLoadIC,6 builtin_count,KeyedLoadIC_Megamorphic,2116 builtin_count,KeyedLoadICTrampoline,1 -builtin_count,KeyedLoadICBaseline,781 +builtin_count,KeyedLoadICBaseline,768 builtin_count,EnumeratedKeyedLoadICBaseline,5 -builtin_count,KeyedLoadICTrampoline_Megamorphic,790 -builtin_count,StoreGlobalIC,120 +builtin_count,KeyedLoadICTrampoline_Megamorphic,799 +builtin_count,StoreGlobalIC,73 builtin_count,StoreGlobalICTrampoline,0 builtin_count,StoreGlobalICBaseline,5 -builtin_count,StoreIC,621 +builtin_count,StoreIC,609 builtin_count,StoreIC_Megamorphic,1137 builtin_count,StoreICTrampoline,20 -builtin_count,StoreICTrampoline_Megamorphic,553 -builtin_count,StoreICBaseline,567 +builtin_count,StoreICTrampoline_Megamorphic,555 +builtin_count,StoreICBaseline,555 builtin_count,DefineNamedOwnIC,68 builtin_count,DefineNamedOwnICBaseline,63 -builtin_count,KeyedStoreIC,442 +builtin_count,KeyedStoreIC,431 builtin_count,KeyedStoreICTrampoline,1 -builtin_count,KeyedStoreICTrampoline_Megamorphic,261 -builtin_count,KeyedStoreICBaseline,402 +builtin_count,KeyedStoreICTrampoline_Megamorphic,267 +builtin_count,KeyedStoreICBaseline,391 builtin_count,DefineKeyedOwnIC,2 -builtin_count,StoreInArrayLiteralIC,37 -builtin_count,StoreInArrayLiteralICBaseline,33 -builtin_count,LoadGlobalIC,835 +builtin_count,StoreInArrayLiteralIC,38 +builtin_count,StoreInArrayLiteralICBaseline,34 +builtin_count,LoadGlobalIC,831 builtin_count,LoadGlobalICInsideTypeof,1 -builtin_count,LoadGlobalICTrampoline,57 -builtin_count,LoadGlobalICBaseline,765 +builtin_count,LoadGlobalICTrampoline,59 +builtin_count,LoadGlobalICBaseline,758 builtin_count,LoadGlobalICInsideTypeofTrampoline,0 builtin_count,LoadGlobalICInsideTypeofBaseline,1 builtin_count,LookupGlobalICBaseline,1 builtin_count,LookupGlobalICInsideTypeofBaseline,0 -builtin_count,KeyedHasIC,633 +builtin_count,KeyedHasIC,634 builtin_count,KeyedHasICBaseline,5 builtin_count,KeyedHasIC_Megamorphic,632 builtin_count,IterableToList,0 @@ -5785,38 +5795,38 @@ builtin_count,MapPrototypeValues,0 builtin_count,MapIteratorPrototypeNext,8 builtin_count,MapIteratorToList,0 -builtin_count,Add_Baseline,496 -builtin_count,AddSmi_Baseline,486 -builtin_count,Subtract_Baseline,108 +builtin_count,Add_Baseline,493 +builtin_count,AddSmi_Baseline,479 +builtin_count,Subtract_Baseline,107 builtin_count,SubtractSmi_Baseline,64 -builtin_count,Multiply_Baseline,157 -builtin_count,MultiplySmi_Baseline,25 +builtin_count,Multiply_Baseline,158 +builtin_count,MultiplySmi_Baseline,24 builtin_count,Divide_Baseline,13 builtin_count,DivideSmi_Baseline,4 builtin_count,Modulus_Baseline,2 builtin_count,ModulusSmi_Baseline,4 builtin_count,Exponentiate_Baseline,0 -builtin_count,BitwiseAnd_Baseline,28 -builtin_count,BitwiseAndSmi_Baseline,110 -builtin_count,BitwiseOr_Baseline,54 -builtin_count,BitwiseOrSmi_Baseline,253 +builtin_count,BitwiseAnd_Baseline,27 +builtin_count,BitwiseAndSmi_Baseline,100 +builtin_count,BitwiseOr_Baseline,52 +builtin_count,BitwiseOrSmi_Baseline,247 builtin_count,BitwiseXor_Baseline,34 builtin_count,BitwiseXorSmi_Baseline,1 -builtin_count,ShiftLeft_Baseline,5 -builtin_count,ShiftLeftSmi_Baseline,68 -builtin_count,ShiftRight_Baseline,7 -builtin_count,ShiftRightSmi_Baseline,208 +builtin_count,ShiftLeft_Baseline,4 +builtin_count,ShiftLeftSmi_Baseline,66 +builtin_count,ShiftRight_Baseline,6 +builtin_count,ShiftRightSmi_Baseline,205 builtin_count,ShiftRightLogical_Baseline,1 builtin_count,ShiftRightLogicalSmi_Baseline,15 -builtin_count,Equal_Baseline,293 -builtin_count,StrictEqual_Baseline,432 -builtin_count,LessThan_Baseline,422 +builtin_count,Equal_Baseline,288 +builtin_count,StrictEqual_Baseline,431 +builtin_count,LessThan_Baseline,411 builtin_count,GreaterThan_Baseline,145 builtin_count,LessThanOrEqual_Baseline,54 -builtin_count,GreaterThanOrEqual_Baseline,103 +builtin_count,GreaterThanOrEqual_Baseline,102 builtin_count,BitwiseNot_Baseline,5 -builtin_count,Decrement_Baseline,52 -builtin_count,Increment_Baseline,286 +builtin_count,Decrement_Baseline,47 +builtin_count,Increment_Baseline,278 builtin_count,Negate_Baseline,11 builtin_count,ObjectAssign,1 builtin_count,ObjectCreate,3 @@ -5828,7 +5838,7 @@ builtin_count,ObjectPrototypeHasOwnProperty,211 builtin_count,ObjectToString,55 builtin_count,InstanceOf,10 -builtin_count,InstanceOf_Baseline,71 +builtin_count,InstanceOf_Baseline,72 builtin_count,ForInEnumerate,52 builtin_count,ForInPrepare,1 builtin_count,ForInFilter,195 @@ -5846,7 +5856,7 @@ builtin_count,SetPrototypeValues,2 builtin_count,SetIteratorPrototypeNext,40 builtin_count,SetOrSetIteratorToList,0 -builtin_count,StringFromCharCode,26 +builtin_count,StringFromCharCode,25 builtin_count,StringPrototypeReplace,216 builtin_count,StringPrototypeSplit,47 builtin_count,TypedArrayConstructor,2 @@ -5872,7 +5882,7 @@ builtin_count,AsyncGeneratorYieldWithAwaitResolveClosure,7 builtin_count,StringAdd_CheckNone,10000 builtin_count,SubString,1468 -builtin_count,GetProperty,672 +builtin_count,GetProperty,673 builtin_count,GetPropertyWithReceiver,15 builtin_count,SetProperty,0 builtin_count,CreateDataProperty,1 @@ -5923,12 +5933,12 @@ builtin_count,StringPrototypeConcat,0 builtin_count,StringConstructor,29 builtin_count,StringAddConvertLeft,15 -builtin_count,StringAddConvertRight,175 +builtin_count,StringAddConvertRight,174 builtin_count,StringCharAt,8 builtin_count,FastNewClosureBaseline,76 -builtin_count,FastNewFunctionContextFunction,80 -builtin_count,CreateRegExpLiteral,33 -builtin_count,CreateShallowArrayLiteral,17 +builtin_count,FastNewFunctionContextFunction,81 +builtin_count,CreateRegExpLiteral,34 +builtin_count,CreateShallowArrayLiteral,18 builtin_count,CreateEmptyArrayLiteral,25 builtin_count,CreateShallowObjectLiteral,27 builtin_count,ObjectConstructor,21 @@ -5940,7 +5950,7 @@ builtin_count,ToNumeric,14 builtin_count,NumberToString,1330 builtin_count,ToBoolean,25 -builtin_count,ToBooleanForBaselineJump,951 +builtin_count,ToBooleanForBaselineJump,960 builtin_count,ToLength,2 builtin_count,ToName,41 builtin_count,ToObject,216 @@ -5954,7 +5964,7 @@ builtin_count,DataViewPrototypeGetFloat64,0 builtin_count,DataViewPrototypeSetUint32,0 builtin_count,DataViewPrototypeSetFloat64,0 -builtin_count,FunctionPrototypeHasInstance,83 +builtin_count,FunctionPrototypeHasInstance,85 builtin_count,FastFunctionPrototypeBind,2 builtin_count,ForInNext,6 builtin_count,GetIteratorWithFeedback,0 @@ -5986,7 +5996,7 @@ builtin_count,NumberParseFloat,10 builtin_count,ParseInt,118 builtin_count,NumberParseInt,5 -builtin_count,Add,12 +builtin_count,Add,11 builtin_count,Subtract,0 builtin_count,Multiply,0 builtin_count,Divide,0 @@ -6053,7 +6063,7 @@ builtin_count,StringPrototypeSlice,9 builtin_count,StringPrototypeStartsWith,0 builtin_count,StringPrototypeSubstr,0 -builtin_count,StringPrototypeSubstring,2 +builtin_count,StringPrototypeSubstring,1 builtin_count,StringPrototypeTrim,1 builtin_count,SymbolPrototypeToString,2 builtin_count,CreateTypedArray,55 @@ -6096,31 +6106,31 @@ builtin_count,CanUseSameAccessor_FastObjectElements_0,33 builtin_count,StringPrototypeToLowerCaseIntl,1 builtin_count,StringToLowerCaseIntl,128 -builtin_count,WideHandler,64 +builtin_count,WideHandler,65 builtin_count,ExtraWideHandler,16 -builtin_count,LdarHandler,210 -builtin_count,LdaZeroHandler,22 -builtin_count,LdaSmiHandler,23 +builtin_count,LdarHandler,213 +builtin_count,LdaZeroHandler,23 +builtin_count,LdaSmiHandler,24 builtin_count,LdaUndefinedHandler,12 -builtin_count,LdaNullHandler,1 +builtin_count,LdaNullHandler,2 builtin_count,LdaTheHoleHandler,0 builtin_count,LdaTrueHandler,3 builtin_count,LdaFalseHandler,5 -builtin_count,LdaConstantHandler,20 +builtin_count,LdaConstantHandler,21 builtin_count,LdaContextSlotHandler,1 builtin_count,LdaImmutableContextSlotHandler,9 -builtin_count,LdaCurrentContextSlotHandler,17 +builtin_count,LdaCurrentContextSlotHandler,18 builtin_count,LdaImmutableCurrentContextSlotHandler,30 builtin_count,StarHandler,30 -builtin_count,MovHandler,37 +builtin_count,MovHandler,39 builtin_count,PushContextHandler,2 builtin_count,PopContextHandler,0 builtin_count,TestReferenceEqualHandler,1 -builtin_count,TestUndetectableHandler,1 +builtin_count,TestUndetectableHandler,2 builtin_count,TestNullHandler,0 builtin_count,TestUndefinedHandler,0 builtin_count,TestTypeOfHandler,1 -builtin_count,LdaGlobalHandler,48 +builtin_count,LdaGlobalHandler,50 builtin_count,LdaGlobalInsideTypeofHandler,0 builtin_count,StaGlobalHandler,2 builtin_count,StaContextSlotHandler,0 @@ -6130,17 +6140,17 @@ builtin_count,LdaLookupGlobalSlotHandler,1 builtin_count,LdaLookupGlobalSlotInsideTypeofHandler,0 builtin_count,StaLookupSlotHandler,0 -builtin_count,GetNamedPropertyHandler,143 +builtin_count,GetNamedPropertyHandler,145 builtin_count,GetNamedPropertyFromSuperHandler,0 builtin_count,GetKeyedPropertyHandler,54 builtin_count,GetEnumeratedKeyedPropertyHandler,1 -builtin_count,SetNamedPropertyHandler,16 +builtin_count,SetNamedPropertyHandler,17 builtin_count,DefineNamedOwnPropertyHandler,3 -builtin_count,SetKeyedPropertyHandler,37 +builtin_count,SetKeyedPropertyHandler,38 builtin_count,DefineKeyedOwnPropertyHandler,0 builtin_count,StaInArrayLiteralHandler,3 builtin_count,DefineKeyedOwnPropertyInLiteralHandler,0 -builtin_count,AddHandler,32 +builtin_count,AddHandler,33 builtin_count,SubHandler,6 builtin_count,MulHandler,15 builtin_count,DivHandler,1 @@ -6153,7 +6163,7 @@ builtin_count,ShiftRightHandler,0 builtin_count,ShiftRightLogicalHandler,0 builtin_count,AddSmiHandler,11 -builtin_count,SubSmiHandler,2 +builtin_count,SubSmiHandler,3 builtin_count,MulSmiHandler,5 builtin_count,DivSmiHandler,3 builtin_count,ModSmiHandler,1 @@ -6162,8 +6172,8 @@ builtin_count,BitwiseAndSmiHandler,2 builtin_count,ShiftLeftSmiHandler,4 builtin_count,ShiftRightSmiHandler,7 -builtin_count,ShiftRightLogicalSmiHandler,0 -builtin_count,IncHandler,40 +builtin_count,ShiftRightLogicalSmiHandler,1 +builtin_count,IncHandler,41 builtin_count,DecHandler,7 builtin_count,NegateHandler,0 builtin_count,BitwiseNotHandler,0 @@ -6174,22 +6184,22 @@ builtin_count,DeletePropertySloppyHandler,0 builtin_count,FindNonDefaultConstructorOrConstructHandler,0 builtin_count,CallAnyReceiverHandler,0 -builtin_count,CallPropertyHandler,3 +builtin_count,CallPropertyHandler,4 builtin_count,CallProperty0Handler,12 -builtin_count,CallProperty1Handler,26 +builtin_count,CallProperty1Handler,27 builtin_count,CallProperty2Handler,6 builtin_count,CallUndefinedReceiverHandler,1 -builtin_count,CallUndefinedReceiver0Handler,10 +builtin_count,CallUndefinedReceiver0Handler,9 builtin_count,CallUndefinedReceiver1Handler,7 builtin_count,CallUndefinedReceiver2Handler,6 builtin_count,CallWithSpreadHandler,0 builtin_count,CallRuntimeHandler,0 builtin_count,CallJSRuntimeHandler,0 builtin_count,InvokeIntrinsicHandler,1 -builtin_count,ConstructHandler,5 +builtin_count,ConstructHandler,6 builtin_count,ConstructWithSpreadHandler,0 builtin_count,ConstructForwardAllArgsHandler,0 -builtin_count,TestEqualHandler,11 +builtin_count,TestEqualHandler,12 builtin_count,TestEqualStrictHandler,10 builtin_count,TestLessThanHandler,34 builtin_count,TestGreaterThanHandler,4 @@ -6217,7 +6227,7 @@ builtin_count,CreateUnmappedArgumentsHandler,0 builtin_count,CreateRestParameterHandler,0 builtin_count,JumpLoopHandler,46 -builtin_count,JumpHandler,7 +builtin_count,JumpHandler,8 builtin_count,JumpConstantHandler,0 builtin_count,JumpIfUndefinedConstantHandler,0 builtin_count,JumpIfNotUndefinedConstantHandler,0 @@ -6230,7 +6240,7 @@ builtin_count,JumpIfToBooleanTrueHandler,11 builtin_count,JumpIfToBooleanFalseHandler,26 builtin_count,JumpIfTrueHandler,11 -builtin_count,JumpIfFalseHandler,59 +builtin_count,JumpIfFalseHandler,60 builtin_count,JumpIfNullHandler,0 builtin_count,JumpIfNotNullHandler,0 builtin_count,JumpIfUndefinedHandler,1 @@ -6246,7 +6256,7 @@ builtin_count,SetPendingMessageHandler,0 builtin_count,ThrowHandler,2 builtin_count,ReThrowHandler,0 -builtin_count,ReturnHandler,37 +builtin_count,ReturnHandler,38 builtin_count,ThrowReferenceErrorIfHoleHandler,1 builtin_count,ThrowSuperNotCalledIfHoleHandler,0 builtin_count,ThrowSuperAlreadyCalledIfNotHoleHandler,0 @@ -6255,7 +6265,7 @@ builtin_count,SuspendGeneratorHandler,0 builtin_count,ResumeGeneratorHandler,0 builtin_count,GetIteratorHandler,0 -builtin_count,ShortStarHandler,105 +builtin_count,ShortStarHandler,106 builtin_count,LdarWideHandler,0 builtin_count,LdaSmiWideHandler,11 builtin_count,LdaConstantWideHandler,1 @@ -6353,20 +6363,20 @@ builtin_count,CallUndefinedReceiverExtraWideHandler,0 builtin_count,CallUndefinedReceiver1ExtraWideHandler,4 builtin_count,CallUndefinedReceiver2ExtraWideHandler,0 -block_count,RecordWriteSaveFP,0,2761 -block_count,RecordWriteSaveFP,1,2685 +block_count,RecordWriteSaveFP,0,2758 +block_count,RecordWriteSaveFP,1,2640 block_count,RecordWriteSaveFP,2,0 -block_count,RecordWriteSaveFP,3,2685 -block_count,RecordWriteSaveFP,4,2685 -block_count,RecordWriteSaveFP,5,2681 -block_count,RecordWriteSaveFP,6,3 +block_count,RecordWriteSaveFP,3,2640 +block_count,RecordWriteSaveFP,4,2640 +block_count,RecordWriteSaveFP,5,2637 +block_count,RecordWriteSaveFP,6,2 block_count,RecordWriteSaveFP,7,0 -block_count,RecordWriteSaveFP,8,3 -block_count,RecordWriteSaveFP,9,2685 -block_count,RecordWriteSaveFP,10,75 -block_count,RecordWriteSaveFP,11,48 -block_count,RecordWriteSaveFP,12,44 -block_count,RecordWriteSaveFP,13,44 +block_count,RecordWriteSaveFP,8,2 +block_count,RecordWriteSaveFP,9,2640 +block_count,RecordWriteSaveFP,10,117 +block_count,RecordWriteSaveFP,11,79 +block_count,RecordWriteSaveFP,12,75 +block_count,RecordWriteSaveFP,13,75 block_count,RecordWriteSaveFP,14,0 block_count,RecordWriteSaveFP,15,3 block_count,RecordWriteSaveFP,16,3 @@ -6374,9 +6384,9 @@ block_count,RecordWriteSaveFP,18,0 block_count,RecordWriteSaveFP,19,0 block_count,RecordWriteSaveFP,20,0 -block_count,RecordWriteSaveFP,21,27 -block_count,RecordWriteSaveFP,22,75 -block_count,RecordWriteSaveFP,23,75 +block_count,RecordWriteSaveFP,21,37 +block_count,RecordWriteSaveFP,22,117 +block_count,RecordWriteSaveFP,23,117 block_count,RecordWriteSaveFP,24,0 block_count,RecordWriteSaveFP,25,0 block_count,RecordWriteSaveFP,26,0 @@ -6393,22 +6403,22 @@ block_count,RecordWriteSaveFP,37,0 block_count,RecordWriteSaveFP,38,0 block_count,RecordWriteSaveFP,39,0 -block_count,RecordWriteSaveFP,40,75 -block_count,RecordWriteSaveFP,41,75 -block_count,RecordWriteSaveFP,42,70 -block_count,RecordWriteSaveFP,43,70 +block_count,RecordWriteSaveFP,40,117 +block_count,RecordWriteSaveFP,41,117 +block_count,RecordWriteSaveFP,42,113 +block_count,RecordWriteSaveFP,43,113 block_count,RecordWriteSaveFP,44,0 block_count,RecordWriteSaveFP,45,0 block_count,RecordWriteSaveFP,46,0 -block_count,RecordWriteSaveFP,47,5 -block_count,RecordWriteSaveFP,48,5 +block_count,RecordWriteSaveFP,47,4 +block_count,RecordWriteSaveFP,48,4 block_count,RecordWriteSaveFP,49,0 block_count,RecordWriteSaveFP,50,0 block_count,RecordWriteSaveFP,51,0 block_count,RecordWriteSaveFP,52,0 block_count,RecordWriteSaveFP,53,0 -block_count,RecordWriteSaveFP,54,75 -block_count,RecordWriteIgnoreFP,0,4 +block_count,RecordWriteSaveFP,54,117 +block_count,RecordWriteIgnoreFP,0,3 block_count,RecordWriteIgnoreFP,1,3 block_count,RecordWriteIgnoreFP,2,0 block_count,RecordWriteIgnoreFP,3,3 @@ -6477,9 +6487,9 @@ block_count,AdaptorWithBuiltinExitFrame3,1,6 block_count,AdaptorWithBuiltinExitFrame3,2,1 block_count,AdaptorWithBuiltinExitFrame3,3,7 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,0,331 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,331 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,2,76 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,0,333 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,333 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,2,77 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,3,66 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,4,66 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,5,66 @@ -6512,7 +6522,7 @@ block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,32,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,33,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,34,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,35,65 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,35,66 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,36,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,37,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,38,0 @@ -6545,10 +6555,10 @@ block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,65,10 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,66,255 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,67,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,68,331 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,0,1252 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1,1252 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,2,76 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,68,333 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,0,1254 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1,1254 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,2,74 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,3,28 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,4,27 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,5,27 @@ -6611,10 +6621,10 @@ block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,62,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,63,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,64,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,65,48 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,66,1176 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,65,46 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,66,1179 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,67,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,68,1252 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,68,1254 block_count,Call_ReceiverIsAny_Baseline_Compact,0,4 block_count,Call_ReceiverIsAny_Baseline_Compact,1,4 block_count,Call_ReceiverIsAny_Baseline_Compact,2,0 @@ -6788,8 +6798,8 @@ block_count,CallWithSpread,62,0 block_count,CallWithSpread,63,0 block_count,CallWithSpread,64,12 -block_count,CallWithSpread_Baseline,0,1 -block_count,CallWithSpread_Baseline,1,1 +block_count,CallWithSpread_Baseline,0,2 +block_count,CallWithSpread_Baseline,1,2 block_count,CallWithSpread_Baseline,2,0 block_count,CallWithSpread_Baseline,3,0 block_count,CallWithSpread_Baseline,4,0 @@ -6856,22 +6866,22 @@ block_count,CallWithSpread_Baseline,65,0 block_count,CallWithSpread_Baseline,66,1 block_count,CallWithSpread_Baseline,67,0 -block_count,CallWithSpread_Baseline,68,1 -block_count,CallWithSpread_Baseline,69,1 +block_count,CallWithSpread_Baseline,68,2 +block_count,CallWithSpread_Baseline,69,2 block_count,CallWithSpread_Baseline,70,0 -block_count,CallWithSpread_Baseline,71,1 +block_count,CallWithSpread_Baseline,71,2 block_count,CallWithSpread_Baseline,72,0 -block_count,CallWithSpread_Baseline,73,1 +block_count,CallWithSpread_Baseline,73,2 block_count,CallWithSpread_Baseline,74,0 -block_count,CallWithSpread_Baseline,75,1 -block_count,CallWithSpread_Baseline,76,1 -block_count,CallWithSpread_Baseline,77,1 +block_count,CallWithSpread_Baseline,75,2 +block_count,CallWithSpread_Baseline,76,2 +block_count,CallWithSpread_Baseline,77,2 block_count,CallWithSpread_Baseline,78,0 block_count,CallWithSpread_Baseline,79,0 block_count,CallWithSpread_Baseline,80,0 block_count,CallWithSpread_Baseline,81,0 block_count,CallWithSpread_Baseline,82,0 -block_count,CallWithSpread_Baseline,83,1 +block_count,CallWithSpread_Baseline,83,2 block_count,CallWithSpread_Baseline,84,0 block_count,CallWithSpread_Baseline,85,0 block_count,CallWithSpread_Baseline,86,0 @@ -6920,7 +6930,7 @@ block_count,CallWithSpread_Baseline,129,0 block_count,CallWithSpread_Baseline,130,0 block_count,CallWithSpread_Baseline,131,0 -block_count,CallWithSpread_Baseline,132,1 +block_count,CallWithSpread_Baseline,132,2 block_count,CallWithArrayLike,0,31 block_count,CallWithArrayLike,1,31 block_count,CallWithArrayLike,2,0 @@ -7243,7 +7253,7 @@ block_count,ConstructForwardAllArgs_Baseline,41,0 block_count,ConstructForwardAllArgs_Baseline,42,0 block_count,ConstructForwardAllArgs_Baseline,43,1 -block_count,Construct_Baseline,0,107 +block_count,Construct_Baseline,0,108 block_count,Construct_Baseline,1,6 block_count,Construct_Baseline,2,3 block_count,Construct_Baseline,3,3 @@ -7286,15 +7296,15 @@ block_count,Construct_Baseline,40,0 block_count,Construct_Baseline,41,3 block_count,Construct_Baseline,42,3 -block_count,Construct_Baseline,43,100 +block_count,Construct_Baseline,43,101 block_count,Construct_Baseline,44,104 -block_count,FastNewObject,0,340 +block_count,FastNewObject,0,328 block_count,FastNewObject,1,0 -block_count,FastNewObject,2,340 -block_count,FastNewObject,3,340 -block_count,FastNewObject,4,337 -block_count,FastNewObject,5,337 -block_count,FastNewObject,6,337 +block_count,FastNewObject,2,328 +block_count,FastNewObject,3,328 +block_count,FastNewObject,4,325 +block_count,FastNewObject,5,325 +block_count,FastNewObject,6,325 block_count,FastNewObject,7,0 block_count,FastNewObject,8,0 block_count,FastNewObject,9,0 @@ -7320,25 +7330,25 @@ block_count,FastNewObject,29,0 block_count,FastNewObject,30,0 block_count,FastNewObject,31,0 -block_count,FastNewObject,32,337 -block_count,FastNewObject,33,337 +block_count,FastNewObject,32,325 +block_count,FastNewObject,33,325 block_count,FastNewObject,34,0 -block_count,FastNewObject,35,337 +block_count,FastNewObject,35,325 block_count,FastNewObject,36,0 block_count,FastNewObject,37,0 -block_count,FastNewObject,38,337 -block_count,FastNewObject,39,337 +block_count,FastNewObject,38,325 +block_count,FastNewObject,39,325 block_count,FastNewObject,40,1 -block_count,FastNewObject,41,335 +block_count,FastNewObject,41,324 block_count,FastNewObject,42,39 -block_count,FastNewObject,43,296 -block_count,FastNewObject,44,518 -block_count,FastNewObject,45,221 -block_count,FastNewObject,46,296 -block_count,FastNewObject,47,335 -block_count,FastNewObject,48,242 -block_count,FastNewObject,49,93 -block_count,FastNewObject,50,337 +block_count,FastNewObject,43,284 +block_count,FastNewObject,44,476 +block_count,FastNewObject,45,191 +block_count,FastNewObject,46,284 +block_count,FastNewObject,47,324 +block_count,FastNewObject,48,238 +block_count,FastNewObject,49,85 +block_count,FastNewObject,50,325 block_count,FastNewObject,51,0 block_count,FastNewObject,52,0 block_count,FastNewObject,53,0 @@ -7369,7 +7379,7 @@ block_count,FastNewObject,78,0 block_count,FastNewObject,79,2 block_count,FastNewClosure,0,85 -block_count,FastNewClosure,1,80 +block_count,FastNewClosure,1,81 block_count,FastNewClosure,2,80 block_count,FastNewClosure,3,0 block_count,FastNewClosure,4,4 @@ -7382,7 +7392,7 @@ block_count,FastNewClosure,11,0 block_count,FastNewClosure,12,0 block_count,FastNewClosure,13,85 -block_count,FastNewClosure,14,25 +block_count,FastNewClosure,14,26 block_count,FastNewClosure,15,59 block_count,FastNewClosure,16,59 block_count,FastNewClosure,17,0 @@ -7393,10 +7403,10 @@ block_count,FastNewClosure,22,0 block_count,FastNewClosure,23,59 block_count,FastNewClosure,24,85 -block_count,FastNewClosure,25,25 +block_count,FastNewClosure,25,26 block_count,FastNewClosure,26,59 block_count,StringEqual,0,674 -block_count,StringEqual,1,686 +block_count,StringEqual,1,687 block_count,StringEqual,2,264 block_count,StringEqual,3,15 block_count,StringEqual,4,13 @@ -8036,8 +8046,8 @@ block_count,OrderedHashTableHealIndex,8,0 block_count,OrderedHashTableHealIndex,9,0 block_count,OrderedHashTableHealIndex,10,0 -block_count,CompileLazy,0,221 -block_count,CompileLazy,1,221 +block_count,CompileLazy,0,222 +block_count,CompileLazy,1,222 block_count,CompileLazy,2,0 block_count,CompileLazy,3,4 block_count,CompileLazy,4,217 @@ -8061,7 +8071,7 @@ block_count,CompileLazy,22,0 block_count,CompileLazy,23,0 block_count,CompileLazy,24,221 -block_count,CompileLazy,25,220 +block_count,CompileLazy,25,221 block_count,CompileLazy,26,220 block_count,CompileLazy,27,27 block_count,CompileLazy,28,193 @@ -8199,16 +8209,16 @@ block_count,GrowFastSmiOrObjectElements,11,305 block_count,GrowFastSmiOrObjectElements,12,0 block_count,GrowFastSmiOrObjectElements,13,305 -block_count,GrowFastSmiOrObjectElements,14,4038 -block_count,GrowFastSmiOrObjectElements,15,3732 +block_count,GrowFastSmiOrObjectElements,14,4037 +block_count,GrowFastSmiOrObjectElements,15,3731 block_count,GrowFastSmiOrObjectElements,16,305 block_count,GrowFastSmiOrObjectElements,17,305 block_count,GrowFastSmiOrObjectElements,18,15 block_count,GrowFastSmiOrObjectElements,19,290 block_count,GrowFastSmiOrObjectElements,20,305 block_count,GrowFastSmiOrObjectElements,21,40 -block_count,GrowFastSmiOrObjectElements,22,6229 -block_count,GrowFastSmiOrObjectElements,23,6189 +block_count,GrowFastSmiOrObjectElements,22,6227 +block_count,GrowFastSmiOrObjectElements,23,6186 block_count,GrowFastSmiOrObjectElements,24,40 block_count,GrowFastSmiOrObjectElements,25,265 block_count,GrowFastSmiOrObjectElements,26,0 @@ -8261,7 +8271,7 @@ block_count,ToNumber_Baseline,22,0 block_count,ToNumber_Baseline,23,0 block_count,ToNumber_Baseline,24,0 -block_count,ToNumeric_Baseline,0,82 +block_count,ToNumeric_Baseline,0,78 block_count,ToNumeric_Baseline,1,0 block_count,ToNumeric_Baseline,2,0 block_count,ToNumeric_Baseline,3,0 @@ -8289,10 +8299,10 @@ block_count,ToNumeric_Baseline,25,0 block_count,ToNumeric_Baseline,26,0 block_count,ToNumeric_Baseline,27,0 -block_count,ToNumeric_Baseline,28,82 -block_count,ToNumeric_Baseline,29,82 +block_count,ToNumeric_Baseline,28,77 +block_count,ToNumeric_Baseline,29,78 block_count,ToNumeric_Baseline,30,0 -block_count,ToNumeric_Baseline,31,82 +block_count,ToNumeric_Baseline,31,78 block_count,ToNumberConvertBigInt,0,2 block_count,ToNumberConvertBigInt,1,2 block_count,ToNumberConvertBigInt,2,0 @@ -8877,14 +8887,14 @@ block_count,KeyedStoreIC_Megamorphic,176,10 block_count,KeyedStoreIC_Megamorphic,177,0 block_count,KeyedStoreIC_Megamorphic,178,10 -block_count,KeyedStoreIC_Megamorphic,179,87 -block_count,KeyedStoreIC_Megamorphic,180,87 +block_count,KeyedStoreIC_Megamorphic,179,86 +block_count,KeyedStoreIC_Megamorphic,180,86 block_count,KeyedStoreIC_Megamorphic,181,0 -block_count,KeyedStoreIC_Megamorphic,182,87 +block_count,KeyedStoreIC_Megamorphic,182,86 block_count,KeyedStoreIC_Megamorphic,183,38 block_count,KeyedStoreIC_Megamorphic,184,48 -block_count,KeyedStoreIC_Megamorphic,185,87 -block_count,KeyedStoreIC_Megamorphic,186,77 +block_count,KeyedStoreIC_Megamorphic,185,86 +block_count,KeyedStoreIC_Megamorphic,186,76 block_count,KeyedStoreIC_Megamorphic,187,10 block_count,KeyedStoreIC_Megamorphic,188,10 block_count,KeyedStoreIC_Megamorphic,189,10 @@ -8948,7 +8958,7 @@ block_count,KeyedStoreIC_Megamorphic,247,7 block_count,KeyedStoreIC_Megamorphic,248,0 block_count,KeyedStoreIC_Megamorphic,249,7 -block_count,KeyedStoreIC_Megamorphic,250,41 +block_count,KeyedStoreIC_Megamorphic,250,40 block_count,KeyedStoreIC_Megamorphic,251,0 block_count,KeyedStoreIC_Megamorphic,252,0 block_count,KeyedStoreIC_Megamorphic,253,0 @@ -9387,7 +9397,7 @@ block_count,KeyedStoreIC_Megamorphic,686,0 block_count,KeyedStoreIC_Megamorphic,687,68 block_count,KeyedStoreIC_Megamorphic,688,68 -block_count,KeyedStoreIC_Megamorphic,689,133 +block_count,KeyedStoreIC_Megamorphic,689,134 block_count,KeyedStoreIC_Megamorphic,690,75 block_count,KeyedStoreIC_Megamorphic,691,65 block_count,KeyedStoreIC_Megamorphic,692,9 @@ -12411,26 +12421,26 @@ block_count,KeyedLoadIC_SloppyArguments,20,0 block_count,KeyedLoadIC_SloppyArguments,21,0 block_count,KeyedLoadIC_SloppyArguments,22,0 -block_count,StoreFastElementIC_InBounds,0,411 +block_count,StoreFastElementIC_InBounds,0,400 block_count,StoreFastElementIC_InBounds,1,0 -block_count,StoreFastElementIC_InBounds,2,11 -block_count,StoreFastElementIC_InBounds,3,11 +block_count,StoreFastElementIC_InBounds,2,10 +block_count,StoreFastElementIC_InBounds,3,10 block_count,StoreFastElementIC_InBounds,4,0 block_count,StoreFastElementIC_InBounds,5,0 block_count,StoreFastElementIC_InBounds,6,0 block_count,StoreFastElementIC_InBounds,7,0 block_count,StoreFastElementIC_InBounds,8,0 -block_count,StoreFastElementIC_InBounds,9,11 -block_count,StoreFastElementIC_InBounds,10,11 +block_count,StoreFastElementIC_InBounds,9,10 +block_count,StoreFastElementIC_InBounds,10,10 block_count,StoreFastElementIC_InBounds,11,0 -block_count,StoreFastElementIC_InBounds,12,11 +block_count,StoreFastElementIC_InBounds,12,10 block_count,StoreFastElementIC_InBounds,13,0 -block_count,StoreFastElementIC_InBounds,14,11 -block_count,StoreFastElementIC_InBounds,15,11 +block_count,StoreFastElementIC_InBounds,14,10 +block_count,StoreFastElementIC_InBounds,15,10 block_count,StoreFastElementIC_InBounds,16,0 -block_count,StoreFastElementIC_InBounds,17,11 +block_count,StoreFastElementIC_InBounds,17,10 block_count,StoreFastElementIC_InBounds,18,0 -block_count,StoreFastElementIC_InBounds,19,11 +block_count,StoreFastElementIC_InBounds,19,10 block_count,StoreFastElementIC_InBounds,20,0 block_count,StoreFastElementIC_InBounds,21,12 block_count,StoreFastElementIC_InBounds,22,12 @@ -12451,22 +12461,22 @@ block_count,StoreFastElementIC_InBounds,37,0 block_count,StoreFastElementIC_InBounds,38,12 block_count,StoreFastElementIC_InBounds,39,0 -block_count,StoreFastElementIC_InBounds,40,22 -block_count,StoreFastElementIC_InBounds,41,22 +block_count,StoreFastElementIC_InBounds,40,23 +block_count,StoreFastElementIC_InBounds,41,23 block_count,StoreFastElementIC_InBounds,42,0 block_count,StoreFastElementIC_InBounds,43,0 block_count,StoreFastElementIC_InBounds,44,0 block_count,StoreFastElementIC_InBounds,45,0 block_count,StoreFastElementIC_InBounds,46,0 -block_count,StoreFastElementIC_InBounds,47,22 -block_count,StoreFastElementIC_InBounds,48,22 +block_count,StoreFastElementIC_InBounds,47,23 +block_count,StoreFastElementIC_InBounds,48,23 block_count,StoreFastElementIC_InBounds,49,0 -block_count,StoreFastElementIC_InBounds,50,22 -block_count,StoreFastElementIC_InBounds,51,22 +block_count,StoreFastElementIC_InBounds,50,23 +block_count,StoreFastElementIC_InBounds,51,23 block_count,StoreFastElementIC_InBounds,52,0 -block_count,StoreFastElementIC_InBounds,53,22 +block_count,StoreFastElementIC_InBounds,53,23 block_count,StoreFastElementIC_InBounds,54,0 -block_count,StoreFastElementIC_InBounds,55,22 +block_count,StoreFastElementIC_InBounds,55,23 block_count,StoreFastElementIC_InBounds,56,0 block_count,StoreFastElementIC_InBounds,57,0 block_count,StoreFastElementIC_InBounds,58,0 @@ -12629,26 +12639,26 @@ block_count,StoreFastElementIC_InBounds,215,17 block_count,StoreFastElementIC_InBounds,216,0 block_count,StoreFastElementIC_InBounds,217,17 -block_count,StoreFastElementIC_InBounds,218,68 +block_count,StoreFastElementIC_InBounds,218,62 block_count,StoreFastElementIC_InBounds,219,0 block_count,StoreFastElementIC_InBounds,220,0 block_count,StoreFastElementIC_InBounds,221,0 block_count,StoreFastElementIC_InBounds,222,0 block_count,StoreFastElementIC_InBounds,223,0 -block_count,StoreFastElementIC_InBounds,224,68 -block_count,StoreFastElementIC_InBounds,225,68 -block_count,StoreFastElementIC_InBounds,226,68 +block_count,StoreFastElementIC_InBounds,224,62 +block_count,StoreFastElementIC_InBounds,225,62 +block_count,StoreFastElementIC_InBounds,226,62 block_count,StoreFastElementIC_InBounds,227,0 block_count,StoreFastElementIC_InBounds,228,0 block_count,StoreFastElementIC_InBounds,229,0 block_count,StoreFastElementIC_InBounds,230,0 block_count,StoreFastElementIC_InBounds,231,0 block_count,StoreFastElementIC_InBounds,232,0 -block_count,StoreFastElementIC_InBounds,233,68 -block_count,StoreFastElementIC_InBounds,234,68 -block_count,StoreFastElementIC_InBounds,235,68 +block_count,StoreFastElementIC_InBounds,233,62 +block_count,StoreFastElementIC_InBounds,234,62 +block_count,StoreFastElementIC_InBounds,235,62 block_count,StoreFastElementIC_InBounds,236,0 -block_count,StoreFastElementIC_InBounds,237,68 +block_count,StoreFastElementIC_InBounds,237,62 block_count,StoreFastElementIC_InBounds,238,0 block_count,StoreFastElementIC_InBounds,239,0 block_count,StoreFastElementIC_InBounds,240,17 @@ -12726,12 +12736,12 @@ block_count,StoreFastElementIC_InBounds,312,3 block_count,StoreFastElementIC_InBounds,313,3 block_count,StoreFastElementIC_InBounds,314,3 -block_count,StoreFastElementIC_InBounds,315,1 -block_count,StoreFastElementIC_InBounds,316,1 +block_count,StoreFastElementIC_InBounds,315,0 +block_count,StoreFastElementIC_InBounds,316,0 block_count,StoreFastElementIC_InBounds,317,0 block_count,StoreFastElementIC_InBounds,318,0 block_count,StoreFastElementIC_InBounds,319,0 -block_count,StoreFastElementIC_InBounds,320,1 +block_count,StoreFastElementIC_InBounds,320,0 block_count,StoreFastElementIC_InBounds,321,2 block_count,StoreFastElementIC_InBounds,322,3 block_count,StoreFastElementIC_InBounds,323,3 @@ -12745,26 +12755,26 @@ block_count,StoreFastElementIC_InBounds,331,0 block_count,StoreFastElementIC_InBounds,332,0 block_count,StoreFastElementIC_InBounds,333,0 -block_count,StoreFastElementIC_InBounds,334,171 +block_count,StoreFastElementIC_InBounds,334,169 block_count,StoreFastElementIC_InBounds,335,0 block_count,StoreFastElementIC_InBounds,336,0 block_count,StoreFastElementIC_InBounds,337,0 block_count,StoreFastElementIC_InBounds,338,0 block_count,StoreFastElementIC_InBounds,339,0 -block_count,StoreFastElementIC_InBounds,340,171 -block_count,StoreFastElementIC_InBounds,341,171 -block_count,StoreFastElementIC_InBounds,342,171 +block_count,StoreFastElementIC_InBounds,340,169 +block_count,StoreFastElementIC_InBounds,341,169 +block_count,StoreFastElementIC_InBounds,342,169 block_count,StoreFastElementIC_InBounds,343,4 block_count,StoreFastElementIC_InBounds,344,4 block_count,StoreFastElementIC_InBounds,345,0 block_count,StoreFastElementIC_InBounds,346,0 block_count,StoreFastElementIC_InBounds,347,0 block_count,StoreFastElementIC_InBounds,348,4 -block_count,StoreFastElementIC_InBounds,349,167 -block_count,StoreFastElementIC_InBounds,350,171 -block_count,StoreFastElementIC_InBounds,351,171 +block_count,StoreFastElementIC_InBounds,349,164 +block_count,StoreFastElementIC_InBounds,350,169 +block_count,StoreFastElementIC_InBounds,351,169 block_count,StoreFastElementIC_InBounds,352,0 -block_count,StoreFastElementIC_InBounds,353,171 +block_count,StoreFastElementIC_InBounds,353,169 block_count,StoreFastElementIC_InBounds,354,0 block_count,StoreFastElementIC_InBounds,355,0 block_count,StoreFastElementIC_InBounds,356,0 @@ -12821,26 +12831,26 @@ block_count,StoreFastElementIC_InBounds,407,0 block_count,StoreFastElementIC_InBounds,408,0 block_count,StoreFastElementIC_InBounds,409,0 -block_count,StoreFastElementIC_InBounds,410,48 +block_count,StoreFastElementIC_InBounds,410,45 block_count,StoreFastElementIC_InBounds,411,0 block_count,StoreFastElementIC_InBounds,412,0 block_count,StoreFastElementIC_InBounds,413,0 block_count,StoreFastElementIC_InBounds,414,0 block_count,StoreFastElementIC_InBounds,415,0 -block_count,StoreFastElementIC_InBounds,416,48 -block_count,StoreFastElementIC_InBounds,417,48 -block_count,StoreFastElementIC_InBounds,418,48 +block_count,StoreFastElementIC_InBounds,416,45 +block_count,StoreFastElementIC_InBounds,417,45 +block_count,StoreFastElementIC_InBounds,418,45 block_count,StoreFastElementIC_InBounds,419,42 block_count,StoreFastElementIC_InBounds,420,42 block_count,StoreFastElementIC_InBounds,421,0 block_count,StoreFastElementIC_InBounds,422,0 block_count,StoreFastElementIC_InBounds,423,0 block_count,StoreFastElementIC_InBounds,424,42 -block_count,StoreFastElementIC_InBounds,425,5 -block_count,StoreFastElementIC_InBounds,426,48 -block_count,StoreFastElementIC_InBounds,427,48 +block_count,StoreFastElementIC_InBounds,425,3 +block_count,StoreFastElementIC_InBounds,426,45 +block_count,StoreFastElementIC_InBounds,427,45 block_count,StoreFastElementIC_InBounds,428,0 -block_count,StoreFastElementIC_InBounds,429,48 +block_count,StoreFastElementIC_InBounds,429,45 block_count,StoreFastElementIC_InBounds,430,0 block_count,StoreFastElementIC_InBounds,431,0 block_count,StoreFastElementIC_InBounds,432,0 @@ -13714,23 +13724,23 @@ block_count,StoreFastElementIC_InBounds,1300,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,0,41 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,1,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,2,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,2,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,3,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,4,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,5,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,6,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,7,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,8,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,9,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,8,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,9,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,10,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,11,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,11,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,12,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,13,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,14,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,13,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,14,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,15,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,16,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,17,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,18,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,18,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,19,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,20,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,21,0 @@ -13753,8 +13763,8 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,38,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,39,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,40,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,41,3 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,42,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,41,4 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,42,4 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,43,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,44,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,45,0 @@ -13772,12 +13782,12 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,57,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,58,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,59,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,60,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,61,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,60,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,61,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,62,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,63,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,64,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,65,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,63,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,64,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,65,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,66,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,67,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,68,0 @@ -13806,9 +13816,9 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,91,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,92,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,93,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,94,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,94,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,95,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,96,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,96,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,97,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,98,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,99,0 @@ -13904,17 +13914,17 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,189,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,190,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,191,3 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,192,29 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,192,28 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,193,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,194,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,195,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,196,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,197,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,198,29 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,199,29 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,198,28 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,199,28 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,200,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,201,29 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,202,29 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,201,28 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,202,28 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,203,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,204,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,205,2 @@ -13934,14 +13944,14 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,219,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,220,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,221,25 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,222,23 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,222,22 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,223,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,224,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,225,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,226,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,227,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,228,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,229,23 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,229,22 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,230,21 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,231,1 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,232,0 @@ -13964,8 +13974,8 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,249,26 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,250,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,251,26 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,252,29 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,253,29 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,252,28 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,253,28 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,254,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,255,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,256,0 @@ -13994,9 +14004,9 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,279,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,280,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,281,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,282,29 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,282,28 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,283,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,284,29 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,284,28 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,285,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,286,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,287,0 @@ -19219,7 +19229,7 @@ block_count,ArrayConstructor,1,0 block_count,ArrayConstructor,2,1 block_count,ArrayConstructor,3,1 -block_count,ArrayConstructorImpl,0,203 +block_count,ArrayConstructorImpl,0,217 block_count,ArrayConstructorImpl,1,104 block_count,ArrayConstructorImpl,2,3 block_count,ArrayConstructorImpl,3,2 @@ -19261,8 +19271,8 @@ block_count,ArrayConstructorImpl,39,0 block_count,ArrayConstructorImpl,40,100 block_count,ArrayConstructorImpl,41,0 -block_count,ArrayConstructorImpl,42,98 -block_count,ArrayConstructorImpl,43,98 +block_count,ArrayConstructorImpl,42,113 +block_count,ArrayConstructorImpl,43,113 block_count,ArrayNoArgumentConstructor_PackedSmi_DontOverride,0,0 block_count,ArrayNoArgumentConstructor_PackedSmi_DontOverride,1,0 block_count,ArrayNoArgumentConstructor_PackedSmi_DontOverride,2,0 @@ -20237,26 +20247,26 @@ block_count,ArrayPrototypePop,37,0 block_count,ArrayPrototypePop,38,0 block_count,ArrayPrototypePop,39,1 -block_count,ArrayPrototypePush,0,299 +block_count,ArrayPrototypePush,0,302 block_count,ArrayPrototypePush,1,0 -block_count,ArrayPrototypePush,2,299 -block_count,ArrayPrototypePush,3,299 -block_count,ArrayPrototypePush,4,299 -block_count,ArrayPrototypePush,5,299 -block_count,ArrayPrototypePush,6,299 +block_count,ArrayPrototypePush,2,302 +block_count,ArrayPrototypePush,3,302 +block_count,ArrayPrototypePush,4,302 +block_count,ArrayPrototypePush,5,302 +block_count,ArrayPrototypePush,6,302 block_count,ArrayPrototypePush,7,0 -block_count,ArrayPrototypePush,8,299 -block_count,ArrayPrototypePush,9,299 -block_count,ArrayPrototypePush,10,299 +block_count,ArrayPrototypePush,8,302 +block_count,ArrayPrototypePush,9,302 +block_count,ArrayPrototypePush,10,302 block_count,ArrayPrototypePush,11,0 -block_count,ArrayPrototypePush,12,299 -block_count,ArrayPrototypePush,13,299 +block_count,ArrayPrototypePush,12,302 +block_count,ArrayPrototypePush,13,302 block_count,ArrayPrototypePush,14,0 -block_count,ArrayPrototypePush,15,299 -block_count,ArrayPrototypePush,16,299 -block_count,ArrayPrototypePush,17,27 -block_count,ArrayPrototypePush,18,27 -block_count,ArrayPrototypePush,19,26 +block_count,ArrayPrototypePush,15,302 +block_count,ArrayPrototypePush,16,302 +block_count,ArrayPrototypePush,17,28 +block_count,ArrayPrototypePush,18,28 +block_count,ArrayPrototypePush,19,27 block_count,ArrayPrototypePush,20,0 block_count,ArrayPrototypePush,21,0 block_count,ArrayPrototypePush,22,0 @@ -20278,24 +20288,24 @@ block_count,ArrayPrototypePush,38,0 block_count,ArrayPrototypePush,39,0 block_count,ArrayPrototypePush,40,0 -block_count,ArrayPrototypePush,41,62 -block_count,ArrayPrototypePush,42,62 +block_count,ArrayPrototypePush,41,64 +block_count,ArrayPrototypePush,42,64 block_count,ArrayPrototypePush,43,0 block_count,ArrayPrototypePush,44,0 block_count,ArrayPrototypePush,45,0 block_count,ArrayPrototypePush,46,0 block_count,ArrayPrototypePush,47,0 -block_count,ArrayPrototypePush,48,27 -block_count,ArrayPrototypePush,49,27 -block_count,ArrayPrototypePush,50,27 -block_count,ArrayPrototypePush,51,27 -block_count,ArrayPrototypePush,52,27 +block_count,ArrayPrototypePush,48,28 +block_count,ArrayPrototypePush,49,28 +block_count,ArrayPrototypePush,50,28 +block_count,ArrayPrototypePush,51,28 +block_count,ArrayPrototypePush,52,28 block_count,ArrayPrototypePush,53,0 -block_count,ArrayPrototypePush,54,27 +block_count,ArrayPrototypePush,54,28 block_count,ArrayPrototypePush,55,0 block_count,ArrayPrototypePush,56,0 block_count,ArrayPrototypePush,57,0 -block_count,ArrayPrototypePush,58,27 +block_count,ArrayPrototypePush,58,28 block_count,ArrayPrototypePush,59,0 block_count,ArrayPrototypePush,60,0 block_count,ArrayPrototypePush,61,0 @@ -20304,8 +20314,8 @@ block_count,ArrayPrototypePush,64,0 block_count,ArrayPrototypePush,65,0 block_count,ArrayPrototypePush,66,0 -block_count,ArrayPrototypePush,67,271 -block_count,ArrayPrototypePush,68,269 +block_count,ArrayPrototypePush,67,273 +block_count,ArrayPrototypePush,68,271 block_count,ArrayPrototypePush,69,2 block_count,ArrayPrototypePush,70,2 block_count,ArrayPrototypePush,71,2 @@ -20370,9 +20380,9 @@ block_count,ArrayPrototypePush,130,0 block_count,ArrayPrototypePush,131,0 block_count,ArrayPrototypePush,132,0 -block_count,ArrayPrototypePush,133,269 -block_count,ArrayPrototypePush,134,269 -block_count,ArrayPrototypePush,135,248 +block_count,ArrayPrototypePush,133,272 +block_count,ArrayPrototypePush,134,271 +block_count,ArrayPrototypePush,135,250 block_count,ArrayPrototypePush,136,21 block_count,ArrayPrototypePush,137,21 block_count,ArrayPrototypePush,138,21 @@ -20386,7 +20396,7 @@ block_count,ArrayPrototypePush,146,21 block_count,ArrayPrototypePush,147,0 block_count,ArrayPrototypePush,148,21 -block_count,ArrayPrototypePush,149,215 +block_count,ArrayPrototypePush,149,216 block_count,ArrayPrototypePush,150,194 block_count,ArrayPrototypePush,151,21 block_count,ArrayPrototypePush,152,21 @@ -20401,15 +20411,15 @@ block_count,ArrayPrototypePush,161,21 block_count,ArrayPrototypePush,162,0 block_count,ArrayPrototypePush,163,0 -block_count,ArrayPrototypePush,164,269 -block_count,ArrayPrototypePush,165,269 -block_count,ArrayPrototypePush,166,277 -block_count,ArrayPrototypePush,167,277 +block_count,ArrayPrototypePush,164,271 +block_count,ArrayPrototypePush,165,271 +block_count,ArrayPrototypePush,166,280 +block_count,ArrayPrototypePush,167,280 block_count,ArrayPrototypePush,168,8 -block_count,ArrayPrototypePush,169,269 +block_count,ArrayPrototypePush,169,271 block_count,ArrayPrototypePush,170,0 block_count,ArrayPrototypePush,171,0 -block_count,ArrayPrototypePush,172,269 +block_count,ArrayPrototypePush,172,271 block_count,ArrayPrototypePush,173,0 block_count,ArrayPrototypePush,174,0 block_count,ArrayPrototypePush,175,0 @@ -20734,8 +20744,8 @@ block_count,ExtractFastJSArray,28,0 block_count,ExtractFastJSArray,29,0 block_count,ExtractFastJSArray,30,0 -block_count,ExtractFastJSArray,31,0 -block_count,ExtractFastJSArray,32,0 +block_count,ExtractFastJSArray,31,4 +block_count,ExtractFastJSArray,32,4 block_count,ExtractFastJSArray,33,0 block_count,ExtractFastJSArray,34,0 block_count,ExtractFastJSArray,35,0 @@ -21022,7 +21032,7 @@ block_count,CreateObjectFromSlowBoilerplateHelper,86,49 block_count,CreateObjectFromSlowBoilerplateHelper,87,49 block_count,CreateObjectFromSlowBoilerplateHelper,88,108 -block_count,CreateObjectFromSlowBoilerplateHelper,89,107 +block_count,CreateObjectFromSlowBoilerplateHelper,89,108 block_count,CreateObjectFromSlowBoilerplateHelper,90,41 block_count,CreateObjectFromSlowBoilerplateHelper,91,0 block_count,CreateObjectFromSlowBoilerplateHelper,92,41 @@ -21211,13 +21221,13 @@ block_count,ArrayPrototypeValues,12,0 block_count,ArrayPrototypeValues,13,29 block_count,ArrayPrototypeValues,14,29 -block_count,ArrayIteratorPrototypeNext,0,68 +block_count,ArrayIteratorPrototypeNext,0,69 block_count,ArrayIteratorPrototypeNext,1,0 -block_count,ArrayIteratorPrototypeNext,2,68 -block_count,ArrayIteratorPrototypeNext,3,68 -block_count,ArrayIteratorPrototypeNext,4,68 +block_count,ArrayIteratorPrototypeNext,2,69 +block_count,ArrayIteratorPrototypeNext,3,69 +block_count,ArrayIteratorPrototypeNext,4,69 block_count,ArrayIteratorPrototypeNext,5,0 -block_count,ArrayIteratorPrototypeNext,6,68 +block_count,ArrayIteratorPrototypeNext,6,69 block_count,ArrayIteratorPrototypeNext,7,2 block_count,ArrayIteratorPrototypeNext,8,2 block_count,ArrayIteratorPrototypeNext,9,0 @@ -21406,14 +21416,14 @@ block_count,ArrayIteratorPrototypeNext,192,66 block_count,ArrayIteratorPrototypeNext,193,66 block_count,ArrayIteratorPrototypeNext,194,16 -block_count,ArrayIteratorPrototypeNext,195,49 -block_count,ArrayIteratorPrototypeNext,196,49 +block_count,ArrayIteratorPrototypeNext,195,50 +block_count,ArrayIteratorPrototypeNext,196,50 block_count,ArrayIteratorPrototypeNext,197,0 block_count,ArrayIteratorPrototypeNext,198,0 block_count,ArrayIteratorPrototypeNext,199,0 block_count,ArrayIteratorPrototypeNext,200,0 -block_count,ArrayIteratorPrototypeNext,201,49 -block_count,ArrayIteratorPrototypeNext,202,49 +block_count,ArrayIteratorPrototypeNext,201,50 +block_count,ArrayIteratorPrototypeNext,202,50 block_count,ArrayIteratorPrototypeNext,203,0 block_count,ArrayIteratorPrototypeNext,204,0 block_count,ArrayIteratorPrototypeNext,205,0 @@ -21433,13 +21443,13 @@ block_count,ArrayIteratorPrototypeNext,219,0 block_count,ArrayIteratorPrototypeNext,220,0 block_count,ArrayIteratorPrototypeNext,221,4 -block_count,ArrayIteratorPrototypeNext,222,38 +block_count,ArrayIteratorPrototypeNext,222,39 block_count,ArrayIteratorPrototypeNext,223,0 block_count,ArrayIteratorPrototypeNext,224,0 block_count,ArrayIteratorPrototypeNext,225,0 -block_count,ArrayIteratorPrototypeNext,226,42 +block_count,ArrayIteratorPrototypeNext,226,43 block_count,ArrayIteratorPrototypeNext,227,0 -block_count,ArrayIteratorPrototypeNext,228,42 +block_count,ArrayIteratorPrototypeNext,228,43 block_count,ArrayIteratorPrototypeNext,229,0 block_count,ArrayIteratorPrototypeNext,230,6 block_count,ArrayIteratorPrototypeNext,231,0 @@ -21460,7 +21470,7 @@ block_count,ArrayIteratorPrototypeNext,246,0 block_count,ArrayIteratorPrototypeNext,247,0 block_count,ArrayIteratorPrototypeNext,248,0 -block_count,ArrayIteratorPrototypeNext,249,49 +block_count,ArrayIteratorPrototypeNext,249,50 block_count,ArrayIteratorPrototypeNext,250,0 block_count,ArrayIteratorPrototypeNext,251,0 block_count,ArrayIteratorPrototypeNext,252,0 @@ -21486,12 +21496,12 @@ block_count,ArrayIteratorPrototypeNext,272,0 block_count,ArrayIteratorPrototypeNext,273,0 block_count,ArrayIteratorPrototypeNext,274,51 -block_count,ArrayIteratorPrototypeNext,275,68 +block_count,ArrayIteratorPrototypeNext,275,69 block_count,ArrayIteratorPrototypeNext,276,0 -block_count,ArrayIteratorPrototypeNext,277,68 +block_count,ArrayIteratorPrototypeNext,277,69 block_count,ArrayIteratorPrototypeNext,278,0 -block_count,ArrayIteratorPrototypeNext,279,68 -block_count,ArrayIteratorPrototypeNext,280,68 +block_count,ArrayIteratorPrototypeNext,279,69 +block_count,ArrayIteratorPrototypeNext,280,69 block_count,AsyncFunctionEnter,0,0 block_count,AsyncFunctionEnter,1,0 block_count,AsyncFunctionEnter,2,0 @@ -21890,15 +21900,15 @@ block_count,GlobalIsNaN,8,0 block_count,GlobalIsNaN,9,0 block_count,GlobalIsNaN,10,0 -block_count,LoadIC,0,4991 -block_count,LoadIC,1,4990 +block_count,LoadIC,0,4986 +block_count,LoadIC,1,4985 block_count,LoadIC,2,1 -block_count,LoadIC,3,4991 -block_count,LoadIC,4,4991 -block_count,LoadIC,5,1331 +block_count,LoadIC,3,4986 +block_count,LoadIC,4,4986 +block_count,LoadIC,5,1307 block_count,LoadIC,6,0 -block_count,LoadIC,7,1330 -block_count,LoadIC,8,252 +block_count,LoadIC,7,1306 +block_count,LoadIC,8,259 block_count,LoadIC,9,1 block_count,LoadIC,10,1 block_count,LoadIC,11,0 @@ -21912,35 +21922,35 @@ block_count,LoadIC,19,0 block_count,LoadIC,20,0 block_count,LoadIC,21,0 -block_count,LoadIC,22,251 -block_count,LoadIC,23,251 +block_count,LoadIC,22,257 +block_count,LoadIC,23,257 block_count,LoadIC,24,0 -block_count,LoadIC,25,251 -block_count,LoadIC,26,216 -block_count,LoadIC,27,213 +block_count,LoadIC,25,257 +block_count,LoadIC,26,219 +block_count,LoadIC,27,217 block_count,LoadIC,28,2 -block_count,LoadIC,29,34 -block_count,LoadIC,30,37 -block_count,LoadIC,31,35 -block_count,LoadIC,32,35 +block_count,LoadIC,29,38 +block_count,LoadIC,30,40 +block_count,LoadIC,31,37 +block_count,LoadIC,32,37 block_count,LoadIC,33,0 block_count,LoadIC,34,2 -block_count,LoadIC,35,1078 -block_count,LoadIC,36,1750 -block_count,LoadIC,37,672 -block_count,LoadIC,38,672 +block_count,LoadIC,35,1047 +block_count,LoadIC,36,1728 +block_count,LoadIC,37,681 +block_count,LoadIC,38,681 block_count,LoadIC,39,0 -block_count,LoadIC,40,1077 -block_count,LoadIC,41,3660 -block_count,LoadIC,42,4986 -block_count,LoadIC,43,1672 -block_count,LoadIC,44,1664 -block_count,LoadIC,45,1384 -block_count,LoadIC,46,1384 +block_count,LoadIC,40,1047 +block_count,LoadIC,41,3679 +block_count,LoadIC,42,4982 +block_count,LoadIC,43,1680 +block_count,LoadIC,44,1672 +block_count,LoadIC,45,1391 +block_count,LoadIC,46,1391 block_count,LoadIC,47,0 -block_count,LoadIC,48,1384 +block_count,LoadIC,48,1391 block_count,LoadIC,49,0 -block_count,LoadIC,50,1384 +block_count,LoadIC,50,1391 block_count,LoadIC,51,178 block_count,LoadIC,52,33 block_count,LoadIC,53,33 @@ -22013,25 +22023,25 @@ block_count,LoadIC,120,0 block_count,LoadIC,121,144 block_count,LoadIC,122,0 -block_count,LoadIC,123,1206 -block_count,LoadIC,124,1383 -block_count,LoadIC,125,1382 -block_count,LoadIC,126,1305 -block_count,LoadIC,127,1305 +block_count,LoadIC,123,1213 +block_count,LoadIC,124,1390 +block_count,LoadIC,125,1389 +block_count,LoadIC,126,1312 +block_count,LoadIC,127,1312 block_count,LoadIC,128,0 block_count,LoadIC,129,76 -block_count,LoadIC,130,1382 +block_count,LoadIC,130,1389 block_count,LoadIC,131,0 block_count,LoadIC,132,280 block_count,LoadIC,133,8 block_count,LoadIC,134,8 block_count,LoadIC,135,0 -block_count,LoadIC,136,3313 -block_count,LoadIC,137,4696 -block_count,LoadIC,138,1604 -block_count,LoadIC,139,510 -block_count,LoadIC,140,433 -block_count,LoadIC,141,222 +block_count,LoadIC,136,3301 +block_count,LoadIC,137,4691 +block_count,LoadIC,138,1611 +block_count,LoadIC,139,511 +block_count,LoadIC,140,434 +block_count,LoadIC,141,223 block_count,LoadIC,142,12 block_count,LoadIC,143,2 block_count,LoadIC,144,2 @@ -22101,7 +22111,7 @@ block_count,LoadIC,208,0 block_count,LoadIC,209,0 block_count,LoadIC,210,10 -block_count,LoadIC,211,210 +block_count,LoadIC,211,211 block_count,LoadIC,212,210 block_count,LoadIC,213,210 block_count,LoadIC,214,0 @@ -22159,19 +22169,19 @@ block_count,LoadIC,266,0 block_count,LoadIC,267,210 block_count,LoadIC,268,76 -block_count,LoadIC,269,1094 -block_count,LoadIC,270,3091 -block_count,LoadIC,271,3091 -block_count,LoadIC,272,799 -block_count,LoadIC,273,2292 -block_count,LoadIC,274,3091 -block_count,LoadIC,275,2940 -block_count,LoadIC,276,151 -block_count,LoadIC,277,151 -block_count,LoadIC,278,151 +block_count,LoadIC,269,1100 +block_count,LoadIC,270,3079 +block_count,LoadIC,271,3079 +block_count,LoadIC,272,805 +block_count,LoadIC,273,2274 +block_count,LoadIC,274,3079 +block_count,LoadIC,275,2929 +block_count,LoadIC,276,150 +block_count,LoadIC,277,150 +block_count,LoadIC,278,150 block_count,LoadIC,279,0 -block_count,LoadIC,280,151 -block_count,LoadIC,281,151 +block_count,LoadIC,280,150 +block_count,LoadIC,281,150 block_count,LoadIC,282,0 block_count,LoadIC,283,0 block_count,LoadIC,284,0 @@ -22226,26 +22236,26 @@ block_count,LoadIC,333,0 block_count,LoadIC,334,0 block_count,LoadIC,335,4 -block_count,LoadIC_Megamorphic,0,8676 -block_count,LoadIC_Megamorphic,1,8675 +block_count,LoadIC_Megamorphic,0,8670 +block_count,LoadIC_Megamorphic,1,8669 block_count,LoadIC_Megamorphic,2,1 -block_count,LoadIC_Megamorphic,3,8676 -block_count,LoadIC_Megamorphic,4,8676 +block_count,LoadIC_Megamorphic,3,8670 +block_count,LoadIC_Megamorphic,4,8670 block_count,LoadIC_Megamorphic,5,0 -block_count,LoadIC_Megamorphic,6,8676 -block_count,LoadIC_Megamorphic,7,7214 -block_count,LoadIC_Megamorphic,8,7177 -block_count,LoadIC_Megamorphic,9,36 -block_count,LoadIC_Megamorphic,10,1462 -block_count,LoadIC_Megamorphic,11,1499 -block_count,LoadIC_Megamorphic,12,1485 -block_count,LoadIC_Megamorphic,13,1483 +block_count,LoadIC_Megamorphic,6,8670 +block_count,LoadIC_Megamorphic,7,7396 +block_count,LoadIC_Megamorphic,8,7358 +block_count,LoadIC_Megamorphic,9,38 +block_count,LoadIC_Megamorphic,10,1274 +block_count,LoadIC_Megamorphic,11,1312 +block_count,LoadIC_Megamorphic,12,1299 +block_count,LoadIC_Megamorphic,13,1296 block_count,LoadIC_Megamorphic,14,2 block_count,LoadIC_Megamorphic,15,13 -block_count,LoadIC_Megamorphic,16,8660 +block_count,LoadIC_Megamorphic,16,8655 block_count,LoadIC_Megamorphic,17,3176 block_count,LoadIC_Megamorphic,18,3176 -block_count,LoadIC_Megamorphic,19,3167 +block_count,LoadIC_Megamorphic,19,3166 block_count,LoadIC_Megamorphic,20,3166 block_count,LoadIC_Megamorphic,21,0 block_count,LoadIC_Megamorphic,22,3166 @@ -22336,8 +22346,8 @@ block_count,LoadIC_Megamorphic,107,0 block_count,LoadIC_Megamorphic,108,0 block_count,LoadIC_Megamorphic,109,0 -block_count,LoadIC_Megamorphic,110,5484 -block_count,LoadIC_Megamorphic,111,8649 +block_count,LoadIC_Megamorphic,110,5478 +block_count,LoadIC_Megamorphic,111,8643 block_count,LoadIC_Megamorphic,112,3796 block_count,LoadIC_Megamorphic,113,1993 block_count,LoadIC_Megamorphic,114,1325 @@ -22470,12 +22480,12 @@ block_count,LoadIC_Megamorphic,241,1 block_count,LoadIC_Megamorphic,242,667 block_count,LoadIC_Megamorphic,243,1803 -block_count,LoadIC_Megamorphic,244,4853 -block_count,LoadIC_Megamorphic,245,4853 -block_count,LoadIC_Megamorphic,246,253 -block_count,LoadIC_Megamorphic,247,4599 -block_count,LoadIC_Megamorphic,248,4853 -block_count,LoadIC_Megamorphic,249,4834 +block_count,LoadIC_Megamorphic,244,4847 +block_count,LoadIC_Megamorphic,245,4847 +block_count,LoadIC_Megamorphic,246,252 +block_count,LoadIC_Megamorphic,247,4595 +block_count,LoadIC_Megamorphic,248,4847 +block_count,LoadIC_Megamorphic,249,4829 block_count,LoadIC_Megamorphic,250,18 block_count,LoadIC_Megamorphic,251,18 block_count,LoadIC_Megamorphic,252,18 @@ -22535,7 +22545,7 @@ block_count,LoadIC_Megamorphic,306,0 block_count,LoadIC_Megamorphic,307,0 block_count,LoadIC_Megamorphic,308,0 -block_count,LoadIC_Megamorphic,309,16 +block_count,LoadIC_Megamorphic,309,15 block_count,LoadIC_Noninlined,0,5 block_count,LoadIC_Noninlined,1,5 block_count,LoadIC_Noninlined,2,0 @@ -22860,15 +22870,15 @@ block_count,LoadIC_Noninlined,321,0 block_count,LoadIC_Noninlined,322,0 block_count,LoadIC_Noninlined,323,1 -block_count,LoadICTrampoline,0,302 -block_count,LoadICTrampoline,1,302 +block_count,LoadICTrampoline,0,300 +block_count,LoadICTrampoline,1,300 block_count,LoadICTrampoline,2,0 -block_count,LoadICTrampoline,3,302 -block_count,LoadICBaseline,0,4481 -block_count,LoadICTrampoline_Megamorphic,0,5303 -block_count,LoadICTrampoline_Megamorphic,1,5303 +block_count,LoadICTrampoline,3,300 +block_count,LoadICBaseline,0,4478 +block_count,LoadICTrampoline_Megamorphic,0,5310 +block_count,LoadICTrampoline_Megamorphic,1,5310 block_count,LoadICTrampoline_Megamorphic,2,0 -block_count,LoadICTrampoline_Megamorphic,3,5303 +block_count,LoadICTrampoline_Megamorphic,3,5310 block_count,LoadSuperIC,0,4 block_count,LoadSuperIC,1,4 block_count,LoadSuperIC,2,4 @@ -23477,16 +23487,16 @@ block_count,LoadSuperIC,605,0 block_count,LoadSuperIC,606,0 block_count,LoadSuperICBaseline,0,4 -block_count,KeyedLoadIC,0,837 -block_count,KeyedLoadIC,1,837 +block_count,KeyedLoadIC,0,825 +block_count,KeyedLoadIC,1,825 block_count,KeyedLoadIC,2,0 -block_count,KeyedLoadIC,3,837 -block_count,KeyedLoadIC,4,837 -block_count,KeyedLoadIC,5,835 +block_count,KeyedLoadIC,3,825 +block_count,KeyedLoadIC,4,825 +block_count,KeyedLoadIC,5,823 block_count,KeyedLoadIC,6,84 block_count,KeyedLoadIC,7,0 block_count,KeyedLoadIC,8,84 -block_count,KeyedLoadIC,9,44 +block_count,KeyedLoadIC,9,45 block_count,KeyedLoadIC,10,1 block_count,KeyedLoadIC,11,1 block_count,KeyedLoadIC,12,0 @@ -23524,15 +23534,15 @@ block_count,KeyedLoadIC,44,1 block_count,KeyedLoadIC,45,1 block_count,KeyedLoadIC,46,0 -block_count,KeyedLoadIC,47,42 -block_count,KeyedLoadIC,48,39 -block_count,KeyedLoadIC,49,66 -block_count,KeyedLoadIC,50,26 -block_count,KeyedLoadIC,51,26 +block_count,KeyedLoadIC,47,43 +block_count,KeyedLoadIC,48,38 +block_count,KeyedLoadIC,49,64 +block_count,KeyedLoadIC,50,25 +block_count,KeyedLoadIC,51,25 block_count,KeyedLoadIC,52,0 -block_count,KeyedLoadIC,53,39 -block_count,KeyedLoadIC,54,750 -block_count,KeyedLoadIC,55,790 +block_count,KeyedLoadIC,53,38 +block_count,KeyedLoadIC,54,738 +block_count,KeyedLoadIC,55,777 block_count,KeyedLoadIC,56,1 block_count,KeyedLoadIC,57,1 block_count,KeyedLoadIC,58,0 @@ -23626,8 +23636,8 @@ block_count,KeyedLoadIC,146,0 block_count,KeyedLoadIC,147,0 block_count,KeyedLoadIC,148,0 -block_count,KeyedLoadIC,149,788 -block_count,KeyedLoadIC,150,788 +block_count,KeyedLoadIC,149,775 +block_count,KeyedLoadIC,150,775 block_count,KeyedLoadIC,151,6 block_count,KeyedLoadIC,152,0 block_count,KeyedLoadIC,153,0 @@ -23902,7 +23912,7 @@ block_count,KeyedLoadIC,422,0 block_count,KeyedLoadIC,423,0 block_count,KeyedLoadIC,424,0 -block_count,KeyedLoadIC,425,782 +block_count,KeyedLoadIC,425,769 block_count,KeyedLoadIC,426,0 block_count,KeyedLoadIC,427,0 block_count,KeyedLoadIC,428,0 @@ -23913,30 +23923,30 @@ block_count,KeyedLoadIC,433,0 block_count,KeyedLoadIC,434,0 block_count,KeyedLoadIC,435,0 -block_count,KeyedLoadIC,436,781 -block_count,KeyedLoadIC,437,781 -block_count,KeyedLoadIC,438,782 -block_count,KeyedLoadIC,439,478 +block_count,KeyedLoadIC,436,769 +block_count,KeyedLoadIC,437,769 +block_count,KeyedLoadIC,438,769 +block_count,KeyedLoadIC,439,471 block_count,KeyedLoadIC,440,9 -block_count,KeyedLoadIC,441,468 -block_count,KeyedLoadIC,442,478 +block_count,KeyedLoadIC,441,461 +block_count,KeyedLoadIC,442,471 block_count,KeyedLoadIC,443,1 -block_count,KeyedLoadIC,444,476 +block_count,KeyedLoadIC,444,469 block_count,KeyedLoadIC,445,0 block_count,KeyedLoadIC,446,34 -block_count,KeyedLoadIC,447,254 +block_count,KeyedLoadIC,447,248 block_count,KeyedLoadIC,448,0 block_count,KeyedLoadIC,449,0 block_count,KeyedLoadIC,450,0 block_count,KeyedLoadIC,451,0 -block_count,KeyedLoadIC,452,288 +block_count,KeyedLoadIC,452,282 block_count,KeyedLoadIC,453,23 block_count,KeyedLoadIC,454,75 block_count,KeyedLoadIC,455,0 block_count,KeyedLoadIC,456,0 block_count,KeyedLoadIC,457,0 -block_count,KeyedLoadIC,458,99 -block_count,KeyedLoadIC,459,94 +block_count,KeyedLoadIC,458,98 +block_count,KeyedLoadIC,459,93 block_count,KeyedLoadIC,460,4 block_count,KeyedLoadIC,461,35 block_count,KeyedLoadIC,462,0 @@ -23948,8 +23958,8 @@ block_count,KeyedLoadIC,468,53 block_count,KeyedLoadIC,469,53 block_count,KeyedLoadIC,470,0 -block_count,KeyedLoadIC,471,303 -block_count,KeyedLoadIC,472,303 +block_count,KeyedLoadIC,471,298 +block_count,KeyedLoadIC,472,298 block_count,KeyedLoadIC,473,0 block_count,KeyedLoadIC,474,0 block_count,KeyedLoadIC,475,0 @@ -23972,19 +23982,19 @@ block_count,KeyedLoadIC,492,0 block_count,KeyedLoadIC,493,0 block_count,KeyedLoadIC,494,0 -block_count,KeyedLoadIC,495,303 -block_count,KeyedLoadIC,496,303 +block_count,KeyedLoadIC,495,298 +block_count,KeyedLoadIC,496,298 block_count,KeyedLoadIC,497,0 -block_count,KeyedLoadIC,498,303 +block_count,KeyedLoadIC,498,298 block_count,KeyedLoadIC,499,0 -block_count,KeyedLoadIC,500,47 +block_count,KeyedLoadIC,500,45 block_count,KeyedLoadIC,501,0 -block_count,KeyedLoadIC,502,2 -block_count,KeyedLoadIC,503,12 +block_count,KeyedLoadIC,502,1 +block_count,KeyedLoadIC,503,13 block_count,KeyedLoadIC,504,0 block_count,KeyedLoadIC,505,1 -block_count,KeyedLoadIC,506,170 -block_count,KeyedLoadIC,507,69 +block_count,KeyedLoadIC,506,167 +block_count,KeyedLoadIC,507,68 block_count,KeyedLoadIC,508,0 block_count,KeyedLoadIC,509,0 block_count,KeyedLoadIC,510,0 @@ -24043,16 +24053,16 @@ block_count,KeyedLoadIC,563,0 block_count,KeyedLoadIC,564,0 block_count,KeyedLoadIC,565,0 -block_count,KeyedLoadIC,566,170 -block_count,KeyedLoadIC,567,167 +block_count,KeyedLoadIC,566,167 +block_count,KeyedLoadIC,567,164 block_count,KeyedLoadIC,568,2 block_count,KeyedLoadIC,569,0 block_count,KeyedLoadIC,570,2 block_count,KeyedLoadIC,571,2 -block_count,KeyedLoadIC,572,69 +block_count,KeyedLoadIC,572,68 block_count,KeyedLoadIC,573,0 -block_count,KeyedLoadIC,574,69 -block_count,KeyedLoadIC,575,69 +block_count,KeyedLoadIC,574,68 +block_count,KeyedLoadIC,575,68 block_count,KeyedLoadIC,576,0 block_count,KeyedLoadIC,577,0 block_count,KeyedLoadIC,578,0 @@ -24130,7 +24140,7 @@ block_count,KeyedLoadIC,650,0 block_count,KeyedLoadIC,651,0 block_count,KeyedLoadIC,652,2 -block_count,KeyedLoadIC,653,45 +block_count,KeyedLoadIC,653,46 block_count,KeyedLoadIC,654,0 block_count,KeyedLoadIC,655,0 block_count,EnumeratedKeyedLoadIC,0,6 @@ -24839,7 +24849,7 @@ block_count,KeyedLoadIC_Megamorphic,21,1638 block_count,KeyedLoadIC_Megamorphic,22,899 block_count,KeyedLoadIC_Megamorphic,23,739 -block_count,KeyedLoadIC_Megamorphic,24,62 +block_count,KeyedLoadIC_Megamorphic,24,63 block_count,KeyedLoadIC_Megamorphic,25,0 block_count,KeyedLoadIC_Megamorphic,26,85 block_count,KeyedLoadIC_Megamorphic,27,37 @@ -25033,12 +25043,12 @@ block_count,KeyedLoadIC_Megamorphic,215,484 block_count,KeyedLoadIC_Megamorphic,216,8 block_count,KeyedLoadIC_Megamorphic,217,0 -block_count,KeyedLoadIC_Megamorphic,218,686 +block_count,KeyedLoadIC_Megamorphic,218,685 block_count,KeyedLoadIC_Megamorphic,219,0 -block_count,KeyedLoadIC_Megamorphic,220,686 +block_count,KeyedLoadIC_Megamorphic,220,685 block_count,KeyedLoadIC_Megamorphic,221,26 block_count,KeyedLoadIC_Megamorphic,222,659 -block_count,KeyedLoadIC_Megamorphic,223,2676 +block_count,KeyedLoadIC_Megamorphic,223,2675 block_count,KeyedLoadIC_Megamorphic,224,2614 block_count,KeyedLoadIC_Megamorphic,225,2538 block_count,KeyedLoadIC_Megamorphic,226,2016 @@ -25229,13 +25239,13 @@ block_count,KeyedLoadIC_Megamorphic,411,101 block_count,KeyedLoadIC_Megamorphic,412,0 block_count,KeyedLoadIC_Megamorphic,413,101 -block_count,KeyedLoadIC_Megamorphic,414,78 -block_count,KeyedLoadIC_Megamorphic,415,78 +block_count,KeyedLoadIC_Megamorphic,414,75 +block_count,KeyedLoadIC_Megamorphic,415,75 block_count,KeyedLoadIC_Megamorphic,416,0 -block_count,KeyedLoadIC_Megamorphic,417,23 -block_count,KeyedLoadIC_Megamorphic,418,23 -block_count,KeyedLoadIC_Megamorphic,419,9 -block_count,KeyedLoadIC_Megamorphic,420,9 +block_count,KeyedLoadIC_Megamorphic,417,26 +block_count,KeyedLoadIC_Megamorphic,418,26 +block_count,KeyedLoadIC_Megamorphic,419,12 +block_count,KeyedLoadIC_Megamorphic,420,12 block_count,KeyedLoadIC_Megamorphic,421,0 block_count,KeyedLoadIC_Megamorphic,422,14 block_count,KeyedLoadIC_Megamorphic,423,87 @@ -25982,18 +25992,18 @@ block_count,KeyedLoadICTrampoline,1,1 block_count,KeyedLoadICTrampoline,2,0 block_count,KeyedLoadICTrampoline,3,1 -block_count,KeyedLoadICBaseline,0,781 +block_count,KeyedLoadICBaseline,0,768 block_count,EnumeratedKeyedLoadICBaseline,0,5 -block_count,KeyedLoadICTrampoline_Megamorphic,0,790 -block_count,KeyedLoadICTrampoline_Megamorphic,1,790 +block_count,KeyedLoadICTrampoline_Megamorphic,0,799 +block_count,KeyedLoadICTrampoline_Megamorphic,1,799 block_count,KeyedLoadICTrampoline_Megamorphic,2,0 -block_count,KeyedLoadICTrampoline_Megamorphic,3,790 -block_count,StoreGlobalIC,0,120 -block_count,StoreGlobalIC,1,120 -block_count,StoreGlobalIC,2,120 -block_count,StoreGlobalIC,3,120 -block_count,StoreGlobalIC,4,120 -block_count,StoreGlobalIC,5,119 +block_count,KeyedLoadICTrampoline_Megamorphic,3,799 +block_count,StoreGlobalIC,0,73 +block_count,StoreGlobalIC,1,73 +block_count,StoreGlobalIC,2,73 +block_count,StoreGlobalIC,3,73 +block_count,StoreGlobalIC,4,73 +block_count,StoreGlobalIC,5,73 block_count,StoreGlobalIC,6,6 block_count,StoreGlobalIC,7,0 block_count,StoreGlobalIC,8,0 @@ -26003,7 +26013,7 @@ block_count,StoreGlobalIC,12,6 block_count,StoreGlobalIC,13,0 block_count,StoreGlobalIC,14,6 -block_count,StoreGlobalIC,15,113 +block_count,StoreGlobalIC,15,66 block_count,StoreGlobalIC,16,0 block_count,StoreGlobalIC,17,0 block_count,StoreGlobalIC,18,0 @@ -26436,39 +26446,39 @@ block_count,StoreGlobalICTrampoline,2,0 block_count,StoreGlobalICTrampoline,3,0 block_count,StoreGlobalICBaseline,0,5 -block_count,StoreIC,0,621 -block_count,StoreIC,1,621 +block_count,StoreIC,0,609 +block_count,StoreIC,1,609 block_count,StoreIC,2,0 -block_count,StoreIC,3,621 -block_count,StoreIC,4,620 -block_count,StoreIC,5,615 -block_count,StoreIC,6,194 +block_count,StoreIC,3,609 +block_count,StoreIC,4,609 +block_count,StoreIC,5,604 +block_count,StoreIC,6,181 block_count,StoreIC,7,0 -block_count,StoreIC,8,194 +block_count,StoreIC,8,181 block_count,StoreIC,9,37 block_count,StoreIC,10,0 -block_count,StoreIC,11,36 -block_count,StoreIC,12,36 +block_count,StoreIC,11,37 +block_count,StoreIC,12,37 block_count,StoreIC,13,0 -block_count,StoreIC,14,36 -block_count,StoreIC,15,33 +block_count,StoreIC,14,37 +block_count,StoreIC,15,34 block_count,StoreIC,16,33 block_count,StoreIC,17,0 block_count,StoreIC,18,3 block_count,StoreIC,19,3 -block_count,StoreIC,20,3 -block_count,StoreIC,21,3 +block_count,StoreIC,20,2 +block_count,StoreIC,21,2 block_count,StoreIC,22,0 block_count,StoreIC,23,0 -block_count,StoreIC,24,157 -block_count,StoreIC,25,235 -block_count,StoreIC,26,77 -block_count,StoreIC,27,77 +block_count,StoreIC,24,143 +block_count,StoreIC,25,222 +block_count,StoreIC,26,78 +block_count,StoreIC,27,78 block_count,StoreIC,28,0 -block_count,StoreIC,29,157 -block_count,StoreIC,30,420 -block_count,StoreIC,31,614 -block_count,StoreIC,32,217 +block_count,StoreIC,29,143 +block_count,StoreIC,30,422 +block_count,StoreIC,31,602 +block_count,StoreIC,32,216 block_count,StoreIC,33,8 block_count,StoreIC,34,8 block_count,StoreIC,35,8 @@ -26609,8 +26619,8 @@ block_count,StoreIC,170,0 block_count,StoreIC,171,0 block_count,StoreIC,172,0 -block_count,StoreIC,173,209 -block_count,StoreIC,174,209 +block_count,StoreIC,173,208 +block_count,StoreIC,174,208 block_count,StoreIC,175,205 block_count,StoreIC,176,205 block_count,StoreIC,177,205 @@ -26624,7 +26634,7 @@ block_count,StoreIC,185,0 block_count,StoreIC,186,205 block_count,StoreIC,187,169 -block_count,StoreIC,188,163 +block_count,StoreIC,188,162 block_count,StoreIC,189,4 block_count,StoreIC,190,4 block_count,StoreIC,191,0 @@ -26633,7 +26643,7 @@ block_count,StoreIC,194,30 block_count,StoreIC,195,0 block_count,StoreIC,196,30 -block_count,StoreIC,197,128 +block_count,StoreIC,197,127 block_count,StoreIC,198,0 block_count,StoreIC,199,6 block_count,StoreIC,200,4 @@ -26652,7 +26662,7 @@ block_count,StoreIC,213,0 block_count,StoreIC,214,0 block_count,StoreIC,215,0 -block_count,StoreIC,216,38 +block_count,StoreIC,216,39 block_count,StoreIC,217,39 block_count,StoreIC,218,39 block_count,StoreIC,219,0 @@ -26684,7 +26694,7 @@ block_count,StoreIC,245,7 block_count,StoreIC,246,7 block_count,StoreIC,247,2 -block_count,StoreIC,248,4 +block_count,StoreIC,248,5 block_count,StoreIC,249,18 block_count,StoreIC,250,21 block_count,StoreIC,251,39 @@ -26717,7 +26727,7 @@ block_count,StoreIC,278,0 block_count,StoreIC,279,0 block_count,StoreIC,280,0 -block_count,StoreIC,281,396 +block_count,StoreIC,281,386 block_count,StoreIC,282,12 block_count,StoreIC,283,12 block_count,StoreIC,284,12 @@ -26742,19 +26752,19 @@ block_count,StoreIC,303,0 block_count,StoreIC,304,0 block_count,StoreIC,305,0 -block_count,StoreIC,306,384 -block_count,StoreIC,307,367 -block_count,StoreIC,308,367 +block_count,StoreIC,306,373 +block_count,StoreIC,307,356 +block_count,StoreIC,308,356 block_count,StoreIC,309,35 -block_count,StoreIC,310,33 -block_count,StoreIC,311,33 +block_count,StoreIC,310,32 +block_count,StoreIC,311,32 block_count,StoreIC,312,0 -block_count,StoreIC,313,2 +block_count,StoreIC,313,3 block_count,StoreIC,314,35 block_count,StoreIC,315,0 block_count,StoreIC,316,35 block_count,StoreIC,317,5 -block_count,StoreIC,318,30 +block_count,StoreIC,318,29 block_count,StoreIC,319,35 block_count,StoreIC,320,35 block_count,StoreIC,321,0 @@ -26764,36 +26774,36 @@ block_count,StoreIC,325,0 block_count,StoreIC,326,5 block_count,StoreIC,327,1 -block_count,StoreIC,328,3 +block_count,StoreIC,328,4 block_count,StoreIC,329,5 block_count,StoreIC,330,5 block_count,StoreIC,331,0 block_count,StoreIC,332,0 block_count,StoreIC,333,0 -block_count,StoreIC,334,171 -block_count,StoreIC,335,171 -block_count,StoreIC,336,171 -block_count,StoreIC,337,9 +block_count,StoreIC,334,169 +block_count,StoreIC,335,169 +block_count,StoreIC,336,169 +block_count,StoreIC,337,10 block_count,StoreIC,338,0 -block_count,StoreIC,339,9 -block_count,StoreIC,340,161 +block_count,StoreIC,339,10 +block_count,StoreIC,340,158 block_count,StoreIC,341,0 -block_count,StoreIC,342,171 -block_count,StoreIC,343,38 -block_count,StoreIC,344,132 -block_count,StoreIC,345,171 -block_count,StoreIC,346,171 +block_count,StoreIC,342,169 +block_count,StoreIC,343,39 +block_count,StoreIC,344,129 +block_count,StoreIC,345,169 +block_count,StoreIC,346,169 block_count,StoreIC,347,0 block_count,StoreIC,348,0 block_count,StoreIC,349,0 block_count,StoreIC,350,0 -block_count,StoreIC,351,154 +block_count,StoreIC,351,146 block_count,StoreIC,352,0 -block_count,StoreIC,353,154 -block_count,StoreIC,354,26 -block_count,StoreIC,355,128 -block_count,StoreIC,356,154 -block_count,StoreIC,357,154 +block_count,StoreIC,353,146 +block_count,StoreIC,354,25 +block_count,StoreIC,355,120 +block_count,StoreIC,356,146 +block_count,StoreIC,357,146 block_count,StoreIC,358,0 block_count,StoreIC,359,0 block_count,StoreIC,360,0 @@ -26827,17 +26837,17 @@ block_count,StoreIC_Megamorphic,4,1137 block_count,StoreIC_Megamorphic,5,0 block_count,StoreIC_Megamorphic,6,1137 -block_count,StoreIC_Megamorphic,7,988 -block_count,StoreIC_Megamorphic,8,965 -block_count,StoreIC_Megamorphic,9,23 -block_count,StoreIC_Megamorphic,10,148 -block_count,StoreIC_Megamorphic,11,172 -block_count,StoreIC_Megamorphic,12,171 -block_count,StoreIC_Megamorphic,13,170 +block_count,StoreIC_Megamorphic,7,1032 +block_count,StoreIC_Megamorphic,8,1022 +block_count,StoreIC_Megamorphic,9,9 +block_count,StoreIC_Megamorphic,10,105 +block_count,StoreIC_Megamorphic,11,115 +block_count,StoreIC_Megamorphic,12,114 +block_count,StoreIC_Megamorphic,13,112 block_count,StoreIC_Megamorphic,14,1 block_count,StoreIC_Megamorphic,15,0 block_count,StoreIC_Megamorphic,16,1135 -block_count,StoreIC_Megamorphic,17,450 +block_count,StoreIC_Megamorphic,17,451 block_count,StoreIC_Megamorphic,18,1 block_count,StoreIC_Megamorphic,19,1 block_count,StoreIC_Megamorphic,20,1 @@ -27002,7 +27012,7 @@ block_count,StoreIC_Megamorphic,179,48 block_count,StoreIC_Megamorphic,180,0 block_count,StoreIC_Megamorphic,181,48 -block_count,StoreIC_Megamorphic,182,122 +block_count,StoreIC_Megamorphic,182,123 block_count,StoreIC_Megamorphic,183,0 block_count,StoreIC_Megamorphic,184,0 block_count,StoreIC_Megamorphic,185,0 @@ -27057,8 +27067,8 @@ block_count,StoreIC_Megamorphic,234,11 block_count,StoreIC_Megamorphic,235,14 block_count,StoreIC_Megamorphic,236,25 -block_count,StoreIC_Megamorphic,237,246 -block_count,StoreIC_Megamorphic,238,246 +block_count,StoreIC_Megamorphic,237,247 +block_count,StoreIC_Megamorphic,238,247 block_count,StoreIC_Megamorphic,239,0 block_count,StoreIC_Megamorphic,240,0 block_count,StoreIC_Megamorphic,241,0 @@ -27086,7 +27096,7 @@ block_count,StoreIC_Megamorphic,263,0 block_count,StoreIC_Megamorphic,264,0 block_count,StoreIC_Megamorphic,265,0 -block_count,StoreIC_Megamorphic,266,685 +block_count,StoreIC_Megamorphic,266,684 block_count,StoreIC_Megamorphic,267,0 block_count,StoreIC_Megamorphic,268,0 block_count,StoreIC_Megamorphic,269,0 @@ -27145,24 +27155,24 @@ block_count,StoreIC_Megamorphic,322,0 block_count,StoreIC_Megamorphic,323,0 block_count,StoreIC_Megamorphic,324,0 -block_count,StoreIC_Megamorphic,325,388 +block_count,StoreIC_Megamorphic,325,387 block_count,StoreIC_Megamorphic,326,0 block_count,StoreIC_Megamorphic,327,388 block_count,StoreIC_Megamorphic,328,1 -block_count,StoreIC_Megamorphic,329,387 +block_count,StoreIC_Megamorphic,329,386 block_count,StoreIC_Megamorphic,330,388 block_count,StoreIC_Megamorphic,331,388 block_count,StoreIC_Megamorphic,332,0 block_count,StoreIC_Megamorphic,333,0 block_count,StoreIC_Megamorphic,334,0 block_count,StoreIC_Megamorphic,335,0 -block_count,StoreIC_Megamorphic,336,289 +block_count,StoreIC_Megamorphic,336,288 block_count,StoreIC_Megamorphic,337,0 -block_count,StoreIC_Megamorphic,338,289 +block_count,StoreIC_Megamorphic,338,288 block_count,StoreIC_Megamorphic,339,2 block_count,StoreIC_Megamorphic,340,286 -block_count,StoreIC_Megamorphic,341,289 -block_count,StoreIC_Megamorphic,342,289 +block_count,StoreIC_Megamorphic,341,288 +block_count,StoreIC_Megamorphic,342,288 block_count,StoreIC_Megamorphic,343,0 block_count,StoreIC_Megamorphic,344,0 block_count,StoreIC_Megamorphic,345,0 @@ -27191,17 +27201,17 @@ block_count,StoreICTrampoline,1,20 block_count,StoreICTrampoline,2,0 block_count,StoreICTrampoline,3,20 -block_count,StoreICTrampoline_Megamorphic,0,553 -block_count,StoreICTrampoline_Megamorphic,1,553 +block_count,StoreICTrampoline_Megamorphic,0,555 +block_count,StoreICTrampoline_Megamorphic,1,555 block_count,StoreICTrampoline_Megamorphic,2,0 -block_count,StoreICTrampoline_Megamorphic,3,553 -block_count,StoreICBaseline,0,567 +block_count,StoreICTrampoline_Megamorphic,3,555 +block_count,StoreICBaseline,0,555 block_count,DefineNamedOwnIC,0,68 block_count,DefineNamedOwnIC,1,68 block_count,DefineNamedOwnIC,2,0 block_count,DefineNamedOwnIC,3,68 block_count,DefineNamedOwnIC,4,68 -block_count,DefineNamedOwnIC,5,65 +block_count,DefineNamedOwnIC,5,64 block_count,DefineNamedOwnIC,6,0 block_count,DefineNamedOwnIC,7,0 block_count,DefineNamedOwnIC,8,0 @@ -27526,7 +27536,7 @@ block_count,DefineNamedOwnIC,327,8 block_count,DefineNamedOwnIC,328,0 block_count,DefineNamedOwnIC,329,8 -block_count,DefineNamedOwnIC,330,44 +block_count,DefineNamedOwnIC,330,43 block_count,DefineNamedOwnIC,331,0 block_count,DefineNamedOwnIC,332,52 block_count,DefineNamedOwnIC,333,0 @@ -27571,12 +27581,12 @@ block_count,DefineNamedOwnIC,372,0 block_count,DefineNamedOwnIC,373,0 block_count,DefineNamedOwnICBaseline,0,63 -block_count,KeyedStoreIC,0,442 -block_count,KeyedStoreIC,1,442 +block_count,KeyedStoreIC,0,431 +block_count,KeyedStoreIC,1,431 block_count,KeyedStoreIC,2,0 -block_count,KeyedStoreIC,3,442 -block_count,KeyedStoreIC,4,442 -block_count,KeyedStoreIC,5,440 +block_count,KeyedStoreIC,3,431 +block_count,KeyedStoreIC,4,431 +block_count,KeyedStoreIC,5,429 block_count,KeyedStoreIC,6,38 block_count,KeyedStoreIC,7,0 block_count,KeyedStoreIC,8,38 @@ -27591,22 +27601,22 @@ block_count,KeyedStoreIC,17,0 block_count,KeyedStoreIC,18,19 block_count,KeyedStoreIC,19,18 -block_count,KeyedStoreIC,20,32 -block_count,KeyedStoreIC,21,14 -block_count,KeyedStoreIC,22,14 +block_count,KeyedStoreIC,20,31 +block_count,KeyedStoreIC,21,13 +block_count,KeyedStoreIC,22,13 block_count,KeyedStoreIC,23,0 block_count,KeyedStoreIC,24,18 -block_count,KeyedStoreIC,25,401 -block_count,KeyedStoreIC,26,420 -block_count,KeyedStoreIC,27,419 -block_count,KeyedStoreIC,28,418 -block_count,KeyedStoreIC,29,90 -block_count,KeyedStoreIC,30,90 +block_count,KeyedStoreIC,25,390 +block_count,KeyedStoreIC,26,409 +block_count,KeyedStoreIC,27,408 +block_count,KeyedStoreIC,28,407 +block_count,KeyedStoreIC,29,89 +block_count,KeyedStoreIC,30,89 block_count,KeyedStoreIC,31,0 -block_count,KeyedStoreIC,32,90 +block_count,KeyedStoreIC,32,89 block_count,KeyedStoreIC,33,0 -block_count,KeyedStoreIC,34,90 -block_count,KeyedStoreIC,35,90 +block_count,KeyedStoreIC,34,89 +block_count,KeyedStoreIC,35,89 block_count,KeyedStoreIC,36,1 block_count,KeyedStoreIC,37,1 block_count,KeyedStoreIC,38,1 @@ -27773,7 +27783,7 @@ block_count,KeyedStoreIC,199,0 block_count,KeyedStoreIC,200,0 block_count,KeyedStoreIC,201,0 -block_count,KeyedStoreIC,202,328 +block_count,KeyedStoreIC,202,318 block_count,KeyedStoreIC,203,0 block_count,KeyedStoreIC,204,0 block_count,KeyedStoreIC,205,0 @@ -28017,11 +28027,11 @@ block_count,KeyedStoreICTrampoline,1,1 block_count,KeyedStoreICTrampoline,2,0 block_count,KeyedStoreICTrampoline,3,1 -block_count,KeyedStoreICTrampoline_Megamorphic,0,261 -block_count,KeyedStoreICTrampoline_Megamorphic,1,261 +block_count,KeyedStoreICTrampoline_Megamorphic,0,267 +block_count,KeyedStoreICTrampoline_Megamorphic,1,267 block_count,KeyedStoreICTrampoline_Megamorphic,2,0 -block_count,KeyedStoreICTrampoline_Megamorphic,3,261 -block_count,KeyedStoreICBaseline,0,402 +block_count,KeyedStoreICTrampoline_Megamorphic,3,267 +block_count,KeyedStoreICBaseline,0,391 block_count,DefineKeyedOwnIC,0,2 block_count,DefineKeyedOwnIC,1,2 block_count,DefineKeyedOwnIC,2,0 @@ -28460,12 +28470,12 @@ block_count,DefineKeyedOwnIC,435,0 block_count,DefineKeyedOwnIC,436,2 block_count,DefineKeyedOwnIC,437,2 -block_count,StoreInArrayLiteralIC,0,37 -block_count,StoreInArrayLiteralIC,1,37 +block_count,StoreInArrayLiteralIC,0,38 +block_count,StoreInArrayLiteralIC,1,38 block_count,StoreInArrayLiteralIC,2,0 -block_count,StoreInArrayLiteralIC,3,37 -block_count,StoreInArrayLiteralIC,4,37 -block_count,StoreInArrayLiteralIC,5,36 +block_count,StoreInArrayLiteralIC,3,38 +block_count,StoreInArrayLiteralIC,4,38 +block_count,StoreInArrayLiteralIC,5,37 block_count,StoreInArrayLiteralIC,6,2 block_count,StoreInArrayLiteralIC,7,0 block_count,StoreInArrayLiteralIC,8,2 @@ -28479,24 +28489,24 @@ block_count,StoreInArrayLiteralIC,16,0 block_count,StoreInArrayLiteralIC,17,2 block_count,StoreInArrayLiteralIC,18,34 -block_count,StoreInArrayLiteralIC,19,36 -block_count,StoreInArrayLiteralIC,20,36 +block_count,StoreInArrayLiteralIC,19,37 +block_count,StoreInArrayLiteralIC,20,37 block_count,StoreInArrayLiteralIC,21,0 block_count,StoreInArrayLiteralIC,22,0 block_count,StoreInArrayLiteralIC,23,0 block_count,StoreInArrayLiteralIC,24,0 block_count,StoreInArrayLiteralIC,25,0 -block_count,StoreInArrayLiteralIC,26,36 +block_count,StoreInArrayLiteralIC,26,37 block_count,StoreInArrayLiteralIC,27,0 block_count,StoreInArrayLiteralIC,28,1 block_count,StoreInArrayLiteralIC,29,0 block_count,StoreInArrayLiteralIC,30,0 -block_count,StoreInArrayLiteralICBaseline,0,33 -block_count,LoadGlobalIC,0,835 -block_count,LoadGlobalIC,1,835 -block_count,LoadGlobalIC,2,742 -block_count,LoadGlobalIC,3,742 -block_count,LoadGlobalIC,4,742 +block_count,StoreInArrayLiteralICBaseline,0,34 +block_count,LoadGlobalIC,0,831 +block_count,LoadGlobalIC,1,831 +block_count,LoadGlobalIC,2,737 +block_count,LoadGlobalIC,3,737 +block_count,LoadGlobalIC,4,737 block_count,LoadGlobalIC,5,0 block_count,LoadGlobalIC,6,0 block_count,LoadGlobalIC,7,0 @@ -28947,11 +28957,11 @@ block_count,LoadGlobalICInsideTypeof,222,0 block_count,LoadGlobalICInsideTypeof,223,0 block_count,LoadGlobalICInsideTypeof,224,0 -block_count,LoadGlobalICTrampoline,0,57 -block_count,LoadGlobalICTrampoline,1,57 +block_count,LoadGlobalICTrampoline,0,59 +block_count,LoadGlobalICTrampoline,1,59 block_count,LoadGlobalICTrampoline,2,0 -block_count,LoadGlobalICTrampoline,3,57 -block_count,LoadGlobalICBaseline,0,765 +block_count,LoadGlobalICTrampoline,3,59 +block_count,LoadGlobalICBaseline,0,758 block_count,LoadGlobalICInsideTypeofTrampoline,0,0 block_count,LoadGlobalICInsideTypeofTrampoline,1,0 block_count,LoadGlobalICInsideTypeofTrampoline,2,0 @@ -28983,16 +28993,16 @@ block_count,LookupGlobalICInsideTypeofBaseline,10,0 block_count,LookupGlobalICInsideTypeofBaseline,11,0 block_count,LookupGlobalICInsideTypeofBaseline,12,0 -block_count,KeyedHasIC,0,633 -block_count,KeyedHasIC,1,633 +block_count,KeyedHasIC,0,634 +block_count,KeyedHasIC,1,634 block_count,KeyedHasIC,2,0 -block_count,KeyedHasIC,3,633 -block_count,KeyedHasIC,4,633 -block_count,KeyedHasIC,5,633 -block_count,KeyedHasIC,6,633 +block_count,KeyedHasIC,3,634 +block_count,KeyedHasIC,4,634 +block_count,KeyedHasIC,5,634 +block_count,KeyedHasIC,6,634 block_count,KeyedHasIC,7,0 -block_count,KeyedHasIC,8,633 -block_count,KeyedHasIC,9,633 +block_count,KeyedHasIC,8,634 +block_count,KeyedHasIC,9,634 block_count,KeyedHasIC,10,1 block_count,KeyedHasIC,11,1 block_count,KeyedHasIC,12,0 @@ -29265,12 +29275,12 @@ block_count,KeyedHasIC_Megamorphic,2,0 block_count,KeyedHasIC_Megamorphic,3,632 block_count,KeyedHasIC_Megamorphic,4,632 -block_count,KeyedHasIC_Megamorphic,5,630 -block_count,KeyedHasIC_Megamorphic,6,630 +block_count,KeyedHasIC_Megamorphic,5,631 +block_count,KeyedHasIC_Megamorphic,6,631 block_count,KeyedHasIC_Megamorphic,7,0 block_count,KeyedHasIC_Megamorphic,8,0 block_count,KeyedHasIC_Megamorphic,9,0 -block_count,KeyedHasIC_Megamorphic,10,630 +block_count,KeyedHasIC_Megamorphic,10,631 block_count,KeyedHasIC_Megamorphic,11,629 block_count,KeyedHasIC_Megamorphic,12,0 block_count,KeyedHasIC_Megamorphic,13,0 @@ -29290,23 +29300,23 @@ block_count,KeyedHasIC_Megamorphic,27,0 block_count,KeyedHasIC_Megamorphic,28,0 block_count,KeyedHasIC_Megamorphic,29,1 -block_count,KeyedHasIC_Megamorphic,30,629 -block_count,KeyedHasIC_Megamorphic,31,2489 -block_count,KeyedHasIC_Megamorphic,32,2489 -block_count,KeyedHasIC_Megamorphic,33,2486 -block_count,KeyedHasIC_Megamorphic,34,2380 +block_count,KeyedHasIC_Megamorphic,30,630 +block_count,KeyedHasIC_Megamorphic,31,2492 +block_count,KeyedHasIC_Megamorphic,32,2492 +block_count,KeyedHasIC_Megamorphic,33,2489 +block_count,KeyedHasIC_Megamorphic,34,2383 block_count,KeyedHasIC_Megamorphic,35,626 block_count,KeyedHasIC_Megamorphic,36,626 block_count,KeyedHasIC_Megamorphic,37,0 block_count,KeyedHasIC_Megamorphic,38,626 -block_count,KeyedHasIC_Megamorphic,39,3757 -block_count,KeyedHasIC_Megamorphic,40,3757 +block_count,KeyedHasIC_Megamorphic,39,3761 +block_count,KeyedHasIC_Megamorphic,40,3761 block_count,KeyedHasIC_Megamorphic,41,0 -block_count,KeyedHasIC_Megamorphic,42,3757 -block_count,KeyedHasIC_Megamorphic,43,1861 -block_count,KeyedHasIC_Megamorphic,44,1895 -block_count,KeyedHasIC_Megamorphic,45,3757 -block_count,KeyedHasIC_Megamorphic,46,3130 +block_count,KeyedHasIC_Megamorphic,42,3761 +block_count,KeyedHasIC_Megamorphic,43,1863 +block_count,KeyedHasIC_Megamorphic,44,1897 +block_count,KeyedHasIC_Megamorphic,45,3761 +block_count,KeyedHasIC_Megamorphic,46,3134 block_count,KeyedHasIC_Megamorphic,47,626 block_count,KeyedHasIC_Megamorphic,48,626 block_count,KeyedHasIC_Megamorphic,49,626 @@ -29320,22 +29330,22 @@ block_count,KeyedHasIC_Megamorphic,57,0 block_count,KeyedHasIC_Megamorphic,58,626 block_count,KeyedHasIC_Megamorphic,59,0 -block_count,KeyedHasIC_Megamorphic,60,1754 +block_count,KeyedHasIC_Megamorphic,60,1756 block_count,KeyedHasIC_Megamorphic,61,0 -block_count,KeyedHasIC_Megamorphic,62,1754 -block_count,KeyedHasIC_Megamorphic,63,426 -block_count,KeyedHasIC_Megamorphic,64,1327 -block_count,KeyedHasIC_Megamorphic,65,6581 -block_count,KeyedHasIC_Megamorphic,66,6579 -block_count,KeyedHasIC_Megamorphic,67,6576 -block_count,KeyedHasIC_Megamorphic,68,5253 -block_count,KeyedHasIC_Megamorphic,69,1323 +block_count,KeyedHasIC_Megamorphic,62,1756 +block_count,KeyedHasIC_Megamorphic,63,427 +block_count,KeyedHasIC_Megamorphic,64,1329 +block_count,KeyedHasIC_Megamorphic,65,6594 +block_count,KeyedHasIC_Megamorphic,66,6592 +block_count,KeyedHasIC_Megamorphic,67,6590 +block_count,KeyedHasIC_Megamorphic,68,5265 +block_count,KeyedHasIC_Megamorphic,69,1324 block_count,KeyedHasIC_Megamorphic,70,2 block_count,KeyedHasIC_Megamorphic,71,2 -block_count,KeyedHasIC_Megamorphic,72,1750 -block_count,KeyedHasIC_Megamorphic,73,877 -block_count,KeyedHasIC_Megamorphic,74,872 -block_count,KeyedHasIC_Megamorphic,75,872 +block_count,KeyedHasIC_Megamorphic,72,1752 +block_count,KeyedHasIC_Megamorphic,73,878 +block_count,KeyedHasIC_Megamorphic,74,873 +block_count,KeyedHasIC_Megamorphic,75,873 block_count,KeyedHasIC_Megamorphic,76,0 block_count,KeyedHasIC_Megamorphic,77,105 block_count,KeyedHasIC_Megamorphic,78,2 @@ -29376,8 +29386,8 @@ block_count,KeyedHasIC_Megamorphic,113,0 block_count,KeyedHasIC_Megamorphic,114,0 block_count,KeyedHasIC_Megamorphic,115,0 -block_count,KeyedHasIC_Megamorphic,116,2482 -block_count,KeyedHasIC_Megamorphic,117,2482 +block_count,KeyedHasIC_Megamorphic,116,2485 +block_count,KeyedHasIC_Megamorphic,117,2485 block_count,KeyedHasIC_Megamorphic,118,0 block_count,KeyedHasIC_Megamorphic,119,0 block_count,KeyedHasIC_Megamorphic,120,0 @@ -29415,14 +29425,14 @@ block_count,KeyedHasIC_Megamorphic,152,0 block_count,KeyedHasIC_Megamorphic,153,0 block_count,KeyedHasIC_Megamorphic,154,0 -block_count,KeyedHasIC_Megamorphic,155,2482 +block_count,KeyedHasIC_Megamorphic,155,2485 block_count,KeyedHasIC_Megamorphic,156,4 block_count,KeyedHasIC_Megamorphic,157,4 block_count,KeyedHasIC_Megamorphic,158,0 -block_count,KeyedHasIC_Megamorphic,159,2478 -block_count,KeyedHasIC_Megamorphic,160,2482 -block_count,KeyedHasIC_Megamorphic,161,1859 -block_count,KeyedHasIC_Megamorphic,162,622 +block_count,KeyedHasIC_Megamorphic,159,2480 +block_count,KeyedHasIC_Megamorphic,160,2485 +block_count,KeyedHasIC_Megamorphic,161,1861 +block_count,KeyedHasIC_Megamorphic,162,623 block_count,KeyedHasIC_Megamorphic,163,1 block_count,KeyedHasIC_Megamorphic,164,1 block_count,KeyedHasIC_Megamorphic,165,1 @@ -29809,9 +29819,9 @@ block_count,FindOrderedHashMapEntry,14,50 block_count,FindOrderedHashMapEntry,15,55 block_count,FindOrderedHashMapEntry,16,114 -block_count,FindOrderedHashMapEntry,17,215 -block_count,FindOrderedHashMapEntry,18,122 -block_count,FindOrderedHashMapEntry,19,101 +block_count,FindOrderedHashMapEntry,17,282 +block_count,FindOrderedHashMapEntry,18,188 +block_count,FindOrderedHashMapEntry,19,167 block_count,FindOrderedHashMapEntry,20,20 block_count,FindOrderedHashMapEntry,21,93 block_count,FindOrderedHashMapEntry,22,0 @@ -29847,7 +29857,7 @@ block_count,FindOrderedHashMapEntry,52,218 block_count,FindOrderedHashMapEntry,53,7 block_count,FindOrderedHashMapEntry,54,226 -block_count,FindOrderedHashMapEntry,55,282 +block_count,FindOrderedHashMapEntry,55,283 block_count,FindOrderedHashMapEntry,56,246 block_count,FindOrderedHashMapEntry,57,246 block_count,FindOrderedHashMapEntry,58,1 @@ -30655,26 +30665,26 @@ block_count,MapIteratorToList,54,0 block_count,MapIteratorToList,55,0 block_count,MapIteratorToList,56,0 -block_count,Add_Baseline,0,496 -block_count,Add_Baseline,1,291 +block_count,Add_Baseline,0,493 +block_count,Add_Baseline,1,288 block_count,Add_Baseline,2,5 block_count,Add_Baseline,3,5 block_count,Add_Baseline,4,0 -block_count,Add_Baseline,5,285 -block_count,Add_Baseline,6,285 +block_count,Add_Baseline,5,282 +block_count,Add_Baseline,6,282 block_count,Add_Baseline,7,0 -block_count,Add_Baseline,8,285 -block_count,Add_Baseline,9,285 +block_count,Add_Baseline,8,282 +block_count,Add_Baseline,9,282 block_count,Add_Baseline,10,0 -block_count,Add_Baseline,11,205 -block_count,Add_Baseline,12,125 -block_count,Add_Baseline,13,106 -block_count,Add_Baseline,14,106 +block_count,Add_Baseline,11,204 +block_count,Add_Baseline,12,126 +block_count,Add_Baseline,13,107 +block_count,Add_Baseline,14,107 block_count,Add_Baseline,15,0 -block_count,Add_Baseline,16,19 -block_count,Add_Baseline,17,79 -block_count,Add_Baseline,18,79 -block_count,Add_Baseline,19,74 +block_count,Add_Baseline,16,18 +block_count,Add_Baseline,17,78 +block_count,Add_Baseline,18,78 +block_count,Add_Baseline,19,73 block_count,Add_Baseline,20,0 block_count,Add_Baseline,21,0 block_count,Add_Baseline,22,0 @@ -30688,7 +30698,7 @@ block_count,Add_Baseline,30,0 block_count,Add_Baseline,31,0 block_count,Add_Baseline,32,0 -block_count,Add_Baseline,33,74 +block_count,Add_Baseline,33,73 block_count,Add_Baseline,34,5 block_count,Add_Baseline,35,5 block_count,Add_Baseline,36,0 @@ -30697,10 +30707,10 @@ block_count,Add_Baseline,39,0 block_count,Add_Baseline,40,0 block_count,Add_Baseline,41,0 -block_count,Add_Baseline,42,68 +block_count,Add_Baseline,42,67 block_count,Add_Baseline,43,0 -block_count,Add_Baseline,44,68 -block_count,Add_Baseline,45,68 +block_count,Add_Baseline,44,67 +block_count,Add_Baseline,45,67 block_count,Add_Baseline,46,4 block_count,Add_Baseline,47,0 block_count,Add_Baseline,48,0 @@ -30723,15 +30733,15 @@ block_count,Add_Baseline,65,0 block_count,Add_Baseline,66,131 block_count,Add_Baseline,67,131 -block_count,AddSmi_Baseline,0,486 -block_count,AddSmi_Baseline,1,484 -block_count,AddSmi_Baseline,2,484 +block_count,AddSmi_Baseline,0,479 +block_count,AddSmi_Baseline,1,477 +block_count,AddSmi_Baseline,2,477 block_count,AddSmi_Baseline,3,0 -block_count,AddSmi_Baseline,4,484 -block_count,AddSmi_Baseline,5,484 +block_count,AddSmi_Baseline,4,477 +block_count,AddSmi_Baseline,5,477 block_count,AddSmi_Baseline,6,0 -block_count,AddSmi_Baseline,7,2 -block_count,AddSmi_Baseline,8,2 +block_count,AddSmi_Baseline,7,1 +block_count,AddSmi_Baseline,8,1 block_count,AddSmi_Baseline,9,0 block_count,AddSmi_Baseline,10,0 block_count,AddSmi_Baseline,11,0 @@ -30775,28 +30785,28 @@ block_count,AddSmi_Baseline,49,0 block_count,AddSmi_Baseline,50,0 block_count,AddSmi_Baseline,51,0 -block_count,AddSmi_Baseline,52,2 +block_count,AddSmi_Baseline,52,1 block_count,AddSmi_Baseline,53,0 -block_count,AddSmi_Baseline,54,2 -block_count,AddSmi_Baseline,55,2 +block_count,AddSmi_Baseline,54,1 +block_count,AddSmi_Baseline,55,1 block_count,AddSmi_Baseline,56,0 -block_count,AddSmi_Baseline,57,2 -block_count,AddSmi_Baseline,58,2 -block_count,Subtract_Baseline,0,108 -block_count,Subtract_Baseline,1,58 +block_count,AddSmi_Baseline,57,1 +block_count,AddSmi_Baseline,58,1 +block_count,Subtract_Baseline,0,107 +block_count,Subtract_Baseline,1,56 block_count,Subtract_Baseline,2,4 block_count,Subtract_Baseline,3,4 block_count,Subtract_Baseline,4,0 -block_count,Subtract_Baseline,5,53 -block_count,Subtract_Baseline,6,53 +block_count,Subtract_Baseline,5,51 +block_count,Subtract_Baseline,6,51 block_count,Subtract_Baseline,7,0 block_count,Subtract_Baseline,8,0 block_count,Subtract_Baseline,9,0 block_count,Subtract_Baseline,10,0 -block_count,Subtract_Baseline,11,53 +block_count,Subtract_Baseline,11,51 block_count,Subtract_Baseline,12,0 -block_count,Subtract_Baseline,13,53 -block_count,Subtract_Baseline,14,53 +block_count,Subtract_Baseline,13,51 +block_count,Subtract_Baseline,14,51 block_count,Subtract_Baseline,15,50 block_count,Subtract_Baseline,16,50 block_count,Subtract_Baseline,17,47 @@ -30858,8 +30868,8 @@ block_count,SubtractSmi_Baseline,16,0 block_count,SubtractSmi_Baseline,17,15 block_count,SubtractSmi_Baseline,18,15 -block_count,Multiply_Baseline,0,157 -block_count,Multiply_Baseline,1,25 +block_count,Multiply_Baseline,0,158 +block_count,Multiply_Baseline,1,26 block_count,Multiply_Baseline,2,13 block_count,Multiply_Baseline,3,13 block_count,Multiply_Baseline,4,0 @@ -30886,10 +30896,10 @@ block_count,Multiply_Baseline,25,0 block_count,Multiply_Baseline,26,12 block_count,Multiply_Baseline,27,12 -block_count,Multiply_Baseline,28,131 -block_count,Multiply_Baseline,29,131 -block_count,Multiply_Baseline,30,123 -block_count,Multiply_Baseline,31,123 +block_count,Multiply_Baseline,28,132 +block_count,Multiply_Baseline,29,132 +block_count,Multiply_Baseline,30,124 +block_count,Multiply_Baseline,31,124 block_count,Multiply_Baseline,32,0 block_count,Multiply_Baseline,33,7 block_count,Multiply_Baseline,34,0 @@ -30923,14 +30933,14 @@ block_count,Multiply_Baseline,62,0 block_count,Multiply_Baseline,63,0 block_count,Multiply_Baseline,64,0 -block_count,Multiply_Baseline,65,144 +block_count,Multiply_Baseline,65,145 block_count,Multiply_Baseline,66,0 -block_count,Multiply_Baseline,67,144 -block_count,Multiply_Baseline,68,144 +block_count,Multiply_Baseline,67,145 +block_count,Multiply_Baseline,68,145 block_count,Multiply_Baseline,69,0 -block_count,Multiply_Baseline,70,144 -block_count,Multiply_Baseline,71,144 -block_count,MultiplySmi_Baseline,0,25 +block_count,Multiply_Baseline,70,145 +block_count,Multiply_Baseline,71,145 +block_count,MultiplySmi_Baseline,0,24 block_count,MultiplySmi_Baseline,1,20 block_count,MultiplySmi_Baseline,2,20 block_count,MultiplySmi_Baseline,3,13 @@ -30954,14 +30964,14 @@ block_count,MultiplySmi_Baseline,21,0 block_count,MultiplySmi_Baseline,22,20 block_count,MultiplySmi_Baseline,23,20 -block_count,MultiplySmi_Baseline,24,4 -block_count,MultiplySmi_Baseline,25,4 +block_count,MultiplySmi_Baseline,24,3 +block_count,MultiplySmi_Baseline,25,3 block_count,MultiplySmi_Baseline,26,0 -block_count,MultiplySmi_Baseline,27,4 -block_count,MultiplySmi_Baseline,28,4 +block_count,MultiplySmi_Baseline,27,3 +block_count,MultiplySmi_Baseline,28,3 block_count,MultiplySmi_Baseline,29,0 -block_count,MultiplySmi_Baseline,30,4 -block_count,MultiplySmi_Baseline,31,4 +block_count,MultiplySmi_Baseline,30,3 +block_count,MultiplySmi_Baseline,31,3 block_count,MultiplySmi_Baseline,32,0 block_count,MultiplySmi_Baseline,33,0 block_count,MultiplySmi_Baseline,34,0 @@ -30999,7 +31009,7 @@ block_count,Divide_Baseline,4,0 block_count,Divide_Baseline,5,3 block_count,Divide_Baseline,6,3 -block_count,Divide_Baseline,7,3 +block_count,Divide_Baseline,7,2 block_count,Divide_Baseline,8,0 block_count,Divide_Baseline,9,0 block_count,Divide_Baseline,10,0 @@ -31067,7 +31077,7 @@ block_count,DivideSmi_Baseline,0,4 block_count,DivideSmi_Baseline,1,3 block_count,DivideSmi_Baseline,2,3 -block_count,DivideSmi_Baseline,3,2 +block_count,DivideSmi_Baseline,3,3 block_count,DivideSmi_Baseline,4,0 block_count,DivideSmi_Baseline,5,0 block_count,DivideSmi_Baseline,6,0 @@ -31273,7 +31283,7 @@ block_count,Exponentiate_Baseline,46,0 block_count,Exponentiate_Baseline,47,0 block_count,Exponentiate_Baseline,48,0 -block_count,BitwiseAnd_Baseline,0,28 +block_count,BitwiseAnd_Baseline,0,27 block_count,BitwiseAnd_Baseline,1,22 block_count,BitwiseAnd_Baseline,2,5 block_count,BitwiseAnd_Baseline,3,5 @@ -31317,8 +31327,8 @@ block_count,BitwiseAnd_Baseline,41,0 block_count,BitwiseAnd_Baseline,42,0 block_count,BitwiseAnd_Baseline,43,4 -block_count,BitwiseAnd_Baseline,44,28 -block_count,BitwiseAnd_Baseline,45,20 +block_count,BitwiseAnd_Baseline,44,27 +block_count,BitwiseAnd_Baseline,45,19 block_count,BitwiseAnd_Baseline,46,7 block_count,BitwiseAnd_Baseline,47,7 block_count,BitwiseAnd_Baseline,48,1 @@ -31339,20 +31349,20 @@ block_count,BitwiseAnd_Baseline,63,0 block_count,BitwiseAnd_Baseline,64,0 block_count,BitwiseAnd_Baseline,65,6 -block_count,BitwiseAnd_Baseline,66,28 +block_count,BitwiseAnd_Baseline,66,27 block_count,BitwiseAnd_Baseline,67,24 block_count,BitwiseAnd_Baseline,68,3 block_count,BitwiseAnd_Baseline,69,0 block_count,BitwiseAnd_Baseline,70,3 block_count,BitwiseAnd_Baseline,71,3 -block_count,BitwiseAnd_Baseline,72,28 +block_count,BitwiseAnd_Baseline,72,27 block_count,BitwiseAnd_Baseline,73,3 block_count,BitwiseAnd_Baseline,74,24 -block_count,BitwiseAnd_Baseline,75,28 +block_count,BitwiseAnd_Baseline,75,27 block_count,BitwiseAnd_Baseline,76,0 -block_count,BitwiseAnd_Baseline,77,28 -block_count,BitwiseAnd_Baseline,78,28 -block_count,BitwiseAndSmi_Baseline,0,110 +block_count,BitwiseAnd_Baseline,77,27 +block_count,BitwiseAnd_Baseline,78,27 +block_count,BitwiseAndSmi_Baseline,0,100 block_count,BitwiseAndSmi_Baseline,1,5 block_count,BitwiseAndSmi_Baseline,2,5 block_count,BitwiseAndSmi_Baseline,3,1 @@ -31383,12 +31393,12 @@ block_count,BitwiseAndSmi_Baseline,28,0 block_count,BitwiseAndSmi_Baseline,29,5 block_count,BitwiseAndSmi_Baseline,30,5 -block_count,BitwiseAndSmi_Baseline,31,104 -block_count,BitwiseAndSmi_Baseline,32,110 +block_count,BitwiseAndSmi_Baseline,31,94 +block_count,BitwiseAndSmi_Baseline,32,100 block_count,BitwiseAndSmi_Baseline,33,0 -block_count,BitwiseAndSmi_Baseline,34,110 -block_count,BitwiseOr_Baseline,0,54 -block_count,BitwiseOr_Baseline,1,50 +block_count,BitwiseAndSmi_Baseline,34,100 +block_count,BitwiseOr_Baseline,0,52 +block_count,BitwiseOr_Baseline,1,47 block_count,BitwiseOr_Baseline,2,4 block_count,BitwiseOr_Baseline,3,4 block_count,BitwiseOr_Baseline,4,0 @@ -31431,8 +31441,8 @@ block_count,BitwiseOr_Baseline,41,0 block_count,BitwiseOr_Baseline,42,0 block_count,BitwiseOr_Baseline,43,4 -block_count,BitwiseOr_Baseline,44,54 -block_count,BitwiseOr_Baseline,45,51 +block_count,BitwiseOr_Baseline,44,52 +block_count,BitwiseOr_Baseline,45,49 block_count,BitwiseOr_Baseline,46,3 block_count,BitwiseOr_Baseline,47,3 block_count,BitwiseOr_Baseline,48,0 @@ -31453,20 +31463,20 @@ block_count,BitwiseOr_Baseline,63,0 block_count,BitwiseOr_Baseline,64,0 block_count,BitwiseOr_Baseline,65,3 -block_count,BitwiseOr_Baseline,66,54 -block_count,BitwiseOr_Baseline,67,49 +block_count,BitwiseOr_Baseline,66,52 +block_count,BitwiseOr_Baseline,67,46 block_count,BitwiseOr_Baseline,68,5 block_count,BitwiseOr_Baseline,69,0 block_count,BitwiseOr_Baseline,70,5 block_count,BitwiseOr_Baseline,71,5 -block_count,BitwiseOr_Baseline,72,54 +block_count,BitwiseOr_Baseline,72,52 block_count,BitwiseOr_Baseline,73,5 -block_count,BitwiseOr_Baseline,74,49 -block_count,BitwiseOr_Baseline,75,54 +block_count,BitwiseOr_Baseline,74,46 +block_count,BitwiseOr_Baseline,75,52 block_count,BitwiseOr_Baseline,76,0 -block_count,BitwiseOr_Baseline,77,54 -block_count,BitwiseOr_Baseline,78,54 -block_count,BitwiseOrSmi_Baseline,0,253 +block_count,BitwiseOr_Baseline,77,52 +block_count,BitwiseOr_Baseline,78,52 +block_count,BitwiseOrSmi_Baseline,0,247 block_count,BitwiseOrSmi_Baseline,1,4 block_count,BitwiseOrSmi_Baseline,2,4 block_count,BitwiseOrSmi_Baseline,3,0 @@ -31497,10 +31507,10 @@ block_count,BitwiseOrSmi_Baseline,28,2 block_count,BitwiseOrSmi_Baseline,29,2 block_count,BitwiseOrSmi_Baseline,30,4 -block_count,BitwiseOrSmi_Baseline,31,248 -block_count,BitwiseOrSmi_Baseline,32,253 +block_count,BitwiseOrSmi_Baseline,31,242 +block_count,BitwiseOrSmi_Baseline,32,247 block_count,BitwiseOrSmi_Baseline,33,0 -block_count,BitwiseOrSmi_Baseline,34,252 +block_count,BitwiseOrSmi_Baseline,34,247 block_count,BitwiseXor_Baseline,0,34 block_count,BitwiseXor_Baseline,1,19 block_count,BitwiseXor_Baseline,2,15 @@ -31544,7 +31554,7 @@ block_count,BitwiseXor_Baseline,40,0 block_count,BitwiseXor_Baseline,41,0 block_count,BitwiseXor_Baseline,42,0 -block_count,BitwiseXor_Baseline,43,15 +block_count,BitwiseXor_Baseline,43,14 block_count,BitwiseXor_Baseline,44,34 block_count,BitwiseXor_Baseline,45,16 block_count,BitwiseXor_Baseline,46,18 @@ -31615,8 +31625,8 @@ block_count,BitwiseXorSmi_Baseline,32,1 block_count,BitwiseXorSmi_Baseline,33,0 block_count,BitwiseXorSmi_Baseline,34,1 -block_count,ShiftLeft_Baseline,0,5 -block_count,ShiftLeft_Baseline,1,5 +block_count,ShiftLeft_Baseline,0,4 +block_count,ShiftLeft_Baseline,1,4 block_count,ShiftLeft_Baseline,2,0 block_count,ShiftLeft_Baseline,3,0 block_count,ShiftLeft_Baseline,4,0 @@ -31659,8 +31669,8 @@ block_count,ShiftLeft_Baseline,41,0 block_count,ShiftLeft_Baseline,42,0 block_count,ShiftLeft_Baseline,43,0 -block_count,ShiftLeft_Baseline,44,5 -block_count,ShiftLeft_Baseline,45,5 +block_count,ShiftLeft_Baseline,44,4 +block_count,ShiftLeft_Baseline,45,4 block_count,ShiftLeft_Baseline,46,0 block_count,ShiftLeft_Baseline,47,0 block_count,ShiftLeft_Baseline,48,0 @@ -31681,20 +31691,20 @@ block_count,ShiftLeft_Baseline,63,0 block_count,ShiftLeft_Baseline,64,0 block_count,ShiftLeft_Baseline,65,0 -block_count,ShiftLeft_Baseline,66,5 +block_count,ShiftLeft_Baseline,66,4 block_count,ShiftLeft_Baseline,67,4 block_count,ShiftLeft_Baseline,68,0 block_count,ShiftLeft_Baseline,69,0 block_count,ShiftLeft_Baseline,70,0 block_count,ShiftLeft_Baseline,71,0 -block_count,ShiftLeft_Baseline,72,5 +block_count,ShiftLeft_Baseline,72,4 block_count,ShiftLeft_Baseline,73,0 block_count,ShiftLeft_Baseline,74,4 -block_count,ShiftLeft_Baseline,75,5 +block_count,ShiftLeft_Baseline,75,4 block_count,ShiftLeft_Baseline,76,0 -block_count,ShiftLeft_Baseline,77,5 -block_count,ShiftLeft_Baseline,78,5 -block_count,ShiftLeftSmi_Baseline,0,68 +block_count,ShiftLeft_Baseline,77,4 +block_count,ShiftLeft_Baseline,78,4 +block_count,ShiftLeftSmi_Baseline,0,66 block_count,ShiftLeftSmi_Baseline,1,5 block_count,ShiftLeftSmi_Baseline,2,5 block_count,ShiftLeftSmi_Baseline,3,0 @@ -31725,21 +31735,21 @@ block_count,ShiftLeftSmi_Baseline,28,2 block_count,ShiftLeftSmi_Baseline,29,3 block_count,ShiftLeftSmi_Baseline,30,5 -block_count,ShiftLeftSmi_Baseline,31,62 -block_count,ShiftLeftSmi_Baseline,32,60 +block_count,ShiftLeftSmi_Baseline,31,60 +block_count,ShiftLeftSmi_Baseline,32,58 block_count,ShiftLeftSmi_Baseline,33,2 block_count,ShiftLeftSmi_Baseline,34,0 block_count,ShiftLeftSmi_Baseline,35,2 block_count,ShiftLeftSmi_Baseline,36,2 -block_count,ShiftLeftSmi_Baseline,37,62 +block_count,ShiftLeftSmi_Baseline,37,60 block_count,ShiftLeftSmi_Baseline,38,2 -block_count,ShiftLeftSmi_Baseline,39,60 -block_count,ShiftLeftSmi_Baseline,40,62 -block_count,ShiftLeftSmi_Baseline,41,68 +block_count,ShiftLeftSmi_Baseline,39,58 +block_count,ShiftLeftSmi_Baseline,40,60 +block_count,ShiftLeftSmi_Baseline,41,66 block_count,ShiftLeftSmi_Baseline,42,0 -block_count,ShiftLeftSmi_Baseline,43,68 -block_count,ShiftRight_Baseline,0,7 -block_count,ShiftRight_Baseline,1,7 +block_count,ShiftLeftSmi_Baseline,43,66 +block_count,ShiftRight_Baseline,0,6 +block_count,ShiftRight_Baseline,1,6 block_count,ShiftRight_Baseline,2,0 block_count,ShiftRight_Baseline,3,0 block_count,ShiftRight_Baseline,4,0 @@ -31782,8 +31792,8 @@ block_count,ShiftRight_Baseline,41,0 block_count,ShiftRight_Baseline,42,0 block_count,ShiftRight_Baseline,43,0 -block_count,ShiftRight_Baseline,44,7 -block_count,ShiftRight_Baseline,45,7 +block_count,ShiftRight_Baseline,44,6 +block_count,ShiftRight_Baseline,45,6 block_count,ShiftRight_Baseline,46,0 block_count,ShiftRight_Baseline,47,0 block_count,ShiftRight_Baseline,48,0 @@ -31804,20 +31814,20 @@ block_count,ShiftRight_Baseline,63,0 block_count,ShiftRight_Baseline,64,0 block_count,ShiftRight_Baseline,65,0 -block_count,ShiftRight_Baseline,66,7 -block_count,ShiftRight_Baseline,67,7 +block_count,ShiftRight_Baseline,66,6 +block_count,ShiftRight_Baseline,67,6 block_count,ShiftRight_Baseline,68,0 block_count,ShiftRight_Baseline,69,0 block_count,ShiftRight_Baseline,70,0 block_count,ShiftRight_Baseline,71,0 -block_count,ShiftRight_Baseline,72,7 +block_count,ShiftRight_Baseline,72,6 block_count,ShiftRight_Baseline,73,0 -block_count,ShiftRight_Baseline,74,7 -block_count,ShiftRight_Baseline,75,7 +block_count,ShiftRight_Baseline,74,6 +block_count,ShiftRight_Baseline,75,6 block_count,ShiftRight_Baseline,76,0 -block_count,ShiftRight_Baseline,77,7 -block_count,ShiftRight_Baseline,78,7 -block_count,ShiftRightSmi_Baseline,0,208 +block_count,ShiftRight_Baseline,77,6 +block_count,ShiftRight_Baseline,78,6 +block_count,ShiftRightSmi_Baseline,0,205 block_count,ShiftRightSmi_Baseline,1,4 block_count,ShiftRightSmi_Baseline,2,4 block_count,ShiftRightSmi_Baseline,3,0 @@ -31848,10 +31858,10 @@ block_count,ShiftRightSmi_Baseline,28,0 block_count,ShiftRightSmi_Baseline,29,4 block_count,ShiftRightSmi_Baseline,30,4 -block_count,ShiftRightSmi_Baseline,31,204 -block_count,ShiftRightSmi_Baseline,32,208 +block_count,ShiftRightSmi_Baseline,31,200 +block_count,ShiftRightSmi_Baseline,32,205 block_count,ShiftRightSmi_Baseline,33,0 -block_count,ShiftRightSmi_Baseline,34,208 +block_count,ShiftRightSmi_Baseline,34,205 block_count,ShiftRightLogical_Baseline,0,1 block_count,ShiftRightLogical_Baseline,1,1 block_count,ShiftRightLogical_Baseline,2,0 @@ -31972,12 +31982,12 @@ block_count,ShiftRightLogicalSmi_Baseline,41,15 block_count,ShiftRightLogicalSmi_Baseline,42,0 block_count,ShiftRightLogicalSmi_Baseline,43,15 -block_count,Equal_Baseline,0,293 -block_count,Equal_Baseline,1,296 -block_count,Equal_Baseline,2,225 +block_count,Equal_Baseline,0,288 +block_count,Equal_Baseline,1,292 +block_count,Equal_Baseline,2,222 block_count,Equal_Baseline,3,52 -block_count,Equal_Baseline,4,49 -block_count,Equal_Baseline,5,19 +block_count,Equal_Baseline,4,50 +block_count,Equal_Baseline,5,20 block_count,Equal_Baseline,6,19 block_count,Equal_Baseline,7,16 block_count,Equal_Baseline,8,12 @@ -32042,10 +32052,10 @@ block_count,Equal_Baseline,67,0 block_count,Equal_Baseline,68,0 block_count,Equal_Baseline,69,0 -block_count,Equal_Baseline,70,29 +block_count,Equal_Baseline,70,30 block_count,Equal_Baseline,71,0 block_count,Equal_Baseline,72,29 -block_count,Equal_Baseline,73,20 +block_count,Equal_Baseline,73,21 block_count,Equal_Baseline,74,8 block_count,Equal_Baseline,75,8 block_count,Equal_Baseline,76,8 @@ -32059,7 +32069,7 @@ block_count,Equal_Baseline,84,29 block_count,Equal_Baseline,85,2 block_count,Equal_Baseline,86,2 -block_count,Equal_Baseline,87,173 +block_count,Equal_Baseline,87,169 block_count,Equal_Baseline,88,4 block_count,Equal_Baseline,89,0 block_count,Equal_Baseline,90,0 @@ -32079,7 +32089,7 @@ block_count,Equal_Baseline,104,0 block_count,Equal_Baseline,105,0 block_count,Equal_Baseline,106,3 -block_count,Equal_Baseline,107,169 +block_count,Equal_Baseline,107,165 block_count,Equal_Baseline,108,0 block_count,Equal_Baseline,109,0 block_count,Equal_Baseline,110,0 @@ -32095,8 +32105,8 @@ block_count,Equal_Baseline,120,6 block_count,Equal_Baseline,121,4 block_count,Equal_Baseline,122,2 -block_count,Equal_Baseline,123,70 -block_count,Equal_Baseline,124,13 +block_count,Equal_Baseline,123,69 +block_count,Equal_Baseline,124,14 block_count,Equal_Baseline,125,13 block_count,Equal_Baseline,126,9 block_count,Equal_Baseline,127,3 @@ -32114,26 +32124,26 @@ block_count,Equal_Baseline,139,0 block_count,Equal_Baseline,140,0 block_count,Equal_Baseline,141,0 -block_count,Equal_Baseline,142,57 -block_count,Equal_Baseline,143,73 -block_count,Equal_Baseline,144,190 -block_count,Equal_Baseline,145,293 +block_count,Equal_Baseline,142,55 +block_count,Equal_Baseline,143,72 +block_count,Equal_Baseline,144,186 +block_count,Equal_Baseline,145,288 block_count,Equal_Baseline,146,0 -block_count,Equal_Baseline,147,292 -block_count,StrictEqual_Baseline,0,432 -block_count,StrictEqual_Baseline,1,359 +block_count,Equal_Baseline,147,288 +block_count,StrictEqual_Baseline,0,431 +block_count,StrictEqual_Baseline,1,357 block_count,StrictEqual_Baseline,2,246 block_count,StrictEqual_Baseline,3,246 -block_count,StrictEqual_Baseline,4,245 +block_count,StrictEqual_Baseline,4,244 block_count,StrictEqual_Baseline,5,121 block_count,StrictEqual_Baseline,6,121 -block_count,StrictEqual_Baseline,7,54 +block_count,StrictEqual_Baseline,7,53 block_count,StrictEqual_Baseline,8,52 -block_count,StrictEqual_Baseline,9,42 +block_count,StrictEqual_Baseline,9,41 block_count,StrictEqual_Baseline,10,0 -block_count,StrictEqual_Baseline,11,42 +block_count,StrictEqual_Baseline,11,41 block_count,StrictEqual_Baseline,12,0 -block_count,StrictEqual_Baseline,13,42 +block_count,StrictEqual_Baseline,13,41 block_count,StrictEqual_Baseline,14,10 block_count,StrictEqual_Baseline,15,4 block_count,StrictEqual_Baseline,16,5 @@ -32150,13 +32160,13 @@ block_count,StrictEqual_Baseline,27,0 block_count,StrictEqual_Baseline,28,123 block_count,StrictEqual_Baseline,29,0 -block_count,StrictEqual_Baseline,30,123 +block_count,StrictEqual_Baseline,30,122 block_count,StrictEqual_Baseline,31,32 block_count,StrictEqual_Baseline,32,90 -block_count,StrictEqual_Baseline,33,123 +block_count,StrictEqual_Baseline,33,122 block_count,StrictEqual_Baseline,34,0 block_count,StrictEqual_Baseline,35,122 -block_count,StrictEqual_Baseline,36,123 +block_count,StrictEqual_Baseline,36,122 block_count,StrictEqual_Baseline,37,85 block_count,StrictEqual_Baseline,38,37 block_count,StrictEqual_Baseline,39,1 @@ -32169,15 +32179,15 @@ block_count,StrictEqual_Baseline,46,0 block_count,StrictEqual_Baseline,47,0 block_count,StrictEqual_Baseline,48,0 -block_count,StrictEqual_Baseline,49,113 +block_count,StrictEqual_Baseline,49,111 block_count,StrictEqual_Baseline,50,1 block_count,StrictEqual_Baseline,51,0 block_count,StrictEqual_Baseline,52,0 block_count,StrictEqual_Baseline,53,0 block_count,StrictEqual_Baseline,54,0 -block_count,StrictEqual_Baseline,55,112 +block_count,StrictEqual_Baseline,55,110 block_count,StrictEqual_Baseline,56,9 -block_count,StrictEqual_Baseline,57,73 +block_count,StrictEqual_Baseline,57,74 block_count,StrictEqual_Baseline,58,34 block_count,StrictEqual_Baseline,59,34 block_count,StrictEqual_Baseline,60,19 @@ -32188,7 +32198,7 @@ block_count,StrictEqual_Baseline,65,1 block_count,StrictEqual_Baseline,66,1 block_count,StrictEqual_Baseline,67,0 -block_count,StrictEqual_Baseline,68,15 +block_count,StrictEqual_Baseline,68,16 block_count,StrictEqual_Baseline,69,14 block_count,StrictEqual_Baseline,70,0 block_count,StrictEqual_Baseline,71,14 @@ -32197,13 +32207,13 @@ block_count,StrictEqual_Baseline,74,0 block_count,StrictEqual_Baseline,75,0 block_count,StrictEqual_Baseline,76,39 -block_count,StrictEqual_Baseline,77,236 -block_count,StrictEqual_Baseline,78,73 -block_count,StrictEqual_Baseline,79,432 +block_count,StrictEqual_Baseline,77,234 +block_count,StrictEqual_Baseline,78,74 +block_count,StrictEqual_Baseline,79,431 block_count,StrictEqual_Baseline,80,0 -block_count,StrictEqual_Baseline,81,432 -block_count,LessThan_Baseline,0,422 -block_count,LessThan_Baseline,1,422 +block_count,StrictEqual_Baseline,81,431 +block_count,LessThan_Baseline,0,411 +block_count,LessThan_Baseline,1,411 block_count,LessThan_Baseline,2,35 block_count,LessThan_Baseline,3,8 block_count,LessThan_Baseline,4,0 @@ -32281,7 +32291,7 @@ block_count,LessThan_Baseline,76,0 block_count,LessThan_Baseline,77,0 block_count,LessThan_Baseline,78,7 -block_count,LessThan_Baseline,79,26 +block_count,LessThan_Baseline,79,27 block_count,LessThan_Baseline,80,0 block_count,LessThan_Baseline,81,0 block_count,LessThan_Baseline,82,0 @@ -32292,7 +32302,7 @@ block_count,LessThan_Baseline,87,0 block_count,LessThan_Baseline,88,0 block_count,LessThan_Baseline,89,26 -block_count,LessThan_Baseline,90,386 +block_count,LessThan_Baseline,90,375 block_count,LessThan_Baseline,91,1 block_count,LessThan_Baseline,92,0 block_count,LessThan_Baseline,93,0 @@ -32304,22 +32314,22 @@ block_count,LessThan_Baseline,99,0 block_count,LessThan_Baseline,100,0 block_count,LessThan_Baseline,101,1 -block_count,LessThan_Baseline,102,385 -block_count,LessThan_Baseline,103,104 -block_count,LessThan_Baseline,104,280 +block_count,LessThan_Baseline,102,374 +block_count,LessThan_Baseline,103,99 +block_count,LessThan_Baseline,104,274 block_count,LessThan_Baseline,105,0 block_count,LessThan_Baseline,106,0 block_count,LessThan_Baseline,107,0 block_count,LessThan_Baseline,108,0 block_count,LessThan_Baseline,109,0 -block_count,LessThan_Baseline,110,35 +block_count,LessThan_Baseline,110,36 block_count,LessThan_Baseline,111,28 block_count,LessThan_Baseline,112,7 -block_count,LessThan_Baseline,113,133 -block_count,LessThan_Baseline,114,288 -block_count,LessThan_Baseline,115,422 +block_count,LessThan_Baseline,113,128 +block_count,LessThan_Baseline,114,282 +block_count,LessThan_Baseline,115,411 block_count,LessThan_Baseline,116,0 -block_count,LessThan_Baseline,117,421 +block_count,LessThan_Baseline,117,411 block_count,GreaterThan_Baseline,0,145 block_count,GreaterThan_Baseline,1,146 block_count,GreaterThan_Baseline,2,13 @@ -32423,8 +32433,8 @@ block_count,GreaterThan_Baseline,100,0 block_count,GreaterThan_Baseline,101,0 block_count,GreaterThan_Baseline,102,133 -block_count,GreaterThan_Baseline,103,84 -block_count,GreaterThan_Baseline,104,48 +block_count,GreaterThan_Baseline,103,86 +block_count,GreaterThan_Baseline,104,47 block_count,GreaterThan_Baseline,105,0 block_count,GreaterThan_Baseline,106,0 block_count,GreaterThan_Baseline,107,0 @@ -32433,8 +32443,8 @@ block_count,GreaterThan_Baseline,110,12 block_count,GreaterThan_Baseline,111,6 block_count,GreaterThan_Baseline,112,5 -block_count,GreaterThan_Baseline,113,91 -block_count,GreaterThan_Baseline,114,54 +block_count,GreaterThan_Baseline,113,92 +block_count,GreaterThan_Baseline,114,52 block_count,GreaterThan_Baseline,115,145 block_count,GreaterThan_Baseline,116,0 block_count,GreaterThan_Baseline,117,145 @@ -32556,10 +32566,10 @@ block_count,LessThanOrEqual_Baseline,115,54 block_count,LessThanOrEqual_Baseline,116,0 block_count,LessThanOrEqual_Baseline,117,54 -block_count,GreaterThanOrEqual_Baseline,0,103 -block_count,GreaterThanOrEqual_Baseline,1,103 +block_count,GreaterThanOrEqual_Baseline,0,102 +block_count,GreaterThanOrEqual_Baseline,1,102 block_count,GreaterThanOrEqual_Baseline,2,12 -block_count,GreaterThanOrEqual_Baseline,3,9 +block_count,GreaterThanOrEqual_Baseline,3,8 block_count,GreaterThanOrEqual_Baseline,4,0 block_count,GreaterThanOrEqual_Baseline,5,0 block_count,GreaterThanOrEqual_Baseline,6,0 @@ -32658,7 +32668,7 @@ block_count,GreaterThanOrEqual_Baseline,99,0 block_count,GreaterThanOrEqual_Baseline,100,0 block_count,GreaterThanOrEqual_Baseline,101,0 -block_count,GreaterThanOrEqual_Baseline,102,90 +block_count,GreaterThanOrEqual_Baseline,102,89 block_count,GreaterThanOrEqual_Baseline,103,53 block_count,GreaterThanOrEqual_Baseline,104,36 block_count,GreaterThanOrEqual_Baseline,105,0 @@ -32667,13 +32677,13 @@ block_count,GreaterThanOrEqual_Baseline,108,0 block_count,GreaterThanOrEqual_Baseline,109,0 block_count,GreaterThanOrEqual_Baseline,110,12 -block_count,GreaterThanOrEqual_Baseline,111,6 +block_count,GreaterThanOrEqual_Baseline,111,5 block_count,GreaterThanOrEqual_Baseline,112,6 -block_count,GreaterThanOrEqual_Baseline,113,60 -block_count,GreaterThanOrEqual_Baseline,114,43 -block_count,GreaterThanOrEqual_Baseline,115,103 +block_count,GreaterThanOrEqual_Baseline,113,59 +block_count,GreaterThanOrEqual_Baseline,114,42 +block_count,GreaterThanOrEqual_Baseline,115,102 block_count,GreaterThanOrEqual_Baseline,116,0 -block_count,GreaterThanOrEqual_Baseline,117,103 +block_count,GreaterThanOrEqual_Baseline,117,102 block_count,BitwiseNot_Baseline,0,5 block_count,BitwiseNot_Baseline,1,5 block_count,BitwiseNot_Baseline,2,0 @@ -32709,8 +32719,8 @@ block_count,BitwiseNot_Baseline,32,0 block_count,BitwiseNot_Baseline,33,5 block_count,BitwiseNot_Baseline,34,5 -block_count,Decrement_Baseline,0,52 -block_count,Decrement_Baseline,1,52 +block_count,Decrement_Baseline,0,47 +block_count,Decrement_Baseline,1,47 block_count,Decrement_Baseline,2,0 block_count,Decrement_Baseline,3,0 block_count,Decrement_Baseline,4,0 @@ -32725,18 +32735,18 @@ block_count,Decrement_Baseline,13,0 block_count,Decrement_Baseline,14,0 block_count,Decrement_Baseline,15,0 -block_count,Decrement_Baseline,16,51 -block_count,Decrement_Baseline,17,51 +block_count,Decrement_Baseline,16,47 +block_count,Decrement_Baseline,17,47 block_count,Decrement_Baseline,18,0 block_count,Decrement_Baseline,19,0 block_count,Decrement_Baseline,20,0 block_count,Decrement_Baseline,21,0 block_count,Decrement_Baseline,22,0 -block_count,Decrement_Baseline,23,52 +block_count,Decrement_Baseline,23,47 block_count,Decrement_Baseline,24,0 -block_count,Decrement_Baseline,25,52 -block_count,Increment_Baseline,0,286 -block_count,Increment_Baseline,1,286 +block_count,Decrement_Baseline,25,47 +block_count,Increment_Baseline,0,278 +block_count,Increment_Baseline,1,278 block_count,Increment_Baseline,2,0 block_count,Increment_Baseline,3,0 block_count,Increment_Baseline,4,0 @@ -32751,16 +32761,16 @@ block_count,Increment_Baseline,13,0 block_count,Increment_Baseline,14,0 block_count,Increment_Baseline,15,0 -block_count,Increment_Baseline,16,285 -block_count,Increment_Baseline,17,285 +block_count,Increment_Baseline,16,277 +block_count,Increment_Baseline,17,277 block_count,Increment_Baseline,18,0 block_count,Increment_Baseline,19,0 block_count,Increment_Baseline,20,0 block_count,Increment_Baseline,21,0 block_count,Increment_Baseline,22,0 -block_count,Increment_Baseline,23,286 +block_count,Increment_Baseline,23,278 block_count,Increment_Baseline,24,0 -block_count,Increment_Baseline,25,286 +block_count,Increment_Baseline,25,278 block_count,Negate_Baseline,0,11 block_count,Negate_Baseline,1,11 block_count,Negate_Baseline,2,10 @@ -33999,8 +34009,8 @@ block_count,InstanceOf,34,0 block_count,InstanceOf,35,0 block_count,InstanceOf,36,10 -block_count,InstanceOf_Baseline,0,71 -block_count,InstanceOf_Baseline,1,71 +block_count,InstanceOf_Baseline,0,72 +block_count,InstanceOf_Baseline,1,72 block_count,InstanceOf_Baseline,2,2 block_count,InstanceOf_Baseline,3,0 block_count,InstanceOf_Baseline,4,0 @@ -34019,14 +34029,14 @@ block_count,InstanceOf_Baseline,17,0 block_count,InstanceOf_Baseline,18,0 block_count,InstanceOf_Baseline,19,2 -block_count,InstanceOf_Baseline,20,69 +block_count,InstanceOf_Baseline,20,70 block_count,InstanceOf_Baseline,21,0 -block_count,InstanceOf_Baseline,22,71 -block_count,InstanceOf_Baseline,23,71 +block_count,InstanceOf_Baseline,22,72 +block_count,InstanceOf_Baseline,23,72 block_count,InstanceOf_Baseline,24,0 -block_count,InstanceOf_Baseline,25,71 +block_count,InstanceOf_Baseline,25,72 block_count,InstanceOf_Baseline,26,0 -block_count,InstanceOf_Baseline,27,71 +block_count,InstanceOf_Baseline,27,72 block_count,InstanceOf_Baseline,28,0 block_count,InstanceOf_Baseline,29,0 block_count,InstanceOf_Baseline,30,0 @@ -34057,7 +34067,7 @@ block_count,InstanceOf_Baseline,55,0 block_count,InstanceOf_Baseline,56,0 block_count,InstanceOf_Baseline,57,0 -block_count,InstanceOf_Baseline,58,71 +block_count,InstanceOf_Baseline,58,72 block_count,InstanceOf_Baseline,59,0 block_count,InstanceOf_Baseline,60,0 block_count,ForInEnumerate,0,52 @@ -35250,7 +35260,7 @@ block_count,SetPrototypeAdd,29,62 block_count,SetPrototypeAdd,30,88 block_count,SetPrototypeAdd,31,27 -block_count,SetPrototypeAdd,32,26 +block_count,SetPrototypeAdd,32,25 block_count,SetPrototypeAdd,33,1 block_count,SetPrototypeAdd,34,60 block_count,SetPrototypeAdd,35,0 @@ -35573,10 +35583,10 @@ block_count,SetOrSetIteratorToList,54,0 block_count,SetOrSetIteratorToList,55,0 block_count,SetOrSetIteratorToList,56,0 -block_count,StringFromCharCode,0,26 +block_count,StringFromCharCode,0,25 block_count,StringFromCharCode,1,0 -block_count,StringFromCharCode,2,26 -block_count,StringFromCharCode,3,26 +block_count,StringFromCharCode,2,25 +block_count,StringFromCharCode,3,25 block_count,StringFromCharCode,4,7 block_count,StringFromCharCode,5,7 block_count,StringFromCharCode,6,7 @@ -35647,23 +35657,23 @@ block_count,StringFromCharCode,71,0 block_count,StringFromCharCode,72,0 block_count,StringFromCharCode,73,0 -block_count,StringFromCharCode,74,18 -block_count,StringFromCharCode,75,15 -block_count,StringFromCharCode,76,3 -block_count,StringFromCharCode,77,3 +block_count,StringFromCharCode,74,17 +block_count,StringFromCharCode,75,14 +block_count,StringFromCharCode,76,2 +block_count,StringFromCharCode,77,2 block_count,StringFromCharCode,78,2 block_count,StringFromCharCode,79,2 block_count,StringFromCharCode,80,0 block_count,StringFromCharCode,81,2 block_count,StringFromCharCode,82,0 block_count,StringFromCharCode,83,2 -block_count,StringFromCharCode,84,1 -block_count,StringFromCharCode,85,18 +block_count,StringFromCharCode,84,0 +block_count,StringFromCharCode,85,17 block_count,StringFromCharCode,86,0 block_count,StringFromCharCode,87,0 block_count,StringFromCharCode,88,0 block_count,StringFromCharCode,89,0 -block_count,StringFromCharCode,90,18 +block_count,StringFromCharCode,90,17 block_count,StringPrototypeReplace,0,216 block_count,StringPrototypeReplace,1,0 block_count,StringPrototypeReplace,2,216 @@ -35682,20 +35692,20 @@ block_count,StringPrototypeReplace,15,174 block_count,StringPrototypeReplace,16,174 block_count,StringPrototypeReplace,17,0 -block_count,StringPrototypeReplace,18,174 -block_count,StringPrototypeReplace,19,174 +block_count,StringPrototypeReplace,18,173 +block_count,StringPrototypeReplace,19,173 block_count,StringPrototypeReplace,20,0 -block_count,StringPrototypeReplace,21,174 +block_count,StringPrototypeReplace,21,173 block_count,StringPrototypeReplace,22,0 -block_count,StringPrototypeReplace,23,174 +block_count,StringPrototypeReplace,23,173 block_count,StringPrototypeReplace,24,0 -block_count,StringPrototypeReplace,25,174 +block_count,StringPrototypeReplace,25,173 block_count,StringPrototypeReplace,26,0 -block_count,StringPrototypeReplace,27,174 +block_count,StringPrototypeReplace,27,173 block_count,StringPrototypeReplace,28,0 -block_count,StringPrototypeReplace,29,174 +block_count,StringPrototypeReplace,29,173 block_count,StringPrototypeReplace,30,0 -block_count,StringPrototypeReplace,31,174 +block_count,StringPrototypeReplace,31,173 block_count,StringPrototypeReplace,32,0 block_count,StringPrototypeReplace,33,0 block_count,StringPrototypeReplace,34,0 @@ -36820,9 +36830,9 @@ block_count,WeakMapLookupHashIndex,27,64 block_count,WeakMapLookupHashIndex,28,1 block_count,WeakMapLookupHashIndex,29,64 -block_count,WeakMapLookupHashIndex,30,94 -block_count,WeakMapLookupHashIndex,31,94 -block_count,WeakMapLookupHashIndex,32,29 +block_count,WeakMapLookupHashIndex,30,99 +block_count,WeakMapLookupHashIndex,31,99 +block_count,WeakMapLookupHashIndex,32,34 block_count,WeakMapLookupHashIndex,33,64 block_count,WeakMapLookupHashIndex,34,0 block_count,WeakMapGet,0,33 @@ -37702,17 +37712,17 @@ block_count,SubString,222,98 block_count,SubString,223,214 block_count,SubString,224,214 -block_count,GetProperty,0,672 -block_count,GetProperty,1,672 +block_count,GetProperty,0,673 +block_count,GetProperty,1,673 block_count,GetProperty,2,0 -block_count,GetProperty,3,672 -block_count,GetProperty,4,668 -block_count,GetProperty,5,668 -block_count,GetProperty,6,668 +block_count,GetProperty,3,673 +block_count,GetProperty,4,669 +block_count,GetProperty,5,669 +block_count,GetProperty,6,669 block_count,GetProperty,7,0 block_count,GetProperty,8,0 block_count,GetProperty,9,0 -block_count,GetProperty,10,668 +block_count,GetProperty,10,669 block_count,GetProperty,11,546 block_count,GetProperty,12,0 block_count,GetProperty,13,0 @@ -37731,12 +37741,12 @@ block_count,GetProperty,26,0 block_count,GetProperty,27,0 block_count,GetProperty,28,0 -block_count,GetProperty,29,121 -block_count,GetProperty,30,668 -block_count,GetProperty,31,1655 -block_count,GetProperty,32,1655 -block_count,GetProperty,33,1655 -block_count,GetProperty,34,1635 +block_count,GetProperty,29,122 +block_count,GetProperty,30,669 +block_count,GetProperty,31,1658 +block_count,GetProperty,32,1658 +block_count,GetProperty,33,1657 +block_count,GetProperty,34,1638 block_count,GetProperty,35,273 block_count,GetProperty,36,273 block_count,GetProperty,37,0 @@ -37762,29 +37772,29 @@ block_count,GetProperty,57,219 block_count,GetProperty,58,53 block_count,GetProperty,59,0 -block_count,GetProperty,60,1362 +block_count,GetProperty,60,1365 block_count,GetProperty,61,0 -block_count,GetProperty,62,1362 +block_count,GetProperty,62,1365 block_count,GetProperty,63,284 -block_count,GetProperty,64,1077 -block_count,GetProperty,65,2704 -block_count,GetProperty,66,2379 -block_count,GetProperty,67,2273 -block_count,GetProperty,68,1627 -block_count,GetProperty,69,646 +block_count,GetProperty,64,1080 +block_count,GetProperty,65,2712 +block_count,GetProperty,66,2386 +block_count,GetProperty,67,2280 +block_count,GetProperty,68,1632 +block_count,GetProperty,69,647 block_count,GetProperty,70,106 -block_count,GetProperty,71,324 -block_count,GetProperty,72,931 -block_count,GetProperty,73,415 -block_count,GetProperty,74,515 -block_count,GetProperty,75,506 +block_count,GetProperty,71,325 +block_count,GetProperty,72,932 +block_count,GetProperty,73,416 +block_count,GetProperty,74,516 +block_count,GetProperty,75,508 block_count,GetProperty,76,8 -block_count,GetProperty,77,659 +block_count,GetProperty,77,660 block_count,GetProperty,78,1 -block_count,GetProperty,79,657 -block_count,GetProperty,80,646 +block_count,GetProperty,79,658 +block_count,GetProperty,80,647 block_count,GetProperty,81,0 -block_count,GetProperty,82,646 +block_count,GetProperty,82,647 block_count,GetProperty,83,11 block_count,GetProperty,84,0 block_count,GetProperty,85,11 @@ -37792,7 +37802,7 @@ block_count,GetProperty,87,0 block_count,GetProperty,88,0 block_count,GetProperty,89,0 -block_count,GetProperty,90,659 +block_count,GetProperty,90,660 block_count,GetProperty,91,19 block_count,GetProperty,92,0 block_count,GetProperty,93,0 @@ -37835,8 +37845,8 @@ block_count,GetProperty,130,0 block_count,GetProperty,131,0 block_count,GetProperty,132,0 -block_count,GetProperty,133,996 -block_count,GetProperty,134,995 +block_count,GetProperty,133,997 +block_count,GetProperty,134,996 block_count,GetProperty,135,1 block_count,GetProperty,136,0 block_count,GetProperty,137,0 @@ -37874,10 +37884,10 @@ block_count,GetProperty,169,0 block_count,GetProperty,170,0 block_count,GetProperty,171,0 -block_count,GetProperty,172,996 -block_count,GetProperty,173,987 +block_count,GetProperty,172,997 +block_count,GetProperty,173,989 block_count,GetProperty,174,8 -block_count,GetProperty,175,659 +block_count,GetProperty,175,660 block_count,GetProperty,176,1 block_count,GetProperty,177,1 block_count,GetProperty,178,0 @@ -37917,7 +37927,7 @@ block_count,GetProperty,212,0 block_count,GetProperty,213,0 block_count,GetProperty,214,0 -block_count,GetProperty,215,657 +block_count,GetProperty,215,658 block_count,GetProperty,216,0 block_count,GetProperty,217,4 block_count,GetProperty,218,0 @@ -45771,7 +45781,7 @@ block_count,StringPrototypeCharAt,12,0 block_count,StringPrototypeCharAt,13,108 block_count,StringPrototypeCharAt,14,108 -block_count,StringPrototypeCharAt,15,105 +block_count,StringPrototypeCharAt,15,106 block_count,StringPrototypeCharAt,16,59 block_count,StringPrototypeCharAt,17,118 block_count,StringPrototypeCharAt,18,1 @@ -45793,16 +45803,16 @@ block_count,StringPrototypeCharAt,34,0 block_count,StringPrototypeCharAt,35,0 block_count,StringPrototypeCharAt,36,46 -block_count,StringPrototypeCharAt,37,105 -block_count,StringPrototypeCharAt,38,105 +block_count,StringPrototypeCharAt,37,106 +block_count,StringPrototypeCharAt,38,106 block_count,StringPrototypeCharAt,39,12 block_count,StringPrototypeCharAt,40,93 -block_count,StringPrototypeCharAt,41,105 +block_count,StringPrototypeCharAt,41,106 block_count,StringPrototypeCharAt,42,0 block_count,StringPrototypeCharAt,43,0 block_count,StringPrototypeCharAt,44,0 block_count,StringPrototypeCharAt,45,0 -block_count,StringPrototypeCharAt,46,105 +block_count,StringPrototypeCharAt,46,106 block_count,StringPrototypeCharAt,47,2 block_count,StringPrototypeCharCodeAt,0,101 block_count,StringPrototypeCharCodeAt,1,0 @@ -45821,7 +45831,7 @@ block_count,StringPrototypeCharCodeAt,14,101 block_count,StringPrototypeCharCodeAt,15,101 block_count,StringPrototypeCharCodeAt,16,63 -block_count,StringPrototypeCharCodeAt,17,127 +block_count,StringPrototypeCharCodeAt,17,126 block_count,StringPrototypeCharCodeAt,18,62 block_count,StringPrototypeCharCodeAt,19,62 block_count,StringPrototypeCharCodeAt,20,0 @@ -46220,14 +46230,14 @@ block_count,StringAddConvertLeft,172,0 block_count,StringAddConvertLeft,173,0 block_count,StringAddConvertLeft,174,0 -block_count,StringAddConvertRight,0,175 +block_count,StringAddConvertRight,0,174 block_count,StringAddConvertRight,1,162 block_count,StringAddConvertRight,2,121 block_count,StringAddConvertRight,3,41 block_count,StringAddConvertRight,4,12 block_count,StringAddConvertRight,5,53 -block_count,StringAddConvertRight,6,175 -block_count,StringAddConvertRight,7,175 +block_count,StringAddConvertRight,6,174 +block_count,StringAddConvertRight,7,174 block_count,StringAddConvertRight,8,162 block_count,StringAddConvertRight,9,162 block_count,StringAddConvertRight,10,0 @@ -46428,27 +46438,27 @@ block_count,StringCharAt,30,0 block_count,StringCharAt,31,8 block_count,FastNewClosureBaseline,0,76 -block_count,FastNewFunctionContextFunction,0,80 -block_count,FastNewFunctionContextFunction,1,80 +block_count,FastNewFunctionContextFunction,0,81 +block_count,FastNewFunctionContextFunction,1,81 block_count,FastNewFunctionContextFunction,2,0 -block_count,FastNewFunctionContextFunction,3,80 +block_count,FastNewFunctionContextFunction,3,81 block_count,FastNewFunctionContextFunction,4,0 block_count,FastNewFunctionContextFunction,5,0 -block_count,FastNewFunctionContextFunction,6,80 +block_count,FastNewFunctionContextFunction,6,81 block_count,FastNewFunctionContextFunction,7,0 -block_count,FastNewFunctionContextFunction,8,80 +block_count,FastNewFunctionContextFunction,8,81 block_count,FastNewFunctionContextFunction,9,0 -block_count,FastNewFunctionContextFunction,10,80 +block_count,FastNewFunctionContextFunction,10,81 block_count,FastNewFunctionContextFunction,11,22 block_count,FastNewFunctionContextFunction,12,58 -block_count,FastNewFunctionContextFunction,13,791 +block_count,FastNewFunctionContextFunction,13,792 block_count,FastNewFunctionContextFunction,14,733 block_count,FastNewFunctionContextFunction,15,58 -block_count,FastNewFunctionContextFunction,16,80 +block_count,FastNewFunctionContextFunction,16,81 block_count,FastNewFunctionContextFunction,17,49 -block_count,FastNewFunctionContextFunction,18,30 -block_count,CreateRegExpLiteral,0,33 -block_count,CreateRegExpLiteral,1,33 +block_count,FastNewFunctionContextFunction,18,31 +block_count,CreateRegExpLiteral,0,34 +block_count,CreateRegExpLiteral,1,34 block_count,CreateRegExpLiteral,2,0 block_count,CreateRegExpLiteral,3,33 block_count,CreateRegExpLiteral,4,0 @@ -46458,21 +46468,21 @@ block_count,CreateRegExpLiteral,8,33 block_count,CreateRegExpLiteral,9,0 block_count,CreateRegExpLiteral,10,0 -block_count,CreateShallowArrayLiteral,0,17 -block_count,CreateShallowArrayLiteral,1,17 +block_count,CreateShallowArrayLiteral,0,18 +block_count,CreateShallowArrayLiteral,1,18 block_count,CreateShallowArrayLiteral,2,0 -block_count,CreateShallowArrayLiteral,3,17 -block_count,CreateShallowArrayLiteral,4,17 +block_count,CreateShallowArrayLiteral,3,18 +block_count,CreateShallowArrayLiteral,4,18 block_count,CreateShallowArrayLiteral,5,16 -block_count,CreateShallowArrayLiteral,6,11 -block_count,CreateShallowArrayLiteral,7,11 -block_count,CreateShallowArrayLiteral,8,11 +block_count,CreateShallowArrayLiteral,6,12 +block_count,CreateShallowArrayLiteral,7,12 +block_count,CreateShallowArrayLiteral,8,12 block_count,CreateShallowArrayLiteral,9,0 -block_count,CreateShallowArrayLiteral,10,11 +block_count,CreateShallowArrayLiteral,10,12 block_count,CreateShallowArrayLiteral,11,0 block_count,CreateShallowArrayLiteral,12,0 -block_count,CreateShallowArrayLiteral,13,11 -block_count,CreateShallowArrayLiteral,14,11 +block_count,CreateShallowArrayLiteral,13,12 +block_count,CreateShallowArrayLiteral,14,12 block_count,CreateShallowArrayLiteral,15,0 block_count,CreateShallowArrayLiteral,16,0 block_count,CreateShallowArrayLiteral,17,0 @@ -46482,7 +46492,7 @@ block_count,CreateShallowArrayLiteral,21,0 block_count,CreateShallowArrayLiteral,22,0 block_count,CreateShallowArrayLiteral,23,0 -block_count,CreateShallowArrayLiteral,24,11 +block_count,CreateShallowArrayLiteral,24,12 block_count,CreateShallowArrayLiteral,25,0 block_count,CreateShallowArrayLiteral,26,0 block_count,CreateShallowArrayLiteral,27,0 @@ -46494,8 +46504,8 @@ block_count,CreateShallowArrayLiteral,33,0 block_count,CreateShallowArrayLiteral,34,0 block_count,CreateShallowArrayLiteral,35,0 -block_count,CreateShallowArrayLiteral,36,11 -block_count,CreateShallowArrayLiteral,37,11 +block_count,CreateShallowArrayLiteral,36,12 +block_count,CreateShallowArrayLiteral,37,12 block_count,CreateShallowArrayLiteral,38,0 block_count,CreateShallowArrayLiteral,39,4 block_count,CreateShallowArrayLiteral,40,16 @@ -46527,15 +46537,15 @@ block_count,CreateShallowArrayLiteral,66,1 block_count,CreateShallowArrayLiteral,67,0 block_count,CreateShallowArrayLiteral,68,0 -block_count,CreateShallowArrayLiteral,69,17 +block_count,CreateShallowArrayLiteral,69,18 block_count,CreateShallowArrayLiteral,70,0 -block_count,CreateShallowArrayLiteral,71,17 -block_count,CreateShallowArrayLiteral,72,17 +block_count,CreateShallowArrayLiteral,71,18 +block_count,CreateShallowArrayLiteral,72,18 block_count,CreateShallowArrayLiteral,73,0 -block_count,CreateShallowArrayLiteral,74,17 +block_count,CreateShallowArrayLiteral,74,18 block_count,CreateShallowArrayLiteral,75,0 -block_count,CreateShallowArrayLiteral,76,17 -block_count,CreateShallowArrayLiteral,77,17 +block_count,CreateShallowArrayLiteral,76,18 +block_count,CreateShallowArrayLiteral,77,18 block_count,CreateShallowArrayLiteral,78,0 block_count,CreateShallowArrayLiteral,79,0 block_count,CreateEmptyArrayLiteral,0,25 @@ -46709,7 +46719,7 @@ block_count,CreateShallowObjectLiteral,156,0 block_count,CreateShallowObjectLiteral,157,70 block_count,CreateShallowObjectLiteral,158,7 -block_count,CreateShallowObjectLiteral,159,78 +block_count,CreateShallowObjectLiteral,159,77 block_count,CreateShallowObjectLiteral,160,51 block_count,CreateShallowObjectLiteral,161,26 block_count,CreateShallowObjectLiteral,162,0 @@ -46926,7 +46936,7 @@ block_count,ToBoolean,1,24 block_count,ToBoolean,2,23 block_count,ToBoolean,3,22 -block_count,ToBoolean,4,21 +block_count,ToBoolean,4,22 block_count,ToBoolean,5,1 block_count,ToBoolean,6,1 block_count,ToBoolean,7,1 @@ -46943,24 +46953,24 @@ block_count,ToBoolean,18,0 block_count,ToBoolean,19,0 block_count,ToBoolean,20,0 -block_count,ToBooleanForBaselineJump,0,951 -block_count,ToBooleanForBaselineJump,1,878 -block_count,ToBooleanForBaselineJump,2,531 -block_count,ToBooleanForBaselineJump,3,330 -block_count,ToBooleanForBaselineJump,4,330 -block_count,ToBooleanForBaselineJump,5,160 -block_count,ToBooleanForBaselineJump,6,158 -block_count,ToBooleanForBaselineJump,7,158 +block_count,ToBooleanForBaselineJump,0,960 +block_count,ToBooleanForBaselineJump,1,887 +block_count,ToBooleanForBaselineJump,2,537 +block_count,ToBooleanForBaselineJump,3,337 +block_count,ToBooleanForBaselineJump,4,336 +block_count,ToBooleanForBaselineJump,5,163 +block_count,ToBooleanForBaselineJump,6,162 +block_count,ToBooleanForBaselineJump,7,162 block_count,ToBooleanForBaselineJump,8,0 block_count,ToBooleanForBaselineJump,9,0 block_count,ToBooleanForBaselineJump,10,0 block_count,ToBooleanForBaselineJump,11,1 block_count,ToBooleanForBaselineJump,12,0 block_count,ToBooleanForBaselineJump,13,0 -block_count,ToBooleanForBaselineJump,14,170 +block_count,ToBooleanForBaselineJump,14,172 block_count,ToBooleanForBaselineJump,15,0 block_count,ToBooleanForBaselineJump,16,200 -block_count,ToBooleanForBaselineJump,17,347 +block_count,ToBooleanForBaselineJump,17,349 block_count,ToBooleanForBaselineJump,18,73 block_count,ToBooleanForBaselineJump,19,44 block_count,ToBooleanForBaselineJump,20,28 @@ -47717,39 +47727,39 @@ block_count,DataViewPrototypeSetFloat64,114,0 block_count,DataViewPrototypeSetFloat64,115,0 block_count,DataViewPrototypeSetFloat64,116,0 -block_count,FunctionPrototypeHasInstance,0,83 +block_count,FunctionPrototypeHasInstance,0,85 block_count,FunctionPrototypeHasInstance,1,0 -block_count,FunctionPrototypeHasInstance,2,83 -block_count,FunctionPrototypeHasInstance,3,83 -block_count,FunctionPrototypeHasInstance,4,83 -block_count,FunctionPrototypeHasInstance,5,83 +block_count,FunctionPrototypeHasInstance,2,85 +block_count,FunctionPrototypeHasInstance,3,85 +block_count,FunctionPrototypeHasInstance,4,84 +block_count,FunctionPrototypeHasInstance,5,84 block_count,FunctionPrototypeHasInstance,6,0 -block_count,FunctionPrototypeHasInstance,7,83 +block_count,FunctionPrototypeHasInstance,7,84 block_count,FunctionPrototypeHasInstance,8,0 block_count,FunctionPrototypeHasInstance,9,0 block_count,FunctionPrototypeHasInstance,10,0 -block_count,FunctionPrototypeHasInstance,11,83 -block_count,FunctionPrototypeHasInstance,12,83 -block_count,FunctionPrototypeHasInstance,13,83 +block_count,FunctionPrototypeHasInstance,11,84 +block_count,FunctionPrototypeHasInstance,12,84 +block_count,FunctionPrototypeHasInstance,13,84 block_count,FunctionPrototypeHasInstance,14,4 block_count,FunctionPrototypeHasInstance,15,4 block_count,FunctionPrototypeHasInstance,16,0 -block_count,FunctionPrototypeHasInstance,17,78 -block_count,FunctionPrototypeHasInstance,18,83 -block_count,FunctionPrototypeHasInstance,19,280 -block_count,FunctionPrototypeHasInstance,20,274 +block_count,FunctionPrototypeHasInstance,17,80 +block_count,FunctionPrototypeHasInstance,18,84 +block_count,FunctionPrototypeHasInstance,19,285 +block_count,FunctionPrototypeHasInstance,20,279 block_count,FunctionPrototypeHasInstance,21,6 block_count,FunctionPrototypeHasInstance,22,6 block_count,FunctionPrototypeHasInstance,23,6 block_count,FunctionPrototypeHasInstance,24,0 block_count,FunctionPrototypeHasInstance,25,0 block_count,FunctionPrototypeHasInstance,26,0 -block_count,FunctionPrototypeHasInstance,27,280 -block_count,FunctionPrototypeHasInstance,28,229 -block_count,FunctionPrototypeHasInstance,29,197 +block_count,FunctionPrototypeHasInstance,27,285 +block_count,FunctionPrototypeHasInstance,28,232 +block_count,FunctionPrototypeHasInstance,29,201 block_count,FunctionPrototypeHasInstance,30,31 -block_count,FunctionPrototypeHasInstance,31,51 -block_count,FunctionPrototypeHasInstance,32,83 +block_count,FunctionPrototypeHasInstance,31,52 +block_count,FunctionPrototypeHasInstance,32,84 block_count,FunctionPrototypeHasInstance,33,0 block_count,FunctionPrototypeHasInstance,34,0 block_count,FunctionPrototypeHasInstance,35,0 @@ -48120,7 +48130,7 @@ block_count,MathMin,15,1 block_count,MathMin,16,0 block_count,MathMin,17,1 -block_count,MathMin,18,1 +block_count,MathMin,18,0 block_count,MathMin,19,0 block_count,MathMin,20,0 block_count,MathMin,21,0 @@ -48714,7 +48724,7 @@ block_count,NumberParseInt,0,5 block_count,NumberParseInt,1,0 block_count,NumberParseInt,2,5 -block_count,Add,0,12 +block_count,Add,0,11 block_count,Add,1,12 block_count,Add,2,0 block_count,Add,3,0 @@ -49147,7 +49157,7 @@ block_count,GreaterThanOrEqual,41,0 block_count,GreaterThanOrEqual,42,6 block_count,Equal,0,46 -block_count,Equal,1,130 +block_count,Equal,1,129 block_count,Equal,2,127 block_count,Equal,3,73 block_count,Equal,4,56 @@ -49204,7 +49214,7 @@ block_count,Equal,55,3 block_count,Equal,56,17 block_count,Equal,57,35 -block_count,Equal,58,54 +block_count,Equal,58,53 block_count,Equal,59,53 block_count,Equal,60,29 block_count,Equal,61,4 @@ -49237,7 +49247,7 @@ block_count,StrictEqual,1,1180 block_count,StrictEqual,2,1151 block_count,StrictEqual,3,1109 -block_count,StrictEqual,4,1084 +block_count,StrictEqual,4,1085 block_count,StrictEqual,5,163 block_count,StrictEqual,6,163 block_count,StrictEqual,7,0 @@ -52457,15 +52467,15 @@ block_count,RegExpPrototypeTest,86,0 block_count,RegExpPrototypeTest,87,0 block_count,RegExpPrototypeTest,88,0 -block_count,RegExpPrototypeTest,89,39 +block_count,RegExpPrototypeTest,89,38 block_count,RegExpPrototypeTest,90,49 block_count,RegExpPrototypeTest,91,49 block_count,RegExpPrototypeTest,92,0 block_count,RegExpPrototypeTest,93,48 block_count,RegExpPrototypeTest,94,49 -block_count,RegExpPrototypeTest,95,49 -block_count,RegExpPrototypeTest,96,49 -block_count,RegExpPrototypeTest,97,49 +block_count,RegExpPrototypeTest,95,48 +block_count,RegExpPrototypeTest,96,48 +block_count,RegExpPrototypeTest,97,48 block_count,RegExpPrototypeTest,98,40 block_count,RegExpPrototypeTest,99,0 block_count,RegExpPrototypeTest,100,0 @@ -52498,7 +52508,7 @@ block_count,RegExpPrototypeTest,127,40 block_count,RegExpPrototypeTest,128,40 block_count,RegExpPrototypeTest,129,0 -block_count,RegExpPrototypeTest,130,49 +block_count,RegExpPrototypeTest,130,48 block_count,RegExpPrototypeTest,131,34 block_count,RegExpPrototypeTest,132,83 block_count,RegExpPrototypeTest,133,74 @@ -53612,7 +53622,7 @@ block_count,StringPrototypeSlice,65,8 block_count,StringPrototypeSlice,66,8 block_count,StringPrototypeSlice,67,8 -block_count,StringPrototypeSlice,68,5 +block_count,StringPrototypeSlice,68,6 block_count,StringPrototypeSlice,69,4 block_count,StringPrototypeSlice,70,8 block_count,StringPrototypeSlice,71,1 @@ -53626,7 +53636,7 @@ block_count,StringPrototypeSlice,79,0 block_count,StringPrototypeSlice,80,1 block_count,StringPrototypeSlice,81,5 -block_count,StringPrototypeSlice,82,2 +block_count,StringPrototypeSlice,82,3 block_count,StringPrototypeSlice,83,0 block_count,StringPrototypeSlice,84,0 block_count,StringPrototypeSlice,85,0 @@ -54395,27 +54405,27 @@ block_count,StringPrototypeSubstr,286,0 block_count,StringPrototypeSubstr,287,0 block_count,StringPrototypeSubstr,288,0 -block_count,StringPrototypeSubstring,0,2 +block_count,StringPrototypeSubstring,0,1 block_count,StringPrototypeSubstring,1,0 -block_count,StringPrototypeSubstring,2,2 -block_count,StringPrototypeSubstring,3,2 -block_count,StringPrototypeSubstring,4,2 +block_count,StringPrototypeSubstring,2,1 +block_count,StringPrototypeSubstring,3,1 +block_count,StringPrototypeSubstring,4,1 block_count,StringPrototypeSubstring,5,0 block_count,StringPrototypeSubstring,6,0 block_count,StringPrototypeSubstring,7,0 -block_count,StringPrototypeSubstring,8,2 +block_count,StringPrototypeSubstring,8,1 block_count,StringPrototypeSubstring,9,0 -block_count,StringPrototypeSubstring,10,2 -block_count,StringPrototypeSubstring,11,2 +block_count,StringPrototypeSubstring,10,1 +block_count,StringPrototypeSubstring,11,1 block_count,StringPrototypeSubstring,12,0 -block_count,StringPrototypeSubstring,13,2 +block_count,StringPrototypeSubstring,13,1 block_count,StringPrototypeSubstring,14,0 -block_count,StringPrototypeSubstring,15,2 -block_count,StringPrototypeSubstring,16,2 +block_count,StringPrototypeSubstring,15,1 +block_count,StringPrototypeSubstring,16,1 block_count,StringPrototypeSubstring,17,0 -block_count,StringPrototypeSubstring,18,2 -block_count,StringPrototypeSubstring,19,2 -block_count,StringPrototypeSubstring,20,2 +block_count,StringPrototypeSubstring,18,1 +block_count,StringPrototypeSubstring,19,1 +block_count,StringPrototypeSubstring,20,1 block_count,StringPrototypeSubstring,21,1 block_count,StringPrototypeSubstring,22,0 block_count,StringPrototypeSubstring,23,0 @@ -54424,11 +54434,11 @@ block_count,StringPrototypeSubstring,26,0 block_count,StringPrototypeSubstring,27,0 block_count,StringPrototypeSubstring,28,0 -block_count,StringPrototypeSubstring,29,2 -block_count,StringPrototypeSubstring,30,2 +block_count,StringPrototypeSubstring,29,1 +block_count,StringPrototypeSubstring,30,1 block_count,StringPrototypeSubstring,31,1 block_count,StringPrototypeSubstring,32,0 -block_count,StringPrototypeSubstring,33,2 +block_count,StringPrototypeSubstring,33,1 block_count,StringPrototypeSubstring,34,0 block_count,StringPrototypeSubstring,35,1 block_count,StringPrototypeSubstring,36,1 @@ -54445,10 +54455,10 @@ block_count,StringPrototypeSubstring,47,0 block_count,StringPrototypeSubstring,48,0 block_count,StringPrototypeSubstring,49,1 -block_count,StringPrototypeSubstring,50,2 -block_count,StringPrototypeSubstring,51,2 +block_count,StringPrototypeSubstring,50,1 +block_count,StringPrototypeSubstring,51,1 block_count,StringPrototypeSubstring,52,0 -block_count,StringPrototypeSubstring,53,2 +block_count,StringPrototypeSubstring,53,1 block_count,StringPrototypeSubstring,54,1 block_count,StringPrototypeSubstring,55,1 block_count,StringPrototypeSubstring,56,1 @@ -56960,12 +56970,12 @@ block_count,NewRestArgumentsElements,10,0 block_count,NewRestArgumentsElements,11,0 block_count,NewRestArgumentsElements,12,10 -block_count,NewRestArgumentsElements,13,33 -block_count,NewRestArgumentsElements,14,22 -block_count,NewRestArgumentsElements,15,22 -block_count,NewRestArgumentsElements,16,22 +block_count,NewRestArgumentsElements,13,32 +block_count,NewRestArgumentsElements,14,21 +block_count,NewRestArgumentsElements,15,21 +block_count,NewRestArgumentsElements,16,21 block_count,NewRestArgumentsElements,17,0 -block_count,NewRestArgumentsElements,18,22 +block_count,NewRestArgumentsElements,18,21 block_count,NewRestArgumentsElements,19,0 block_count,NewRestArgumentsElements,20,10 block_count,NewRestArgumentsElements,21,0 @@ -57123,12 +57133,12 @@ block_count,FastNewRestArguments,17,0 block_count,FastNewRestArguments,18,0 block_count,FastNewRestArguments,19,1 -block_count,FastNewRestArguments,20,4 -block_count,FastNewRestArguments,21,2 -block_count,FastNewRestArguments,22,2 -block_count,FastNewRestArguments,23,2 +block_count,FastNewRestArguments,20,5 +block_count,FastNewRestArguments,21,3 +block_count,FastNewRestArguments,22,3 +block_count,FastNewRestArguments,23,3 block_count,FastNewRestArguments,24,0 -block_count,FastNewRestArguments,25,2 +block_count,FastNewRestArguments,25,3 block_count,FastNewRestArguments,26,0 block_count,FastNewRestArguments,27,1 block_count,FastNewRestArguments,28,0 @@ -58652,8 +58662,8 @@ block_count,StringFastLocaleCompare,326,370 block_count,StringFastLocaleCompare,327,1174 block_count,StringFastLocaleCompare,328,5749 -block_count,StringFastLocaleCompare,329,5740 -block_count,StringFastLocaleCompare,330,5740 +block_count,StringFastLocaleCompare,329,5739 +block_count,StringFastLocaleCompare,330,5739 block_count,StringFastLocaleCompare,331,5690 block_count,StringFastLocaleCompare,332,5690 block_count,StringFastLocaleCompare,333,4575 @@ -59295,19 +59305,19 @@ block_count,StringToLowerCaseIntl,39,0 block_count,StringToLowerCaseIntl,40,0 block_count,StringToLowerCaseIntl,41,0 -block_count,WideHandler,0,64 +block_count,WideHandler,0,65 block_count,ExtraWideHandler,0,16 -block_count,LdarHandler,0,210 -block_count,LdaZeroHandler,0,22 -block_count,LdaZeroHandler,1,16 -block_count,LdaZeroHandler,2,5 -block_count,LdaSmiHandler,0,23 +block_count,LdarHandler,0,213 +block_count,LdaZeroHandler,0,23 +block_count,LdaZeroHandler,1,17 +block_count,LdaZeroHandler,2,6 +block_count,LdaSmiHandler,0,24 block_count,LdaSmiHandler,1,15 block_count,LdaSmiHandler,2,8 block_count,LdaUndefinedHandler,0,12 -block_count,LdaUndefinedHandler,1,11 +block_count,LdaUndefinedHandler,1,12 block_count,LdaUndefinedHandler,2,0 -block_count,LdaNullHandler,0,1 +block_count,LdaNullHandler,0,2 block_count,LdaNullHandler,1,1 block_count,LdaNullHandler,2,0 block_count,LdaTheHoleHandler,0,0 @@ -59315,7 +59325,7 @@ block_count,LdaTheHoleHandler,2,0 block_count,LdaTrueHandler,0,3 block_count,LdaFalseHandler,0,5 -block_count,LdaConstantHandler,0,20 +block_count,LdaConstantHandler,0,21 block_count,LdaConstantHandler,1,11 block_count,LdaConstantHandler,2,9 block_count,LdaContextSlotHandler,0,1 @@ -59343,10 +59353,10 @@ block_count,LdaImmutableContextSlotHandler,9,0 block_count,LdaImmutableContextSlotHandler,10,9 block_count,LdaImmutableContextSlotHandler,11,2 -block_count,LdaImmutableContextSlotHandler,12,6 -block_count,LdaCurrentContextSlotHandler,0,17 +block_count,LdaImmutableContextSlotHandler,12,7 +block_count,LdaCurrentContextSlotHandler,0,18 block_count,LdaCurrentContextSlotHandler,1,0 -block_count,LdaCurrentContextSlotHandler,2,17 +block_count,LdaCurrentContextSlotHandler,2,18 block_count,LdaCurrentContextSlotHandler,3,7 block_count,LdaCurrentContextSlotHandler,4,10 block_count,LdaImmutableCurrentContextSlotHandler,0,30 @@ -59355,20 +59365,20 @@ block_count,LdaImmutableCurrentContextSlotHandler,3,5 block_count,LdaImmutableCurrentContextSlotHandler,4,25 block_count,StarHandler,0,30 -block_count,MovHandler,0,37 +block_count,MovHandler,0,39 block_count,PushContextHandler,0,2 block_count,PopContextHandler,0,0 block_count,TestReferenceEqualHandler,0,1 block_count,TestReferenceEqualHandler,1,1 block_count,TestReferenceEqualHandler,2,0 block_count,TestReferenceEqualHandler,3,1 -block_count,TestUndetectableHandler,0,1 -block_count,TestUndetectableHandler,1,1 +block_count,TestUndetectableHandler,0,2 +block_count,TestUndetectableHandler,1,2 block_count,TestUndetectableHandler,2,1 block_count,TestUndetectableHandler,3,0 -block_count,TestUndetectableHandler,4,1 +block_count,TestUndetectableHandler,4,2 block_count,TestUndetectableHandler,5,0 -block_count,TestUndetectableHandler,6,1 +block_count,TestUndetectableHandler,6,2 block_count,TestNullHandler,0,0 block_count,TestNullHandler,1,0 block_count,TestNullHandler,2,0 @@ -59428,13 +59438,13 @@ block_count,TestTypeOfHandler,48,0 block_count,TestTypeOfHandler,49,0 block_count,TestTypeOfHandler,50,1 -block_count,LdaGlobalHandler,0,48 -block_count,LdaGlobalHandler,1,39 -block_count,LdaGlobalHandler,2,38 -block_count,LdaGlobalHandler,3,38 -block_count,LdaGlobalHandler,4,38 +block_count,LdaGlobalHandler,0,50 +block_count,LdaGlobalHandler,1,41 +block_count,LdaGlobalHandler,2,40 +block_count,LdaGlobalHandler,3,40 +block_count,LdaGlobalHandler,4,40 block_count,LdaGlobalHandler,5,12 -block_count,LdaGlobalHandler,6,26 +block_count,LdaGlobalHandler,6,28 block_count,LdaGlobalHandler,7,0 block_count,LdaGlobalHandler,8,0 block_count,LdaGlobalHandler,9,0 @@ -59701,11 +59711,11 @@ block_count,LdaGlobalHandler,270,0 block_count,LdaGlobalHandler,271,0 block_count,LdaGlobalHandler,272,0 -block_count,LdaGlobalHandler,273,1 +block_count,LdaGlobalHandler,273,0 block_count,LdaGlobalHandler,274,0 -block_count,LdaGlobalHandler,275,1 +block_count,LdaGlobalHandler,275,0 block_count,LdaGlobalHandler,276,0 -block_count,LdaGlobalHandler,277,1 +block_count,LdaGlobalHandler,277,0 block_count,LdaGlobalHandler,278,0 block_count,LdaGlobalHandler,279,0 block_count,LdaGlobalHandler,280,8 @@ -60655,31 +60665,31 @@ block_count,StaLookupSlotHandler,3,0 block_count,StaLookupSlotHandler,4,0 block_count,StaLookupSlotHandler,5,0 -block_count,GetNamedPropertyHandler,0,143 -block_count,GetNamedPropertyHandler,1,119 -block_count,GetNamedPropertyHandler,2,118 +block_count,GetNamedPropertyHandler,0,145 +block_count,GetNamedPropertyHandler,1,121 +block_count,GetNamedPropertyHandler,2,120 block_count,GetNamedPropertyHandler,3,0 -block_count,GetNamedPropertyHandler,4,119 -block_count,GetNamedPropertyHandler,5,11 +block_count,GetNamedPropertyHandler,4,121 +block_count,GetNamedPropertyHandler,5,10 block_count,GetNamedPropertyHandler,6,0 -block_count,GetNamedPropertyHandler,7,11 +block_count,GetNamedPropertyHandler,7,10 block_count,GetNamedPropertyHandler,8,5 -block_count,GetNamedPropertyHandler,9,6 -block_count,GetNamedPropertyHandler,10,10 +block_count,GetNamedPropertyHandler,9,5 +block_count,GetNamedPropertyHandler,10,9 block_count,GetNamedPropertyHandler,11,4 block_count,GetNamedPropertyHandler,12,4 block_count,GetNamedPropertyHandler,13,0 -block_count,GetNamedPropertyHandler,14,6 -block_count,GetNamedPropertyHandler,15,107 -block_count,GetNamedPropertyHandler,16,113 -block_count,GetNamedPropertyHandler,17,37 -block_count,GetNamedPropertyHandler,18,37 -block_count,GetNamedPropertyHandler,19,33 -block_count,GetNamedPropertyHandler,20,33 +block_count,GetNamedPropertyHandler,14,5 +block_count,GetNamedPropertyHandler,15,110 +block_count,GetNamedPropertyHandler,16,115 +block_count,GetNamedPropertyHandler,17,38 +block_count,GetNamedPropertyHandler,18,38 +block_count,GetNamedPropertyHandler,19,34 +block_count,GetNamedPropertyHandler,20,34 block_count,GetNamedPropertyHandler,21,0 -block_count,GetNamedPropertyHandler,22,33 +block_count,GetNamedPropertyHandler,22,34 block_count,GetNamedPropertyHandler,23,0 -block_count,GetNamedPropertyHandler,24,33 +block_count,GetNamedPropertyHandler,24,34 block_count,GetNamedPropertyHandler,25,7 block_count,GetNamedPropertyHandler,26,0 block_count,GetNamedPropertyHandler,27,0 @@ -60754,21 +60764,21 @@ block_count,GetNamedPropertyHandler,96,7 block_count,GetNamedPropertyHandler,97,0 block_count,GetNamedPropertyHandler,98,26 -block_count,GetNamedPropertyHandler,99,33 -block_count,GetNamedPropertyHandler,100,33 -block_count,GetNamedPropertyHandler,101,32 -block_count,GetNamedPropertyHandler,102,32 +block_count,GetNamedPropertyHandler,99,34 +block_count,GetNamedPropertyHandler,100,34 +block_count,GetNamedPropertyHandler,101,33 +block_count,GetNamedPropertyHandler,102,33 block_count,GetNamedPropertyHandler,103,0 block_count,GetNamedPropertyHandler,104,0 -block_count,GetNamedPropertyHandler,105,33 +block_count,GetNamedPropertyHandler,105,34 block_count,GetNamedPropertyHandler,106,0 block_count,GetNamedPropertyHandler,107,3 block_count,GetNamedPropertyHandler,108,0 block_count,GetNamedPropertyHandler,109,0 block_count,GetNamedPropertyHandler,110,0 -block_count,GetNamedPropertyHandler,111,76 -block_count,GetNamedPropertyHandler,112,110 -block_count,GetNamedPropertyHandler,113,34 +block_count,GetNamedPropertyHandler,111,77 +block_count,GetNamedPropertyHandler,112,111 +block_count,GetNamedPropertyHandler,113,35 block_count,GetNamedPropertyHandler,114,5 block_count,GetNamedPropertyHandler,115,4 block_count,GetNamedPropertyHandler,116,4 @@ -60902,12 +60912,12 @@ block_count,GetNamedPropertyHandler,244,0 block_count,GetNamedPropertyHandler,245,0 block_count,GetNamedPropertyHandler,246,0 -block_count,GetNamedPropertyHandler,247,28 -block_count,GetNamedPropertyHandler,248,75 -block_count,GetNamedPropertyHandler,249,75 +block_count,GetNamedPropertyHandler,247,29 +block_count,GetNamedPropertyHandler,248,76 +block_count,GetNamedPropertyHandler,249,76 block_count,GetNamedPropertyHandler,250,14 block_count,GetNamedPropertyHandler,251,61 -block_count,GetNamedPropertyHandler,252,75 +block_count,GetNamedPropertyHandler,252,76 block_count,GetNamedPropertyHandler,253,70 block_count,GetNamedPropertyHandler,254,5 block_count,GetNamedPropertyHandler,255,5 @@ -60968,34 +60978,34 @@ block_count,GetNamedPropertyHandler,310,5 block_count,GetNamedPropertyHandler,311,0 block_count,GetNamedPropertyHandler,312,24 -block_count,GetNamedPropertyHandler,313,143 -block_count,GetNamedPropertyHandler,314,37 -block_count,GetNamedPropertyHandler,315,106 +block_count,GetNamedPropertyHandler,313,145 +block_count,GetNamedPropertyHandler,314,38 +block_count,GetNamedPropertyHandler,315,107 block_count,GetNamedPropertyFromSuperHandler,0,0 block_count,GetKeyedPropertyHandler,0,54 -block_count,GetKeyedPropertyHandler,1,25 +block_count,GetKeyedPropertyHandler,1,26 block_count,GetKeyedPropertyHandler,2,28 block_count,GetEnumeratedKeyedPropertyHandler,0,1 -block_count,SetNamedPropertyHandler,0,16 +block_count,SetNamedPropertyHandler,0,17 block_count,DefineNamedOwnPropertyHandler,0,3 -block_count,SetKeyedPropertyHandler,0,37 +block_count,SetKeyedPropertyHandler,0,38 block_count,DefineKeyedOwnPropertyHandler,0,0 block_count,StaInArrayLiteralHandler,0,3 block_count,DefineKeyedOwnPropertyInLiteralHandler,0,0 -block_count,AddHandler,0,32 -block_count,AddHandler,1,12 +block_count,AddHandler,0,33 +block_count,AddHandler,1,13 block_count,AddHandler,2,0 block_count,AddHandler,3,0 block_count,AddHandler,4,0 block_count,AddHandler,5,12 block_count,AddHandler,6,12 -block_count,AddHandler,7,11 +block_count,AddHandler,7,12 block_count,AddHandler,8,0 -block_count,AddHandler,9,11 +block_count,AddHandler,9,12 block_count,AddHandler,10,0 block_count,AddHandler,11,12 block_count,AddHandler,12,0 -block_count,AddHandler,13,19 +block_count,AddHandler,13,20 block_count,AddHandler,14,11 block_count,AddHandler,15,10 block_count,AddHandler,16,10 @@ -61064,7 +61074,7 @@ block_count,AddHandler,79,0 block_count,AddHandler,80,11 block_count,AddHandler,81,11 -block_count,AddHandler,82,32 +block_count,AddHandler,82,33 block_count,AddHandler,83,18 block_count,AddHandler,84,14 block_count,SubHandler,0,6 @@ -61167,8 +61177,8 @@ block_count,MulHandler,27,2 block_count,MulHandler,28,0 block_count,MulHandler,29,2 -block_count,MulHandler,30,9 -block_count,MulHandler,31,9 +block_count,MulHandler,30,10 +block_count,MulHandler,31,10 block_count,MulHandler,32,8 block_count,MulHandler,33,8 block_count,MulHandler,34,0 @@ -61211,7 +61221,7 @@ block_count,MulHandler,71,0 block_count,MulHandler,72,0 block_count,MulHandler,73,13 -block_count,MulHandler,74,12 +block_count,MulHandler,74,13 block_count,MulHandler,75,0 block_count,MulHandler,76,12 block_count,MulHandler,77,0 @@ -61220,7 +61230,7 @@ block_count,MulHandler,80,13 block_count,MulHandler,81,13 block_count,MulHandler,82,15 -block_count,MulHandler,83,12 +block_count,MulHandler,83,11 block_count,MulHandler,84,3 block_count,DivHandler,0,1 block_count,DivHandler,1,0 @@ -62078,7 +62088,7 @@ block_count,AddSmiHandler,73,11 block_count,AddSmiHandler,74,6 block_count,AddSmiHandler,75,4 -block_count,SubSmiHandler,0,2 +block_count,SubSmiHandler,0,3 block_count,SubSmiHandler,1,2 block_count,SubSmiHandler,2,2 block_count,SubSmiHandler,3,0 @@ -62135,7 +62145,7 @@ block_count,SubSmiHandler,54,0 block_count,SubSmiHandler,55,0 block_count,SubSmiHandler,56,0 -block_count,SubSmiHandler,57,2 +block_count,SubSmiHandler,57,3 block_count,SubSmiHandler,58,1 block_count,SubSmiHandler,59,1 block_count,MulSmiHandler,0,5 @@ -62573,7 +62583,7 @@ block_count,ShiftRightSmiHandler,39,7 block_count,ShiftRightSmiHandler,40,0 block_count,ShiftRightSmiHandler,41,7 -block_count,ShiftRightLogicalSmiHandler,0,0 +block_count,ShiftRightLogicalSmiHandler,0,1 block_count,ShiftRightLogicalSmiHandler,1,0 block_count,ShiftRightLogicalSmiHandler,2,0 block_count,ShiftRightLogicalSmiHandler,3,0 @@ -62618,14 +62628,14 @@ block_count,ShiftRightLogicalSmiHandler,42,0 block_count,ShiftRightLogicalSmiHandler,43,0 block_count,ShiftRightLogicalSmiHandler,44,0 -block_count,ShiftRightLogicalSmiHandler,45,0 +block_count,ShiftRightLogicalSmiHandler,45,1 block_count,ShiftRightLogicalSmiHandler,46,0 block_count,ShiftRightLogicalSmiHandler,47,0 block_count,ShiftRightLogicalSmiHandler,48,0 block_count,ShiftRightLogicalSmiHandler,49,0 -block_count,ShiftRightLogicalSmiHandler,50,0 -block_count,IncHandler,0,40 -block_count,IncHandler,1,40 +block_count,ShiftRightLogicalSmiHandler,50,1 +block_count,IncHandler,0,41 +block_count,IncHandler,1,41 block_count,IncHandler,2,0 block_count,IncHandler,3,0 block_count,IncHandler,4,0 @@ -62642,21 +62652,21 @@ block_count,IncHandler,15,0 block_count,IncHandler,16,0 block_count,IncHandler,17,0 -block_count,IncHandler,18,40 -block_count,IncHandler,19,40 +block_count,IncHandler,18,41 +block_count,IncHandler,19,41 block_count,IncHandler,20,0 block_count,IncHandler,21,0 block_count,IncHandler,22,0 block_count,IncHandler,23,0 block_count,IncHandler,24,0 -block_count,IncHandler,25,40 -block_count,IncHandler,26,39 +block_count,IncHandler,25,41 +block_count,IncHandler,26,40 block_count,IncHandler,27,0 -block_count,IncHandler,28,39 +block_count,IncHandler,28,40 block_count,IncHandler,29,0 -block_count,IncHandler,30,40 +block_count,IncHandler,30,41 block_count,IncHandler,31,2 -block_count,IncHandler,32,37 +block_count,IncHandler,32,38 block_count,DecHandler,0,7 block_count,DecHandler,1,7 block_count,DecHandler,2,0 @@ -62947,8 +62957,8 @@ block_count,CallAnyReceiverHandler,66,0 block_count,CallAnyReceiverHandler,67,0 block_count,CallAnyReceiverHandler,68,0 -block_count,CallPropertyHandler,0,3 -block_count,CallPropertyHandler,1,2 +block_count,CallPropertyHandler,0,4 +block_count,CallPropertyHandler,1,3 block_count,CallPropertyHandler,2,0 block_count,CallPropertyHandler,3,0 block_count,CallPropertyHandler,4,0 @@ -63013,11 +63023,11 @@ block_count,CallPropertyHandler,63,0 block_count,CallPropertyHandler,64,0 block_count,CallPropertyHandler,65,0 -block_count,CallPropertyHandler,66,2 +block_count,CallPropertyHandler,66,3 block_count,CallPropertyHandler,67,0 -block_count,CallPropertyHandler,68,3 +block_count,CallPropertyHandler,68,4 block_count,CallProperty0Handler,0,12 -block_count,CallProperty0Handler,1,10 +block_count,CallProperty0Handler,1,11 block_count,CallProperty0Handler,2,0 block_count,CallProperty0Handler,3,0 block_count,CallProperty0Handler,4,0 @@ -63085,7 +63095,7 @@ block_count,CallProperty0Handler,66,10 block_count,CallProperty0Handler,67,1 block_count,CallProperty0Handler,68,12 -block_count,CallProperty1Handler,0,26 +block_count,CallProperty1Handler,0,27 block_count,CallProperty1Handler,1,23 block_count,CallProperty1Handler,2,0 block_count,CallProperty1Handler,3,0 @@ -63153,7 +63163,7 @@ block_count,CallProperty1Handler,65,0 block_count,CallProperty1Handler,66,22 block_count,CallProperty1Handler,67,3 -block_count,CallProperty1Handler,68,26 +block_count,CallProperty1Handler,68,27 block_count,CallProperty2Handler,0,6 block_count,CallProperty2Handler,1,4 block_count,CallProperty2Handler,2,0 @@ -63220,7 +63230,7 @@ block_count,CallProperty2Handler,63,0 block_count,CallProperty2Handler,64,0 block_count,CallProperty2Handler,65,0 -block_count,CallProperty2Handler,66,3 +block_count,CallProperty2Handler,66,4 block_count,CallProperty2Handler,67,1 block_count,CallProperty2Handler,68,6 block_count,CallUndefinedReceiverHandler,0,1 @@ -63292,7 +63302,7 @@ block_count,CallUndefinedReceiverHandler,66,0 block_count,CallUndefinedReceiverHandler,67,0 block_count,CallUndefinedReceiverHandler,68,1 -block_count,CallUndefinedReceiver0Handler,0,10 +block_count,CallUndefinedReceiver0Handler,0,9 block_count,CallUndefinedReceiver0Handler,1,9 block_count,CallUndefinedReceiver0Handler,2,1 block_count,CallUndefinedReceiver0Handler,3,1 @@ -63360,7 +63370,7 @@ block_count,CallUndefinedReceiver0Handler,65,0 block_count,CallUndefinedReceiver0Handler,66,8 block_count,CallUndefinedReceiver0Handler,67,0 -block_count,CallUndefinedReceiver0Handler,68,10 +block_count,CallUndefinedReceiver0Handler,68,9 block_count,CallUndefinedReceiver1Handler,0,7 block_count,CallUndefinedReceiver1Handler,1,5 block_count,CallUndefinedReceiver1Handler,2,0 @@ -63628,8 +63638,8 @@ block_count,InvokeIntrinsicHandler,53,0 block_count,InvokeIntrinsicHandler,54,0 block_count,InvokeIntrinsicHandler,55,1 -block_count,ConstructHandler,0,5 -block_count,ConstructHandler,1,2 +block_count,ConstructHandler,0,6 +block_count,ConstructHandler,1,3 block_count,ConstructHandler,2,0 block_count,ConstructHandler,3,0 block_count,ConstructHandler,4,0 @@ -63680,7 +63690,7 @@ block_count,ConstructHandler,49,5 block_count,ConstructHandler,50,0 block_count,ConstructHandler,51,0 -block_count,ConstructHandler,52,5 +block_count,ConstructHandler,52,6 block_count,ConstructHandler,53,3 block_count,ConstructHandler,54,2 block_count,ConstructWithSpreadHandler,0,0 @@ -63758,11 +63768,11 @@ block_count,ConstructForwardAllArgsHandler,45,0 block_count,ConstructForwardAllArgsHandler,46,0 block_count,ConstructForwardAllArgsHandler,47,0 -block_count,TestEqualHandler,0,11 +block_count,TestEqualHandler,0,12 block_count,TestEqualHandler,1,12 -block_count,TestEqualHandler,2,9 -block_count,TestEqualHandler,3,5 -block_count,TestEqualHandler,4,5 +block_count,TestEqualHandler,2,10 +block_count,TestEqualHandler,3,6 +block_count,TestEqualHandler,4,6 block_count,TestEqualHandler,5,0 block_count,TestEqualHandler,6,0 block_count,TestEqualHandler,7,0 @@ -63865,7 +63875,7 @@ block_count,TestEqualHandler,104,0 block_count,TestEqualHandler,105,0 block_count,TestEqualHandler,106,0 -block_count,TestEqualHandler,107,3 +block_count,TestEqualHandler,107,4 block_count,TestEqualHandler,108,0 block_count,TestEqualHandler,109,0 block_count,TestEqualHandler,110,0 @@ -63905,17 +63915,17 @@ block_count,TestEqualHandler,144,1 block_count,TestEqualHandler,145,2 block_count,TestEqualHandler,146,4 -block_count,TestEqualHandler,147,11 +block_count,TestEqualHandler,147,12 block_count,TestEqualHandler,148,11 block_count,TestEqualHandler,149,0 block_count,TestEqualHandler,150,11 block_count,TestEqualHandler,151,0 -block_count,TestEqualHandler,152,11 +block_count,TestEqualHandler,152,12 block_count,TestEqualStrictHandler,0,10 block_count,TestEqualStrictHandler,1,9 block_count,TestEqualStrictHandler,2,7 -block_count,TestEqualStrictHandler,3,6 -block_count,TestEqualStrictHandler,4,6 +block_count,TestEqualStrictHandler,3,7 +block_count,TestEqualStrictHandler,4,7 block_count,TestEqualStrictHandler,5,2 block_count,TestEqualStrictHandler,6,2 block_count,TestEqualStrictHandler,7,0 @@ -64126,9 +64136,9 @@ block_count,TestLessThanHandler,115,3 block_count,TestLessThanHandler,116,30 block_count,TestLessThanHandler,117,34 -block_count,TestLessThanHandler,118,32 +block_count,TestLessThanHandler,118,33 block_count,TestLessThanHandler,119,0 -block_count,TestLessThanHandler,120,32 +block_count,TestLessThanHandler,120,33 block_count,TestLessThanHandler,121,1 block_count,TestLessThanHandler,122,34 block_count,TestGreaterThanHandler,0,4 @@ -65163,9 +65173,9 @@ block_count,JumpLoopHandler,26,0 block_count,JumpLoopHandler,27,0 block_count,JumpLoopHandler,28,0 -block_count,JumpLoopHandler,29,41 -block_count,JumpLoopHandler,30,41 -block_count,JumpLoopHandler,31,41 +block_count,JumpLoopHandler,29,42 +block_count,JumpLoopHandler,30,42 +block_count,JumpLoopHandler,31,42 block_count,JumpLoopHandler,32,0 block_count,JumpLoopHandler,33,0 block_count,JumpLoopHandler,34,0 @@ -65183,7 +65193,7 @@ block_count,JumpLoopHandler,46,0 block_count,JumpLoopHandler,47,43 block_count,JumpLoopHandler,48,43 -block_count,JumpHandler,0,7 +block_count,JumpHandler,0,8 block_count,JumpConstantHandler,0,0 block_count,JumpIfUndefinedConstantHandler,0,0 block_count,JumpIfUndefinedConstantHandler,1,0 @@ -65250,9 +65260,9 @@ block_count,JumpIfToBooleanFalseConstantHandler,21,0 block_count,JumpIfToBooleanFalseConstantHandler,22,0 block_count,JumpIfToBooleanTrueHandler,0,11 -block_count,JumpIfToBooleanTrueHandler,1,10 +block_count,JumpIfToBooleanTrueHandler,1,11 block_count,JumpIfToBooleanTrueHandler,2,6 -block_count,JumpIfToBooleanTrueHandler,3,5 +block_count,JumpIfToBooleanTrueHandler,3,4 block_count,JumpIfToBooleanTrueHandler,4,4 block_count,JumpIfToBooleanTrueHandler,5,2 block_count,JumpIfToBooleanTrueHandler,6,2 @@ -65278,8 +65288,8 @@ block_count,JumpIfToBooleanFalseHandler,3,7 block_count,JumpIfToBooleanFalseHandler,4,7 block_count,JumpIfToBooleanFalseHandler,5,4 -block_count,JumpIfToBooleanFalseHandler,6,3 -block_count,JumpIfToBooleanFalseHandler,7,3 +block_count,JumpIfToBooleanFalseHandler,6,4 +block_count,JumpIfToBooleanFalseHandler,7,4 block_count,JumpIfToBooleanFalseHandler,8,0 block_count,JumpIfToBooleanFalseHandler,9,0 block_count,JumpIfToBooleanFalseHandler,10,0 @@ -65298,9 +65308,9 @@ block_count,JumpIfTrueHandler,0,11 block_count,JumpIfTrueHandler,1,8 block_count,JumpIfTrueHandler,2,3 -block_count,JumpIfFalseHandler,0,59 -block_count,JumpIfFalseHandler,1,37 -block_count,JumpIfFalseHandler,2,21 +block_count,JumpIfFalseHandler,0,60 +block_count,JumpIfFalseHandler,1,38 +block_count,JumpIfFalseHandler,2,22 block_count,JumpIfNullHandler,0,0 block_count,JumpIfNullHandler,1,0 block_count,JumpIfNullHandler,2,0 @@ -65404,9 +65414,9 @@ block_count,SetPendingMessageHandler,0,0 block_count,ThrowHandler,0,2 block_count,ReThrowHandler,0,0 -block_count,ReturnHandler,0,37 +block_count,ReturnHandler,0,38 block_count,ReturnHandler,1,0 -block_count,ReturnHandler,2,36 +block_count,ReturnHandler,2,38 block_count,ThrowReferenceErrorIfHoleHandler,0,1 block_count,ThrowReferenceErrorIfHoleHandler,1,1 block_count,ThrowReferenceErrorIfHoleHandler,2,0 @@ -65441,7 +65451,7 @@ block_count,ResumeGeneratorHandler,6,0 block_count,ResumeGeneratorHandler,7,0 block_count,GetIteratorHandler,0,0 -block_count,ShortStarHandler,0,105 +block_count,ShortStarHandler,0,106 block_count,LdarWideHandler,0,0 block_count,LdaSmiWideHandler,0,11 block_count,LdaConstantWideHandler,0,1 diff -Nru chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/x86.profile chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x86.profile --- chromium-132.0.6834.110/v8/tools/builtins-pgo/profiles/x86.profile 2025-01-21 15:41:16.000000000 +0000 +++ chromium-132.0.6834.159/v8/tools/builtins-pgo/profiles/x86.profile 2025-01-27 17:37:37.000000000 +0000 @@ -360,7 +360,6 @@ block_hint,KeyedStoreIC_Megamorphic,286,285,0 block_hint,KeyedStoreIC_Megamorphic,288,289,1 block_hint,KeyedStoreIC_Megamorphic,295,294,1 -block_hint,KeyedStoreIC_Megamorphic,315,314,1 block_hint,KeyedStoreIC_Megamorphic,685,613,1 block_hint,KeyedStoreIC_Megamorphic,684,683,1 block_hint,KeyedStoreIC_Megamorphic,699,693,0 @@ -756,7 +755,6 @@ block_hint,ElementsTransitionAndStore_InBounds,626,625,0 block_hint,ElementsTransitionAndStore_InBounds,630,629,1 block_hint,ElementsTransitionAndStore_InBounds,633,632,0 -block_hint,ElementsTransitionAndStore_InBounds,635,634,0 block_hint,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,399,404,0 block_hint,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,401,400,1 block_hint,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,403,402,0 @@ -1343,7 +1341,6 @@ block_hint,LoadIC_Noninlined,1,2,1 block_hint,LoadIC_Noninlined,6,5,0 block_hint,LoadIC_Noninlined,19,18,0 -block_hint,LoadIC_Noninlined,22,23,1 block_hint,LoadIC_Noninlined,121,32,0 block_hint,LoadIC_Noninlined,120,33,0 block_hint,LoadIC_Noninlined,37,34,0 @@ -1455,7 +1452,6 @@ block_hint,KeyedLoadIC_Megamorphic,43,46,0 block_hint,KeyedLoadIC_Megamorphic,48,47,1 block_hint,KeyedLoadIC_Megamorphic,61,56,1 -block_hint,KeyedLoadIC_Megamorphic,60,57,1 block_hint,KeyedLoadIC_Megamorphic,341,62,0 block_hint,KeyedLoadIC_Megamorphic,67,66,0 block_hint,KeyedLoadIC_Megamorphic,71,70,0 @@ -1559,6 +1555,7 @@ block_hint,StoreGlobalIC,20,3,0 block_hint,StoreGlobalIC,19,4,0 block_hint,StoreGlobalIC,16,5,0 +block_hint,StoreGlobalIC,6,15,0 block_hint,StoreGlobalIC,8,11,1 block_hint,StoreGlobalIC,10,9,1 block_hint,StoreGlobalIC,13,14,0 @@ -1571,7 +1568,6 @@ block_hint,StoreIC,7,8,0 block_hint,StoreIC,11,10,1 block_hint,StoreIC,13,12,0 -block_hint,StoreIC,16,17,1 block_hint,StoreIC,27,28,1 block_hint,StoreIC,172,34,0 block_hint,StoreIC,38,35,0 @@ -2108,7 +2104,6 @@ block_hint,Equal_Baseline,98,92,0 block_hint,Equal_Baseline,93,97,1 block_hint,Equal_Baseline,109,110,0 -block_hint,Equal_Baseline,139,125,0 block_hint,Equal_Baseline,130,129,0 block_hint,Equal_Baseline,133,132,1 block_hint,Equal_Baseline,136,137,0 @@ -2134,7 +2129,6 @@ block_hint,LessThan_Baseline,23,16,1 block_hint,LessThan_Baseline,41,29,0 block_hint,LessThan_Baseline,37,30,1 -block_hint,LessThan_Baseline,78,69,1 block_hint,LessThan_Baseline,74,70,0 block_hint,LessThan_Baseline,89,80,1 block_hint,LessThan_Baseline,85,81,0 @@ -4839,6 +4833,8 @@ block_hint,MergeAt,68,73,1 block_hint,MergeAt,69,72,1 block_hint,MergeAt,71,70,0 +block_hint,MergeAt,82,79,0 +block_hint,MergeAt,80,81,0 block_hint,MergeAt,86,85,1 block_hint,MergeAt,88,115,1 block_hint,MergeAt,94,114,1 @@ -5178,7 +5174,6 @@ block_hint,MulSmiHandler,33,30,0 block_hint,MulSmiHandler,32,31,1 block_hint,MulSmiHandler,72,71,1 -block_hint,DivSmiHandler,27,1,0 block_hint,DivSmiHandler,15,2,0 block_hint,DivSmiHandler,4,3,0 block_hint,DivSmiHandler,9,8,0 @@ -5338,11 +5333,12 @@ block_hint,TestEqualHandler,4,85,1 block_hint,TestEqualHandler,19,9,0 block_hint,TestEqualHandler,42,41,1 +block_hint,TestEqualHandler,66,67,0 block_hint,TestEqualHandler,72,71,1 block_hint,TestEqualHandler,82,83,0 block_hint,TestEqualHandler,88,107,0 +block_hint,TestEqualHandler,141,127,0 block_hint,TestEqualHandler,138,139,0 -block_hint,TestEqualHandler,143,142,1 block_hint,TestEqualHandler,150,149,1 block_hint,TestEqualStrictHandler,52,3,0 block_hint,TestEqualStrictHandler,4,51,1 @@ -5464,10 +5460,8 @@ block_hint,JumpLoopHandler,30,44,1 block_hint,JumpLoopHandler,32,31,0 block_hint,JumpLoopHandler,47,46,1 -block_hint,JumpIfToBooleanTrueConstantHandler,15,4,0 -block_hint,JumpIfToBooleanTrueConstantHandler,14,5,1 -block_hint,JumpIfToBooleanTrueConstantHandler,20,19,0 block_hint,JumpIfToBooleanFalseConstantHandler,15,4,0 +block_hint,JumpIfToBooleanTrueHandler,15,4,0 block_hint,JumpIfToBooleanTrueHandler,11,6,0 block_hint,JumpIfToBooleanTrueHandler,8,7,0 block_hint,JumpIfToBooleanFalseHandler,15,4,0 @@ -5503,13 +5497,10 @@ block_hint,GetNamedPropertyWideHandler,318,1,0 block_hint,GetNamedPropertyWideHandler,2,3,1 block_hint,GetNamedPropertyWideHandler,108,18,0 -block_hint,GetNamedPropertyWideHandler,23,20,0 -block_hint,GetNamedPropertyWideHandler,22,21,1 -block_hint,GetNamedPropertyWideHandler,100,106,1 -block_hint,GetNamedPropertyWideHandler,103,102,0 block_hint,GetNamedPropertyWideHandler,259,249,0 block_hint,AddWideHandler,2,5,0 block_hint,AddWideHandler,12,6,0 +block_hint,AddWideHandler,16,17,1 block_hint,AddWideHandler,57,20,0 block_hint,AddWideHandler,21,56,1 block_hint,AddWideHandler,50,40,1 @@ -5610,15 +5601,15 @@ block_hint,BitwiseAndSmiExtraWideHandler,27,26,0 block_hint,BitwiseAndSmiExtraWideHandler,41,38,1 block_hint,CallUndefinedReceiver1ExtraWideHandler,1,67,0 -builtin_count,RecordWriteSaveFP,2728 +builtin_count,RecordWriteSaveFP,2724 builtin_count,RecordWriteIgnoreFP,3 builtin_count,EphemeronKeyBarrierSaveFP,0 builtin_count,AdaptorWithBuiltinExitFrame0,101 builtin_count,AdaptorWithBuiltinExitFrame1,3 builtin_count,AdaptorWithBuiltinExitFrame2,0 builtin_count,AdaptorWithBuiltinExitFrame3,7 -builtin_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,337 -builtin_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1266 +builtin_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,331 +builtin_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1255 builtin_count,Call_ReceiverIsAny_Baseline_Compact,4 builtin_count,CallProxy,0 builtin_count,CallWithSpread,17 @@ -5628,16 +5619,16 @@ builtin_count,ConstructWithSpread,0 builtin_count,ConstructWithSpread_Baseline,0 builtin_count,ConstructForwardAllArgs_Baseline,1 -builtin_count,Construct_Baseline,109 -builtin_count,FastNewObject,350 -builtin_count,FastNewClosure,86 +builtin_count,Construct_Baseline,108 +builtin_count,FastNewObject,320 +builtin_count,FastNewClosure,85 builtin_count,StringEqual,675 builtin_count,StringGreaterThan,0 builtin_count,StringGreaterThanOrEqual,3 builtin_count,StringLessThan,421 builtin_count,StringLessThanOrEqual,43 builtin_count,StringCompare,3 -builtin_count,StringSubstring,502 +builtin_count,StringSubstring,503 builtin_count,OrderedHashTableHealIndex,0 builtin_count,CompileLazy,221 builtin_count,CompileLazyDeoptimizedCode,0 @@ -5651,7 +5642,7 @@ builtin_count,GrowFastSmiOrObjectElements,306 builtin_count,ToNumber,0 builtin_count,ToNumber_Baseline,0 -builtin_count,ToNumeric_Baseline,76 +builtin_count,ToNumeric_Baseline,75 builtin_count,ToNumberConvertBigInt,2 builtin_count,Typeof,26 builtin_count,Typeof_Baseline,2 @@ -5660,14 +5651,14 @@ builtin_count,DefineKeyedOwnIC_Megamorphic,2 builtin_count,LoadGlobalIC_NoFeedback,14 builtin_count,LoadIC_FunctionPrototype,186 -builtin_count,LoadIC_StringLength,107 +builtin_count,LoadIC_StringLength,106 builtin_count,LoadIC_StringWrapperLength,0 builtin_count,LoadIC_NoFeedback,40 builtin_count,StoreIC_NoFeedback,5 builtin_count,DefineNamedOwnIC_NoFeedback,3 builtin_count,KeyedLoadIC_SloppyArguments,1 -builtin_count,StoreFastElementIC_InBounds,399 -builtin_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,40 +builtin_count,StoreFastElementIC_InBounds,405 +builtin_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,39 builtin_count,StoreFastElementIC_NoTransitionHandleCOW,0 builtin_count,ElementsTransitionAndStore_InBounds,1 builtin_count,ElementsTransitionAndStore_NoTransitionGrowAndHandleCOW,0 @@ -5698,7 +5689,7 @@ builtin_count,ArrayIndexOfSmiOrObject,125 builtin_count,ArrayIndexOf,23 builtin_count,ArrayPrototypePop,12 -builtin_count,ArrayPrototypePush,299 +builtin_count,ArrayPrototypePush,301 builtin_count,CloneFastJSArray,171 builtin_count,CloneFastJSArrayFillingHoles,36 builtin_count,ExtractFastJSArray,179 @@ -5709,7 +5700,7 @@ builtin_count,ArrayPrototypeEntries,0 builtin_count,ArrayPrototypeKeys,0 builtin_count,ArrayPrototypeValues,29 -builtin_count,ArrayIteratorPrototypeNext,69 +builtin_count,ArrayIteratorPrototypeNext,68 builtin_count,AsyncFunctionEnter,0 builtin_count,AsyncFunctionResolve,0 builtin_count,AsyncFunctionAwait,4 @@ -5734,42 +5725,42 @@ builtin_count,CallIteratorWithFeedbackLazyDeoptContinuation,0 builtin_count,GlobalIsFinite,0 builtin_count,GlobalIsNaN,0 -builtin_count,LoadIC,5040 -builtin_count,LoadIC_Megamorphic,8665 +builtin_count,LoadIC,4995 +builtin_count,LoadIC_Megamorphic,8673 builtin_count,LoadIC_Noninlined,5 -builtin_count,LoadICTrampoline,301 -builtin_count,LoadICBaseline,4531 -builtin_count,LoadICTrampoline_Megamorphic,5296 +builtin_count,LoadICTrampoline,302 +builtin_count,LoadICBaseline,4485 +builtin_count,LoadICTrampoline_Megamorphic,5302 builtin_count,LoadSuperIC,4 builtin_count,LoadSuperICBaseline,4 -builtin_count,KeyedLoadIC,829 +builtin_count,KeyedLoadIC,826 builtin_count,EnumeratedKeyedLoadIC,6 builtin_count,KeyedLoadIC_Megamorphic,2116 builtin_count,KeyedLoadICTrampoline,1 -builtin_count,KeyedLoadICBaseline,772 +builtin_count,KeyedLoadICBaseline,769 builtin_count,EnumeratedKeyedLoadICBaseline,5 -builtin_count,KeyedLoadICTrampoline_Megamorphic,789 -builtin_count,StoreGlobalIC,125 -builtin_count,StoreGlobalICTrampoline,0 -builtin_count,StoreGlobalICBaseline,6 -builtin_count,StoreIC,618 -builtin_count,StoreIC_Megamorphic,1136 +builtin_count,KeyedLoadICTrampoline_Megamorphic,790 +builtin_count,StoreGlobalIC,321 +builtin_count,StoreGlobalICTrampoline,195 +builtin_count,StoreGlobalICBaseline,5 +builtin_count,StoreIC,614 +builtin_count,StoreIC_Megamorphic,1131 builtin_count,StoreICTrampoline,20 -builtin_count,StoreICTrampoline_Megamorphic,552 -builtin_count,StoreICBaseline,564 -builtin_count,DefineNamedOwnIC,71 -builtin_count,DefineNamedOwnICBaseline,65 -builtin_count,KeyedStoreIC,427 -builtin_count,KeyedStoreICTrampoline,0 +builtin_count,StoreICTrampoline_Megamorphic,548 +builtin_count,StoreICBaseline,560 +builtin_count,DefineNamedOwnIC,70 +builtin_count,DefineNamedOwnICBaseline,64 +builtin_count,KeyedStoreIC,433 +builtin_count,KeyedStoreICTrampoline,1 builtin_count,KeyedStoreICTrampoline_Megamorphic,262 -builtin_count,KeyedStoreICBaseline,387 +builtin_count,KeyedStoreICBaseline,393 builtin_count,DefineKeyedOwnIC,2 builtin_count,StoreInArrayLiteralIC,38 builtin_count,StoreInArrayLiteralICBaseline,34 -builtin_count,LoadGlobalIC,843 +builtin_count,LoadGlobalIC,1070 builtin_count,LoadGlobalICInsideTypeof,1 -builtin_count,LoadGlobalICTrampoline,59 -builtin_count,LoadGlobalICBaseline,768 +builtin_count,LoadGlobalICTrampoline,259 +builtin_count,LoadGlobalICBaseline,761 builtin_count,LoadGlobalICInsideTypeofTrampoline,0 builtin_count,LoadGlobalICInsideTypeofBaseline,1 builtin_count,LookupGlobalICBaseline,1 @@ -5794,38 +5785,38 @@ builtin_count,MapPrototypeValues,0 builtin_count,MapIteratorPrototypeNext,8 builtin_count,MapIteratorToList,0 -builtin_count,Add_Baseline,498 -builtin_count,AddSmi_Baseline,482 -builtin_count,Subtract_Baseline,107 +builtin_count,Add_Baseline,496 +builtin_count,AddSmi_Baseline,480 +builtin_count,Subtract_Baseline,108 builtin_count,SubtractSmi_Baseline,62 -builtin_count,Multiply_Baseline,158 -builtin_count,MultiplySmi_Baseline,25 +builtin_count,Multiply_Baseline,159 +builtin_count,MultiplySmi_Baseline,32 builtin_count,Divide_Baseline,13 builtin_count,DivideSmi_Baseline,4 builtin_count,Modulus_Baseline,2 builtin_count,ModulusSmi_Baseline,4 builtin_count,Exponentiate_Baseline,0 -builtin_count,BitwiseAnd_Baseline,28 -builtin_count,BitwiseAndSmi_Baseline,101 -builtin_count,BitwiseOr_Baseline,53 -builtin_count,BitwiseOrSmi_Baseline,248 +builtin_count,BitwiseAnd_Baseline,27 +builtin_count,BitwiseAndSmi_Baseline,102 +builtin_count,BitwiseOr_Baseline,52 +builtin_count,BitwiseOrSmi_Baseline,256 builtin_count,BitwiseXor_Baseline,35 builtin_count,BitwiseXorSmi_Baseline,1 -builtin_count,ShiftLeft_Baseline,5 -builtin_count,ShiftLeftSmi_Baseline,68 +builtin_count,ShiftLeft_Baseline,4 +builtin_count,ShiftLeftSmi_Baseline,67 builtin_count,ShiftRight_Baseline,6 -builtin_count,ShiftRightSmi_Baseline,207 +builtin_count,ShiftRightSmi_Baseline,206 builtin_count,ShiftRightLogical_Baseline,1 -builtin_count,ShiftRightLogicalSmi_Baseline,16 -builtin_count,Equal_Baseline,296 -builtin_count,StrictEqual_Baseline,437 -builtin_count,LessThan_Baseline,410 +builtin_count,ShiftRightLogicalSmi_Baseline,15 +builtin_count,Equal_Baseline,290 +builtin_count,StrictEqual_Baseline,435 +builtin_count,LessThan_Baseline,407 builtin_count,GreaterThan_Baseline,146 -builtin_count,LessThanOrEqual_Baseline,53 +builtin_count,LessThanOrEqual_Baseline,52 builtin_count,GreaterThanOrEqual_Baseline,104 builtin_count,BitwiseNot_Baseline,5 -builtin_count,Decrement_Baseline,49 -builtin_count,Increment_Baseline,277 +builtin_count,Decrement_Baseline,48 +builtin_count,Increment_Baseline,275 builtin_count,Negate_Baseline,11 builtin_count,ObjectAssign,1 builtin_count,ObjectCreate,3 @@ -5837,7 +5828,7 @@ builtin_count,ObjectPrototypeHasOwnProperty,211 builtin_count,ObjectToString,55 builtin_count,InstanceOf,10 -builtin_count,InstanceOf_Baseline,72 +builtin_count,InstanceOf_Baseline,71 builtin_count,ForInEnumerate,52 builtin_count,ForInPrepare,1 builtin_count,ForInFilter,195 @@ -5860,7 +5851,7 @@ builtin_count,StringPrototypeSplit,47 builtin_count,TypedArrayConstructor,2 builtin_count,TypedArrayPrototypeByteLength,0 -builtin_count,TypedArrayPrototypeLength,12 +builtin_count,TypedArrayPrototypeLength,13 builtin_count,TypedArrayPrototypeToStringTag,0 builtin_count,WasmToJsWrapperCSA,0 builtin_count,WeakMapConstructor,0 @@ -5881,7 +5872,7 @@ builtin_count,AsyncGeneratorYieldWithAwaitResolveClosure,7 builtin_count,StringAdd_CheckNone,10000 builtin_count,SubString,1468 -builtin_count,GetProperty,673 +builtin_count,GetProperty,672 builtin_count,GetPropertyWithReceiver,15 builtin_count,SetProperty,0 builtin_count,CreateDataProperty,1 @@ -5927,16 +5918,16 @@ builtin_count,ToString,65 builtin_count,StringPrototypeToString,16 builtin_count,StringPrototypeCharAt,108 -builtin_count,StringPrototypeCharCodeAt,103 +builtin_count,StringPrototypeCharCodeAt,102 builtin_count,StringPrototypeCodePointAt,0 builtin_count,StringPrototypeConcat,0 builtin_count,StringConstructor,29 builtin_count,StringAddConvertLeft,15 builtin_count,StringAddConvertRight,175 builtin_count,StringCharAt,8 -builtin_count,FastNewClosureBaseline,77 -builtin_count,FastNewFunctionContextFunction,81 -builtin_count,CreateRegExpLiteral,34 +builtin_count,FastNewClosureBaseline,76 +builtin_count,FastNewFunctionContextFunction,80 +builtin_count,CreateRegExpLiteral,33 builtin_count,CreateShallowArrayLiteral,18 builtin_count,CreateEmptyArrayLiteral,25 builtin_count,CreateShallowObjectLiteral,27 @@ -5949,7 +5940,7 @@ builtin_count,ToNumeric,14 builtin_count,NumberToString,1330 builtin_count,ToBoolean,25 -builtin_count,ToBooleanForBaselineJump,974 +builtin_count,ToBooleanForBaselineJump,953 builtin_count,ToLength,2 builtin_count,ToName,41 builtin_count,ToObject,216 @@ -5963,7 +5954,7 @@ builtin_count,DataViewPrototypeGetFloat64,0 builtin_count,DataViewPrototypeSetUint32,0 builtin_count,DataViewPrototypeSetFloat64,0 -builtin_count,FunctionPrototypeHasInstance,84 +builtin_count,FunctionPrototypeHasInstance,83 builtin_count,FastFunctionPrototypeBind,2 builtin_count,ForInNext,6 builtin_count,GetIteratorWithFeedback,0 @@ -6005,7 +5996,7 @@ builtin_count,GreaterThan,582 builtin_count,GreaterThanOrEqual,3 builtin_count,Equal,46 -builtin_count,StrictEqual,1327 +builtin_count,StrictEqual,1328 builtin_count,CreateObjectWithoutProperties,9 builtin_count,ObjectIsExtensible,0 builtin_count,ObjectPreventExtensions,0 @@ -6062,7 +6053,7 @@ builtin_count,StringPrototypeSlice,9 builtin_count,StringPrototypeStartsWith,0 builtin_count,StringPrototypeSubstr,1 -builtin_count,StringPrototypeSubstring,2 +builtin_count,StringPrototypeSubstring,1 builtin_count,StringPrototypeTrim,1 builtin_count,SymbolPrototypeToString,2 builtin_count,CreateTypedArray,55 @@ -6107,11 +6098,11 @@ builtin_count,StringToLowerCaseIntl,128 builtin_count,WideHandler,64 builtin_count,ExtraWideHandler,16 -builtin_count,LdarHandler,211 +builtin_count,LdarHandler,212 builtin_count,LdaZeroHandler,23 -builtin_count,LdaSmiHandler,23 -builtin_count,LdaUndefinedHandler,12 -builtin_count,LdaNullHandler,1 +builtin_count,LdaSmiHandler,24 +builtin_count,LdaUndefinedHandler,13 +builtin_count,LdaNullHandler,2 builtin_count,LdaTheHoleHandler,0 builtin_count,LdaTrueHandler,3 builtin_count,LdaFalseHandler,5 @@ -6121,15 +6112,15 @@ builtin_count,LdaCurrentContextSlotHandler,17 builtin_count,LdaImmutableCurrentContextSlotHandler,30 builtin_count,StarHandler,30 -builtin_count,MovHandler,37 +builtin_count,MovHandler,39 builtin_count,PushContextHandler,2 builtin_count,PopContextHandler,0 builtin_count,TestReferenceEqualHandler,1 -builtin_count,TestUndetectableHandler,1 +builtin_count,TestUndetectableHandler,2 builtin_count,TestNullHandler,0 builtin_count,TestUndefinedHandler,0 builtin_count,TestTypeOfHandler,1 -builtin_count,LdaGlobalHandler,48 +builtin_count,LdaGlobalHandler,50 builtin_count,LdaGlobalInsideTypeofHandler,0 builtin_count,StaGlobalHandler,2 builtin_count,StaContextSlotHandler,0 @@ -6139,17 +6130,17 @@ builtin_count,LdaLookupGlobalSlotHandler,1 builtin_count,LdaLookupGlobalSlotInsideTypeofHandler,0 builtin_count,StaLookupSlotHandler,0 -builtin_count,GetNamedPropertyHandler,145 +builtin_count,GetNamedPropertyHandler,146 builtin_count,GetNamedPropertyFromSuperHandler,0 -builtin_count,GetKeyedPropertyHandler,55 +builtin_count,GetKeyedPropertyHandler,54 builtin_count,GetEnumeratedKeyedPropertyHandler,1 -builtin_count,SetNamedPropertyHandler,16 +builtin_count,SetNamedPropertyHandler,18 builtin_count,DefineNamedOwnPropertyHandler,4 -builtin_count,SetKeyedPropertyHandler,38 +builtin_count,SetKeyedPropertyHandler,37 builtin_count,DefineKeyedOwnPropertyHandler,0 builtin_count,StaInArrayLiteralHandler,3 builtin_count,DefineKeyedOwnPropertyInLiteralHandler,0 -builtin_count,AddHandler,32 +builtin_count,AddHandler,33 builtin_count,SubHandler,6 builtin_count,MulHandler,15 builtin_count,DivHandler,1 @@ -6171,8 +6162,8 @@ builtin_count,BitwiseAndSmiHandler,2 builtin_count,ShiftLeftSmiHandler,4 builtin_count,ShiftRightSmiHandler,7 -builtin_count,ShiftRightLogicalSmiHandler,1 -builtin_count,IncHandler,40 +builtin_count,ShiftRightLogicalSmiHandler,0 +builtin_count,IncHandler,41 builtin_count,DecHandler,7 builtin_count,NegateHandler,0 builtin_count,BitwiseNotHandler,0 @@ -6183,9 +6174,9 @@ builtin_count,DeletePropertySloppyHandler,0 builtin_count,FindNonDefaultConstructorOrConstructHandler,0 builtin_count,CallAnyReceiverHandler,0 -builtin_count,CallPropertyHandler,3 +builtin_count,CallPropertyHandler,4 builtin_count,CallProperty0Handler,12 -builtin_count,CallProperty1Handler,26 +builtin_count,CallProperty1Handler,27 builtin_count,CallProperty2Handler,6 builtin_count,CallUndefinedReceiverHandler,1 builtin_count,CallUndefinedReceiver0Handler,9 @@ -6195,15 +6186,15 @@ builtin_count,CallRuntimeHandler,0 builtin_count,CallJSRuntimeHandler,0 builtin_count,InvokeIntrinsicHandler,1 -builtin_count,ConstructHandler,5 +builtin_count,ConstructHandler,6 builtin_count,ConstructWithSpreadHandler,0 builtin_count,ConstructForwardAllArgsHandler,0 builtin_count,TestEqualHandler,12 builtin_count,TestEqualStrictHandler,10 -builtin_count,TestLessThanHandler,33 +builtin_count,TestLessThanHandler,34 builtin_count,TestGreaterThanHandler,4 builtin_count,TestLessThanOrEqualHandler,2 -builtin_count,TestGreaterThanOrEqualHandler,4 +builtin_count,TestGreaterThanOrEqualHandler,5 builtin_count,TestInstanceOfHandler,1 builtin_count,TestInHandler,0 builtin_count,ToNameHandler,0 @@ -6226,7 +6217,7 @@ builtin_count,CreateUnmappedArgumentsHandler,0 builtin_count,CreateRestParameterHandler,0 builtin_count,JumpLoopHandler,46 -builtin_count,JumpHandler,7 +builtin_count,JumpHandler,8 builtin_count,JumpConstantHandler,0 builtin_count,JumpIfUndefinedConstantHandler,0 builtin_count,JumpIfNotUndefinedConstantHandler,0 @@ -6236,10 +6227,10 @@ builtin_count,JumpIfForInDoneConstantHandler,0 builtin_count,JumpIfToBooleanTrueConstantHandler,0 builtin_count,JumpIfToBooleanFalseConstantHandler,0 -builtin_count,JumpIfToBooleanTrueHandler,12 +builtin_count,JumpIfToBooleanTrueHandler,11 builtin_count,JumpIfToBooleanFalseHandler,26 builtin_count,JumpIfTrueHandler,11 -builtin_count,JumpIfFalseHandler,58 +builtin_count,JumpIfFalseHandler,60 builtin_count,JumpIfNullHandler,0 builtin_count,JumpIfNotNullHandler,0 builtin_count,JumpIfUndefinedHandler,1 @@ -6255,7 +6246,7 @@ builtin_count,SetPendingMessageHandler,0 builtin_count,ThrowHandler,2 builtin_count,ReThrowHandler,0 -builtin_count,ReturnHandler,37 +builtin_count,ReturnHandler,38 builtin_count,ThrowReferenceErrorIfHoleHandler,1 builtin_count,ThrowSuperNotCalledIfHoleHandler,0 builtin_count,ThrowSuperAlreadyCalledIfNotHoleHandler,0 @@ -6264,7 +6255,7 @@ builtin_count,SuspendGeneratorHandler,0 builtin_count,ResumeGeneratorHandler,0 builtin_count,GetIteratorHandler,0 -builtin_count,ShortStarHandler,105 +builtin_count,ShortStarHandler,106 builtin_count,LdarWideHandler,0 builtin_count,LdaSmiWideHandler,11 builtin_count,LdaConstantWideHandler,1 @@ -6362,28 +6353,28 @@ builtin_count,CallUndefinedReceiverExtraWideHandler,0 builtin_count,CallUndefinedReceiver1ExtraWideHandler,4 builtin_count,CallUndefinedReceiver2ExtraWideHandler,0 -block_count,RecordWriteSaveFP,0,2728 -block_count,RecordWriteSaveFP,1,2635 +block_count,RecordWriteSaveFP,0,2724 +block_count,RecordWriteSaveFP,1,2630 block_count,RecordWriteSaveFP,2,0 -block_count,RecordWriteSaveFP,3,2635 -block_count,RecordWriteSaveFP,4,2635 -block_count,RecordWriteSaveFP,5,2632 +block_count,RecordWriteSaveFP,3,2630 +block_count,RecordWriteSaveFP,4,2630 +block_count,RecordWriteSaveFP,5,2627 block_count,RecordWriteSaveFP,6,2 block_count,RecordWriteSaveFP,7,0 block_count,RecordWriteSaveFP,8,2 -block_count,RecordWriteSaveFP,9,2635 +block_count,RecordWriteSaveFP,9,2630 block_count,RecordWriteSaveFP,10,93 -block_count,RecordWriteSaveFP,11,61 -block_count,RecordWriteSaveFP,12,57 -block_count,RecordWriteSaveFP,13,57 +block_count,RecordWriteSaveFP,11,63 +block_count,RecordWriteSaveFP,12,60 +block_count,RecordWriteSaveFP,13,60 block_count,RecordWriteSaveFP,14,0 -block_count,RecordWriteSaveFP,15,4 -block_count,RecordWriteSaveFP,16,4 -block_count,RecordWriteSaveFP,17,4 +block_count,RecordWriteSaveFP,15,3 +block_count,RecordWriteSaveFP,16,3 +block_count,RecordWriteSaveFP,17,3 block_count,RecordWriteSaveFP,18,0 block_count,RecordWriteSaveFP,19,0 block_count,RecordWriteSaveFP,20,0 -block_count,RecordWriteSaveFP,21,31 +block_count,RecordWriteSaveFP,21,29 block_count,RecordWriteSaveFP,22,93 block_count,RecordWriteSaveFP,23,93 block_count,RecordWriteSaveFP,24,0 @@ -6404,13 +6395,13 @@ block_count,RecordWriteSaveFP,39,0 block_count,RecordWriteSaveFP,40,93 block_count,RecordWriteSaveFP,41,93 -block_count,RecordWriteSaveFP,42,87 -block_count,RecordWriteSaveFP,43,87 +block_count,RecordWriteSaveFP,42,89 +block_count,RecordWriteSaveFP,43,89 block_count,RecordWriteSaveFP,44,0 block_count,RecordWriteSaveFP,45,0 block_count,RecordWriteSaveFP,46,0 -block_count,RecordWriteSaveFP,47,6 -block_count,RecordWriteSaveFP,48,6 +block_count,RecordWriteSaveFP,47,3 +block_count,RecordWriteSaveFP,48,3 block_count,RecordWriteSaveFP,49,0 block_count,RecordWriteSaveFP,50,0 block_count,RecordWriteSaveFP,51,0 @@ -6418,15 +6409,15 @@ block_count,RecordWriteSaveFP,53,0 block_count,RecordWriteSaveFP,54,93 block_count,RecordWriteIgnoreFP,0,3 -block_count,RecordWriteIgnoreFP,1,3 +block_count,RecordWriteIgnoreFP,1,2 block_count,RecordWriteIgnoreFP,2,0 -block_count,RecordWriteIgnoreFP,3,3 -block_count,RecordWriteIgnoreFP,4,3 -block_count,RecordWriteIgnoreFP,5,3 +block_count,RecordWriteIgnoreFP,3,2 +block_count,RecordWriteIgnoreFP,4,2 +block_count,RecordWriteIgnoreFP,5,2 block_count,RecordWriteIgnoreFP,6,0 block_count,RecordWriteIgnoreFP,7,0 block_count,RecordWriteIgnoreFP,8,0 -block_count,RecordWriteIgnoreFP,9,3 +block_count,RecordWriteIgnoreFP,9,2 block_count,RecordWriteIgnoreFP,10,0 block_count,RecordWriteIgnoreFP,11,0 block_count,RecordWriteIgnoreFP,12,0 @@ -6486,16 +6477,16 @@ block_count,AdaptorWithBuiltinExitFrame3,1,6 block_count,AdaptorWithBuiltinExitFrame3,2,1 block_count,AdaptorWithBuiltinExitFrame3,3,7 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,0,337 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,337 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,2,78 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,3,67 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,4,67 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,5,67 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,0,331 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,1,331 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,2,75 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,3,65 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,4,65 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,5,65 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,6,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,7,67 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,8,67 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,9,67 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,7,65 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,8,65 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,9,65 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,10,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,11,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,12,0 @@ -6513,15 +6504,15 @@ block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,24,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,25,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,26,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,27,67 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,28,67 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,29,67 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,27,65 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,28,65 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,29,65 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,30,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,31,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,32,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,33,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,34,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,35,67 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,35,65 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,36,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,37,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,38,0 @@ -6552,18 +6543,18 @@ block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,63,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,64,0 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,65,10 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,66,258 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,66,256 block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,67,0 -block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,68,337 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,0,1266 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1,1266 +block_count,Call_ReceiverIsNullOrUndefined_Baseline_Compact,68,331 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,0,1255 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,1,1255 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,2,75 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,3,28 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,4,27 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,5,27 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,3,29 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,4,28 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,5,28 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,6,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,7,27 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,8,27 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,7,28 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,8,28 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,9,22 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,10,5 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,11,0 @@ -6620,10 +6611,10 @@ block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,62,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,63,0 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,64,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,65,47 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,66,1190 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,65,46 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,66,1179 block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,67,0 -block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,68,1266 +block_count,Call_ReceiverIsNotNullOrUndefined_Baseline_Compact,68,1255 block_count,Call_ReceiverIsAny_Baseline_Compact,0,4 block_count,Call_ReceiverIsAny_Baseline_Compact,1,4 block_count,Call_ReceiverIsAny_Baseline_Compact,2,0 @@ -6944,7 +6935,7 @@ block_count,CallWithArrayLike,11,0 block_count,CallWithArrayLike,12,26 block_count,CallWithArrayLike,13,26 -block_count,CallWithArrayLike,14,8 +block_count,CallWithArrayLike,14,9 block_count,CallWithArrayLike,15,8 block_count,CallWithArrayLike,16,0 block_count,CallWithArrayLike,17,17 @@ -7252,7 +7243,7 @@ block_count,ConstructForwardAllArgs_Baseline,41,0 block_count,ConstructForwardAllArgs_Baseline,42,0 block_count,ConstructForwardAllArgs_Baseline,43,1 -block_count,Construct_Baseline,0,109 +block_count,Construct_Baseline,0,108 block_count,Construct_Baseline,1,6 block_count,Construct_Baseline,2,3 block_count,Construct_Baseline,3,3 @@ -7297,13 +7288,13 @@ block_count,Construct_Baseline,42,3 block_count,Construct_Baseline,43,102 block_count,Construct_Baseline,44,105 -block_count,FastNewObject,0,350 +block_count,FastNewObject,0,320 block_count,FastNewObject,1,0 -block_count,FastNewObject,2,350 -block_count,FastNewObject,3,350 -block_count,FastNewObject,4,347 -block_count,FastNewObject,5,347 -block_count,FastNewObject,6,347 +block_count,FastNewObject,2,320 +block_count,FastNewObject,3,320 +block_count,FastNewObject,4,317 +block_count,FastNewObject,5,317 +block_count,FastNewObject,6,317 block_count,FastNewObject,7,0 block_count,FastNewObject,8,0 block_count,FastNewObject,9,0 @@ -7329,25 +7320,25 @@ block_count,FastNewObject,29,0 block_count,FastNewObject,30,0 block_count,FastNewObject,31,0 -block_count,FastNewObject,32,347 -block_count,FastNewObject,33,347 +block_count,FastNewObject,32,317 +block_count,FastNewObject,33,317 block_count,FastNewObject,34,0 -block_count,FastNewObject,35,347 +block_count,FastNewObject,35,317 block_count,FastNewObject,36,0 block_count,FastNewObject,37,0 -block_count,FastNewObject,38,347 -block_count,FastNewObject,39,347 +block_count,FastNewObject,38,317 +block_count,FastNewObject,39,317 block_count,FastNewObject,40,1 -block_count,FastNewObject,41,345 +block_count,FastNewObject,41,316 block_count,FastNewObject,42,39 -block_count,FastNewObject,43,306 -block_count,FastNewObject,44,547 -block_count,FastNewObject,45,241 -block_count,FastNewObject,46,306 -block_count,FastNewObject,47,345 -block_count,FastNewObject,48,258 -block_count,FastNewObject,49,87 -block_count,FastNewObject,50,347 +block_count,FastNewObject,43,276 +block_count,FastNewObject,44,459 +block_count,FastNewObject,45,183 +block_count,FastNewObject,46,276 +block_count,FastNewObject,47,316 +block_count,FastNewObject,48,229 +block_count,FastNewObject,49,86 +block_count,FastNewObject,50,317 block_count,FastNewObject,51,0 block_count,FastNewObject,52,0 block_count,FastNewObject,53,0 @@ -7377,33 +7368,33 @@ block_count,FastNewObject,77,2 block_count,FastNewObject,78,0 block_count,FastNewObject,79,2 -block_count,FastNewClosure,0,86 -block_count,FastNewClosure,1,81 -block_count,FastNewClosure,2,81 +block_count,FastNewClosure,0,85 +block_count,FastNewClosure,1,80 +block_count,FastNewClosure,2,80 block_count,FastNewClosure,3,0 block_count,FastNewClosure,4,4 -block_count,FastNewClosure,5,86 +block_count,FastNewClosure,5,85 block_count,FastNewClosure,6,0 -block_count,FastNewClosure,7,86 +block_count,FastNewClosure,7,85 block_count,FastNewClosure,8,85 block_count,FastNewClosure,9,0 block_count,FastNewClosure,10,85 block_count,FastNewClosure,11,0 block_count,FastNewClosure,12,0 -block_count,FastNewClosure,13,86 +block_count,FastNewClosure,13,85 block_count,FastNewClosure,14,25 -block_count,FastNewClosure,15,60 -block_count,FastNewClosure,16,60 +block_count,FastNewClosure,15,59 +block_count,FastNewClosure,16,59 block_count,FastNewClosure,17,0 block_count,FastNewClosure,18,0 block_count,FastNewClosure,19,0 block_count,FastNewClosure,20,0 -block_count,FastNewClosure,21,60 +block_count,FastNewClosure,21,59 block_count,FastNewClosure,22,0 -block_count,FastNewClosure,23,60 -block_count,FastNewClosure,24,86 +block_count,FastNewClosure,23,59 +block_count,FastNewClosure,24,85 block_count,FastNewClosure,25,25 -block_count,FastNewClosure,26,60 +block_count,FastNewClosure,26,59 block_count,StringEqual,0,675 block_count,StringEqual,1,687 block_count,StringEqual,2,264 @@ -7807,12 +7798,12 @@ block_count,StringCompare,54,0 block_count,StringCompare,55,0 block_count,StringCompare,56,0 -block_count,StringSubstring,0,502 +block_count,StringSubstring,0,503 block_count,StringSubstring,1,492 block_count,StringSubstring,2,492 block_count,StringSubstring,3,398 block_count,StringSubstring,4,211 -block_count,StringSubstring,5,422 +block_count,StringSubstring,5,423 block_count,StringSubstring,6,48 block_count,StringSubstring,7,48 block_count,StringSubstring,8,0 @@ -7863,7 +7854,7 @@ block_count,StringSubstring,53,0 block_count,StringSubstring,54,5 block_count,StringSubstring,55,13 -block_count,StringSubstring,56,8 +block_count,StringSubstring,56,7 block_count,StringSubstring,57,5 block_count,StringSubstring,58,5 block_count,StringSubstring,59,2 @@ -8049,7 +8040,7 @@ block_count,CompileLazy,1,221 block_count,CompileLazy,2,0 block_count,CompileLazy,3,4 -block_count,CompileLazy,4,217 +block_count,CompileLazy,4,216 block_count,CompileLazy,5,0 block_count,CompileLazy,6,0 block_count,CompileLazy,7,0 @@ -8069,9 +8060,9 @@ block_count,CompileLazy,21,0 block_count,CompileLazy,22,0 block_count,CompileLazy,23,0 -block_count,CompileLazy,24,221 -block_count,CompileLazy,25,220 -block_count,CompileLazy,26,220 +block_count,CompileLazy,24,220 +block_count,CompileLazy,25,219 +block_count,CompileLazy,26,219 block_count,CompileLazy,27,27 block_count,CompileLazy,28,192 block_count,CompileLazy,29,192 @@ -8217,7 +8208,7 @@ block_count,GrowFastSmiOrObjectElements,20,306 block_count,GrowFastSmiOrObjectElements,21,40 block_count,GrowFastSmiOrObjectElements,22,6229 -block_count,GrowFastSmiOrObjectElements,23,6189 +block_count,GrowFastSmiOrObjectElements,23,6188 block_count,GrowFastSmiOrObjectElements,24,40 block_count,GrowFastSmiOrObjectElements,25,265 block_count,GrowFastSmiOrObjectElements,26,0 @@ -8270,7 +8261,7 @@ block_count,ToNumber_Baseline,22,0 block_count,ToNumber_Baseline,23,0 block_count,ToNumber_Baseline,24,0 -block_count,ToNumeric_Baseline,0,76 +block_count,ToNumeric_Baseline,0,75 block_count,ToNumeric_Baseline,1,0 block_count,ToNumeric_Baseline,2,0 block_count,ToNumeric_Baseline,3,0 @@ -8298,10 +8289,10 @@ block_count,ToNumeric_Baseline,25,0 block_count,ToNumeric_Baseline,26,0 block_count,ToNumeric_Baseline,27,0 -block_count,ToNumeric_Baseline,28,76 -block_count,ToNumeric_Baseline,29,76 +block_count,ToNumeric_Baseline,28,75 +block_count,ToNumeric_Baseline,29,75 block_count,ToNumeric_Baseline,30,0 -block_count,ToNumeric_Baseline,31,76 +block_count,ToNumeric_Baseline,31,75 block_count,ToNumberConvertBigInt,0,2 block_count,ToNumberConvertBigInt,1,2 block_count,ToNumberConvertBigInt,2,0 @@ -8886,14 +8877,14 @@ block_count,KeyedStoreIC_Megamorphic,176,10 block_count,KeyedStoreIC_Megamorphic,177,0 block_count,KeyedStoreIC_Megamorphic,178,10 -block_count,KeyedStoreIC_Megamorphic,179,86 -block_count,KeyedStoreIC_Megamorphic,180,86 +block_count,KeyedStoreIC_Megamorphic,179,87 +block_count,KeyedStoreIC_Megamorphic,180,87 block_count,KeyedStoreIC_Megamorphic,181,0 -block_count,KeyedStoreIC_Megamorphic,182,86 +block_count,KeyedStoreIC_Megamorphic,182,87 block_count,KeyedStoreIC_Megamorphic,183,38 -block_count,KeyedStoreIC_Megamorphic,184,47 -block_count,KeyedStoreIC_Megamorphic,185,86 -block_count,KeyedStoreIC_Megamorphic,186,76 +block_count,KeyedStoreIC_Megamorphic,184,48 +block_count,KeyedStoreIC_Megamorphic,185,87 +block_count,KeyedStoreIC_Megamorphic,186,77 block_count,KeyedStoreIC_Megamorphic,187,10 block_count,KeyedStoreIC_Megamorphic,188,10 block_count,KeyedStoreIC_Megamorphic,189,10 @@ -8947,7 +8938,7 @@ block_count,KeyedStoreIC_Megamorphic,237,0 block_count,KeyedStoreIC_Megamorphic,238,0 block_count,KeyedStoreIC_Megamorphic,239,59 -block_count,KeyedStoreIC_Megamorphic,240,50 +block_count,KeyedStoreIC_Megamorphic,240,51 block_count,KeyedStoreIC_Megamorphic,241,50 block_count,KeyedStoreIC_Megamorphic,242,2 block_count,KeyedStoreIC_Megamorphic,243,2 @@ -8957,7 +8948,7 @@ block_count,KeyedStoreIC_Megamorphic,247,7 block_count,KeyedStoreIC_Megamorphic,248,0 block_count,KeyedStoreIC_Megamorphic,249,7 -block_count,KeyedStoreIC_Megamorphic,250,40 +block_count,KeyedStoreIC_Megamorphic,250,41 block_count,KeyedStoreIC_Megamorphic,251,0 block_count,KeyedStoreIC_Megamorphic,252,0 block_count,KeyedStoreIC_Megamorphic,253,0 @@ -9396,7 +9387,7 @@ block_count,KeyedStoreIC_Megamorphic,686,0 block_count,KeyedStoreIC_Megamorphic,687,68 block_count,KeyedStoreIC_Megamorphic,688,68 -block_count,KeyedStoreIC_Megamorphic,689,133 +block_count,KeyedStoreIC_Megamorphic,689,134 block_count,KeyedStoreIC_Megamorphic,690,75 block_count,KeyedStoreIC_Megamorphic,691,65 block_count,KeyedStoreIC_Megamorphic,692,9 @@ -11293,9 +11284,9 @@ block_count,LoadIC_FunctionPrototype,0,186 block_count,LoadIC_FunctionPrototype,1,186 block_count,LoadIC_FunctionPrototype,2,1 -block_count,LoadIC_FunctionPrototype,3,185 +block_count,LoadIC_FunctionPrototype,3,184 block_count,LoadIC_FunctionPrototype,4,0 -block_count,LoadIC_StringLength,0,107 +block_count,LoadIC_StringLength,0,106 block_count,LoadIC_StringWrapperLength,0,0 block_count,LoadIC_NoFeedback,0,40 block_count,LoadIC_NoFeedback,1,40 @@ -12420,26 +12411,26 @@ block_count,KeyedLoadIC_SloppyArguments,20,0 block_count,KeyedLoadIC_SloppyArguments,21,0 block_count,KeyedLoadIC_SloppyArguments,22,0 -block_count,StoreFastElementIC_InBounds,0,399 +block_count,StoreFastElementIC_InBounds,0,405 block_count,StoreFastElementIC_InBounds,1,0 -block_count,StoreFastElementIC_InBounds,2,10 -block_count,StoreFastElementIC_InBounds,3,10 +block_count,StoreFastElementIC_InBounds,2,11 +block_count,StoreFastElementIC_InBounds,3,11 block_count,StoreFastElementIC_InBounds,4,0 block_count,StoreFastElementIC_InBounds,5,0 block_count,StoreFastElementIC_InBounds,6,0 block_count,StoreFastElementIC_InBounds,7,0 block_count,StoreFastElementIC_InBounds,8,0 -block_count,StoreFastElementIC_InBounds,9,10 -block_count,StoreFastElementIC_InBounds,10,10 +block_count,StoreFastElementIC_InBounds,9,11 +block_count,StoreFastElementIC_InBounds,10,11 block_count,StoreFastElementIC_InBounds,11,0 -block_count,StoreFastElementIC_InBounds,12,10 +block_count,StoreFastElementIC_InBounds,12,11 block_count,StoreFastElementIC_InBounds,13,0 -block_count,StoreFastElementIC_InBounds,14,10 -block_count,StoreFastElementIC_InBounds,15,10 +block_count,StoreFastElementIC_InBounds,14,11 +block_count,StoreFastElementIC_InBounds,15,11 block_count,StoreFastElementIC_InBounds,16,0 -block_count,StoreFastElementIC_InBounds,17,10 +block_count,StoreFastElementIC_InBounds,17,11 block_count,StoreFastElementIC_InBounds,18,0 -block_count,StoreFastElementIC_InBounds,19,10 +block_count,StoreFastElementIC_InBounds,19,11 block_count,StoreFastElementIC_InBounds,20,0 block_count,StoreFastElementIC_InBounds,21,12 block_count,StoreFastElementIC_InBounds,22,12 @@ -12626,8 +12617,8 @@ block_count,StoreFastElementIC_InBounds,203,0 block_count,StoreFastElementIC_InBounds,204,17 block_count,StoreFastElementIC_InBounds,205,17 -block_count,StoreFastElementIC_InBounds,206,14 -block_count,StoreFastElementIC_InBounds,207,14 +block_count,StoreFastElementIC_InBounds,206,13 +block_count,StoreFastElementIC_InBounds,207,13 block_count,StoreFastElementIC_InBounds,208,0 block_count,StoreFastElementIC_InBounds,209,3 block_count,StoreFastElementIC_InBounds,210,17 @@ -12660,26 +12651,26 @@ block_count,StoreFastElementIC_InBounds,237,58 block_count,StoreFastElementIC_InBounds,238,0 block_count,StoreFastElementIC_InBounds,239,0 -block_count,StoreFastElementIC_InBounds,240,17 +block_count,StoreFastElementIC_InBounds,240,25 block_count,StoreFastElementIC_InBounds,241,0 block_count,StoreFastElementIC_InBounds,242,0 block_count,StoreFastElementIC_InBounds,243,0 block_count,StoreFastElementIC_InBounds,244,0 block_count,StoreFastElementIC_InBounds,245,0 -block_count,StoreFastElementIC_InBounds,246,17 -block_count,StoreFastElementIC_InBounds,247,17 -block_count,StoreFastElementIC_InBounds,248,17 +block_count,StoreFastElementIC_InBounds,246,25 +block_count,StoreFastElementIC_InBounds,247,25 +block_count,StoreFastElementIC_InBounds,248,25 block_count,StoreFastElementIC_InBounds,249,0 block_count,StoreFastElementIC_InBounds,250,0 block_count,StoreFastElementIC_InBounds,251,0 block_count,StoreFastElementIC_InBounds,252,0 block_count,StoreFastElementIC_InBounds,253,0 block_count,StoreFastElementIC_InBounds,254,0 -block_count,StoreFastElementIC_InBounds,255,17 -block_count,StoreFastElementIC_InBounds,256,17 -block_count,StoreFastElementIC_InBounds,257,17 +block_count,StoreFastElementIC_InBounds,255,25 +block_count,StoreFastElementIC_InBounds,256,25 +block_count,StoreFastElementIC_InBounds,257,25 block_count,StoreFastElementIC_InBounds,258,0 -block_count,StoreFastElementIC_InBounds,259,17 +block_count,StoreFastElementIC_InBounds,259,25 block_count,StoreFastElementIC_InBounds,260,0 block_count,StoreFastElementIC_InBounds,261,0 block_count,StoreFastElementIC_InBounds,262,0 @@ -12769,7 +12760,7 @@ block_count,StoreFastElementIC_InBounds,346,0 block_count,StoreFastElementIC_InBounds,347,0 block_count,StoreFastElementIC_InBounds,348,5 -block_count,StoreFastElementIC_InBounds,349,166 +block_count,StoreFastElementIC_InBounds,349,165 block_count,StoreFastElementIC_InBounds,350,171 block_count,StoreFastElementIC_InBounds,351,171 block_count,StoreFastElementIC_InBounds,352,0 @@ -13721,25 +13712,25 @@ block_count,StoreFastElementIC_InBounds,1298,0 block_count,StoreFastElementIC_InBounds,1299,0 block_count,StoreFastElementIC_InBounds,1300,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,0,40 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,0,39 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,1,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,2,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,2,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,3,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,4,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,5,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,6,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,7,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,8,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,9,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,8,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,9,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,10,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,11,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,11,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,12,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,13,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,14,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,13,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,14,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,15,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,16,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,17,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,18,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,18,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,19,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,20,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,21,0 @@ -13762,8 +13753,8 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,38,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,39,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,40,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,41,3 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,42,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,41,4 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,42,4 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,43,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,44,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,45,0 @@ -13782,11 +13773,11 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,58,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,59,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,60,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,61,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,61,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,62,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,63,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,64,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,65,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,63,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,64,3 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,65,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,66,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,67,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,68,0 @@ -13815,9 +13806,9 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,91,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,92,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,93,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,94,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,94,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,95,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,96,2 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,96,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,97,3 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,98,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,99,0 @@ -13858,7 +13849,7 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,134,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,135,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,136,1 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,137,1 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,137,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,138,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,139,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,140,0 @@ -13927,7 +13918,7 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,203,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,204,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,205,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,206,25 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,206,24 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,207,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,208,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,209,2 @@ -13942,7 +13933,7 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,218,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,219,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,220,2 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,221,24 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,221,25 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,222,22 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,223,2 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,224,2 @@ -13970,9 +13961,9 @@ block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,246,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,247,0 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,248,22 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,249,25 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,249,24 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,250,0 -block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,251,25 +block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,251,24 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,252,27 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,253,27 block_count,StoreFastElementIC_NoTransitionGrowAndHandleCOW,254,0 @@ -19376,9 +19367,9 @@ block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,19,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,20,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,21,52 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,22,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,22,52 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,23,0 -block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,24,51 +block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,24,52 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,25,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,26,0 block_count,ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites,27,52 @@ -20230,10 +20221,10 @@ block_count,ArrayPrototypePop,21,0 block_count,ArrayPrototypePop,22,0 block_count,ArrayPrototypePop,23,0 -block_count,ArrayPrototypePop,24,10 +block_count,ArrayPrototypePop,24,11 block_count,ArrayPrototypePop,25,0 -block_count,ArrayPrototypePop,26,10 -block_count,ArrayPrototypePop,27,10 +block_count,ArrayPrototypePop,26,11 +block_count,ArrayPrototypePop,27,11 block_count,ArrayPrototypePop,28,0 block_count,ArrayPrototypePop,29,1 block_count,ArrayPrototypePop,30,0 @@ -20246,25 +20237,25 @@ block_count,ArrayPrototypePop,37,0 block_count,ArrayPrototypePop,38,0 block_count,ArrayPrototypePop,39,1 -block_count,ArrayPrototypePush,0,299 +block_count,ArrayPrototypePush,0,301 block_count,ArrayPrototypePush,1,0 -block_count,ArrayPrototypePush,2,299 -block_count,ArrayPrototypePush,3,299 -block_count,ArrayPrototypePush,4,299 -block_count,ArrayPrototypePush,5,299 -block_count,ArrayPrototypePush,6,299 +block_count,ArrayPrototypePush,2,301 +block_count,ArrayPrototypePush,3,301 +block_count,ArrayPrototypePush,4,301 +block_count,ArrayPrototypePush,5,301 +block_count,ArrayPrototypePush,6,301 block_count,ArrayPrototypePush,7,0 -block_count,ArrayPrototypePush,8,299 -block_count,ArrayPrototypePush,9,299 -block_count,ArrayPrototypePush,10,299 +block_count,ArrayPrototypePush,8,301 +block_count,ArrayPrototypePush,9,301 +block_count,ArrayPrototypePush,10,301 block_count,ArrayPrototypePush,11,0 -block_count,ArrayPrototypePush,12,299 -block_count,ArrayPrototypePush,13,299 +block_count,ArrayPrototypePush,12,301 +block_count,ArrayPrototypePush,13,301 block_count,ArrayPrototypePush,14,0 -block_count,ArrayPrototypePush,15,299 -block_count,ArrayPrototypePush,16,299 -block_count,ArrayPrototypePush,17,27 -block_count,ArrayPrototypePush,18,27 +block_count,ArrayPrototypePush,15,301 +block_count,ArrayPrototypePush,16,301 +block_count,ArrayPrototypePush,17,28 +block_count,ArrayPrototypePush,18,28 block_count,ArrayPrototypePush,19,27 block_count,ArrayPrototypePush,20,0 block_count,ArrayPrototypePush,21,0 @@ -20280,7 +20271,7 @@ block_count,ArrayPrototypePush,31,0 block_count,ArrayPrototypePush,32,0 block_count,ArrayPrototypePush,33,22 -block_count,ArrayPrototypePush,34,22 +block_count,ArrayPrototypePush,34,21 block_count,ArrayPrototypePush,35,0 block_count,ArrayPrototypePush,36,0 block_count,ArrayPrototypePush,37,0 @@ -20294,9 +20285,9 @@ block_count,ArrayPrototypePush,45,0 block_count,ArrayPrototypePush,46,0 block_count,ArrayPrototypePush,47,0 -block_count,ArrayPrototypePush,48,27 -block_count,ArrayPrototypePush,49,27 -block_count,ArrayPrototypePush,50,27 +block_count,ArrayPrototypePush,48,28 +block_count,ArrayPrototypePush,49,28 +block_count,ArrayPrototypePush,50,28 block_count,ArrayPrototypePush,51,27 block_count,ArrayPrototypePush,52,27 block_count,ArrayPrototypePush,53,0 @@ -20313,8 +20304,8 @@ block_count,ArrayPrototypePush,64,0 block_count,ArrayPrototypePush,65,0 block_count,ArrayPrototypePush,66,0 -block_count,ArrayPrototypePush,67,271 -block_count,ArrayPrototypePush,68,269 +block_count,ArrayPrototypePush,67,273 +block_count,ArrayPrototypePush,68,271 block_count,ArrayPrototypePush,69,2 block_count,ArrayPrototypePush,70,2 block_count,ArrayPrototypePush,71,2 @@ -20379,9 +20370,9 @@ block_count,ArrayPrototypePush,130,0 block_count,ArrayPrototypePush,131,0 block_count,ArrayPrototypePush,132,0 -block_count,ArrayPrototypePush,133,269 -block_count,ArrayPrototypePush,134,269 -block_count,ArrayPrototypePush,135,247 +block_count,ArrayPrototypePush,133,271 +block_count,ArrayPrototypePush,134,271 +block_count,ArrayPrototypePush,135,250 block_count,ArrayPrototypePush,136,21 block_count,ArrayPrototypePush,137,21 block_count,ArrayPrototypePush,138,21 @@ -20395,7 +20386,7 @@ block_count,ArrayPrototypePush,146,21 block_count,ArrayPrototypePush,147,0 block_count,ArrayPrototypePush,148,21 -block_count,ArrayPrototypePush,149,214 +block_count,ArrayPrototypePush,149,215 block_count,ArrayPrototypePush,150,193 block_count,ArrayPrototypePush,151,21 block_count,ArrayPrototypePush,152,21 @@ -20410,15 +20401,15 @@ block_count,ArrayPrototypePush,161,21 block_count,ArrayPrototypePush,162,0 block_count,ArrayPrototypePush,163,0 -block_count,ArrayPrototypePush,164,269 -block_count,ArrayPrototypePush,165,268 -block_count,ArrayPrototypePush,166,277 -block_count,ArrayPrototypePush,167,277 +block_count,ArrayPrototypePush,164,271 +block_count,ArrayPrototypePush,165,271 +block_count,ArrayPrototypePush,166,279 +block_count,ArrayPrototypePush,167,279 block_count,ArrayPrototypePush,168,8 -block_count,ArrayPrototypePush,169,268 +block_count,ArrayPrototypePush,169,271 block_count,ArrayPrototypePush,170,0 block_count,ArrayPrototypePush,171,0 -block_count,ArrayPrototypePush,172,269 +block_count,ArrayPrototypePush,172,271 block_count,ArrayPrototypePush,173,0 block_count,ArrayPrototypePush,174,0 block_count,ArrayPrototypePush,175,0 @@ -20743,8 +20734,8 @@ block_count,ExtractFastJSArray,28,0 block_count,ExtractFastJSArray,29,0 block_count,ExtractFastJSArray,30,0 -block_count,ExtractFastJSArray,31,6 -block_count,ExtractFastJSArray,32,6 +block_count,ExtractFastJSArray,31,4 +block_count,ExtractFastJSArray,32,4 block_count,ExtractFastJSArray,33,0 block_count,ExtractFastJSArray,34,0 block_count,ExtractFastJSArray,35,0 @@ -21220,13 +21211,13 @@ block_count,ArrayPrototypeValues,12,0 block_count,ArrayPrototypeValues,13,29 block_count,ArrayPrototypeValues,14,29 -block_count,ArrayIteratorPrototypeNext,0,69 +block_count,ArrayIteratorPrototypeNext,0,68 block_count,ArrayIteratorPrototypeNext,1,0 -block_count,ArrayIteratorPrototypeNext,2,69 -block_count,ArrayIteratorPrototypeNext,3,69 -block_count,ArrayIteratorPrototypeNext,4,69 +block_count,ArrayIteratorPrototypeNext,2,68 +block_count,ArrayIteratorPrototypeNext,3,68 +block_count,ArrayIteratorPrototypeNext,4,68 block_count,ArrayIteratorPrototypeNext,5,0 -block_count,ArrayIteratorPrototypeNext,6,69 +block_count,ArrayIteratorPrototypeNext,6,68 block_count,ArrayIteratorPrototypeNext,7,2 block_count,ArrayIteratorPrototypeNext,8,2 block_count,ArrayIteratorPrototypeNext,9,0 @@ -21415,14 +21406,14 @@ block_count,ArrayIteratorPrototypeNext,192,66 block_count,ArrayIteratorPrototypeNext,193,66 block_count,ArrayIteratorPrototypeNext,194,16 -block_count,ArrayIteratorPrototypeNext,195,50 -block_count,ArrayIteratorPrototypeNext,196,50 +block_count,ArrayIteratorPrototypeNext,195,49 +block_count,ArrayIteratorPrototypeNext,196,49 block_count,ArrayIteratorPrototypeNext,197,0 block_count,ArrayIteratorPrototypeNext,198,0 block_count,ArrayIteratorPrototypeNext,199,0 block_count,ArrayIteratorPrototypeNext,200,0 -block_count,ArrayIteratorPrototypeNext,201,50 -block_count,ArrayIteratorPrototypeNext,202,50 +block_count,ArrayIteratorPrototypeNext,201,49 +block_count,ArrayIteratorPrototypeNext,202,49 block_count,ArrayIteratorPrototypeNext,203,0 block_count,ArrayIteratorPrototypeNext,204,0 block_count,ArrayIteratorPrototypeNext,205,0 @@ -21441,14 +21432,14 @@ block_count,ArrayIteratorPrototypeNext,218,0 block_count,ArrayIteratorPrototypeNext,219,0 block_count,ArrayIteratorPrototypeNext,220,0 -block_count,ArrayIteratorPrototypeNext,221,4 +block_count,ArrayIteratorPrototypeNext,221,3 block_count,ArrayIteratorPrototypeNext,222,38 block_count,ArrayIteratorPrototypeNext,223,0 block_count,ArrayIteratorPrototypeNext,224,0 block_count,ArrayIteratorPrototypeNext,225,0 -block_count,ArrayIteratorPrototypeNext,226,43 +block_count,ArrayIteratorPrototypeNext,226,42 block_count,ArrayIteratorPrototypeNext,227,0 -block_count,ArrayIteratorPrototypeNext,228,43 +block_count,ArrayIteratorPrototypeNext,228,42 block_count,ArrayIteratorPrototypeNext,229,0 block_count,ArrayIteratorPrototypeNext,230,6 block_count,ArrayIteratorPrototypeNext,231,0 @@ -21469,7 +21460,7 @@ block_count,ArrayIteratorPrototypeNext,246,0 block_count,ArrayIteratorPrototypeNext,247,0 block_count,ArrayIteratorPrototypeNext,248,0 -block_count,ArrayIteratorPrototypeNext,249,50 +block_count,ArrayIteratorPrototypeNext,249,49 block_count,ArrayIteratorPrototypeNext,250,0 block_count,ArrayIteratorPrototypeNext,251,0 block_count,ArrayIteratorPrototypeNext,252,0 @@ -21495,12 +21486,12 @@ block_count,ArrayIteratorPrototypeNext,272,0 block_count,ArrayIteratorPrototypeNext,273,0 block_count,ArrayIteratorPrototypeNext,274,51 -block_count,ArrayIteratorPrototypeNext,275,69 +block_count,ArrayIteratorPrototypeNext,275,68 block_count,ArrayIteratorPrototypeNext,276,0 -block_count,ArrayIteratorPrototypeNext,277,69 +block_count,ArrayIteratorPrototypeNext,277,68 block_count,ArrayIteratorPrototypeNext,278,0 -block_count,ArrayIteratorPrototypeNext,279,69 -block_count,ArrayIteratorPrototypeNext,280,69 +block_count,ArrayIteratorPrototypeNext,279,68 +block_count,ArrayIteratorPrototypeNext,280,68 block_count,AsyncFunctionEnter,0,0 block_count,AsyncFunctionEnter,1,0 block_count,AsyncFunctionEnter,2,0 @@ -21765,7 +21756,7 @@ block_count,CreateGeneratorObject,18,1 block_count,CreateGeneratorObject,19,0 block_count,CreateGeneratorObject,20,1 -block_count,CreateGeneratorObject,21,8 +block_count,CreateGeneratorObject,21,7 block_count,CreateGeneratorObject,22,6 block_count,CreateGeneratorObject,23,1 block_count,CreateGeneratorObject,24,1 @@ -21899,15 +21890,15 @@ block_count,GlobalIsNaN,8,0 block_count,GlobalIsNaN,9,0 block_count,GlobalIsNaN,10,0 -block_count,LoadIC,0,5040 -block_count,LoadIC,1,5039 +block_count,LoadIC,0,4995 +block_count,LoadIC,1,4994 block_count,LoadIC,2,1 -block_count,LoadIC,3,5040 -block_count,LoadIC,4,5040 -block_count,LoadIC,5,1327 +block_count,LoadIC,3,4995 +block_count,LoadIC,4,4995 +block_count,LoadIC,5,1313 block_count,LoadIC,6,0 -block_count,LoadIC,7,1326 -block_count,LoadIC,8,265 +block_count,LoadIC,7,1312 +block_count,LoadIC,8,256 block_count,LoadIC,9,1 block_count,LoadIC,10,1 block_count,LoadIC,11,0 @@ -21921,36 +21912,36 @@ block_count,LoadIC,19,0 block_count,LoadIC,20,0 block_count,LoadIC,21,0 -block_count,LoadIC,22,264 -block_count,LoadIC,23,264 +block_count,LoadIC,22,255 +block_count,LoadIC,23,255 block_count,LoadIC,24,0 -block_count,LoadIC,25,264 -block_count,LoadIC,26,227 -block_count,LoadIC,27,225 -block_count,LoadIC,28,2 +block_count,LoadIC,25,255 +block_count,LoadIC,26,218 +block_count,LoadIC,27,215 +block_count,LoadIC,28,3 block_count,LoadIC,29,36 -block_count,LoadIC,30,38 -block_count,LoadIC,31,36 -block_count,LoadIC,32,36 +block_count,LoadIC,30,39 +block_count,LoadIC,31,37 +block_count,LoadIC,32,37 block_count,LoadIC,33,0 block_count,LoadIC,34,2 -block_count,LoadIC,35,1061 -block_count,LoadIC,36,1750 -block_count,LoadIC,37,689 -block_count,LoadIC,38,689 +block_count,LoadIC,35,1056 +block_count,LoadIC,36,1740 +block_count,LoadIC,37,684 +block_count,LoadIC,38,683 block_count,LoadIC,39,0 -block_count,LoadIC,40,1060 -block_count,LoadIC,41,3712 -block_count,LoadIC,42,5035 -block_count,LoadIC,43,1690 -block_count,LoadIC,44,1682 -block_count,LoadIC,45,1401 -block_count,LoadIC,46,1400 +block_count,LoadIC,40,1056 +block_count,LoadIC,41,3681 +block_count,LoadIC,42,4990 +block_count,LoadIC,43,1680 +block_count,LoadIC,44,1672 +block_count,LoadIC,45,1392 +block_count,LoadIC,46,1391 block_count,LoadIC,47,0 -block_count,LoadIC,48,1400 +block_count,LoadIC,48,1391 block_count,LoadIC,49,0 -block_count,LoadIC,50,1400 -block_count,LoadIC,51,180 +block_count,LoadIC,50,1391 +block_count,LoadIC,51,178 block_count,LoadIC,52,33 block_count,LoadIC,53,33 block_count,LoadIC,54,0 @@ -22007,8 +21998,8 @@ block_count,LoadIC,105,0 block_count,LoadIC,106,0 block_count,LoadIC,107,1 -block_count,LoadIC,108,147 -block_count,LoadIC,109,147 +block_count,LoadIC,108,145 +block_count,LoadIC,109,145 block_count,LoadIC,110,0 block_count,LoadIC,111,0 block_count,LoadIC,112,0 @@ -22020,27 +22011,27 @@ block_count,LoadIC,118,0 block_count,LoadIC,119,0 block_count,LoadIC,120,0 -block_count,LoadIC,121,147 +block_count,LoadIC,121,145 block_count,LoadIC,122,0 -block_count,LoadIC,123,1220 -block_count,LoadIC,124,1399 -block_count,LoadIC,125,1398 -block_count,LoadIC,126,1321 -block_count,LoadIC,127,1321 +block_count,LoadIC,123,1213 +block_count,LoadIC,124,1390 +block_count,LoadIC,125,1389 +block_count,LoadIC,126,1311 +block_count,LoadIC,127,1311 block_count,LoadIC,128,0 -block_count,LoadIC,129,77 -block_count,LoadIC,130,1398 +block_count,LoadIC,129,78 +block_count,LoadIC,130,1389 block_count,LoadIC,131,0 -block_count,LoadIC,132,281 +block_count,LoadIC,132,280 block_count,LoadIC,133,8 block_count,LoadIC,134,8 block_count,LoadIC,135,0 -block_count,LoadIC,136,3344 -block_count,LoadIC,137,4743 -block_count,LoadIC,138,1620 -block_count,LoadIC,139,510 -block_count,LoadIC,140,433 -block_count,LoadIC,141,222 +block_count,LoadIC,136,3310 +block_count,LoadIC,137,4699 +block_count,LoadIC,138,1611 +block_count,LoadIC,139,513 +block_count,LoadIC,140,434 +block_count,LoadIC,141,224 block_count,LoadIC,142,12 block_count,LoadIC,143,2 block_count,LoadIC,144,2 @@ -22110,7 +22101,7 @@ block_count,LoadIC,208,0 block_count,LoadIC,209,0 block_count,LoadIC,210,10 -block_count,LoadIC,211,210 +block_count,LoadIC,211,211 block_count,LoadIC,212,210 block_count,LoadIC,213,210 block_count,LoadIC,214,0 @@ -22167,14 +22158,14 @@ block_count,LoadIC,265,0 block_count,LoadIC,266,0 block_count,LoadIC,267,210 -block_count,LoadIC,268,77 -block_count,LoadIC,269,1109 -block_count,LoadIC,270,3122 -block_count,LoadIC,271,3122 -block_count,LoadIC,272,808 -block_count,LoadIC,273,2314 -block_count,LoadIC,274,3122 -block_count,LoadIC,275,2970 +block_count,LoadIC,268,78 +block_count,LoadIC,269,1098 +block_count,LoadIC,270,3088 +block_count,LoadIC,271,3088 +block_count,LoadIC,272,799 +block_count,LoadIC,273,2288 +block_count,LoadIC,274,3088 +block_count,LoadIC,275,2936 block_count,LoadIC,276,152 block_count,LoadIC,277,152 block_count,LoadIC,278,152 @@ -22235,31 +22226,31 @@ block_count,LoadIC,333,0 block_count,LoadIC,334,0 block_count,LoadIC,335,4 -block_count,LoadIC_Megamorphic,0,8665 -block_count,LoadIC_Megamorphic,1,8663 +block_count,LoadIC_Megamorphic,0,8673 +block_count,LoadIC_Megamorphic,1,8671 block_count,LoadIC_Megamorphic,2,1 -block_count,LoadIC_Megamorphic,3,8665 -block_count,LoadIC_Megamorphic,4,8665 +block_count,LoadIC_Megamorphic,3,8673 +block_count,LoadIC_Megamorphic,4,8673 block_count,LoadIC_Megamorphic,5,0 -block_count,LoadIC_Megamorphic,6,8665 -block_count,LoadIC_Megamorphic,7,7301 -block_count,LoadIC_Megamorphic,8,7239 -block_count,LoadIC_Megamorphic,9,61 -block_count,LoadIC_Megamorphic,10,1363 -block_count,LoadIC_Megamorphic,11,1425 -block_count,LoadIC_Megamorphic,12,1412 -block_count,LoadIC_Megamorphic,13,1409 +block_count,LoadIC_Megamorphic,6,8673 +block_count,LoadIC_Megamorphic,7,7365 +block_count,LoadIC_Megamorphic,8,7224 +block_count,LoadIC_Megamorphic,9,141 +block_count,LoadIC_Megamorphic,10,1307 +block_count,LoadIC_Megamorphic,11,1449 +block_count,LoadIC_Megamorphic,12,1435 +block_count,LoadIC_Megamorphic,13,1432 block_count,LoadIC_Megamorphic,14,2 block_count,LoadIC_Megamorphic,15,13 -block_count,LoadIC_Megamorphic,16,8649 -block_count,LoadIC_Megamorphic,17,3174 -block_count,LoadIC_Megamorphic,18,3174 -block_count,LoadIC_Megamorphic,19,3165 -block_count,LoadIC_Megamorphic,20,3165 +block_count,LoadIC_Megamorphic,16,8657 +block_count,LoadIC_Megamorphic,17,3176 +block_count,LoadIC_Megamorphic,18,3176 +block_count,LoadIC_Megamorphic,19,3167 +block_count,LoadIC_Megamorphic,20,3167 block_count,LoadIC_Megamorphic,21,0 -block_count,LoadIC_Megamorphic,22,3164 +block_count,LoadIC_Megamorphic,22,3166 block_count,LoadIC_Megamorphic,23,0 -block_count,LoadIC_Megamorphic,24,3164 +block_count,LoadIC_Megamorphic,24,3166 block_count,LoadIC_Megamorphic,25,6 block_count,LoadIC_Megamorphic,26,3 block_count,LoadIC_Megamorphic,27,3 @@ -22332,22 +22323,22 @@ block_count,LoadIC_Megamorphic,94,0 block_count,LoadIC_Megamorphic,95,2 block_count,LoadIC_Megamorphic,96,0 -block_count,LoadIC_Megamorphic,97,3158 -block_count,LoadIC_Megamorphic,98,3164 -block_count,LoadIC_Megamorphic,99,3163 -block_count,LoadIC_Megamorphic,100,2495 -block_count,LoadIC_Megamorphic,101,2495 +block_count,LoadIC_Megamorphic,97,3160 +block_count,LoadIC_Megamorphic,98,3166 +block_count,LoadIC_Megamorphic,99,3165 +block_count,LoadIC_Megamorphic,100,2497 +block_count,LoadIC_Megamorphic,101,2497 block_count,LoadIC_Megamorphic,102,0 block_count,LoadIC_Megamorphic,103,667 -block_count,LoadIC_Megamorphic,104,3163 +block_count,LoadIC_Megamorphic,104,3165 block_count,LoadIC_Megamorphic,105,1 block_count,LoadIC_Megamorphic,106,9 block_count,LoadIC_Megamorphic,107,0 block_count,LoadIC_Megamorphic,108,0 block_count,LoadIC_Megamorphic,109,0 -block_count,LoadIC_Megamorphic,110,5474 -block_count,LoadIC_Megamorphic,111,8638 -block_count,LoadIC_Megamorphic,112,3794 +block_count,LoadIC_Megamorphic,110,5480 +block_count,LoadIC_Megamorphic,111,8646 +block_count,LoadIC_Megamorphic,112,3796 block_count,LoadIC_Megamorphic,113,1993 block_count,LoadIC_Megamorphic,114,1325 block_count,LoadIC_Megamorphic,115,1323 @@ -22478,13 +22469,13 @@ block_count,LoadIC_Megamorphic,240,0 block_count,LoadIC_Megamorphic,241,1 block_count,LoadIC_Megamorphic,242,667 -block_count,LoadIC_Megamorphic,243,1801 -block_count,LoadIC_Megamorphic,244,4843 -block_count,LoadIC_Megamorphic,245,4843 -block_count,LoadIC_Megamorphic,246,251 -block_count,LoadIC_Megamorphic,247,4591 -block_count,LoadIC_Megamorphic,248,4843 -block_count,LoadIC_Megamorphic,249,4825 +block_count,LoadIC_Megamorphic,243,1803 +block_count,LoadIC_Megamorphic,244,4849 +block_count,LoadIC_Megamorphic,245,4849 +block_count,LoadIC_Megamorphic,246,253 +block_count,LoadIC_Megamorphic,247,4595 +block_count,LoadIC_Megamorphic,248,4849 +block_count,LoadIC_Megamorphic,249,4831 block_count,LoadIC_Megamorphic,250,18 block_count,LoadIC_Megamorphic,251,18 block_count,LoadIC_Megamorphic,252,18 @@ -22869,15 +22860,15 @@ block_count,LoadIC_Noninlined,321,0 block_count,LoadIC_Noninlined,322,0 block_count,LoadIC_Noninlined,323,1 -block_count,LoadICTrampoline,0,301 -block_count,LoadICTrampoline,1,301 +block_count,LoadICTrampoline,0,302 +block_count,LoadICTrampoline,1,302 block_count,LoadICTrampoline,2,0 -block_count,LoadICTrampoline,3,301 -block_count,LoadICBaseline,0,4531 -block_count,LoadICTrampoline_Megamorphic,0,5296 -block_count,LoadICTrampoline_Megamorphic,1,5296 +block_count,LoadICTrampoline,3,302 +block_count,LoadICBaseline,0,4485 +block_count,LoadICTrampoline_Megamorphic,0,5302 +block_count,LoadICTrampoline_Megamorphic,1,5302 block_count,LoadICTrampoline_Megamorphic,2,0 -block_count,LoadICTrampoline_Megamorphic,3,5296 +block_count,LoadICTrampoline_Megamorphic,3,5302 block_count,LoadSuperIC,0,4 block_count,LoadSuperIC,1,4 block_count,LoadSuperIC,2,4 @@ -23486,16 +23477,16 @@ block_count,LoadSuperIC,605,0 block_count,LoadSuperIC,606,0 block_count,LoadSuperICBaseline,0,4 -block_count,KeyedLoadIC,0,829 -block_count,KeyedLoadIC,1,829 +block_count,KeyedLoadIC,0,826 +block_count,KeyedLoadIC,1,826 block_count,KeyedLoadIC,2,0 -block_count,KeyedLoadIC,3,829 -block_count,KeyedLoadIC,4,829 -block_count,KeyedLoadIC,5,827 -block_count,KeyedLoadIC,6,85 +block_count,KeyedLoadIC,3,826 +block_count,KeyedLoadIC,4,826 +block_count,KeyedLoadIC,5,823 +block_count,KeyedLoadIC,6,84 block_count,KeyedLoadIC,7,0 -block_count,KeyedLoadIC,8,85 -block_count,KeyedLoadIC,9,46 +block_count,KeyedLoadIC,8,84 +block_count,KeyedLoadIC,9,45 block_count,KeyedLoadIC,10,1 block_count,KeyedLoadIC,11,1 block_count,KeyedLoadIC,12,0 @@ -23533,15 +23524,15 @@ block_count,KeyedLoadIC,44,1 block_count,KeyedLoadIC,45,1 block_count,KeyedLoadIC,46,0 -block_count,KeyedLoadIC,47,44 -block_count,KeyedLoadIC,48,39 -block_count,KeyedLoadIC,49,65 +block_count,KeyedLoadIC,47,43 +block_count,KeyedLoadIC,48,38 +block_count,KeyedLoadIC,49,64 block_count,KeyedLoadIC,50,25 block_count,KeyedLoadIC,51,25 block_count,KeyedLoadIC,52,0 -block_count,KeyedLoadIC,53,39 -block_count,KeyedLoadIC,54,741 -block_count,KeyedLoadIC,55,780 +block_count,KeyedLoadIC,53,38 +block_count,KeyedLoadIC,54,739 +block_count,KeyedLoadIC,55,778 block_count,KeyedLoadIC,56,1 block_count,KeyedLoadIC,57,1 block_count,KeyedLoadIC,58,0 @@ -23635,9 +23626,9 @@ block_count,KeyedLoadIC,146,0 block_count,KeyedLoadIC,147,0 block_count,KeyedLoadIC,148,0 -block_count,KeyedLoadIC,149,779 -block_count,KeyedLoadIC,150,779 -block_count,KeyedLoadIC,151,7 +block_count,KeyedLoadIC,149,776 +block_count,KeyedLoadIC,150,776 +block_count,KeyedLoadIC,151,6 block_count,KeyedLoadIC,152,0 block_count,KeyedLoadIC,153,0 block_count,KeyedLoadIC,154,0 @@ -23864,15 +23855,15 @@ block_count,KeyedLoadIC,375,0 block_count,KeyedLoadIC,376,0 block_count,KeyedLoadIC,377,0 -block_count,KeyedLoadIC,378,7 +block_count,KeyedLoadIC,378,6 block_count,KeyedLoadIC,379,0 block_count,KeyedLoadIC,380,0 block_count,KeyedLoadIC,381,0 block_count,KeyedLoadIC,382,0 block_count,KeyedLoadIC,383,0 -block_count,KeyedLoadIC,384,7 -block_count,KeyedLoadIC,385,7 -block_count,KeyedLoadIC,386,7 +block_count,KeyedLoadIC,384,6 +block_count,KeyedLoadIC,385,6 +block_count,KeyedLoadIC,386,6 block_count,KeyedLoadIC,387,2 block_count,KeyedLoadIC,388,5 block_count,KeyedLoadIC,389,2 @@ -23893,17 +23884,17 @@ block_count,KeyedLoadIC,404,0 block_count,KeyedLoadIC,405,0 block_count,KeyedLoadIC,406,0 -block_count,KeyedLoadIC,407,4 -block_count,KeyedLoadIC,408,7 -block_count,KeyedLoadIC,409,7 +block_count,KeyedLoadIC,407,3 +block_count,KeyedLoadIC,408,6 +block_count,KeyedLoadIC,409,6 block_count,KeyedLoadIC,410,0 block_count,KeyedLoadIC,411,6 -block_count,KeyedLoadIC,412,7 +block_count,KeyedLoadIC,412,6 block_count,KeyedLoadIC,413,0 block_count,KeyedLoadIC,414,0 block_count,KeyedLoadIC,415,0 block_count,KeyedLoadIC,416,0 -block_count,KeyedLoadIC,417,7 +block_count,KeyedLoadIC,417,6 block_count,KeyedLoadIC,418,0 block_count,KeyedLoadIC,419,0 block_count,KeyedLoadIC,420,0 @@ -23911,7 +23902,7 @@ block_count,KeyedLoadIC,422,0 block_count,KeyedLoadIC,423,0 block_count,KeyedLoadIC,424,0 -block_count,KeyedLoadIC,425,771 +block_count,KeyedLoadIC,425,769 block_count,KeyedLoadIC,426,0 block_count,KeyedLoadIC,427,0 block_count,KeyedLoadIC,428,0 @@ -23922,24 +23913,24 @@ block_count,KeyedLoadIC,433,0 block_count,KeyedLoadIC,434,0 block_count,KeyedLoadIC,435,0 -block_count,KeyedLoadIC,436,771 -block_count,KeyedLoadIC,437,771 -block_count,KeyedLoadIC,438,771 -block_count,KeyedLoadIC,439,473 +block_count,KeyedLoadIC,436,769 +block_count,KeyedLoadIC,437,769 +block_count,KeyedLoadIC,438,769 +block_count,KeyedLoadIC,439,471 block_count,KeyedLoadIC,440,9 -block_count,KeyedLoadIC,441,463 -block_count,KeyedLoadIC,442,473 +block_count,KeyedLoadIC,441,462 +block_count,KeyedLoadIC,442,471 block_count,KeyedLoadIC,443,1 -block_count,KeyedLoadIC,444,471 +block_count,KeyedLoadIC,444,469 block_count,KeyedLoadIC,445,0 -block_count,KeyedLoadIC,446,34 +block_count,KeyedLoadIC,446,33 block_count,KeyedLoadIC,447,247 block_count,KeyedLoadIC,448,0 block_count,KeyedLoadIC,449,0 block_count,KeyedLoadIC,450,0 block_count,KeyedLoadIC,451,0 block_count,KeyedLoadIC,452,281 -block_count,KeyedLoadIC,453,24 +block_count,KeyedLoadIC,453,23 block_count,KeyedLoadIC,454,75 block_count,KeyedLoadIC,455,0 block_count,KeyedLoadIC,456,0 @@ -23947,15 +23938,15 @@ block_count,KeyedLoadIC,458,99 block_count,KeyedLoadIC,459,94 block_count,KeyedLoadIC,460,4 -block_count,KeyedLoadIC,461,35 +block_count,KeyedLoadIC,461,36 block_count,KeyedLoadIC,462,0 -block_count,KeyedLoadIC,463,35 -block_count,KeyedLoadIC,464,35 -block_count,KeyedLoadIC,465,54 -block_count,KeyedLoadIC,466,54 +block_count,KeyedLoadIC,463,36 +block_count,KeyedLoadIC,464,36 +block_count,KeyedLoadIC,465,53 +block_count,KeyedLoadIC,466,53 block_count,KeyedLoadIC,467,0 -block_count,KeyedLoadIC,468,54 -block_count,KeyedLoadIC,469,54 +block_count,KeyedLoadIC,468,53 +block_count,KeyedLoadIC,469,53 block_count,KeyedLoadIC,470,0 block_count,KeyedLoadIC,471,298 block_count,KeyedLoadIC,472,298 @@ -23988,11 +23979,11 @@ block_count,KeyedLoadIC,499,0 block_count,KeyedLoadIC,500,43 block_count,KeyedLoadIC,501,0 -block_count,KeyedLoadIC,502,1 -block_count,KeyedLoadIC,503,13 +block_count,KeyedLoadIC,502,2 +block_count,KeyedLoadIC,503,12 block_count,KeyedLoadIC,504,0 block_count,KeyedLoadIC,505,1 -block_count,KeyedLoadIC,506,169 +block_count,KeyedLoadIC,506,168 block_count,KeyedLoadIC,507,69 block_count,KeyedLoadIC,508,0 block_count,KeyedLoadIC,509,0 @@ -24052,7 +24043,7 @@ block_count,KeyedLoadIC,563,0 block_count,KeyedLoadIC,564,0 block_count,KeyedLoadIC,565,0 -block_count,KeyedLoadIC,566,169 +block_count,KeyedLoadIC,566,168 block_count,KeyedLoadIC,567,166 block_count,KeyedLoadIC,568,2 block_count,KeyedLoadIC,569,0 @@ -24122,19 +24113,19 @@ block_count,KeyedLoadIC,633,1 block_count,KeyedLoadIC,634,1 block_count,KeyedLoadIC,635,4 -block_count,KeyedLoadIC,636,3 -block_count,KeyedLoadIC,637,3 +block_count,KeyedLoadIC,636,2 +block_count,KeyedLoadIC,637,2 block_count,KeyedLoadIC,638,0 block_count,KeyedLoadIC,639,0 block_count,KeyedLoadIC,640,0 block_count,KeyedLoadIC,641,0 block_count,KeyedLoadIC,642,0 -block_count,KeyedLoadIC,643,3 +block_count,KeyedLoadIC,643,2 block_count,KeyedLoadIC,644,0 block_count,KeyedLoadIC,645,0 block_count,KeyedLoadIC,646,0 -block_count,KeyedLoadIC,647,3 -block_count,KeyedLoadIC,648,3 +block_count,KeyedLoadIC,647,2 +block_count,KeyedLoadIC,648,2 block_count,KeyedLoadIC,649,1 block_count,KeyedLoadIC,650,0 block_count,KeyedLoadIC,651,0 @@ -24837,8 +24828,8 @@ block_count,KeyedLoadIC_Megamorphic,10,42 block_count,KeyedLoadIC_Megamorphic,11,37 block_count,KeyedLoadIC_Megamorphic,12,4 -block_count,KeyedLoadIC_Megamorphic,13,1787 -block_count,KeyedLoadIC_Megamorphic,14,1787 +block_count,KeyedLoadIC_Megamorphic,13,1786 +block_count,KeyedLoadIC_Megamorphic,14,1786 block_count,KeyedLoadIC_Megamorphic,15,1701 block_count,KeyedLoadIC_Megamorphic,16,1701 block_count,KeyedLoadIC_Megamorphic,17,1638 @@ -25047,9 +25038,9 @@ block_count,KeyedLoadIC_Megamorphic,220,686 block_count,KeyedLoadIC_Megamorphic,221,26 block_count,KeyedLoadIC_Megamorphic,222,659 -block_count,KeyedLoadIC_Megamorphic,223,2675 +block_count,KeyedLoadIC_Megamorphic,223,2676 block_count,KeyedLoadIC_Megamorphic,224,2614 -block_count,KeyedLoadIC_Megamorphic,225,2538 +block_count,KeyedLoadIC_Megamorphic,225,2539 block_count,KeyedLoadIC_Megamorphic,226,2016 block_count,KeyedLoadIC_Megamorphic,227,522 block_count,KeyedLoadIC_Megamorphic,228,75 @@ -25201,9 +25192,9 @@ block_count,KeyedLoadIC_Megamorphic,374,0 block_count,KeyedLoadIC_Megamorphic,375,0 block_count,KeyedLoadIC_Megamorphic,376,0 -block_count,KeyedLoadIC_Megamorphic,377,338 +block_count,KeyedLoadIC_Megamorphic,377,337 block_count,KeyedLoadIC_Megamorphic,378,0 -block_count,KeyedLoadIC_Megamorphic,379,338 +block_count,KeyedLoadIC_Megamorphic,379,337 block_count,KeyedLoadIC_Megamorphic,380,8 block_count,KeyedLoadIC_Megamorphic,381,329 block_count,KeyedLoadIC_Megamorphic,382,886 @@ -25233,7 +25224,7 @@ block_count,KeyedLoadIC_Megamorphic,406,41 block_count,KeyedLoadIC_Megamorphic,407,305 block_count,KeyedLoadIC_Megamorphic,408,23 -block_count,KeyedLoadIC_Megamorphic,409,102 +block_count,KeyedLoadIC_Megamorphic,409,101 block_count,KeyedLoadIC_Megamorphic,410,101 block_count,KeyedLoadIC_Megamorphic,411,101 block_count,KeyedLoadIC_Megamorphic,412,0 @@ -25241,10 +25232,10 @@ block_count,KeyedLoadIC_Megamorphic,414,75 block_count,KeyedLoadIC_Megamorphic,415,75 block_count,KeyedLoadIC_Megamorphic,416,0 -block_count,KeyedLoadIC_Megamorphic,417,26 -block_count,KeyedLoadIC_Megamorphic,418,26 -block_count,KeyedLoadIC_Megamorphic,419,12 -block_count,KeyedLoadIC_Megamorphic,420,12 +block_count,KeyedLoadIC_Megamorphic,417,25 +block_count,KeyedLoadIC_Megamorphic,418,25 +block_count,KeyedLoadIC_Megamorphic,419,11 +block_count,KeyedLoadIC_Megamorphic,420,11 block_count,KeyedLoadIC_Megamorphic,421,0 block_count,KeyedLoadIC_Megamorphic,422,14 block_count,KeyedLoadIC_Megamorphic,423,87 @@ -25991,18 +25982,18 @@ block_count,KeyedLoadICTrampoline,1,1 block_count,KeyedLoadICTrampoline,2,0 block_count,KeyedLoadICTrampoline,3,1 -block_count,KeyedLoadICBaseline,0,772 +block_count,KeyedLoadICBaseline,0,769 block_count,EnumeratedKeyedLoadICBaseline,0,5 -block_count,KeyedLoadICTrampoline_Megamorphic,0,789 -block_count,KeyedLoadICTrampoline_Megamorphic,1,789 +block_count,KeyedLoadICTrampoline_Megamorphic,0,790 +block_count,KeyedLoadICTrampoline_Megamorphic,1,790 block_count,KeyedLoadICTrampoline_Megamorphic,2,0 -block_count,KeyedLoadICTrampoline_Megamorphic,3,789 -block_count,StoreGlobalIC,0,125 -block_count,StoreGlobalIC,1,125 -block_count,StoreGlobalIC,2,125 -block_count,StoreGlobalIC,3,125 -block_count,StoreGlobalIC,4,125 -block_count,StoreGlobalIC,5,125 +block_count,KeyedLoadICTrampoline_Megamorphic,3,790 +block_count,StoreGlobalIC,0,321 +block_count,StoreGlobalIC,1,320 +block_count,StoreGlobalIC,2,320 +block_count,StoreGlobalIC,3,320 +block_count,StoreGlobalIC,4,320 +block_count,StoreGlobalIC,5,320 block_count,StoreGlobalIC,6,6 block_count,StoreGlobalIC,7,0 block_count,StoreGlobalIC,8,0 @@ -26012,7 +26003,7 @@ block_count,StoreGlobalIC,12,6 block_count,StoreGlobalIC,13,0 block_count,StoreGlobalIC,14,6 -block_count,StoreGlobalIC,15,118 +block_count,StoreGlobalIC,15,314 block_count,StoreGlobalIC,16,0 block_count,StoreGlobalIC,17,0 block_count,StoreGlobalIC,18,0 @@ -26440,32 +26431,32 @@ block_count,StoreGlobalIC,440,0 block_count,StoreGlobalIC,441,0 block_count,StoreGlobalIC,442,0 -block_count,StoreGlobalICTrampoline,0,0 -block_count,StoreGlobalICTrampoline,1,0 +block_count,StoreGlobalICTrampoline,0,195 +block_count,StoreGlobalICTrampoline,1,195 block_count,StoreGlobalICTrampoline,2,0 -block_count,StoreGlobalICTrampoline,3,0 -block_count,StoreGlobalICBaseline,0,6 -block_count,StoreIC,0,618 -block_count,StoreIC,1,618 +block_count,StoreGlobalICTrampoline,3,195 +block_count,StoreGlobalICBaseline,0,5 +block_count,StoreIC,0,614 +block_count,StoreIC,1,614 block_count,StoreIC,2,0 -block_count,StoreIC,3,618 -block_count,StoreIC,4,618 -block_count,StoreIC,5,612 -block_count,StoreIC,6,184 +block_count,StoreIC,3,614 +block_count,StoreIC,4,614 +block_count,StoreIC,5,609 +block_count,StoreIC,6,183 block_count,StoreIC,7,0 -block_count,StoreIC,8,184 -block_count,StoreIC,9,38 +block_count,StoreIC,8,183 +block_count,StoreIC,9,37 block_count,StoreIC,10,0 -block_count,StoreIC,11,37 -block_count,StoreIC,12,37 +block_count,StoreIC,11,36 +block_count,StoreIC,12,36 block_count,StoreIC,13,0 -block_count,StoreIC,14,37 +block_count,StoreIC,14,36 block_count,StoreIC,15,33 -block_count,StoreIC,16,33 -block_count,StoreIC,17,0 -block_count,StoreIC,18,4 +block_count,StoreIC,16,32 +block_count,StoreIC,17,1 +block_count,StoreIC,18,2 block_count,StoreIC,19,4 -block_count,StoreIC,20,3 +block_count,StoreIC,20,4 block_count,StoreIC,21,3 block_count,StoreIC,22,0 block_count,StoreIC,23,0 @@ -26474,9 +26465,9 @@ block_count,StoreIC,26,78 block_count,StoreIC,27,78 block_count,StoreIC,28,0 -block_count,StoreIC,29,145 -block_count,StoreIC,30,428 -block_count,StoreIC,31,611 +block_count,StoreIC,29,146 +block_count,StoreIC,30,425 +block_count,StoreIC,31,607 block_count,StoreIC,32,218 block_count,StoreIC,33,8 block_count,StoreIC,34,8 @@ -26642,7 +26633,7 @@ block_count,StoreIC,194,30 block_count,StoreIC,195,0 block_count,StoreIC,196,30 -block_count,StoreIC,197,128 +block_count,StoreIC,197,129 block_count,StoreIC,198,0 block_count,StoreIC,199,6 block_count,StoreIC,200,4 @@ -26653,7 +26644,7 @@ block_count,StoreIC,205,0 block_count,StoreIC,206,35 block_count,StoreIC,207,206 -block_count,StoreIC,208,40 +block_count,StoreIC,208,41 block_count,StoreIC,209,0 block_count,StoreIC,210,0 block_count,StoreIC,211,0 @@ -26661,11 +26652,11 @@ block_count,StoreIC,213,0 block_count,StoreIC,214,0 block_count,StoreIC,215,0 -block_count,StoreIC,216,39 -block_count,StoreIC,217,40 -block_count,StoreIC,218,40 +block_count,StoreIC,216,40 +block_count,StoreIC,217,41 +block_count,StoreIC,218,41 block_count,StoreIC,219,0 -block_count,StoreIC,220,40 +block_count,StoreIC,220,41 block_count,StoreIC,221,19 block_count,StoreIC,222,19 block_count,StoreIC,223,0 @@ -26688,7 +26679,7 @@ block_count,StoreIC,240,7 block_count,StoreIC,241,0 block_count,StoreIC,242,7 -block_count,StoreIC,243,16 +block_count,StoreIC,243,17 block_count,StoreIC,244,9 block_count,StoreIC,245,7 block_count,StoreIC,246,7 @@ -26696,11 +26687,11 @@ block_count,StoreIC,248,5 block_count,StoreIC,249,19 block_count,StoreIC,250,21 -block_count,StoreIC,251,40 -block_count,StoreIC,252,166 -block_count,StoreIC,253,160 +block_count,StoreIC,251,41 +block_count,StoreIC,252,165 +block_count,StoreIC,253,159 block_count,StoreIC,254,6 -block_count,StoreIC,255,4 +block_count,StoreIC,255,3 block_count,StoreIC,256,2 block_count,StoreIC,257,6 block_count,StoreIC,258,0 @@ -26726,7 +26717,7 @@ block_count,StoreIC,278,0 block_count,StoreIC,279,0 block_count,StoreIC,280,0 -block_count,StoreIC,281,392 +block_count,StoreIC,281,389 block_count,StoreIC,282,12 block_count,StoreIC,283,12 block_count,StoreIC,284,12 @@ -26751,9 +26742,9 @@ block_count,StoreIC,303,0 block_count,StoreIC,304,0 block_count,StoreIC,305,0 -block_count,StoreIC,306,380 -block_count,StoreIC,307,363 -block_count,StoreIC,308,363 +block_count,StoreIC,306,376 +block_count,StoreIC,307,359 +block_count,StoreIC,308,359 block_count,StoreIC,309,36 block_count,StoreIC,310,33 block_count,StoreIC,311,33 @@ -26773,36 +26764,36 @@ block_count,StoreIC,325,0 block_count,StoreIC,326,5 block_count,StoreIC,327,1 -block_count,StoreIC,328,3 +block_count,StoreIC,328,4 block_count,StoreIC,329,5 block_count,StoreIC,330,5 block_count,StoreIC,331,0 block_count,StoreIC,332,0 block_count,StoreIC,333,0 -block_count,StoreIC,334,172 -block_count,StoreIC,335,172 -block_count,StoreIC,336,172 +block_count,StoreIC,334,168 +block_count,StoreIC,335,168 +block_count,StoreIC,336,168 block_count,StoreIC,337,10 block_count,StoreIC,338,0 block_count,StoreIC,339,10 -block_count,StoreIC,340,162 +block_count,StoreIC,340,158 block_count,StoreIC,341,0 -block_count,StoreIC,342,172 +block_count,StoreIC,342,168 block_count,StoreIC,343,39 -block_count,StoreIC,344,132 -block_count,StoreIC,345,172 -block_count,StoreIC,346,172 +block_count,StoreIC,344,129 +block_count,StoreIC,345,168 +block_count,StoreIC,346,168 block_count,StoreIC,347,0 block_count,StoreIC,348,0 block_count,StoreIC,349,0 block_count,StoreIC,350,0 -block_count,StoreIC,351,149 +block_count,StoreIC,351,148 block_count,StoreIC,352,0 -block_count,StoreIC,353,149 -block_count,StoreIC,354,26 -block_count,StoreIC,355,123 -block_count,StoreIC,356,149 -block_count,StoreIC,357,149 +block_count,StoreIC,353,148 +block_count,StoreIC,354,25 +block_count,StoreIC,355,122 +block_count,StoreIC,356,148 +block_count,StoreIC,357,148 block_count,StoreIC,358,0 block_count,StoreIC,359,0 block_count,StoreIC,360,0 @@ -26829,24 +26820,24 @@ block_count,StoreIC,381,5 block_count,StoreIC,382,0 block_count,StoreIC,383,1 -block_count,StoreIC_Megamorphic,0,1136 -block_count,StoreIC_Megamorphic,1,1136 +block_count,StoreIC_Megamorphic,0,1131 +block_count,StoreIC_Megamorphic,1,1131 block_count,StoreIC_Megamorphic,2,0 -block_count,StoreIC_Megamorphic,3,1136 -block_count,StoreIC_Megamorphic,4,1136 +block_count,StoreIC_Megamorphic,3,1131 +block_count,StoreIC_Megamorphic,4,1131 block_count,StoreIC_Megamorphic,5,0 -block_count,StoreIC_Megamorphic,6,1136 -block_count,StoreIC_Megamorphic,7,1009 -block_count,StoreIC_Megamorphic,8,981 -block_count,StoreIC_Megamorphic,9,27 -block_count,StoreIC_Megamorphic,10,127 -block_count,StoreIC_Megamorphic,11,154 -block_count,StoreIC_Megamorphic,12,154 -block_count,StoreIC_Megamorphic,13,152 +block_count,StoreIC_Megamorphic,6,1131 +block_count,StoreIC_Megamorphic,7,992 +block_count,StoreIC_Megamorphic,8,891 +block_count,StoreIC_Megamorphic,9,100 +block_count,StoreIC_Megamorphic,10,138 +block_count,StoreIC_Megamorphic,11,239 +block_count,StoreIC_Megamorphic,12,238 +block_count,StoreIC_Megamorphic,13,237 block_count,StoreIC_Megamorphic,14,1 block_count,StoreIC_Megamorphic,15,0 -block_count,StoreIC_Megamorphic,16,1134 -block_count,StoreIC_Megamorphic,17,450 +block_count,StoreIC_Megamorphic,16,1128 +block_count,StoreIC_Megamorphic,17,443 block_count,StoreIC_Megamorphic,18,1 block_count,StoreIC_Megamorphic,19,1 block_count,StoreIC_Megamorphic,20,1 @@ -26987,41 +26978,41 @@ block_count,StoreIC_Megamorphic,155,0 block_count,StoreIC_Megamorphic,156,0 block_count,StoreIC_Megamorphic,157,0 -block_count,StoreIC_Megamorphic,158,448 -block_count,StoreIC_Megamorphic,159,448 -block_count,StoreIC_Megamorphic,160,272 -block_count,StoreIC_Megamorphic,161,272 -block_count,StoreIC_Megamorphic,162,272 +block_count,StoreIC_Megamorphic,158,442 +block_count,StoreIC_Megamorphic,159,442 +block_count,StoreIC_Megamorphic,160,265 +block_count,StoreIC_Megamorphic,161,265 +block_count,StoreIC_Megamorphic,162,265 block_count,StoreIC_Megamorphic,163,0 -block_count,StoreIC_Megamorphic,164,272 +block_count,StoreIC_Megamorphic,164,265 block_count,StoreIC_Megamorphic,165,0 -block_count,StoreIC_Megamorphic,166,272 -block_count,StoreIC_Megamorphic,167,272 +block_count,StoreIC_Megamorphic,166,265 +block_count,StoreIC_Megamorphic,167,265 block_count,StoreIC_Megamorphic,168,0 block_count,StoreIC_Megamorphic,169,0 block_count,StoreIC_Megamorphic,170,0 -block_count,StoreIC_Megamorphic,171,272 -block_count,StoreIC_Megamorphic,172,170 -block_count,StoreIC_Megamorphic,173,170 +block_count,StoreIC_Megamorphic,171,265 +block_count,StoreIC_Megamorphic,172,167 +block_count,StoreIC_Megamorphic,173,167 block_count,StoreIC_Megamorphic,174,0 block_count,StoreIC_Megamorphic,175,0 block_count,StoreIC_Megamorphic,176,0 -block_count,StoreIC_Megamorphic,177,170 -block_count,StoreIC_Megamorphic,178,170 +block_count,StoreIC_Megamorphic,177,167 +block_count,StoreIC_Megamorphic,178,167 block_count,StoreIC_Megamorphic,179,47 block_count,StoreIC_Megamorphic,180,0 block_count,StoreIC_Megamorphic,181,47 -block_count,StoreIC_Megamorphic,182,122 +block_count,StoreIC_Megamorphic,182,119 block_count,StoreIC_Megamorphic,183,0 block_count,StoreIC_Megamorphic,184,0 block_count,StoreIC_Megamorphic,185,0 block_count,StoreIC_Megamorphic,186,0 block_count,StoreIC_Megamorphic,187,0 block_count,StoreIC_Megamorphic,188,0 -block_count,StoreIC_Megamorphic,189,101 +block_count,StoreIC_Megamorphic,189,97 block_count,StoreIC_Megamorphic,190,0 -block_count,StoreIC_Megamorphic,191,101 -block_count,StoreIC_Megamorphic,192,272 +block_count,StoreIC_Megamorphic,191,97 +block_count,StoreIC_Megamorphic,192,265 block_count,StoreIC_Megamorphic,193,25 block_count,StoreIC_Megamorphic,194,0 block_count,StoreIC_Megamorphic,195,0 @@ -27057,7 +27048,7 @@ block_count,StoreIC_Megamorphic,225,2 block_count,StoreIC_Megamorphic,226,0 block_count,StoreIC_Megamorphic,227,2 -block_count,StoreIC_Megamorphic,228,2 +block_count,StoreIC_Megamorphic,228,3 block_count,StoreIC_Megamorphic,229,0 block_count,StoreIC_Megamorphic,230,2 block_count,StoreIC_Megamorphic,231,2 @@ -27066,8 +27057,8 @@ block_count,StoreIC_Megamorphic,234,11 block_count,StoreIC_Megamorphic,235,14 block_count,StoreIC_Megamorphic,236,25 -block_count,StoreIC_Megamorphic,237,246 -block_count,StoreIC_Megamorphic,238,246 +block_count,StoreIC_Megamorphic,237,240 +block_count,StoreIC_Megamorphic,238,240 block_count,StoreIC_Megamorphic,239,0 block_count,StoreIC_Megamorphic,240,0 block_count,StoreIC_Megamorphic,241,0 @@ -27095,7 +27086,7 @@ block_count,StoreIC_Megamorphic,263,0 block_count,StoreIC_Megamorphic,264,0 block_count,StoreIC_Megamorphic,265,0 -block_count,StoreIC_Megamorphic,266,684 +block_count,StoreIC_Megamorphic,266,685 block_count,StoreIC_Megamorphic,267,0 block_count,StoreIC_Megamorphic,268,0 block_count,StoreIC_Megamorphic,269,0 @@ -27148,30 +27139,30 @@ block_count,StoreIC_Megamorphic,316,0 block_count,StoreIC_Megamorphic,317,0 block_count,StoreIC_Megamorphic,318,0 -block_count,StoreIC_Megamorphic,319,388 -block_count,StoreIC_Megamorphic,320,388 -block_count,StoreIC_Megamorphic,321,388 +block_count,StoreIC_Megamorphic,319,389 +block_count,StoreIC_Megamorphic,320,389 +block_count,StoreIC_Megamorphic,321,389 block_count,StoreIC_Megamorphic,322,0 block_count,StoreIC_Megamorphic,323,0 block_count,StoreIC_Megamorphic,324,0 -block_count,StoreIC_Megamorphic,325,387 +block_count,StoreIC_Megamorphic,325,388 block_count,StoreIC_Megamorphic,326,0 -block_count,StoreIC_Megamorphic,327,388 +block_count,StoreIC_Megamorphic,327,389 block_count,StoreIC_Megamorphic,328,1 -block_count,StoreIC_Megamorphic,329,386 -block_count,StoreIC_Megamorphic,330,388 -block_count,StoreIC_Megamorphic,331,388 +block_count,StoreIC_Megamorphic,329,387 +block_count,StoreIC_Megamorphic,330,389 +block_count,StoreIC_Megamorphic,331,389 block_count,StoreIC_Megamorphic,332,0 block_count,StoreIC_Megamorphic,333,0 block_count,StoreIC_Megamorphic,334,0 block_count,StoreIC_Megamorphic,335,0 -block_count,StoreIC_Megamorphic,336,288 +block_count,StoreIC_Megamorphic,336,289 block_count,StoreIC_Megamorphic,337,0 -block_count,StoreIC_Megamorphic,338,288 +block_count,StoreIC_Megamorphic,338,289 block_count,StoreIC_Megamorphic,339,2 block_count,StoreIC_Megamorphic,340,286 -block_count,StoreIC_Megamorphic,341,288 -block_count,StoreIC_Megamorphic,342,288 +block_count,StoreIC_Megamorphic,341,289 +block_count,StoreIC_Megamorphic,342,289 block_count,StoreIC_Megamorphic,343,0 block_count,StoreIC_Megamorphic,344,0 block_count,StoreIC_Megamorphic,345,0 @@ -27200,17 +27191,17 @@ block_count,StoreICTrampoline,1,20 block_count,StoreICTrampoline,2,0 block_count,StoreICTrampoline,3,20 -block_count,StoreICTrampoline_Megamorphic,0,552 -block_count,StoreICTrampoline_Megamorphic,1,552 +block_count,StoreICTrampoline_Megamorphic,0,548 +block_count,StoreICTrampoline_Megamorphic,1,548 block_count,StoreICTrampoline_Megamorphic,2,0 -block_count,StoreICTrampoline_Megamorphic,3,552 -block_count,StoreICBaseline,0,564 -block_count,DefineNamedOwnIC,0,71 -block_count,DefineNamedOwnIC,1,71 +block_count,StoreICTrampoline_Megamorphic,3,548 +block_count,StoreICBaseline,0,560 +block_count,DefineNamedOwnIC,0,70 +block_count,DefineNamedOwnIC,1,70 block_count,DefineNamedOwnIC,2,0 -block_count,DefineNamedOwnIC,3,71 -block_count,DefineNamedOwnIC,4,71 -block_count,DefineNamedOwnIC,5,67 +block_count,DefineNamedOwnIC,3,70 +block_count,DefineNamedOwnIC,4,70 +block_count,DefineNamedOwnIC,5,66 block_count,DefineNamedOwnIC,6,0 block_count,DefineNamedOwnIC,7,0 block_count,DefineNamedOwnIC,8,0 @@ -27235,8 +27226,8 @@ block_count,DefineNamedOwnIC,27,0 block_count,DefineNamedOwnIC,28,0 block_count,DefineNamedOwnIC,29,0 -block_count,DefineNamedOwnIC,30,67 -block_count,DefineNamedOwnIC,31,67 +block_count,DefineNamedOwnIC,30,66 +block_count,DefineNamedOwnIC,31,66 block_count,DefineNamedOwnIC,32,0 block_count,DefineNamedOwnIC,33,0 block_count,DefineNamedOwnIC,34,0 @@ -27481,7 +27472,7 @@ block_count,DefineNamedOwnIC,273,0 block_count,DefineNamedOwnIC,274,0 block_count,DefineNamedOwnIC,275,0 -block_count,DefineNamedOwnIC,276,67 +block_count,DefineNamedOwnIC,276,66 block_count,DefineNamedOwnIC,277,0 block_count,DefineNamedOwnIC,278,0 block_count,DefineNamedOwnIC,279,0 @@ -27501,9 +27492,9 @@ block_count,DefineNamedOwnIC,293,0 block_count,DefineNamedOwnIC,294,0 block_count,DefineNamedOwnIC,295,0 -block_count,DefineNamedOwnIC,296,67 -block_count,DefineNamedOwnIC,297,67 -block_count,DefineNamedOwnIC,298,67 +block_count,DefineNamedOwnIC,296,66 +block_count,DefineNamedOwnIC,297,66 +block_count,DefineNamedOwnIC,298,66 block_count,DefineNamedOwnIC,299,0 block_count,DefineNamedOwnIC,300,0 block_count,DefineNamedOwnIC,301,0 @@ -27535,7 +27526,7 @@ block_count,DefineNamedOwnIC,327,8 block_count,DefineNamedOwnIC,328,0 block_count,DefineNamedOwnIC,329,8 -block_count,DefineNamedOwnIC,330,45 +block_count,DefineNamedOwnIC,330,44 block_count,DefineNamedOwnIC,331,0 block_count,DefineNamedOwnIC,332,53 block_count,DefineNamedOwnIC,333,0 @@ -27546,13 +27537,13 @@ block_count,DefineNamedOwnIC,338,0 block_count,DefineNamedOwnIC,339,0 block_count,DefineNamedOwnIC,340,0 -block_count,DefineNamedOwnIC,341,10 +block_count,DefineNamedOwnIC,341,9 block_count,DefineNamedOwnIC,342,0 -block_count,DefineNamedOwnIC,343,10 +block_count,DefineNamedOwnIC,343,9 block_count,DefineNamedOwnIC,344,0 -block_count,DefineNamedOwnIC,345,10 -block_count,DefineNamedOwnIC,346,10 -block_count,DefineNamedOwnIC,347,10 +block_count,DefineNamedOwnIC,345,9 +block_count,DefineNamedOwnIC,346,9 +block_count,DefineNamedOwnIC,347,9 block_count,DefineNamedOwnIC,348,0 block_count,DefineNamedOwnIC,349,0 block_count,DefineNamedOwnIC,350,0 @@ -27579,17 +27570,17 @@ block_count,DefineNamedOwnIC,371,3 block_count,DefineNamedOwnIC,372,0 block_count,DefineNamedOwnIC,373,0 -block_count,DefineNamedOwnICBaseline,0,65 -block_count,KeyedStoreIC,0,427 -block_count,KeyedStoreIC,1,427 +block_count,DefineNamedOwnICBaseline,0,64 +block_count,KeyedStoreIC,0,433 +block_count,KeyedStoreIC,1,433 block_count,KeyedStoreIC,2,0 -block_count,KeyedStoreIC,3,427 -block_count,KeyedStoreIC,4,427 -block_count,KeyedStoreIC,5,425 -block_count,KeyedStoreIC,6,37 +block_count,KeyedStoreIC,3,433 +block_count,KeyedStoreIC,4,433 +block_count,KeyedStoreIC,5,431 +block_count,KeyedStoreIC,6,38 block_count,KeyedStoreIC,7,0 -block_count,KeyedStoreIC,8,37 -block_count,KeyedStoreIC,9,19 +block_count,KeyedStoreIC,8,38 +block_count,KeyedStoreIC,9,20 block_count,KeyedStoreIC,10,0 block_count,KeyedStoreIC,11,0 block_count,KeyedStoreIC,12,0 @@ -27605,23 +27596,23 @@ block_count,KeyedStoreIC,22,13 block_count,KeyedStoreIC,23,0 block_count,KeyedStoreIC,24,17 -block_count,KeyedStoreIC,25,387 -block_count,KeyedStoreIC,26,405 -block_count,KeyedStoreIC,27,404 -block_count,KeyedStoreIC,28,404 -block_count,KeyedStoreIC,29,88 -block_count,KeyedStoreIC,30,88 +block_count,KeyedStoreIC,25,393 +block_count,KeyedStoreIC,26,411 +block_count,KeyedStoreIC,27,410 +block_count,KeyedStoreIC,28,410 +block_count,KeyedStoreIC,29,87 +block_count,KeyedStoreIC,30,87 block_count,KeyedStoreIC,31,0 -block_count,KeyedStoreIC,32,88 +block_count,KeyedStoreIC,32,87 block_count,KeyedStoreIC,33,0 -block_count,KeyedStoreIC,34,88 -block_count,KeyedStoreIC,35,88 +block_count,KeyedStoreIC,34,87 +block_count,KeyedStoreIC,35,87 block_count,KeyedStoreIC,36,1 block_count,KeyedStoreIC,37,1 block_count,KeyedStoreIC,38,1 block_count,KeyedStoreIC,39,0 block_count,KeyedStoreIC,40,0 -block_count,KeyedStoreIC,41,86 +block_count,KeyedStoreIC,41,85 block_count,KeyedStoreIC,42,0 block_count,KeyedStoreIC,43,0 block_count,KeyedStoreIC,44,0 @@ -27782,7 +27773,7 @@ block_count,KeyedStoreIC,199,0 block_count,KeyedStoreIC,200,0 block_count,KeyedStoreIC,201,0 -block_count,KeyedStoreIC,202,316 +block_count,KeyedStoreIC,202,322 block_count,KeyedStoreIC,203,0 block_count,KeyedStoreIC,204,0 block_count,KeyedStoreIC,205,0 @@ -28022,15 +28013,15 @@ block_count,KeyedStoreIC,439,21 block_count,KeyedStoreIC,440,0 block_count,KeyedStoreIC,441,0 -block_count,KeyedStoreICTrampoline,0,0 -block_count,KeyedStoreICTrampoline,1,0 +block_count,KeyedStoreICTrampoline,0,1 +block_count,KeyedStoreICTrampoline,1,1 block_count,KeyedStoreICTrampoline,2,0 -block_count,KeyedStoreICTrampoline,3,0 +block_count,KeyedStoreICTrampoline,3,1 block_count,KeyedStoreICTrampoline_Megamorphic,0,262 block_count,KeyedStoreICTrampoline_Megamorphic,1,262 block_count,KeyedStoreICTrampoline_Megamorphic,2,0 block_count,KeyedStoreICTrampoline_Megamorphic,3,262 -block_count,KeyedStoreICBaseline,0,387 +block_count,KeyedStoreICBaseline,0,393 block_count,DefineKeyedOwnIC,0,2 block_count,DefineKeyedOwnIC,1,2 block_count,DefineKeyedOwnIC,2,0 @@ -28501,11 +28492,11 @@ block_count,StoreInArrayLiteralIC,29,0 block_count,StoreInArrayLiteralIC,30,0 block_count,StoreInArrayLiteralICBaseline,0,34 -block_count,LoadGlobalIC,0,843 -block_count,LoadGlobalIC,1,843 -block_count,LoadGlobalIC,2,749 -block_count,LoadGlobalIC,3,749 -block_count,LoadGlobalIC,4,749 +block_count,LoadGlobalIC,0,1070 +block_count,LoadGlobalIC,1,1070 +block_count,LoadGlobalIC,2,975 +block_count,LoadGlobalIC,3,975 +block_count,LoadGlobalIC,4,975 block_count,LoadGlobalIC,5,0 block_count,LoadGlobalIC,6,0 block_count,LoadGlobalIC,7,0 @@ -28726,11 +28717,11 @@ block_count,LoadGlobalIC,222,0 block_count,LoadGlobalIC,223,0 block_count,LoadGlobalIC,224,0 -block_count,LoadGlobalIC,225,93 +block_count,LoadGlobalIC,225,94 block_count,LoadGlobalIC,226,0 -block_count,LoadGlobalIC,227,93 +block_count,LoadGlobalIC,227,94 block_count,LoadGlobalIC,228,0 -block_count,LoadGlobalIC,229,93 +block_count,LoadGlobalIC,229,94 block_count,LoadGlobalICInsideTypeof,0,1 block_count,LoadGlobalICInsideTypeof,1,1 block_count,LoadGlobalICInsideTypeof,2,1 @@ -28956,11 +28947,11 @@ block_count,LoadGlobalICInsideTypeof,222,0 block_count,LoadGlobalICInsideTypeof,223,0 block_count,LoadGlobalICInsideTypeof,224,0 -block_count,LoadGlobalICTrampoline,0,59 -block_count,LoadGlobalICTrampoline,1,59 +block_count,LoadGlobalICTrampoline,0,259 +block_count,LoadGlobalICTrampoline,1,259 block_count,LoadGlobalICTrampoline,2,0 -block_count,LoadGlobalICTrampoline,3,59 -block_count,LoadGlobalICBaseline,0,768 +block_count,LoadGlobalICTrampoline,3,259 +block_count,LoadGlobalICBaseline,0,761 block_count,LoadGlobalICInsideTypeofTrampoline,0,0 block_count,LoadGlobalICInsideTypeofTrampoline,1,0 block_count,LoadGlobalICInsideTypeofTrampoline,2,0 @@ -29818,9 +29809,9 @@ block_count,FindOrderedHashMapEntry,14,50 block_count,FindOrderedHashMapEntry,15,55 block_count,FindOrderedHashMapEntry,16,114 -block_count,FindOrderedHashMapEntry,17,187 -block_count,FindOrderedHashMapEntry,18,93 -block_count,FindOrderedHashMapEntry,19,72 +block_count,FindOrderedHashMapEntry,17,131 +block_count,FindOrderedHashMapEntry,18,37 +block_count,FindOrderedHashMapEntry,19,16 block_count,FindOrderedHashMapEntry,20,20 block_count,FindOrderedHashMapEntry,21,93 block_count,FindOrderedHashMapEntry,22,0 @@ -30297,8 +30288,8 @@ block_count,MapPrototypeSet,28,40 block_count,MapPrototypeSet,29,40 block_count,MapPrototypeSet,30,68 -block_count,MapPrototypeSet,31,37 -block_count,MapPrototypeSet,32,27 +block_count,MapPrototypeSet,31,38 +block_count,MapPrototypeSet,32,28 block_count,MapPrototypeSet,33,9 block_count,MapPrototypeSet,34,30 block_count,MapPrototypeSet,35,0 @@ -30664,26 +30655,26 @@ block_count,MapIteratorToList,54,0 block_count,MapIteratorToList,55,0 block_count,MapIteratorToList,56,0 -block_count,Add_Baseline,0,498 -block_count,Add_Baseline,1,291 +block_count,Add_Baseline,0,496 +block_count,Add_Baseline,1,290 block_count,Add_Baseline,2,5 block_count,Add_Baseline,3,5 block_count,Add_Baseline,4,0 -block_count,Add_Baseline,5,285 -block_count,Add_Baseline,6,285 +block_count,Add_Baseline,5,284 +block_count,Add_Baseline,6,284 block_count,Add_Baseline,7,0 -block_count,Add_Baseline,8,285 -block_count,Add_Baseline,9,285 +block_count,Add_Baseline,8,284 +block_count,Add_Baseline,9,284 block_count,Add_Baseline,10,0 -block_count,Add_Baseline,11,207 -block_count,Add_Baseline,12,126 +block_count,Add_Baseline,11,205 +block_count,Add_Baseline,12,127 block_count,Add_Baseline,13,107 block_count,Add_Baseline,14,107 block_count,Add_Baseline,15,0 block_count,Add_Baseline,16,19 -block_count,Add_Baseline,17,80 -block_count,Add_Baseline,18,80 -block_count,Add_Baseline,19,75 +block_count,Add_Baseline,17,78 +block_count,Add_Baseline,18,78 +block_count,Add_Baseline,19,73 block_count,Add_Baseline,20,0 block_count,Add_Baseline,21,0 block_count,Add_Baseline,22,0 @@ -30697,7 +30688,7 @@ block_count,Add_Baseline,30,0 block_count,Add_Baseline,31,0 block_count,Add_Baseline,32,0 -block_count,Add_Baseline,33,75 +block_count,Add_Baseline,33,73 block_count,Add_Baseline,34,5 block_count,Add_Baseline,35,5 block_count,Add_Baseline,36,0 @@ -30706,10 +30697,10 @@ block_count,Add_Baseline,39,0 block_count,Add_Baseline,40,0 block_count,Add_Baseline,41,0 -block_count,Add_Baseline,42,69 +block_count,Add_Baseline,42,67 block_count,Add_Baseline,43,0 -block_count,Add_Baseline,44,69 -block_count,Add_Baseline,45,69 +block_count,Add_Baseline,44,67 +block_count,Add_Baseline,45,67 block_count,Add_Baseline,46,5 block_count,Add_Baseline,47,0 block_count,Add_Baseline,48,0 @@ -30732,12 +30723,12 @@ block_count,Add_Baseline,65,0 block_count,Add_Baseline,66,132 block_count,Add_Baseline,67,132 -block_count,AddSmi_Baseline,0,482 -block_count,AddSmi_Baseline,1,480 -block_count,AddSmi_Baseline,2,480 +block_count,AddSmi_Baseline,0,480 +block_count,AddSmi_Baseline,1,478 +block_count,AddSmi_Baseline,2,478 block_count,AddSmi_Baseline,3,0 -block_count,AddSmi_Baseline,4,480 -block_count,AddSmi_Baseline,5,480 +block_count,AddSmi_Baseline,4,478 +block_count,AddSmi_Baseline,5,478 block_count,AddSmi_Baseline,6,0 block_count,AddSmi_Baseline,7,1 block_count,AddSmi_Baseline,8,1 @@ -30784,28 +30775,28 @@ block_count,AddSmi_Baseline,49,0 block_count,AddSmi_Baseline,50,0 block_count,AddSmi_Baseline,51,0 -block_count,AddSmi_Baseline,52,1 +block_count,AddSmi_Baseline,52,2 block_count,AddSmi_Baseline,53,0 -block_count,AddSmi_Baseline,54,1 -block_count,AddSmi_Baseline,55,1 +block_count,AddSmi_Baseline,54,2 +block_count,AddSmi_Baseline,55,2 block_count,AddSmi_Baseline,56,0 -block_count,AddSmi_Baseline,57,1 -block_count,AddSmi_Baseline,58,1 -block_count,Subtract_Baseline,0,107 +block_count,AddSmi_Baseline,57,2 +block_count,AddSmi_Baseline,58,2 +block_count,Subtract_Baseline,0,108 block_count,Subtract_Baseline,1,56 block_count,Subtract_Baseline,2,4 block_count,Subtract_Baseline,3,4 block_count,Subtract_Baseline,4,0 -block_count,Subtract_Baseline,5,51 -block_count,Subtract_Baseline,6,51 +block_count,Subtract_Baseline,5,52 +block_count,Subtract_Baseline,6,52 block_count,Subtract_Baseline,7,0 block_count,Subtract_Baseline,8,0 block_count,Subtract_Baseline,9,0 block_count,Subtract_Baseline,10,0 -block_count,Subtract_Baseline,11,51 +block_count,Subtract_Baseline,11,52 block_count,Subtract_Baseline,12,0 -block_count,Subtract_Baseline,13,51 -block_count,Subtract_Baseline,14,51 +block_count,Subtract_Baseline,13,52 +block_count,Subtract_Baseline,14,52 block_count,Subtract_Baseline,15,51 block_count,Subtract_Baseline,16,51 block_count,Subtract_Baseline,17,48 @@ -30841,13 +30832,13 @@ block_count,Subtract_Baseline,47,0 block_count,Subtract_Baseline,48,0 block_count,Subtract_Baseline,49,0 -block_count,Subtract_Baseline,50,55 +block_count,Subtract_Baseline,50,56 block_count,Subtract_Baseline,51,0 block_count,Subtract_Baseline,52,55 -block_count,Subtract_Baseline,53,55 +block_count,Subtract_Baseline,53,56 block_count,Subtract_Baseline,54,0 block_count,Subtract_Baseline,55,55 -block_count,Subtract_Baseline,56,55 +block_count,Subtract_Baseline,56,56 block_count,SubtractSmi_Baseline,0,62 block_count,SubtractSmi_Baseline,1,47 block_count,SubtractSmi_Baseline,2,47 @@ -30867,7 +30858,7 @@ block_count,SubtractSmi_Baseline,16,0 block_count,SubtractSmi_Baseline,17,15 block_count,SubtractSmi_Baseline,18,15 -block_count,Multiply_Baseline,0,158 +block_count,Multiply_Baseline,0,159 block_count,Multiply_Baseline,1,26 block_count,Multiply_Baseline,2,13 block_count,Multiply_Baseline,3,13 @@ -30932,37 +30923,37 @@ block_count,Multiply_Baseline,62,0 block_count,Multiply_Baseline,63,0 block_count,Multiply_Baseline,64,0 -block_count,Multiply_Baseline,65,145 +block_count,Multiply_Baseline,65,146 block_count,Multiply_Baseline,66,0 -block_count,Multiply_Baseline,67,145 -block_count,Multiply_Baseline,68,145 +block_count,Multiply_Baseline,67,146 +block_count,Multiply_Baseline,68,146 block_count,Multiply_Baseline,69,0 -block_count,Multiply_Baseline,70,145 -block_count,Multiply_Baseline,71,145 -block_count,MultiplySmi_Baseline,0,25 -block_count,MultiplySmi_Baseline,1,21 -block_count,MultiplySmi_Baseline,2,20 -block_count,MultiplySmi_Baseline,3,13 -block_count,MultiplySmi_Baseline,4,13 +block_count,Multiply_Baseline,70,146 +block_count,Multiply_Baseline,71,146 +block_count,MultiplySmi_Baseline,0,32 +block_count,MultiplySmi_Baseline,1,28 +block_count,MultiplySmi_Baseline,2,28 +block_count,MultiplySmi_Baseline,3,17 +block_count,MultiplySmi_Baseline,4,17 block_count,MultiplySmi_Baseline,5,0 block_count,MultiplySmi_Baseline,6,0 block_count,MultiplySmi_Baseline,7,0 block_count,MultiplySmi_Baseline,8,0 -block_count,MultiplySmi_Baseline,9,13 -block_count,MultiplySmi_Baseline,10,6 -block_count,MultiplySmi_Baseline,11,6 +block_count,MultiplySmi_Baseline,9,17 +block_count,MultiplySmi_Baseline,10,10 +block_count,MultiplySmi_Baseline,11,10 block_count,MultiplySmi_Baseline,12,0 block_count,MultiplySmi_Baseline,13,0 block_count,MultiplySmi_Baseline,14,0 block_count,MultiplySmi_Baseline,15,0 block_count,MultiplySmi_Baseline,16,0 -block_count,MultiplySmi_Baseline,17,21 +block_count,MultiplySmi_Baseline,17,28 block_count,MultiplySmi_Baseline,18,0 -block_count,MultiplySmi_Baseline,19,20 -block_count,MultiplySmi_Baseline,20,21 +block_count,MultiplySmi_Baseline,19,28 +block_count,MultiplySmi_Baseline,20,28 block_count,MultiplySmi_Baseline,21,0 -block_count,MultiplySmi_Baseline,22,21 -block_count,MultiplySmi_Baseline,23,21 +block_count,MultiplySmi_Baseline,22,28 +block_count,MultiplySmi_Baseline,23,28 block_count,MultiplySmi_Baseline,24,4 block_count,MultiplySmi_Baseline,25,4 block_count,MultiplySmi_Baseline,26,0 @@ -31008,7 +30999,7 @@ block_count,Divide_Baseline,4,0 block_count,Divide_Baseline,5,3 block_count,Divide_Baseline,6,3 -block_count,Divide_Baseline,7,3 +block_count,Divide_Baseline,7,2 block_count,Divide_Baseline,8,0 block_count,Divide_Baseline,9,0 block_count,Divide_Baseline,10,0 @@ -31282,8 +31273,8 @@ block_count,Exponentiate_Baseline,46,0 block_count,Exponentiate_Baseline,47,0 block_count,Exponentiate_Baseline,48,0 -block_count,BitwiseAnd_Baseline,0,28 -block_count,BitwiseAnd_Baseline,1,23 +block_count,BitwiseAnd_Baseline,0,27 +block_count,BitwiseAnd_Baseline,1,22 block_count,BitwiseAnd_Baseline,2,5 block_count,BitwiseAnd_Baseline,3,5 block_count,BitwiseAnd_Baseline,4,0 @@ -31326,7 +31317,7 @@ block_count,BitwiseAnd_Baseline,41,0 block_count,BitwiseAnd_Baseline,42,0 block_count,BitwiseAnd_Baseline,43,4 -block_count,BitwiseAnd_Baseline,44,28 +block_count,BitwiseAnd_Baseline,44,27 block_count,BitwiseAnd_Baseline,45,20 block_count,BitwiseAnd_Baseline,46,7 block_count,BitwiseAnd_Baseline,47,7 @@ -31348,20 +31339,20 @@ block_count,BitwiseAnd_Baseline,63,0 block_count,BitwiseAnd_Baseline,64,0 block_count,BitwiseAnd_Baseline,65,6 -block_count,BitwiseAnd_Baseline,66,28 -block_count,BitwiseAnd_Baseline,67,25 +block_count,BitwiseAnd_Baseline,66,27 +block_count,BitwiseAnd_Baseline,67,24 block_count,BitwiseAnd_Baseline,68,3 block_count,BitwiseAnd_Baseline,69,0 block_count,BitwiseAnd_Baseline,70,3 block_count,BitwiseAnd_Baseline,71,3 -block_count,BitwiseAnd_Baseline,72,28 +block_count,BitwiseAnd_Baseline,72,27 block_count,BitwiseAnd_Baseline,73,3 -block_count,BitwiseAnd_Baseline,74,25 -block_count,BitwiseAnd_Baseline,75,28 +block_count,BitwiseAnd_Baseline,74,24 +block_count,BitwiseAnd_Baseline,75,27 block_count,BitwiseAnd_Baseline,76,0 -block_count,BitwiseAnd_Baseline,77,28 -block_count,BitwiseAnd_Baseline,78,28 -block_count,BitwiseAndSmi_Baseline,0,101 +block_count,BitwiseAnd_Baseline,77,27 +block_count,BitwiseAnd_Baseline,78,27 +block_count,BitwiseAndSmi_Baseline,0,102 block_count,BitwiseAndSmi_Baseline,1,5 block_count,BitwiseAndSmi_Baseline,2,5 block_count,BitwiseAndSmi_Baseline,3,1 @@ -31381,7 +31372,7 @@ block_count,BitwiseAndSmi_Baseline,17,0 block_count,BitwiseAndSmi_Baseline,18,0 block_count,BitwiseAndSmi_Baseline,19,0 -block_count,BitwiseAndSmi_Baseline,20,4 +block_count,BitwiseAndSmi_Baseline,20,3 block_count,BitwiseAndSmi_Baseline,21,5 block_count,BitwiseAndSmi_Baseline,22,5 block_count,BitwiseAndSmi_Baseline,23,0 @@ -31392,14 +31383,14 @@ block_count,BitwiseAndSmi_Baseline,28,0 block_count,BitwiseAndSmi_Baseline,29,5 block_count,BitwiseAndSmi_Baseline,30,5 -block_count,BitwiseAndSmi_Baseline,31,95 -block_count,BitwiseAndSmi_Baseline,32,101 +block_count,BitwiseAndSmi_Baseline,31,96 +block_count,BitwiseAndSmi_Baseline,32,102 block_count,BitwiseAndSmi_Baseline,33,0 -block_count,BitwiseAndSmi_Baseline,34,101 -block_count,BitwiseOr_Baseline,0,53 -block_count,BitwiseOr_Baseline,1,48 -block_count,BitwiseOr_Baseline,2,5 -block_count,BitwiseOr_Baseline,3,5 +block_count,BitwiseAndSmi_Baseline,34,102 +block_count,BitwiseOr_Baseline,0,52 +block_count,BitwiseOr_Baseline,1,47 +block_count,BitwiseOr_Baseline,2,4 +block_count,BitwiseOr_Baseline,3,4 block_count,BitwiseOr_Baseline,4,0 block_count,BitwiseOr_Baseline,5,0 block_count,BitwiseOr_Baseline,6,0 @@ -31439,9 +31430,9 @@ block_count,BitwiseOr_Baseline,40,0 block_count,BitwiseOr_Baseline,41,0 block_count,BitwiseOr_Baseline,42,0 -block_count,BitwiseOr_Baseline,43,5 -block_count,BitwiseOr_Baseline,44,53 -block_count,BitwiseOr_Baseline,45,50 +block_count,BitwiseOr_Baseline,43,4 +block_count,BitwiseOr_Baseline,44,52 +block_count,BitwiseOr_Baseline,45,49 block_count,BitwiseOr_Baseline,46,3 block_count,BitwiseOr_Baseline,47,3 block_count,BitwiseOr_Baseline,48,0 @@ -31461,21 +31452,21 @@ block_count,BitwiseOr_Baseline,62,0 block_count,BitwiseOr_Baseline,63,0 block_count,BitwiseOr_Baseline,64,0 -block_count,BitwiseOr_Baseline,65,3 -block_count,BitwiseOr_Baseline,66,53 -block_count,BitwiseOr_Baseline,67,47 -block_count,BitwiseOr_Baseline,68,6 +block_count,BitwiseOr_Baseline,65,2 +block_count,BitwiseOr_Baseline,66,52 +block_count,BitwiseOr_Baseline,67,46 +block_count,BitwiseOr_Baseline,68,5 block_count,BitwiseOr_Baseline,69,0 -block_count,BitwiseOr_Baseline,70,6 -block_count,BitwiseOr_Baseline,71,6 -block_count,BitwiseOr_Baseline,72,53 -block_count,BitwiseOr_Baseline,73,6 -block_count,BitwiseOr_Baseline,74,47 -block_count,BitwiseOr_Baseline,75,53 +block_count,BitwiseOr_Baseline,70,5 +block_count,BitwiseOr_Baseline,71,5 +block_count,BitwiseOr_Baseline,72,52 +block_count,BitwiseOr_Baseline,73,5 +block_count,BitwiseOr_Baseline,74,46 +block_count,BitwiseOr_Baseline,75,52 block_count,BitwiseOr_Baseline,76,0 -block_count,BitwiseOr_Baseline,77,53 -block_count,BitwiseOr_Baseline,78,53 -block_count,BitwiseOrSmi_Baseline,0,248 +block_count,BitwiseOr_Baseline,77,52 +block_count,BitwiseOr_Baseline,78,52 +block_count,BitwiseOrSmi_Baseline,0,256 block_count,BitwiseOrSmi_Baseline,1,4 block_count,BitwiseOrSmi_Baseline,2,4 block_count,BitwiseOrSmi_Baseline,3,0 @@ -31506,10 +31497,10 @@ block_count,BitwiseOrSmi_Baseline,28,2 block_count,BitwiseOrSmi_Baseline,29,2 block_count,BitwiseOrSmi_Baseline,30,4 -block_count,BitwiseOrSmi_Baseline,31,243 -block_count,BitwiseOrSmi_Baseline,32,248 +block_count,BitwiseOrSmi_Baseline,31,251 +block_count,BitwiseOrSmi_Baseline,32,256 block_count,BitwiseOrSmi_Baseline,33,0 -block_count,BitwiseOrSmi_Baseline,34,248 +block_count,BitwiseOrSmi_Baseline,34,256 block_count,BitwiseXor_Baseline,0,35 block_count,BitwiseXor_Baseline,1,20 block_count,BitwiseXor_Baseline,2,15 @@ -31624,7 +31615,7 @@ block_count,BitwiseXorSmi_Baseline,32,1 block_count,BitwiseXorSmi_Baseline,33,0 block_count,BitwiseXorSmi_Baseline,34,1 -block_count,ShiftLeft_Baseline,0,5 +block_count,ShiftLeft_Baseline,0,4 block_count,ShiftLeft_Baseline,1,4 block_count,ShiftLeft_Baseline,2,0 block_count,ShiftLeft_Baseline,3,0 @@ -31668,8 +31659,8 @@ block_count,ShiftLeft_Baseline,41,0 block_count,ShiftLeft_Baseline,42,0 block_count,ShiftLeft_Baseline,43,0 -block_count,ShiftLeft_Baseline,44,5 -block_count,ShiftLeft_Baseline,45,5 +block_count,ShiftLeft_Baseline,44,4 +block_count,ShiftLeft_Baseline,45,4 block_count,ShiftLeft_Baseline,46,0 block_count,ShiftLeft_Baseline,47,0 block_count,ShiftLeft_Baseline,48,0 @@ -31690,20 +31681,20 @@ block_count,ShiftLeft_Baseline,63,0 block_count,ShiftLeft_Baseline,64,0 block_count,ShiftLeft_Baseline,65,0 -block_count,ShiftLeft_Baseline,66,5 +block_count,ShiftLeft_Baseline,66,4 block_count,ShiftLeft_Baseline,67,4 block_count,ShiftLeft_Baseline,68,0 block_count,ShiftLeft_Baseline,69,0 block_count,ShiftLeft_Baseline,70,0 block_count,ShiftLeft_Baseline,71,0 -block_count,ShiftLeft_Baseline,72,5 +block_count,ShiftLeft_Baseline,72,4 block_count,ShiftLeft_Baseline,73,0 block_count,ShiftLeft_Baseline,74,4 -block_count,ShiftLeft_Baseline,75,5 +block_count,ShiftLeft_Baseline,75,4 block_count,ShiftLeft_Baseline,76,0 -block_count,ShiftLeft_Baseline,77,5 -block_count,ShiftLeft_Baseline,78,5 -block_count,ShiftLeftSmi_Baseline,0,68 +block_count,ShiftLeft_Baseline,77,4 +block_count,ShiftLeft_Baseline,78,4 +block_count,ShiftLeftSmi_Baseline,0,67 block_count,ShiftLeftSmi_Baseline,1,5 block_count,ShiftLeftSmi_Baseline,2,5 block_count,ShiftLeftSmi_Baseline,3,0 @@ -31734,19 +31725,19 @@ block_count,ShiftLeftSmi_Baseline,28,2 block_count,ShiftLeftSmi_Baseline,29,3 block_count,ShiftLeftSmi_Baseline,30,5 -block_count,ShiftLeftSmi_Baseline,31,62 +block_count,ShiftLeftSmi_Baseline,31,61 block_count,ShiftLeftSmi_Baseline,32,59 block_count,ShiftLeftSmi_Baseline,33,2 block_count,ShiftLeftSmi_Baseline,34,0 block_count,ShiftLeftSmi_Baseline,35,2 block_count,ShiftLeftSmi_Baseline,36,2 -block_count,ShiftLeftSmi_Baseline,37,62 +block_count,ShiftLeftSmi_Baseline,37,61 block_count,ShiftLeftSmi_Baseline,38,2 block_count,ShiftLeftSmi_Baseline,39,59 -block_count,ShiftLeftSmi_Baseline,40,62 -block_count,ShiftLeftSmi_Baseline,41,68 +block_count,ShiftLeftSmi_Baseline,40,61 +block_count,ShiftLeftSmi_Baseline,41,67 block_count,ShiftLeftSmi_Baseline,42,0 -block_count,ShiftLeftSmi_Baseline,43,68 +block_count,ShiftLeftSmi_Baseline,43,67 block_count,ShiftRight_Baseline,0,6 block_count,ShiftRight_Baseline,1,6 block_count,ShiftRight_Baseline,2,0 @@ -31826,7 +31817,7 @@ block_count,ShiftRight_Baseline,76,0 block_count,ShiftRight_Baseline,77,6 block_count,ShiftRight_Baseline,78,6 -block_count,ShiftRightSmi_Baseline,0,207 +block_count,ShiftRightSmi_Baseline,0,206 block_count,ShiftRightSmi_Baseline,1,4 block_count,ShiftRightSmi_Baseline,2,4 block_count,ShiftRightSmi_Baseline,3,0 @@ -31858,9 +31849,9 @@ block_count,ShiftRightSmi_Baseline,29,4 block_count,ShiftRightSmi_Baseline,30,4 block_count,ShiftRightSmi_Baseline,31,202 -block_count,ShiftRightSmi_Baseline,32,207 +block_count,ShiftRightSmi_Baseline,32,206 block_count,ShiftRightSmi_Baseline,33,0 -block_count,ShiftRightSmi_Baseline,34,207 +block_count,ShiftRightSmi_Baseline,34,206 block_count,ShiftRightLogical_Baseline,0,1 block_count,ShiftRightLogical_Baseline,1,1 block_count,ShiftRightLogical_Baseline,2,0 @@ -31937,7 +31928,7 @@ block_count,ShiftRightLogical_Baseline,73,1 block_count,ShiftRightLogical_Baseline,74,0 block_count,ShiftRightLogical_Baseline,75,1 -block_count,ShiftRightLogicalSmi_Baseline,0,16 +block_count,ShiftRightLogicalSmi_Baseline,0,15 block_count,ShiftRightLogicalSmi_Baseline,1,7 block_count,ShiftRightLogicalSmi_Baseline,2,7 block_count,ShiftRightLogicalSmi_Baseline,3,0 @@ -31978,19 +31969,19 @@ block_count,ShiftRightLogicalSmi_Baseline,38,0 block_count,ShiftRightLogicalSmi_Baseline,39,7 block_count,ShiftRightLogicalSmi_Baseline,40,8 -block_count,ShiftRightLogicalSmi_Baseline,41,16 +block_count,ShiftRightLogicalSmi_Baseline,41,15 block_count,ShiftRightLogicalSmi_Baseline,42,0 -block_count,ShiftRightLogicalSmi_Baseline,43,16 -block_count,Equal_Baseline,0,296 -block_count,Equal_Baseline,1,300 -block_count,Equal_Baseline,2,227 -block_count,Equal_Baseline,3,56 -block_count,Equal_Baseline,4,53 -block_count,Equal_Baseline,5,23 -block_count,Equal_Baseline,6,22 -block_count,Equal_Baseline,7,19 -block_count,Equal_Baseline,8,16 -block_count,Equal_Baseline,9,16 +block_count,ShiftRightLogicalSmi_Baseline,43,15 +block_count,Equal_Baseline,0,290 +block_count,Equal_Baseline,1,294 +block_count,Equal_Baseline,2,223 +block_count,Equal_Baseline,3,52 +block_count,Equal_Baseline,4,50 +block_count,Equal_Baseline,5,19 +block_count,Equal_Baseline,6,19 +block_count,Equal_Baseline,7,16 +block_count,Equal_Baseline,8,12 +block_count,Equal_Baseline,9,12 block_count,Equal_Baseline,10,0 block_count,Equal_Baseline,11,0 block_count,Equal_Baseline,12,0 @@ -31999,7 +31990,7 @@ block_count,Equal_Baseline,15,0 block_count,Equal_Baseline,16,0 block_count,Equal_Baseline,17,0 -block_count,Equal_Baseline,18,15 +block_count,Equal_Baseline,18,12 block_count,Equal_Baseline,19,0 block_count,Equal_Baseline,20,0 block_count,Equal_Baseline,21,0 @@ -32021,7 +32012,7 @@ block_count,Equal_Baseline,37,0 block_count,Equal_Baseline,38,0 block_count,Equal_Baseline,39,3 -block_count,Equal_Baseline,40,3 +block_count,Equal_Baseline,40,2 block_count,Equal_Baseline,41,0 block_count,Equal_Baseline,42,2 block_count,Equal_Baseline,43,0 @@ -32053,19 +32044,19 @@ block_count,Equal_Baseline,69,0 block_count,Equal_Baseline,70,30 block_count,Equal_Baseline,71,0 -block_count,Equal_Baseline,72,30 +block_count,Equal_Baseline,72,29 block_count,Equal_Baseline,73,21 block_count,Equal_Baseline,74,8 block_count,Equal_Baseline,75,8 block_count,Equal_Baseline,76,8 block_count,Equal_Baseline,77,0 -block_count,Equal_Baseline,78,30 +block_count,Equal_Baseline,78,29 block_count,Equal_Baseline,79,3 block_count,Equal_Baseline,80,26 -block_count,Equal_Baseline,81,30 +block_count,Equal_Baseline,81,29 block_count,Equal_Baseline,82,0 -block_count,Equal_Baseline,83,30 -block_count,Equal_Baseline,84,30 +block_count,Equal_Baseline,83,29 +block_count,Equal_Baseline,84,29 block_count,Equal_Baseline,85,2 block_count,Equal_Baseline,86,2 block_count,Equal_Baseline,87,171 @@ -32088,7 +32079,7 @@ block_count,Equal_Baseline,104,0 block_count,Equal_Baseline,105,0 block_count,Equal_Baseline,106,3 -block_count,Equal_Baseline,107,167 +block_count,Equal_Baseline,107,166 block_count,Equal_Baseline,108,0 block_count,Equal_Baseline,109,0 block_count,Equal_Baseline,110,0 @@ -32102,12 +32093,12 @@ block_count,Equal_Baseline,118,0 block_count,Equal_Baseline,119,0 block_count,Equal_Baseline,120,6 -block_count,Equal_Baseline,121,4 +block_count,Equal_Baseline,121,3 block_count,Equal_Baseline,122,2 -block_count,Equal_Baseline,123,72 -block_count,Equal_Baseline,124,15 -block_count,Equal_Baseline,125,15 -block_count,Equal_Baseline,126,10 +block_count,Equal_Baseline,123,71 +block_count,Equal_Baseline,124,14 +block_count,Equal_Baseline,125,13 +block_count,Equal_Baseline,126,9 block_count,Equal_Baseline,127,3 block_count,Equal_Baseline,128,0 block_count,Equal_Baseline,129,0 @@ -32115,7 +32106,7 @@ block_count,Equal_Baseline,131,3 block_count,Equal_Baseline,132,0 block_count,Equal_Baseline,133,3 -block_count,Equal_Baseline,134,7 +block_count,Equal_Baseline,134,5 block_count,Equal_Baseline,135,4 block_count,Equal_Baseline,136,0 block_count,Equal_Baseline,137,4 @@ -32124,25 +32115,25 @@ block_count,Equal_Baseline,140,0 block_count,Equal_Baseline,141,0 block_count,Equal_Baseline,142,56 -block_count,Equal_Baseline,143,74 -block_count,Equal_Baseline,144,191 -block_count,Equal_Baseline,145,296 +block_count,Equal_Baseline,143,73 +block_count,Equal_Baseline,144,187 +block_count,Equal_Baseline,145,290 block_count,Equal_Baseline,146,0 -block_count,Equal_Baseline,147,296 -block_count,StrictEqual_Baseline,0,437 -block_count,StrictEqual_Baseline,1,363 -block_count,StrictEqual_Baseline,2,250 -block_count,StrictEqual_Baseline,3,250 -block_count,StrictEqual_Baseline,4,249 -block_count,StrictEqual_Baseline,5,123 -block_count,StrictEqual_Baseline,6,123 -block_count,StrictEqual_Baseline,7,54 +block_count,Equal_Baseline,147,290 +block_count,StrictEqual_Baseline,0,435 +block_count,StrictEqual_Baseline,1,360 +block_count,StrictEqual_Baseline,2,249 +block_count,StrictEqual_Baseline,3,249 +block_count,StrictEqual_Baseline,4,248 +block_count,StrictEqual_Baseline,5,122 +block_count,StrictEqual_Baseline,6,122 +block_count,StrictEqual_Baseline,7,53 block_count,StrictEqual_Baseline,8,52 -block_count,StrictEqual_Baseline,9,42 +block_count,StrictEqual_Baseline,9,41 block_count,StrictEqual_Baseline,10,0 -block_count,StrictEqual_Baseline,11,42 +block_count,StrictEqual_Baseline,11,41 block_count,StrictEqual_Baseline,12,0 -block_count,StrictEqual_Baseline,13,42 +block_count,StrictEqual_Baseline,13,41 block_count,StrictEqual_Baseline,14,10 block_count,StrictEqual_Baseline,15,4 block_count,StrictEqual_Baseline,16,5 @@ -32168,7 +32159,7 @@ block_count,StrictEqual_Baseline,36,125 block_count,StrictEqual_Baseline,37,87 block_count,StrictEqual_Baseline,38,37 -block_count,StrictEqual_Baseline,39,1 +block_count,StrictEqual_Baseline,39,0 block_count,StrictEqual_Baseline,40,0 block_count,StrictEqual_Baseline,41,0 block_count,StrictEqual_Baseline,42,0 @@ -32178,15 +32169,15 @@ block_count,StrictEqual_Baseline,46,0 block_count,StrictEqual_Baseline,47,0 block_count,StrictEqual_Baseline,48,0 -block_count,StrictEqual_Baseline,49,113 +block_count,StrictEqual_Baseline,49,111 block_count,StrictEqual_Baseline,50,1 block_count,StrictEqual_Baseline,51,0 block_count,StrictEqual_Baseline,52,0 block_count,StrictEqual_Baseline,53,0 block_count,StrictEqual_Baseline,54,0 -block_count,StrictEqual_Baseline,55,112 +block_count,StrictEqual_Baseline,55,110 block_count,StrictEqual_Baseline,56,9 -block_count,StrictEqual_Baseline,57,74 +block_count,StrictEqual_Baseline,57,75 block_count,StrictEqual_Baseline,58,34 block_count,StrictEqual_Baseline,59,34 block_count,StrictEqual_Baseline,60,19 @@ -32198,22 +32189,22 @@ block_count,StrictEqual_Baseline,66,1 block_count,StrictEqual_Baseline,67,0 block_count,StrictEqual_Baseline,68,16 -block_count,StrictEqual_Baseline,69,15 +block_count,StrictEqual_Baseline,69,14 block_count,StrictEqual_Baseline,70,0 block_count,StrictEqual_Baseline,71,14 -block_count,StrictEqual_Baseline,72,15 +block_count,StrictEqual_Baseline,72,14 block_count,StrictEqual_Baseline,73,0 block_count,StrictEqual_Baseline,74,0 block_count,StrictEqual_Baseline,75,0 -block_count,StrictEqual_Baseline,76,39 -block_count,StrictEqual_Baseline,77,238 -block_count,StrictEqual_Baseline,78,74 -block_count,StrictEqual_Baseline,79,437 +block_count,StrictEqual_Baseline,76,40 +block_count,StrictEqual_Baseline,77,235 +block_count,StrictEqual_Baseline,78,75 +block_count,StrictEqual_Baseline,79,435 block_count,StrictEqual_Baseline,80,0 -block_count,StrictEqual_Baseline,81,437 -block_count,LessThan_Baseline,0,410 -block_count,LessThan_Baseline,1,410 -block_count,LessThan_Baseline,2,34 +block_count,StrictEqual_Baseline,81,435 +block_count,LessThan_Baseline,0,407 +block_count,LessThan_Baseline,1,407 +block_count,LessThan_Baseline,2,35 block_count,LessThan_Baseline,3,8 block_count,LessThan_Baseline,4,0 block_count,LessThan_Baseline,5,0 @@ -32279,7 +32270,7 @@ block_count,LessThan_Baseline,65,0 block_count,LessThan_Baseline,66,0 block_count,LessThan_Baseline,67,0 -block_count,LessThan_Baseline,68,8 +block_count,LessThan_Baseline,68,7 block_count,LessThan_Baseline,69,0 block_count,LessThan_Baseline,70,0 block_count,LessThan_Baseline,71,0 @@ -32301,7 +32292,7 @@ block_count,LessThan_Baseline,87,0 block_count,LessThan_Baseline,88,0 block_count,LessThan_Baseline,89,26 -block_count,LessThan_Baseline,90,375 +block_count,LessThan_Baseline,90,372 block_count,LessThan_Baseline,91,1 block_count,LessThan_Baseline,92,0 block_count,LessThan_Baseline,93,0 @@ -32313,25 +32304,25 @@ block_count,LessThan_Baseline,99,0 block_count,LessThan_Baseline,100,0 block_count,LessThan_Baseline,101,1 -block_count,LessThan_Baseline,102,374 -block_count,LessThan_Baseline,103,100 -block_count,LessThan_Baseline,104,274 +block_count,LessThan_Baseline,102,370 +block_count,LessThan_Baseline,103,97 +block_count,LessThan_Baseline,104,273 block_count,LessThan_Baseline,105,0 block_count,LessThan_Baseline,106,0 block_count,LessThan_Baseline,107,0 block_count,LessThan_Baseline,108,0 block_count,LessThan_Baseline,109,0 block_count,LessThan_Baseline,110,35 -block_count,LessThan_Baseline,111,27 +block_count,LessThan_Baseline,111,28 block_count,LessThan_Baseline,112,7 -block_count,LessThan_Baseline,113,128 -block_count,LessThan_Baseline,114,281 -block_count,LessThan_Baseline,115,410 +block_count,LessThan_Baseline,113,125 +block_count,LessThan_Baseline,114,280 +block_count,LessThan_Baseline,115,407 block_count,LessThan_Baseline,116,0 -block_count,LessThan_Baseline,117,410 +block_count,LessThan_Baseline,117,407 block_count,GreaterThan_Baseline,0,146 -block_count,GreaterThan_Baseline,1,146 -block_count,GreaterThan_Baseline,2,13 +block_count,GreaterThan_Baseline,1,147 +block_count,GreaterThan_Baseline,2,12 block_count,GreaterThan_Baseline,3,7 block_count,GreaterThan_Baseline,4,0 block_count,GreaterThan_Baseline,5,0 @@ -32419,7 +32410,7 @@ block_count,GreaterThan_Baseline,87,0 block_count,GreaterThan_Baseline,88,0 block_count,GreaterThan_Baseline,89,4 -block_count,GreaterThan_Baseline,90,133 +block_count,GreaterThan_Baseline,90,134 block_count,GreaterThan_Baseline,91,0 block_count,GreaterThan_Baseline,92,0 block_count,GreaterThan_Baseline,93,0 @@ -32431,9 +32422,9 @@ block_count,GreaterThan_Baseline,99,0 block_count,GreaterThan_Baseline,100,0 block_count,GreaterThan_Baseline,101,0 -block_count,GreaterThan_Baseline,102,133 -block_count,GreaterThan_Baseline,103,85 -block_count,GreaterThan_Baseline,104,48 +block_count,GreaterThan_Baseline,102,134 +block_count,GreaterThan_Baseline,103,86 +block_count,GreaterThan_Baseline,104,47 block_count,GreaterThan_Baseline,105,0 block_count,GreaterThan_Baseline,106,0 block_count,GreaterThan_Baseline,107,0 @@ -32442,13 +32433,13 @@ block_count,GreaterThan_Baseline,110,12 block_count,GreaterThan_Baseline,111,6 block_count,GreaterThan_Baseline,112,5 -block_count,GreaterThan_Baseline,113,92 -block_count,GreaterThan_Baseline,114,54 +block_count,GreaterThan_Baseline,113,93 +block_count,GreaterThan_Baseline,114,52 block_count,GreaterThan_Baseline,115,146 block_count,GreaterThan_Baseline,116,0 block_count,GreaterThan_Baseline,117,146 -block_count,LessThanOrEqual_Baseline,0,53 -block_count,LessThanOrEqual_Baseline,1,53 +block_count,LessThanOrEqual_Baseline,0,52 +block_count,LessThanOrEqual_Baseline,1,52 block_count,LessThanOrEqual_Baseline,2,5 block_count,LessThanOrEqual_Baseline,3,2 block_count,LessThanOrEqual_Baseline,4,0 @@ -32549,7 +32540,7 @@ block_count,LessThanOrEqual_Baseline,99,0 block_count,LessThanOrEqual_Baseline,100,0 block_count,LessThanOrEqual_Baseline,101,1 -block_count,LessThanOrEqual_Baseline,102,46 +block_count,LessThanOrEqual_Baseline,102,45 block_count,LessThanOrEqual_Baseline,103,4 block_count,LessThanOrEqual_Baseline,104,41 block_count,LessThanOrEqual_Baseline,105,0 @@ -32562,9 +32553,9 @@ block_count,LessThanOrEqual_Baseline,112,4 block_count,LessThanOrEqual_Baseline,113,7 block_count,LessThanOrEqual_Baseline,114,45 -block_count,LessThanOrEqual_Baseline,115,53 +block_count,LessThanOrEqual_Baseline,115,52 block_count,LessThanOrEqual_Baseline,116,0 -block_count,LessThanOrEqual_Baseline,117,53 +block_count,LessThanOrEqual_Baseline,117,52 block_count,GreaterThanOrEqual_Baseline,0,104 block_count,GreaterThanOrEqual_Baseline,1,104 block_count,GreaterThanOrEqual_Baseline,2,12 @@ -32667,7 +32658,7 @@ block_count,GreaterThanOrEqual_Baseline,99,0 block_count,GreaterThanOrEqual_Baseline,100,0 block_count,GreaterThanOrEqual_Baseline,101,0 -block_count,GreaterThanOrEqual_Baseline,102,91 +block_count,GreaterThanOrEqual_Baseline,102,90 block_count,GreaterThanOrEqual_Baseline,103,54 block_count,GreaterThanOrEqual_Baseline,104,36 block_count,GreaterThanOrEqual_Baseline,105,0 @@ -32718,8 +32709,8 @@ block_count,BitwiseNot_Baseline,32,0 block_count,BitwiseNot_Baseline,33,5 block_count,BitwiseNot_Baseline,34,5 -block_count,Decrement_Baseline,0,49 -block_count,Decrement_Baseline,1,49 +block_count,Decrement_Baseline,0,48 +block_count,Decrement_Baseline,1,48 block_count,Decrement_Baseline,2,0 block_count,Decrement_Baseline,3,0 block_count,Decrement_Baseline,4,0 @@ -32734,18 +32725,18 @@ block_count,Decrement_Baseline,13,0 block_count,Decrement_Baseline,14,0 block_count,Decrement_Baseline,15,0 -block_count,Decrement_Baseline,16,49 -block_count,Decrement_Baseline,17,49 +block_count,Decrement_Baseline,16,48 +block_count,Decrement_Baseline,17,48 block_count,Decrement_Baseline,18,0 block_count,Decrement_Baseline,19,0 block_count,Decrement_Baseline,20,0 block_count,Decrement_Baseline,21,0 block_count,Decrement_Baseline,22,0 -block_count,Decrement_Baseline,23,49 +block_count,Decrement_Baseline,23,48 block_count,Decrement_Baseline,24,0 -block_count,Decrement_Baseline,25,49 -block_count,Increment_Baseline,0,277 -block_count,Increment_Baseline,1,277 +block_count,Decrement_Baseline,25,48 +block_count,Increment_Baseline,0,275 +block_count,Increment_Baseline,1,275 block_count,Increment_Baseline,2,0 block_count,Increment_Baseline,3,0 block_count,Increment_Baseline,4,0 @@ -32760,16 +32751,16 @@ block_count,Increment_Baseline,13,0 block_count,Increment_Baseline,14,0 block_count,Increment_Baseline,15,0 -block_count,Increment_Baseline,16,277 -block_count,Increment_Baseline,17,277 +block_count,Increment_Baseline,16,275 +block_count,Increment_Baseline,17,275 block_count,Increment_Baseline,18,0 block_count,Increment_Baseline,19,0 block_count,Increment_Baseline,20,0 block_count,Increment_Baseline,21,0 block_count,Increment_Baseline,22,0 -block_count,Increment_Baseline,23,277 +block_count,Increment_Baseline,23,275 block_count,Increment_Baseline,24,0 -block_count,Increment_Baseline,25,277 +block_count,Increment_Baseline,25,275 block_count,Negate_Baseline,0,11 block_count,Negate_Baseline,1,11 block_count,Negate_Baseline,2,10 @@ -33114,7 +33105,7 @@ block_count,ObjectCreate,62,2 block_count,ObjectCreate,63,0 block_count,ObjectCreate,64,2 -block_count,ObjectCreate,65,12 +block_count,ObjectCreate,65,13 block_count,ObjectCreate,66,10 block_count,ObjectCreate,67,2 block_count,ObjectCreate,68,2 @@ -34008,8 +33999,8 @@ block_count,InstanceOf,34,0 block_count,InstanceOf,35,0 block_count,InstanceOf,36,10 -block_count,InstanceOf_Baseline,0,72 -block_count,InstanceOf_Baseline,1,72 +block_count,InstanceOf_Baseline,0,71 +block_count,InstanceOf_Baseline,1,71 block_count,InstanceOf_Baseline,2,2 block_count,InstanceOf_Baseline,3,0 block_count,InstanceOf_Baseline,4,0 @@ -34028,14 +34019,14 @@ block_count,InstanceOf_Baseline,17,0 block_count,InstanceOf_Baseline,18,0 block_count,InstanceOf_Baseline,19,2 -block_count,InstanceOf_Baseline,20,70 +block_count,InstanceOf_Baseline,20,69 block_count,InstanceOf_Baseline,21,0 -block_count,InstanceOf_Baseline,22,72 -block_count,InstanceOf_Baseline,23,72 +block_count,InstanceOf_Baseline,22,71 +block_count,InstanceOf_Baseline,23,71 block_count,InstanceOf_Baseline,24,0 -block_count,InstanceOf_Baseline,25,72 +block_count,InstanceOf_Baseline,25,71 block_count,InstanceOf_Baseline,26,0 -block_count,InstanceOf_Baseline,27,72 +block_count,InstanceOf_Baseline,27,71 block_count,InstanceOf_Baseline,28,0 block_count,InstanceOf_Baseline,29,0 block_count,InstanceOf_Baseline,30,0 @@ -34066,7 +34057,7 @@ block_count,InstanceOf_Baseline,55,0 block_count,InstanceOf_Baseline,56,0 block_count,InstanceOf_Baseline,57,0 -block_count,InstanceOf_Baseline,58,72 +block_count,InstanceOf_Baseline,58,71 block_count,InstanceOf_Baseline,59,0 block_count,InstanceOf_Baseline,60,0 block_count,ForInEnumerate,0,52 @@ -35656,18 +35647,18 @@ block_count,StringFromCharCode,71,0 block_count,StringFromCharCode,72,0 block_count,StringFromCharCode,73,0 -block_count,StringFromCharCode,74,18 -block_count,StringFromCharCode,75,15 -block_count,StringFromCharCode,76,2 -block_count,StringFromCharCode,77,2 +block_count,StringFromCharCode,74,17 +block_count,StringFromCharCode,75,14 +block_count,StringFromCharCode,76,3 +block_count,StringFromCharCode,77,3 block_count,StringFromCharCode,78,1 block_count,StringFromCharCode,79,1 block_count,StringFromCharCode,80,0 block_count,StringFromCharCode,81,1 block_count,StringFromCharCode,82,0 block_count,StringFromCharCode,83,1 -block_count,StringFromCharCode,84,0 -block_count,StringFromCharCode,85,18 +block_count,StringFromCharCode,84,1 +block_count,StringFromCharCode,85,17 block_count,StringFromCharCode,86,0 block_count,StringFromCharCode,87,0 block_count,StringFromCharCode,88,0 @@ -35995,16 +35986,16 @@ block_count,TypedArrayPrototypeByteLength,10,0 block_count,TypedArrayPrototypeByteLength,11,0 block_count,TypedArrayPrototypeByteLength,12,0 -block_count,TypedArrayPrototypeLength,0,12 +block_count,TypedArrayPrototypeLength,0,13 block_count,TypedArrayPrototypeLength,1,0 -block_count,TypedArrayPrototypeLength,2,12 -block_count,TypedArrayPrototypeLength,3,12 -block_count,TypedArrayPrototypeLength,4,12 +block_count,TypedArrayPrototypeLength,2,13 +block_count,TypedArrayPrototypeLength,3,13 +block_count,TypedArrayPrototypeLength,4,13 block_count,TypedArrayPrototypeLength,5,0 -block_count,TypedArrayPrototypeLength,6,12 -block_count,TypedArrayPrototypeLength,7,12 -block_count,TypedArrayPrototypeLength,8,12 -block_count,TypedArrayPrototypeLength,9,12 +block_count,TypedArrayPrototypeLength,6,13 +block_count,TypedArrayPrototypeLength,7,13 +block_count,TypedArrayPrototypeLength,8,13 +block_count,TypedArrayPrototypeLength,9,13 block_count,TypedArrayPrototypeLength,10,0 block_count,TypedArrayPrototypeLength,11,0 block_count,TypedArrayPrototypeLength,12,0 @@ -36040,8 +36031,8 @@ block_count,TypedArrayPrototypeLength,42,0 block_count,TypedArrayPrototypeLength,43,0 block_count,TypedArrayPrototypeLength,44,0 -block_count,TypedArrayPrototypeLength,45,12 -block_count,TypedArrayPrototypeLength,46,12 +block_count,TypedArrayPrototypeLength,45,13 +block_count,TypedArrayPrototypeLength,46,13 block_count,TypedArrayPrototypeToStringTag,0,0 block_count,TypedArrayPrototypeToStringTag,1,0 block_count,TypedArrayPrototypeToStringTag,2,0 @@ -36829,9 +36820,9 @@ block_count,WeakMapLookupHashIndex,27,64 block_count,WeakMapLookupHashIndex,28,1 block_count,WeakMapLookupHashIndex,29,64 -block_count,WeakMapLookupHashIndex,30,97 -block_count,WeakMapLookupHashIndex,31,97 -block_count,WeakMapLookupHashIndex,32,33 +block_count,WeakMapLookupHashIndex,30,95 +block_count,WeakMapLookupHashIndex,31,95 +block_count,WeakMapLookupHashIndex,32,30 block_count,WeakMapLookupHashIndex,33,64 block_count,WeakMapLookupHashIndex,34,0 block_count,WeakMapGet,0,33 @@ -37371,7 +37362,7 @@ block_count,StringAdd_CheckNone,2,9575 block_count,StringAdd_CheckNone,3,9575 block_count,StringAdd_CheckNone,4,7382 -block_count,StringAdd_CheckNone,5,7379 +block_count,StringAdd_CheckNone,5,7378 block_count,StringAdd_CheckNone,6,3 block_count,StringAdd_CheckNone,7,7382 block_count,StringAdd_CheckNone,8,7382 @@ -37711,17 +37702,17 @@ block_count,SubString,222,98 block_count,SubString,223,214 block_count,SubString,224,214 -block_count,GetProperty,0,673 -block_count,GetProperty,1,673 +block_count,GetProperty,0,672 +block_count,GetProperty,1,672 block_count,GetProperty,2,0 -block_count,GetProperty,3,672 -block_count,GetProperty,4,668 -block_count,GetProperty,5,668 -block_count,GetProperty,6,668 +block_count,GetProperty,3,671 +block_count,GetProperty,4,667 +block_count,GetProperty,5,667 +block_count,GetProperty,6,667 block_count,GetProperty,7,0 block_count,GetProperty,8,0 block_count,GetProperty,9,0 -block_count,GetProperty,10,668 +block_count,GetProperty,10,667 block_count,GetProperty,11,546 block_count,GetProperty,12,0 block_count,GetProperty,13,0 @@ -37740,12 +37731,12 @@ block_count,GetProperty,26,0 block_count,GetProperty,27,0 block_count,GetProperty,28,0 -block_count,GetProperty,29,121 -block_count,GetProperty,30,668 -block_count,GetProperty,31,1657 -block_count,GetProperty,32,1657 -block_count,GetProperty,33,1656 -block_count,GetProperty,34,1637 +block_count,GetProperty,29,120 +block_count,GetProperty,30,667 +block_count,GetProperty,31,1655 +block_count,GetProperty,32,1655 +block_count,GetProperty,33,1655 +block_count,GetProperty,34,1635 block_count,GetProperty,35,273 block_count,GetProperty,36,273 block_count,GetProperty,37,0 @@ -37771,29 +37762,29 @@ block_count,GetProperty,57,219 block_count,GetProperty,58,53 block_count,GetProperty,59,0 -block_count,GetProperty,60,1364 +block_count,GetProperty,60,1362 block_count,GetProperty,61,0 -block_count,GetProperty,62,1364 +block_count,GetProperty,62,1362 block_count,GetProperty,63,284 -block_count,GetProperty,64,1079 -block_count,GetProperty,65,2707 -block_count,GetProperty,66,2382 -block_count,GetProperty,67,2276 -block_count,GetProperty,68,1628 -block_count,GetProperty,69,647 +block_count,GetProperty,64,1077 +block_count,GetProperty,65,2704 +block_count,GetProperty,66,2380 +block_count,GetProperty,67,2273 +block_count,GetProperty,68,1626 +block_count,GetProperty,69,646 block_count,GetProperty,70,106 -block_count,GetProperty,71,325 -block_count,GetProperty,72,932 +block_count,GetProperty,71,324 +block_count,GetProperty,72,931 block_count,GetProperty,73,415 -block_count,GetProperty,74,516 +block_count,GetProperty,74,515 block_count,GetProperty,75,507 block_count,GetProperty,76,8 -block_count,GetProperty,77,660 +block_count,GetProperty,77,659 block_count,GetProperty,78,1 -block_count,GetProperty,79,658 -block_count,GetProperty,80,646 +block_count,GetProperty,79,657 +block_count,GetProperty,80,645 block_count,GetProperty,81,0 -block_count,GetProperty,82,646 +block_count,GetProperty,82,645 block_count,GetProperty,83,11 block_count,GetProperty,84,0 block_count,GetProperty,85,11 @@ -37801,7 +37792,7 @@ block_count,GetProperty,87,0 block_count,GetProperty,88,0 block_count,GetProperty,89,0 -block_count,GetProperty,90,660 +block_count,GetProperty,90,659 block_count,GetProperty,91,19 block_count,GetProperty,92,0 block_count,GetProperty,93,0 @@ -37844,8 +37835,8 @@ block_count,GetProperty,130,0 block_count,GetProperty,131,0 block_count,GetProperty,132,0 -block_count,GetProperty,133,997 -block_count,GetProperty,134,996 +block_count,GetProperty,133,996 +block_count,GetProperty,134,995 block_count,GetProperty,135,1 block_count,GetProperty,136,0 block_count,GetProperty,137,0 @@ -37883,10 +37874,10 @@ block_count,GetProperty,169,0 block_count,GetProperty,170,0 block_count,GetProperty,171,0 -block_count,GetProperty,172,997 +block_count,GetProperty,172,996 block_count,GetProperty,173,988 block_count,GetProperty,174,8 -block_count,GetProperty,175,660 +block_count,GetProperty,175,659 block_count,GetProperty,176,1 block_count,GetProperty,177,1 block_count,GetProperty,178,0 @@ -37926,7 +37917,7 @@ block_count,GetProperty,212,0 block_count,GetProperty,213,0 block_count,GetProperty,214,0 -block_count,GetProperty,215,658 +block_count,GetProperty,215,657 block_count,GetProperty,216,0 block_count,GetProperty,217,4 block_count,GetProperty,218,0 @@ -43385,7 +43376,7 @@ block_count,ArrayMap,72,1 block_count,ArrayMap,73,6 block_count,ArrayMap,74,1 -block_count,ArrayMap,75,5 +block_count,ArrayMap,75,4 block_count,ArrayMap,76,6 block_count,ArrayMap,77,0 block_count,ArrayMap,78,8 @@ -45791,32 +45782,32 @@ block_count,StringPrototypeCharAt,45,0 block_count,StringPrototypeCharAt,46,106 block_count,StringPrototypeCharAt,47,2 -block_count,StringPrototypeCharCodeAt,0,103 +block_count,StringPrototypeCharCodeAt,0,102 block_count,StringPrototypeCharCodeAt,1,0 -block_count,StringPrototypeCharCodeAt,2,103 -block_count,StringPrototypeCharCodeAt,3,103 -block_count,StringPrototypeCharCodeAt,4,103 +block_count,StringPrototypeCharCodeAt,2,102 +block_count,StringPrototypeCharCodeAt,3,102 +block_count,StringPrototypeCharCodeAt,4,102 block_count,StringPrototypeCharCodeAt,5,0 block_count,StringPrototypeCharCodeAt,6,0 block_count,StringPrototypeCharCodeAt,7,0 -block_count,StringPrototypeCharCodeAt,8,103 +block_count,StringPrototypeCharCodeAt,8,102 block_count,StringPrototypeCharCodeAt,9,0 -block_count,StringPrototypeCharCodeAt,10,103 -block_count,StringPrototypeCharCodeAt,11,103 +block_count,StringPrototypeCharCodeAt,10,102 +block_count,StringPrototypeCharCodeAt,11,102 block_count,StringPrototypeCharCodeAt,12,0 -block_count,StringPrototypeCharCodeAt,13,103 -block_count,StringPrototypeCharCodeAt,14,103 -block_count,StringPrototypeCharCodeAt,15,103 -block_count,StringPrototypeCharCodeAt,16,64 -block_count,StringPrototypeCharCodeAt,17,128 +block_count,StringPrototypeCharCodeAt,13,102 +block_count,StringPrototypeCharCodeAt,14,102 +block_count,StringPrototypeCharCodeAt,15,102 +block_count,StringPrototypeCharCodeAt,16,63 +block_count,StringPrototypeCharCodeAt,17,127 block_count,StringPrototypeCharCodeAt,18,62 block_count,StringPrototypeCharCodeAt,19,62 block_count,StringPrototypeCharCodeAt,20,0 block_count,StringPrototypeCharCodeAt,21,0 block_count,StringPrototypeCharCodeAt,22,0 -block_count,StringPrototypeCharCodeAt,23,64 +block_count,StringPrototypeCharCodeAt,23,63 block_count,StringPrototypeCharCodeAt,24,0 -block_count,StringPrototypeCharCodeAt,25,64 +block_count,StringPrototypeCharCodeAt,25,63 block_count,StringPrototypeCharCodeAt,26,0 block_count,StringPrototypeCharCodeAt,27,0 block_count,StringPrototypeCharCodeAt,28,0 @@ -45828,10 +45819,10 @@ block_count,StringPrototypeCharCodeAt,34,0 block_count,StringPrototypeCharCodeAt,35,0 block_count,StringPrototypeCharCodeAt,36,38 -block_count,StringPrototypeCharCodeAt,37,103 -block_count,StringPrototypeCharCodeAt,38,103 -block_count,StringPrototypeCharCodeAt,39,15 -block_count,StringPrototypeCharCodeAt,40,87 +block_count,StringPrototypeCharCodeAt,37,102 +block_count,StringPrototypeCharCodeAt,38,102 +block_count,StringPrototypeCharCodeAt,39,16 +block_count,StringPrototypeCharCodeAt,40,86 block_count,StringPrototypeCharCodeAt,41,0 block_count,StringPrototypeCodePointAt,0,0 block_count,StringPrototypeCodePointAt,1,0 @@ -46414,35 +46405,35 @@ block_count,StringCharAt,29,0 block_count,StringCharAt,30,0 block_count,StringCharAt,31,8 -block_count,FastNewClosureBaseline,0,77 -block_count,FastNewFunctionContextFunction,0,81 -block_count,FastNewFunctionContextFunction,1,81 +block_count,FastNewClosureBaseline,0,76 +block_count,FastNewFunctionContextFunction,0,80 +block_count,FastNewFunctionContextFunction,1,80 block_count,FastNewFunctionContextFunction,2,0 -block_count,FastNewFunctionContextFunction,3,81 +block_count,FastNewFunctionContextFunction,3,80 block_count,FastNewFunctionContextFunction,4,0 block_count,FastNewFunctionContextFunction,5,0 -block_count,FastNewFunctionContextFunction,6,81 +block_count,FastNewFunctionContextFunction,6,80 block_count,FastNewFunctionContextFunction,7,0 -block_count,FastNewFunctionContextFunction,8,81 +block_count,FastNewFunctionContextFunction,8,80 block_count,FastNewFunctionContextFunction,9,0 -block_count,FastNewFunctionContextFunction,10,81 +block_count,FastNewFunctionContextFunction,10,80 block_count,FastNewFunctionContextFunction,11,22 -block_count,FastNewFunctionContextFunction,12,59 -block_count,FastNewFunctionContextFunction,13,793 +block_count,FastNewFunctionContextFunction,12,58 +block_count,FastNewFunctionContextFunction,13,792 block_count,FastNewFunctionContextFunction,14,733 -block_count,FastNewFunctionContextFunction,15,59 -block_count,FastNewFunctionContextFunction,16,81 +block_count,FastNewFunctionContextFunction,15,58 +block_count,FastNewFunctionContextFunction,16,80 block_count,FastNewFunctionContextFunction,17,50 -block_count,FastNewFunctionContextFunction,18,31 -block_count,CreateRegExpLiteral,0,34 -block_count,CreateRegExpLiteral,1,34 +block_count,FastNewFunctionContextFunction,18,30 +block_count,CreateRegExpLiteral,0,33 +block_count,CreateRegExpLiteral,1,33 block_count,CreateRegExpLiteral,2,0 -block_count,CreateRegExpLiteral,3,34 +block_count,CreateRegExpLiteral,3,33 block_count,CreateRegExpLiteral,4,0 -block_count,CreateRegExpLiteral,5,34 -block_count,CreateRegExpLiteral,6,34 +block_count,CreateRegExpLiteral,5,33 +block_count,CreateRegExpLiteral,6,33 block_count,CreateRegExpLiteral,7,0 -block_count,CreateRegExpLiteral,8,34 +block_count,CreateRegExpLiteral,8,33 block_count,CreateRegExpLiteral,9,0 block_count,CreateRegExpLiteral,10,0 block_count,CreateShallowArrayLiteral,0,18 @@ -46666,8 +46657,8 @@ block_count,CreateShallowObjectLiteral,126,0 block_count,CreateShallowObjectLiteral,127,27 block_count,CreateShallowObjectLiteral,128,27 -block_count,CreateShallowObjectLiteral,129,80 -block_count,CreateShallowObjectLiteral,130,73 +block_count,CreateShallowObjectLiteral,129,79 +block_count,CreateShallowObjectLiteral,130,72 block_count,CreateShallowObjectLiteral,131,0 block_count,CreateShallowObjectLiteral,132,0 block_count,CreateShallowObjectLiteral,133,0 @@ -46694,11 +46685,11 @@ block_count,CreateShallowObjectLiteral,154,0 block_count,CreateShallowObjectLiteral,155,0 block_count,CreateShallowObjectLiteral,156,0 -block_count,CreateShallowObjectLiteral,157,72 +block_count,CreateShallowObjectLiteral,157,71 block_count,CreateShallowObjectLiteral,158,7 -block_count,CreateShallowObjectLiteral,159,80 -block_count,CreateShallowObjectLiteral,160,53 -block_count,CreateShallowObjectLiteral,161,27 +block_count,CreateShallowObjectLiteral,159,79 +block_count,CreateShallowObjectLiteral,160,52 +block_count,CreateShallowObjectLiteral,161,26 block_count,CreateShallowObjectLiteral,162,0 block_count,CreateShallowObjectLiteral,163,0 block_count,CreateShallowObjectLiteral,164,0 @@ -46907,7 +46898,7 @@ block_count,NumberToString,65,0 block_count,NumberToString,66,0 block_count,NumberToString,67,0 -block_count,NumberToString,68,1316 +block_count,NumberToString,68,1317 block_count,NumberToString,69,13 block_count,ToBoolean,0,25 block_count,ToBoolean,1,24 @@ -46930,27 +46921,27 @@ block_count,ToBoolean,18,0 block_count,ToBoolean,19,0 block_count,ToBoolean,20,0 -block_count,ToBooleanForBaselineJump,0,974 -block_count,ToBooleanForBaselineJump,1,900 -block_count,ToBooleanForBaselineJump,2,544 -block_count,ToBooleanForBaselineJump,3,342 -block_count,ToBooleanForBaselineJump,4,342 -block_count,ToBooleanForBaselineJump,5,166 -block_count,ToBooleanForBaselineJump,6,165 -block_count,ToBooleanForBaselineJump,7,165 +block_count,ToBooleanForBaselineJump,0,953 +block_count,ToBooleanForBaselineJump,1,880 +block_count,ToBooleanForBaselineJump,2,532 +block_count,ToBooleanForBaselineJump,3,334 +block_count,ToBooleanForBaselineJump,4,333 +block_count,ToBooleanForBaselineJump,5,161 +block_count,ToBooleanForBaselineJump,6,160 +block_count,ToBooleanForBaselineJump,7,160 block_count,ToBooleanForBaselineJump,8,0 block_count,ToBooleanForBaselineJump,9,0 block_count,ToBooleanForBaselineJump,10,0 block_count,ToBooleanForBaselineJump,11,1 block_count,ToBooleanForBaselineJump,12,0 -block_count,ToBooleanForBaselineJump,13,1 -block_count,ToBooleanForBaselineJump,14,175 +block_count,ToBooleanForBaselineJump,13,0 +block_count,ToBooleanForBaselineJump,14,172 block_count,ToBooleanForBaselineJump,15,0 -block_count,ToBooleanForBaselineJump,16,202 -block_count,ToBooleanForBaselineJump,17,355 -block_count,ToBooleanForBaselineJump,18,74 +block_count,ToBooleanForBaselineJump,16,198 +block_count,ToBooleanForBaselineJump,17,348 +block_count,ToBooleanForBaselineJump,18,73 block_count,ToBooleanForBaselineJump,19,44 -block_count,ToBooleanForBaselineJump,20,29 +block_count,ToBooleanForBaselineJump,20,28 block_count,ToLength,0,2 block_count,ToLength,1,2 block_count,ToLength,2,0 @@ -47704,10 +47695,10 @@ block_count,DataViewPrototypeSetFloat64,114,0 block_count,DataViewPrototypeSetFloat64,115,0 block_count,DataViewPrototypeSetFloat64,116,0 -block_count,FunctionPrototypeHasInstance,0,84 +block_count,FunctionPrototypeHasInstance,0,83 block_count,FunctionPrototypeHasInstance,1,0 -block_count,FunctionPrototypeHasInstance,2,84 -block_count,FunctionPrototypeHasInstance,3,84 +block_count,FunctionPrototypeHasInstance,2,83 +block_count,FunctionPrototypeHasInstance,3,83 block_count,FunctionPrototypeHasInstance,4,83 block_count,FunctionPrototypeHasInstance,5,83 block_count,FunctionPrototypeHasInstance,6,0 @@ -47721,21 +47712,21 @@ block_count,FunctionPrototypeHasInstance,14,4 block_count,FunctionPrototypeHasInstance,15,4 block_count,FunctionPrototypeHasInstance,16,0 -block_count,FunctionPrototypeHasInstance,17,79 +block_count,FunctionPrototypeHasInstance,17,78 block_count,FunctionPrototypeHasInstance,18,83 -block_count,FunctionPrototypeHasInstance,19,282 -block_count,FunctionPrototypeHasInstance,20,275 +block_count,FunctionPrototypeHasInstance,19,280 +block_count,FunctionPrototypeHasInstance,20,274 block_count,FunctionPrototypeHasInstance,21,6 block_count,FunctionPrototypeHasInstance,22,6 block_count,FunctionPrototypeHasInstance,23,6 block_count,FunctionPrototypeHasInstance,24,0 block_count,FunctionPrototypeHasInstance,25,0 block_count,FunctionPrototypeHasInstance,26,0 -block_count,FunctionPrototypeHasInstance,27,282 -block_count,FunctionPrototypeHasInstance,28,230 -block_count,FunctionPrototypeHasInstance,29,198 +block_count,FunctionPrototypeHasInstance,27,280 +block_count,FunctionPrototypeHasInstance,28,229 +block_count,FunctionPrototypeHasInstance,29,197 block_count,FunctionPrototypeHasInstance,30,31 -block_count,FunctionPrototypeHasInstance,31,52 +block_count,FunctionPrototypeHasInstance,31,51 block_count,FunctionPrototypeHasInstance,32,83 block_count,FunctionPrototypeHasInstance,33,0 block_count,FunctionPrototypeHasInstance,34,0 @@ -48094,16 +48085,16 @@ block_count,MathMin,2,1 block_count,MathMin,3,1 block_count,MathMin,4,4 -block_count,MathMin,5,3 -block_count,MathMin,6,3 +block_count,MathMin,5,2 +block_count,MathMin,6,2 block_count,MathMin,7,0 -block_count,MathMin,8,3 -block_count,MathMin,9,3 +block_count,MathMin,8,2 +block_count,MathMin,9,2 block_count,MathMin,10,0 block_count,MathMin,11,0 block_count,MathMin,12,0 block_count,MathMin,13,2 -block_count,MathMin,14,3 +block_count,MathMin,14,2 block_count,MathMin,15,1 block_count,MathMin,16,0 block_count,MathMin,17,1 @@ -49220,8 +49211,8 @@ block_count,Equal,84,1 block_count,Equal,85,2 block_count,Equal,86,40 -block_count,StrictEqual,0,1327 -block_count,StrictEqual,1,1179 +block_count,StrictEqual,0,1328 +block_count,StrictEqual,1,1180 block_count,StrictEqual,2,1151 block_count,StrictEqual,3,1109 block_count,StrictEqual,4,1085 @@ -49233,7 +49224,7 @@ block_count,StrictEqual,10,921 block_count,StrictEqual,11,44 block_count,StrictEqual,12,877 -block_count,StrictEqual,13,505 +block_count,StrictEqual,13,506 block_count,StrictEqual,14,371 block_count,StrictEqual,15,24 block_count,StrictEqual,16,42 @@ -49245,7 +49236,7 @@ block_count,StrictEqual,22,0 block_count,StrictEqual,23,0 block_count,StrictEqual,24,0 -block_count,StrictEqual,25,27 +block_count,StrictEqual,25,28 block_count,StrictEqual,26,0 block_count,StrictEqual,27,0 block_count,StrictEqual,28,0 @@ -51245,7 +51236,7 @@ block_count,RegExpMatchFast,280,0 block_count,RegExpMatchFast,281,0 block_count,RegExpMatchFast,282,0 -block_count,RegExpMatchFast,283,137 +block_count,RegExpMatchFast,283,136 block_count,RegExpMatchFast,284,1088 block_count,RegExpMatchFast,285,1088 block_count,RegExpMatchFast,286,110 @@ -51621,7 +51612,7 @@ block_count,RegExpReplace,123,0 block_count,RegExpReplace,124,0 block_count,RegExpReplace,125,0 -block_count,RegExpReplace,126,371 +block_count,RegExpReplace,126,370 block_count,RegExpReplace,127,413 block_count,RegExpReplace,128,413 block_count,RegExpReplace,129,3 @@ -52492,8 +52483,8 @@ block_count,RegExpPrototypeTest,134,75 block_count,RegExpPrototypeTest,135,0 block_count,RegExpPrototypeTest,136,75 -block_count,RegExpPrototypeTest,137,9 -block_count,RegExpPrototypeTest,138,9 +block_count,RegExpPrototypeTest,137,8 +block_count,RegExpPrototypeTest,138,8 block_count,RegExpPrototypeTestFast,0,394 block_count,RegExpPrototypeTestFast,1,394 block_count,RegExpPrototypeTestFast,2,0 @@ -53613,7 +53604,7 @@ block_count,StringPrototypeSlice,79,0 block_count,StringPrototypeSlice,80,1 block_count,StringPrototypeSlice,81,6 -block_count,StringPrototypeSlice,82,3 +block_count,StringPrototypeSlice,82,2 block_count,StringPrototypeSlice,83,0 block_count,StringPrototypeSlice,84,0 block_count,StringPrototypeSlice,85,0 @@ -53787,7 +53778,7 @@ block_count,StringPrototypeSlice,253,0 block_count,StringPrototypeSlice,254,2 block_count,StringPrototypeSlice,255,1 -block_count,StringPrototypeSlice,256,2 +block_count,StringPrototypeSlice,256,3 block_count,StringPrototypeSlice,257,1 block_count,StringPrototypeSlice,258,1 block_count,StringPrototypeSlice,259,0 @@ -54382,27 +54373,27 @@ block_count,StringPrototypeSubstr,286,0 block_count,StringPrototypeSubstr,287,0 block_count,StringPrototypeSubstr,288,0 -block_count,StringPrototypeSubstring,0,2 +block_count,StringPrototypeSubstring,0,1 block_count,StringPrototypeSubstring,1,0 -block_count,StringPrototypeSubstring,2,2 -block_count,StringPrototypeSubstring,3,2 -block_count,StringPrototypeSubstring,4,2 +block_count,StringPrototypeSubstring,2,1 +block_count,StringPrototypeSubstring,3,1 +block_count,StringPrototypeSubstring,4,1 block_count,StringPrototypeSubstring,5,0 block_count,StringPrototypeSubstring,6,0 block_count,StringPrototypeSubstring,7,0 -block_count,StringPrototypeSubstring,8,2 +block_count,StringPrototypeSubstring,8,1 block_count,StringPrototypeSubstring,9,0 -block_count,StringPrototypeSubstring,10,2 -block_count,StringPrototypeSubstring,11,2 +block_count,StringPrototypeSubstring,10,1 +block_count,StringPrototypeSubstring,11,1 block_count,StringPrototypeSubstring,12,0 -block_count,StringPrototypeSubstring,13,2 +block_count,StringPrototypeSubstring,13,1 block_count,StringPrototypeSubstring,14,0 -block_count,StringPrototypeSubstring,15,2 -block_count,StringPrototypeSubstring,16,2 +block_count,StringPrototypeSubstring,15,1 +block_count,StringPrototypeSubstring,16,1 block_count,StringPrototypeSubstring,17,0 -block_count,StringPrototypeSubstring,18,2 -block_count,StringPrototypeSubstring,19,2 -block_count,StringPrototypeSubstring,20,2 +block_count,StringPrototypeSubstring,18,1 +block_count,StringPrototypeSubstring,19,1 +block_count,StringPrototypeSubstring,20,1 block_count,StringPrototypeSubstring,21,1 block_count,StringPrototypeSubstring,22,0 block_count,StringPrototypeSubstring,23,0 @@ -54411,11 +54402,11 @@ block_count,StringPrototypeSubstring,26,0 block_count,StringPrototypeSubstring,27,0 block_count,StringPrototypeSubstring,28,0 -block_count,StringPrototypeSubstring,29,2 -block_count,StringPrototypeSubstring,30,2 +block_count,StringPrototypeSubstring,29,1 +block_count,StringPrototypeSubstring,30,1 block_count,StringPrototypeSubstring,31,1 block_count,StringPrototypeSubstring,32,0 -block_count,StringPrototypeSubstring,33,2 +block_count,StringPrototypeSubstring,33,1 block_count,StringPrototypeSubstring,34,0 block_count,StringPrototypeSubstring,35,1 block_count,StringPrototypeSubstring,36,1 @@ -54432,11 +54423,11 @@ block_count,StringPrototypeSubstring,47,0 block_count,StringPrototypeSubstring,48,0 block_count,StringPrototypeSubstring,49,1 -block_count,StringPrototypeSubstring,50,2 -block_count,StringPrototypeSubstring,51,2 +block_count,StringPrototypeSubstring,50,1 +block_count,StringPrototypeSubstring,51,1 block_count,StringPrototypeSubstring,52,0 -block_count,StringPrototypeSubstring,53,2 -block_count,StringPrototypeSubstring,54,2 +block_count,StringPrototypeSubstring,53,1 +block_count,StringPrototypeSubstring,54,1 block_count,StringPrototypeSubstring,55,1 block_count,StringPrototypeSubstring,56,1 block_count,StringPrototypeSubstring,57,0 @@ -57110,7 +57101,7 @@ block_count,FastNewRestArguments,17,0 block_count,FastNewRestArguments,18,0 block_count,FastNewRestArguments,19,1 -block_count,FastNewRestArguments,20,4 +block_count,FastNewRestArguments,20,3 block_count,FastNewRestArguments,21,2 block_count,FastNewRestArguments,22,2 block_count,FastNewRestArguments,23,2 @@ -57361,7 +57352,7 @@ block_count,StringIndexOf,9,455 block_count,StringIndexOf,10,480 block_count,StringIndexOf,11,42 -block_count,StringIndexOf,12,25 +block_count,StringIndexOf,12,24 block_count,StringIndexOf,13,20 block_count,StringIndexOf,14,4 block_count,StringIndexOf,15,3 @@ -57398,7 +57389,7 @@ block_count,StringIndexOf,46,0 block_count,StringIndexOf,47,0 block_count,StringIndexOf,48,4 -block_count,StringIndexOf,49,25 +block_count,StringIndexOf,49,24 block_count,StringIndexOf,50,17 block_count,StringIndexOf,51,17 block_count,StringIndexOf,52,17 @@ -59284,17 +59275,17 @@ block_count,StringToLowerCaseIntl,41,0 block_count,WideHandler,0,64 block_count,ExtraWideHandler,0,16 -block_count,LdarHandler,0,211 +block_count,LdarHandler,0,212 block_count,LdaZeroHandler,0,23 block_count,LdaZeroHandler,1,17 -block_count,LdaZeroHandler,2,5 -block_count,LdaSmiHandler,0,23 -block_count,LdaSmiHandler,1,14 +block_count,LdaZeroHandler,2,6 +block_count,LdaSmiHandler,0,24 +block_count,LdaSmiHandler,1,15 block_count,LdaSmiHandler,2,8 -block_count,LdaUndefinedHandler,0,12 +block_count,LdaUndefinedHandler,0,13 block_count,LdaUndefinedHandler,1,12 block_count,LdaUndefinedHandler,2,0 -block_count,LdaNullHandler,0,1 +block_count,LdaNullHandler,0,2 block_count,LdaNullHandler,1,1 block_count,LdaNullHandler,2,0 block_count,LdaTheHoleHandler,0,0 @@ -59304,11 +59295,11 @@ block_count,LdaFalseHandler,0,5 block_count,LdaConstantHandler,0,20 block_count,LdaConstantHandler,1,11 -block_count,LdaConstantHandler,2,8 +block_count,LdaConstantHandler,2,9 block_count,LdaContextSlotHandler,0,1 block_count,LdaContextSlotHandler,1,1 -block_count,LdaContextSlotHandler,2,2 -block_count,LdaContextSlotHandler,3,2 +block_count,LdaContextSlotHandler,2,1 +block_count,LdaContextSlotHandler,3,1 block_count,LdaContextSlotHandler,4,0 block_count,LdaContextSlotHandler,5,1 block_count,LdaContextSlotHandler,6,0 @@ -59342,20 +59333,20 @@ block_count,LdaImmutableCurrentContextSlotHandler,3,5 block_count,LdaImmutableCurrentContextSlotHandler,4,25 block_count,StarHandler,0,30 -block_count,MovHandler,0,37 +block_count,MovHandler,0,39 block_count,PushContextHandler,0,2 block_count,PopContextHandler,0,0 block_count,TestReferenceEqualHandler,0,1 block_count,TestReferenceEqualHandler,1,1 block_count,TestReferenceEqualHandler,2,0 block_count,TestReferenceEqualHandler,3,1 -block_count,TestUndetectableHandler,0,1 -block_count,TestUndetectableHandler,1,1 +block_count,TestUndetectableHandler,0,2 +block_count,TestUndetectableHandler,1,2 block_count,TestUndetectableHandler,2,1 block_count,TestUndetectableHandler,3,0 -block_count,TestUndetectableHandler,4,1 +block_count,TestUndetectableHandler,4,2 block_count,TestUndetectableHandler,5,0 -block_count,TestUndetectableHandler,6,1 +block_count,TestUndetectableHandler,6,2 block_count,TestNullHandler,0,0 block_count,TestNullHandler,1,0 block_count,TestNullHandler,2,0 @@ -59412,16 +59403,16 @@ block_count,TestTypeOfHandler,45,0 block_count,TestTypeOfHandler,46,0 block_count,TestTypeOfHandler,47,0 -block_count,TestTypeOfHandler,48,1 +block_count,TestTypeOfHandler,48,0 block_count,TestTypeOfHandler,49,0 block_count,TestTypeOfHandler,50,1 -block_count,LdaGlobalHandler,0,48 -block_count,LdaGlobalHandler,1,39 -block_count,LdaGlobalHandler,2,38 -block_count,LdaGlobalHandler,3,38 -block_count,LdaGlobalHandler,4,38 +block_count,LdaGlobalHandler,0,50 +block_count,LdaGlobalHandler,1,41 +block_count,LdaGlobalHandler,2,40 +block_count,LdaGlobalHandler,3,40 +block_count,LdaGlobalHandler,4,40 block_count,LdaGlobalHandler,5,12 -block_count,LdaGlobalHandler,6,26 +block_count,LdaGlobalHandler,6,28 block_count,LdaGlobalHandler,7,0 block_count,LdaGlobalHandler,8,0 block_count,LdaGlobalHandler,9,0 @@ -60642,31 +60633,31 @@ block_count,StaLookupSlotHandler,3,0 block_count,StaLookupSlotHandler,4,0 block_count,StaLookupSlotHandler,5,0 -block_count,GetNamedPropertyHandler,0,145 -block_count,GetNamedPropertyHandler,1,120 -block_count,GetNamedPropertyHandler,2,120 +block_count,GetNamedPropertyHandler,0,146 +block_count,GetNamedPropertyHandler,1,121 +block_count,GetNamedPropertyHandler,2,121 block_count,GetNamedPropertyHandler,3,0 -block_count,GetNamedPropertyHandler,4,120 -block_count,GetNamedPropertyHandler,5,12 +block_count,GetNamedPropertyHandler,4,121 +block_count,GetNamedPropertyHandler,5,10 block_count,GetNamedPropertyHandler,6,0 -block_count,GetNamedPropertyHandler,7,12 +block_count,GetNamedPropertyHandler,7,10 block_count,GetNamedPropertyHandler,8,5 -block_count,GetNamedPropertyHandler,9,7 -block_count,GetNamedPropertyHandler,10,12 -block_count,GetNamedPropertyHandler,11,5 -block_count,GetNamedPropertyHandler,12,5 +block_count,GetNamedPropertyHandler,9,5 +block_count,GetNamedPropertyHandler,10,9 +block_count,GetNamedPropertyHandler,11,4 +block_count,GetNamedPropertyHandler,12,4 block_count,GetNamedPropertyHandler,13,0 -block_count,GetNamedPropertyHandler,14,7 -block_count,GetNamedPropertyHandler,15,108 -block_count,GetNamedPropertyHandler,16,115 -block_count,GetNamedPropertyHandler,17,38 -block_count,GetNamedPropertyHandler,18,38 -block_count,GetNamedPropertyHandler,19,34 -block_count,GetNamedPropertyHandler,20,34 +block_count,GetNamedPropertyHandler,14,5 +block_count,GetNamedPropertyHandler,15,111 +block_count,GetNamedPropertyHandler,16,116 +block_count,GetNamedPropertyHandler,17,39 +block_count,GetNamedPropertyHandler,18,39 +block_count,GetNamedPropertyHandler,19,35 +block_count,GetNamedPropertyHandler,20,35 block_count,GetNamedPropertyHandler,21,0 -block_count,GetNamedPropertyHandler,22,34 +block_count,GetNamedPropertyHandler,22,35 block_count,GetNamedPropertyHandler,23,0 -block_count,GetNamedPropertyHandler,24,34 +block_count,GetNamedPropertyHandler,24,35 block_count,GetNamedPropertyHandler,25,7 block_count,GetNamedPropertyHandler,26,0 block_count,GetNamedPropertyHandler,27,0 @@ -60741,21 +60732,21 @@ block_count,GetNamedPropertyHandler,96,7 block_count,GetNamedPropertyHandler,97,0 block_count,GetNamedPropertyHandler,98,27 -block_count,GetNamedPropertyHandler,99,34 -block_count,GetNamedPropertyHandler,100,34 -block_count,GetNamedPropertyHandler,101,33 -block_count,GetNamedPropertyHandler,102,33 +block_count,GetNamedPropertyHandler,99,35 +block_count,GetNamedPropertyHandler,100,35 +block_count,GetNamedPropertyHandler,101,34 +block_count,GetNamedPropertyHandler,102,34 block_count,GetNamedPropertyHandler,103,0 block_count,GetNamedPropertyHandler,104,0 -block_count,GetNamedPropertyHandler,105,34 +block_count,GetNamedPropertyHandler,105,35 block_count,GetNamedPropertyHandler,106,0 block_count,GetNamedPropertyHandler,107,3 block_count,GetNamedPropertyHandler,108,0 block_count,GetNamedPropertyHandler,109,0 block_count,GetNamedPropertyHandler,110,0 block_count,GetNamedPropertyHandler,111,77 -block_count,GetNamedPropertyHandler,112,111 -block_count,GetNamedPropertyHandler,113,34 +block_count,GetNamedPropertyHandler,112,112 +block_count,GetNamedPropertyHandler,113,35 block_count,GetNamedPropertyHandler,114,5 block_count,GetNamedPropertyHandler,115,4 block_count,GetNamedPropertyHandler,116,4 @@ -60889,7 +60880,7 @@ block_count,GetNamedPropertyHandler,244,0 block_count,GetNamedPropertyHandler,245,0 block_count,GetNamedPropertyHandler,246,0 -block_count,GetNamedPropertyHandler,247,29 +block_count,GetNamedPropertyHandler,247,30 block_count,GetNamedPropertyHandler,248,76 block_count,GetNamedPropertyHandler,249,76 block_count,GetNamedPropertyHandler,250,14 @@ -60955,34 +60946,34 @@ block_count,GetNamedPropertyHandler,310,5 block_count,GetNamedPropertyHandler,311,0 block_count,GetNamedPropertyHandler,312,24 -block_count,GetNamedPropertyHandler,313,145 -block_count,GetNamedPropertyHandler,314,37 -block_count,GetNamedPropertyHandler,315,107 +block_count,GetNamedPropertyHandler,313,146 +block_count,GetNamedPropertyHandler,314,38 +block_count,GetNamedPropertyHandler,315,108 block_count,GetNamedPropertyFromSuperHandler,0,0 -block_count,GetKeyedPropertyHandler,0,55 -block_count,GetKeyedPropertyHandler,1,26 +block_count,GetKeyedPropertyHandler,0,54 +block_count,GetKeyedPropertyHandler,1,25 block_count,GetKeyedPropertyHandler,2,28 block_count,GetEnumeratedKeyedPropertyHandler,0,1 -block_count,SetNamedPropertyHandler,0,16 +block_count,SetNamedPropertyHandler,0,18 block_count,DefineNamedOwnPropertyHandler,0,4 -block_count,SetKeyedPropertyHandler,0,38 +block_count,SetKeyedPropertyHandler,0,37 block_count,DefineKeyedOwnPropertyHandler,0,0 block_count,StaInArrayLiteralHandler,0,3 block_count,DefineKeyedOwnPropertyInLiteralHandler,0,0 -block_count,AddHandler,0,32 -block_count,AddHandler,1,12 +block_count,AddHandler,0,33 +block_count,AddHandler,1,13 block_count,AddHandler,2,0 block_count,AddHandler,3,0 block_count,AddHandler,4,0 block_count,AddHandler,5,12 block_count,AddHandler,6,12 -block_count,AddHandler,7,11 +block_count,AddHandler,7,12 block_count,AddHandler,8,0 -block_count,AddHandler,9,11 +block_count,AddHandler,9,12 block_count,AddHandler,10,0 block_count,AddHandler,11,12 block_count,AddHandler,12,0 -block_count,AddHandler,13,19 +block_count,AddHandler,13,20 block_count,AddHandler,14,11 block_count,AddHandler,15,10 block_count,AddHandler,16,10 @@ -60990,7 +60981,7 @@ block_count,AddHandler,18,0 block_count,AddHandler,19,8 block_count,AddHandler,20,8 -block_count,AddHandler,21,7 +block_count,AddHandler,21,8 block_count,AddHandler,22,0 block_count,AddHandler,23,0 block_count,AddHandler,24,0 @@ -61008,7 +60999,7 @@ block_count,AddHandler,36,0 block_count,AddHandler,37,0 block_count,AddHandler,38,0 -block_count,AddHandler,39,7 +block_count,AddHandler,39,8 block_count,AddHandler,40,0 block_count,AddHandler,41,0 block_count,AddHandler,42,0 @@ -61020,9 +61011,9 @@ block_count,AddHandler,48,0 block_count,AddHandler,49,0 block_count,AddHandler,50,7 -block_count,AddHandler,51,6 +block_count,AddHandler,51,7 block_count,AddHandler,52,0 -block_count,AddHandler,53,6 +block_count,AddHandler,53,7 block_count,AddHandler,54,0 block_count,AddHandler,55,7 block_count,AddHandler,56,0 @@ -61051,7 +61042,7 @@ block_count,AddHandler,79,0 block_count,AddHandler,80,11 block_count,AddHandler,81,11 -block_count,AddHandler,82,32 +block_count,AddHandler,82,33 block_count,AddHandler,83,18 block_count,AddHandler,84,14 block_count,SubHandler,0,6 @@ -61154,8 +61145,8 @@ block_count,MulHandler,27,2 block_count,MulHandler,28,0 block_count,MulHandler,29,2 -block_count,MulHandler,30,9 -block_count,MulHandler,31,9 +block_count,MulHandler,30,10 +block_count,MulHandler,31,10 block_count,MulHandler,32,8 block_count,MulHandler,33,8 block_count,MulHandler,34,0 @@ -61198,9 +61189,9 @@ block_count,MulHandler,71,0 block_count,MulHandler,72,0 block_count,MulHandler,73,13 -block_count,MulHandler,74,12 +block_count,MulHandler,74,13 block_count,MulHandler,75,0 -block_count,MulHandler,76,12 +block_count,MulHandler,76,13 block_count,MulHandler,77,0 block_count,MulHandler,78,13 block_count,MulHandler,79,0 @@ -62560,7 +62551,7 @@ block_count,ShiftRightSmiHandler,39,7 block_count,ShiftRightSmiHandler,40,0 block_count,ShiftRightSmiHandler,41,7 -block_count,ShiftRightLogicalSmiHandler,0,1 +block_count,ShiftRightLogicalSmiHandler,0,0 block_count,ShiftRightLogicalSmiHandler,1,0 block_count,ShiftRightLogicalSmiHandler,2,0 block_count,ShiftRightLogicalSmiHandler,3,0 @@ -62605,14 +62596,14 @@ block_count,ShiftRightLogicalSmiHandler,42,0 block_count,ShiftRightLogicalSmiHandler,43,0 block_count,ShiftRightLogicalSmiHandler,44,0 -block_count,ShiftRightLogicalSmiHandler,45,1 +block_count,ShiftRightLogicalSmiHandler,45,0 block_count,ShiftRightLogicalSmiHandler,46,0 block_count,ShiftRightLogicalSmiHandler,47,0 block_count,ShiftRightLogicalSmiHandler,48,0 block_count,ShiftRightLogicalSmiHandler,49,0 -block_count,ShiftRightLogicalSmiHandler,50,1 -block_count,IncHandler,0,40 -block_count,IncHandler,1,40 +block_count,ShiftRightLogicalSmiHandler,50,0 +block_count,IncHandler,0,41 +block_count,IncHandler,1,41 block_count,IncHandler,2,0 block_count,IncHandler,3,0 block_count,IncHandler,4,0 @@ -62629,21 +62620,21 @@ block_count,IncHandler,15,0 block_count,IncHandler,16,0 block_count,IncHandler,17,0 -block_count,IncHandler,18,40 -block_count,IncHandler,19,40 +block_count,IncHandler,18,41 +block_count,IncHandler,19,41 block_count,IncHandler,20,0 block_count,IncHandler,21,0 block_count,IncHandler,22,0 block_count,IncHandler,23,0 block_count,IncHandler,24,0 -block_count,IncHandler,25,40 -block_count,IncHandler,26,39 +block_count,IncHandler,25,41 +block_count,IncHandler,26,40 block_count,IncHandler,27,0 -block_count,IncHandler,28,39 +block_count,IncHandler,28,40 block_count,IncHandler,29,0 -block_count,IncHandler,30,40 +block_count,IncHandler,30,41 block_count,IncHandler,31,2 -block_count,IncHandler,32,37 +block_count,IncHandler,32,38 block_count,DecHandler,0,7 block_count,DecHandler,1,7 block_count,DecHandler,2,0 @@ -62934,8 +62925,8 @@ block_count,CallAnyReceiverHandler,66,0 block_count,CallAnyReceiverHandler,67,0 block_count,CallAnyReceiverHandler,68,0 -block_count,CallPropertyHandler,0,3 -block_count,CallPropertyHandler,1,2 +block_count,CallPropertyHandler,0,4 +block_count,CallPropertyHandler,1,3 block_count,CallPropertyHandler,2,0 block_count,CallPropertyHandler,3,0 block_count,CallPropertyHandler,4,0 @@ -63000,9 +62991,9 @@ block_count,CallPropertyHandler,63,0 block_count,CallPropertyHandler,64,0 block_count,CallPropertyHandler,65,0 -block_count,CallPropertyHandler,66,2 +block_count,CallPropertyHandler,66,3 block_count,CallPropertyHandler,67,0 -block_count,CallPropertyHandler,68,3 +block_count,CallPropertyHandler,68,4 block_count,CallProperty0Handler,0,12 block_count,CallProperty0Handler,1,11 block_count,CallProperty0Handler,2,0 @@ -63072,8 +63063,8 @@ block_count,CallProperty0Handler,66,10 block_count,CallProperty0Handler,67,1 block_count,CallProperty0Handler,68,12 -block_count,CallProperty1Handler,0,26 -block_count,CallProperty1Handler,1,22 +block_count,CallProperty1Handler,0,27 +block_count,CallProperty1Handler,1,23 block_count,CallProperty1Handler,2,0 block_count,CallProperty1Handler,3,0 block_count,CallProperty1Handler,4,0 @@ -63138,9 +63129,9 @@ block_count,CallProperty1Handler,63,0 block_count,CallProperty1Handler,64,0 block_count,CallProperty1Handler,65,0 -block_count,CallProperty1Handler,66,22 +block_count,CallProperty1Handler,66,23 block_count,CallProperty1Handler,67,3 -block_count,CallProperty1Handler,68,26 +block_count,CallProperty1Handler,68,27 block_count,CallProperty2Handler,0,6 block_count,CallProperty2Handler,1,4 block_count,CallProperty2Handler,2,0 @@ -63211,7 +63202,7 @@ block_count,CallProperty2Handler,67,1 block_count,CallProperty2Handler,68,6 block_count,CallUndefinedReceiverHandler,0,1 -block_count,CallUndefinedReceiverHandler,1,1 +block_count,CallUndefinedReceiverHandler,1,0 block_count,CallUndefinedReceiverHandler,2,0 block_count,CallUndefinedReceiverHandler,3,0 block_count,CallUndefinedReceiverHandler,4,0 @@ -63345,7 +63336,7 @@ block_count,CallUndefinedReceiver0Handler,63,0 block_count,CallUndefinedReceiver0Handler,64,0 block_count,CallUndefinedReceiver0Handler,65,0 -block_count,CallUndefinedReceiver0Handler,66,8 +block_count,CallUndefinedReceiver0Handler,66,7 block_count,CallUndefinedReceiver0Handler,67,0 block_count,CallUndefinedReceiver0Handler,68,9 block_count,CallUndefinedReceiver1Handler,0,7 @@ -63615,8 +63606,8 @@ block_count,InvokeIntrinsicHandler,53,0 block_count,InvokeIntrinsicHandler,54,0 block_count,InvokeIntrinsicHandler,55,1 -block_count,ConstructHandler,0,5 -block_count,ConstructHandler,1,2 +block_count,ConstructHandler,0,6 +block_count,ConstructHandler,1,3 block_count,ConstructHandler,2,0 block_count,ConstructHandler,3,0 block_count,ConstructHandler,4,0 @@ -63659,15 +63650,15 @@ block_count,ConstructHandler,41,0 block_count,ConstructHandler,42,0 block_count,ConstructHandler,43,0 -block_count,ConstructHandler,44,2 +block_count,ConstructHandler,44,3 block_count,ConstructHandler,45,2 -block_count,ConstructHandler,46,5 -block_count,ConstructHandler,47,5 +block_count,ConstructHandler,46,6 +block_count,ConstructHandler,47,6 block_count,ConstructHandler,48,0 -block_count,ConstructHandler,49,5 +block_count,ConstructHandler,49,6 block_count,ConstructHandler,50,0 block_count,ConstructHandler,51,0 -block_count,ConstructHandler,52,5 +block_count,ConstructHandler,52,6 block_count,ConstructHandler,53,3 block_count,ConstructHandler,54,2 block_count,ConstructWithSpreadHandler,0,0 @@ -63748,8 +63739,8 @@ block_count,TestEqualHandler,0,12 block_count,TestEqualHandler,1,12 block_count,TestEqualHandler,2,10 -block_count,TestEqualHandler,3,6 -block_count,TestEqualHandler,4,6 +block_count,TestEqualHandler,3,5 +block_count,TestEqualHandler,4,5 block_count,TestEqualHandler,5,0 block_count,TestEqualHandler,6,0 block_count,TestEqualHandler,7,0 @@ -63852,7 +63843,7 @@ block_count,TestEqualHandler,104,0 block_count,TestEqualHandler,105,0 block_count,TestEqualHandler,106,0 -block_count,TestEqualHandler,107,3 +block_count,TestEqualHandler,107,4 block_count,TestEqualHandler,108,0 block_count,TestEqualHandler,109,0 block_count,TestEqualHandler,110,0 @@ -63902,7 +63893,7 @@ block_count,TestEqualStrictHandler,1,9 block_count,TestEqualStrictHandler,2,7 block_count,TestEqualStrictHandler,3,7 -block_count,TestEqualStrictHandler,4,7 +block_count,TestEqualStrictHandler,4,6 block_count,TestEqualStrictHandler,5,2 block_count,TestEqualStrictHandler,6,2 block_count,TestEqualStrictHandler,7,0 @@ -63990,13 +63981,13 @@ block_count,TestEqualStrictHandler,89,4 block_count,TestEqualStrictHandler,90,1 block_count,TestEqualStrictHandler,91,10 -block_count,TestEqualStrictHandler,92,9 +block_count,TestEqualStrictHandler,92,8 block_count,TestEqualStrictHandler,93,0 block_count,TestEqualStrictHandler,94,8 block_count,TestEqualStrictHandler,95,1 block_count,TestEqualStrictHandler,96,10 -block_count,TestLessThanHandler,0,33 -block_count,TestLessThanHandler,1,33 +block_count,TestLessThanHandler,0,34 +block_count,TestLessThanHandler,1,34 block_count,TestLessThanHandler,2,0 block_count,TestLessThanHandler,3,0 block_count,TestLessThanHandler,4,0 @@ -64085,7 +64076,7 @@ block_count,TestLessThanHandler,87,0 block_count,TestLessThanHandler,88,0 block_count,TestLessThanHandler,89,0 -block_count,TestLessThanHandler,90,32 +block_count,TestLessThanHandler,90,33 block_count,TestLessThanHandler,91,0 block_count,TestLessThanHandler,92,0 block_count,TestLessThanHandler,93,0 @@ -64097,9 +64088,9 @@ block_count,TestLessThanHandler,99,0 block_count,TestLessThanHandler,100,0 block_count,TestLessThanHandler,101,0 -block_count,TestLessThanHandler,102,32 -block_count,TestLessThanHandler,103,2 -block_count,TestLessThanHandler,104,29 +block_count,TestLessThanHandler,102,33 +block_count,TestLessThanHandler,103,3 +block_count,TestLessThanHandler,104,30 block_count,TestLessThanHandler,105,0 block_count,TestLessThanHandler,106,0 block_count,TestLessThanHandler,107,0 @@ -64111,13 +64102,13 @@ block_count,TestLessThanHandler,113,0 block_count,TestLessThanHandler,114,0 block_count,TestLessThanHandler,115,3 -block_count,TestLessThanHandler,116,29 -block_count,TestLessThanHandler,117,33 -block_count,TestLessThanHandler,118,32 +block_count,TestLessThanHandler,116,30 +block_count,TestLessThanHandler,117,34 +block_count,TestLessThanHandler,118,33 block_count,TestLessThanHandler,119,0 -block_count,TestLessThanHandler,120,32 +block_count,TestLessThanHandler,120,33 block_count,TestLessThanHandler,121,1 -block_count,TestLessThanHandler,122,33 +block_count,TestLessThanHandler,122,34 block_count,TestGreaterThanHandler,0,4 block_count,TestGreaterThanHandler,1,4 block_count,TestGreaterThanHandler,2,1 @@ -64357,15 +64348,15 @@ block_count,TestLessThanOrEqualHandler,113,0 block_count,TestLessThanOrEqualHandler,114,0 block_count,TestLessThanOrEqualHandler,115,0 -block_count,TestLessThanOrEqualHandler,116,2 +block_count,TestLessThanOrEqualHandler,116,1 block_count,TestLessThanOrEqualHandler,117,2 -block_count,TestLessThanOrEqualHandler,118,2 +block_count,TestLessThanOrEqualHandler,118,1 block_count,TestLessThanOrEqualHandler,119,0 -block_count,TestLessThanOrEqualHandler,120,2 +block_count,TestLessThanOrEqualHandler,120,1 block_count,TestLessThanOrEqualHandler,121,0 block_count,TestLessThanOrEqualHandler,122,2 -block_count,TestGreaterThanOrEqualHandler,0,4 -block_count,TestGreaterThanOrEqualHandler,1,4 +block_count,TestGreaterThanOrEqualHandler,0,5 +block_count,TestGreaterThanOrEqualHandler,1,5 block_count,TestGreaterThanOrEqualHandler,2,0 block_count,TestGreaterThanOrEqualHandler,3,0 block_count,TestGreaterThanOrEqualHandler,4,0 @@ -64454,7 +64445,7 @@ block_count,TestGreaterThanOrEqualHandler,87,0 block_count,TestGreaterThanOrEqualHandler,88,0 block_count,TestGreaterThanOrEqualHandler,89,0 -block_count,TestGreaterThanOrEqualHandler,90,3 +block_count,TestGreaterThanOrEqualHandler,90,4 block_count,TestGreaterThanOrEqualHandler,91,0 block_count,TestGreaterThanOrEqualHandler,92,0 block_count,TestGreaterThanOrEqualHandler,93,0 @@ -64466,8 +64457,8 @@ block_count,TestGreaterThanOrEqualHandler,99,0 block_count,TestGreaterThanOrEqualHandler,100,0 block_count,TestGreaterThanOrEqualHandler,101,0 -block_count,TestGreaterThanOrEqualHandler,102,3 -block_count,TestGreaterThanOrEqualHandler,103,2 +block_count,TestGreaterThanOrEqualHandler,102,4 +block_count,TestGreaterThanOrEqualHandler,103,3 block_count,TestGreaterThanOrEqualHandler,104,1 block_count,TestGreaterThanOrEqualHandler,105,0 block_count,TestGreaterThanOrEqualHandler,106,0 @@ -64479,14 +64470,14 @@ block_count,TestGreaterThanOrEqualHandler,112,0 block_count,TestGreaterThanOrEqualHandler,113,0 block_count,TestGreaterThanOrEqualHandler,114,0 -block_count,TestGreaterThanOrEqualHandler,115,2 +block_count,TestGreaterThanOrEqualHandler,115,3 block_count,TestGreaterThanOrEqualHandler,116,1 -block_count,TestGreaterThanOrEqualHandler,117,4 +block_count,TestGreaterThanOrEqualHandler,117,5 block_count,TestGreaterThanOrEqualHandler,118,4 block_count,TestGreaterThanOrEqualHandler,119,0 block_count,TestGreaterThanOrEqualHandler,120,4 block_count,TestGreaterThanOrEqualHandler,121,0 -block_count,TestGreaterThanOrEqualHandler,122,4 +block_count,TestGreaterThanOrEqualHandler,122,5 block_count,TestInstanceOfHandler,0,1 block_count,TestInstanceOfHandler,1,1 block_count,TestInstanceOfHandler,2,0 @@ -65122,11 +65113,11 @@ block_count,CreateRestParameterHandler,35,0 block_count,CreateRestParameterHandler,36,0 block_count,JumpLoopHandler,0,46 -block_count,JumpLoopHandler,1,44 +block_count,JumpLoopHandler,1,45 block_count,JumpLoopHandler,2,1 block_count,JumpLoopHandler,3,0 block_count,JumpLoopHandler,4,1 -block_count,JumpLoopHandler,5,44 +block_count,JumpLoopHandler,5,45 block_count,JumpLoopHandler,6,3 block_count,JumpLoopHandler,7,0 block_count,JumpLoopHandler,8,0 @@ -65166,11 +65157,11 @@ block_count,JumpLoopHandler,42,0 block_count,JumpLoopHandler,43,0 block_count,JumpLoopHandler,44,0 -block_count,JumpLoopHandler,45,42 +block_count,JumpLoopHandler,45,43 block_count,JumpLoopHandler,46,0 -block_count,JumpLoopHandler,47,42 -block_count,JumpLoopHandler,48,42 -block_count,JumpHandler,0,7 +block_count,JumpLoopHandler,47,43 +block_count,JumpLoopHandler,48,43 +block_count,JumpHandler,0,8 block_count,JumpConstantHandler,0,0 block_count,JumpIfUndefinedConstantHandler,0,0 block_count,JumpIfUndefinedConstantHandler,1,0 @@ -65236,11 +65227,11 @@ block_count,JumpIfToBooleanFalseConstantHandler,20,0 block_count,JumpIfToBooleanFalseConstantHandler,21,0 block_count,JumpIfToBooleanFalseConstantHandler,22,0 -block_count,JumpIfToBooleanTrueHandler,0,12 -block_count,JumpIfToBooleanTrueHandler,1,11 +block_count,JumpIfToBooleanTrueHandler,0,11 +block_count,JumpIfToBooleanTrueHandler,1,10 block_count,JumpIfToBooleanTrueHandler,2,6 -block_count,JumpIfToBooleanTrueHandler,3,5 -block_count,JumpIfToBooleanTrueHandler,4,5 +block_count,JumpIfToBooleanTrueHandler,3,4 +block_count,JumpIfToBooleanTrueHandler,4,4 block_count,JumpIfToBooleanTrueHandler,5,2 block_count,JumpIfToBooleanTrueHandler,6,2 block_count,JumpIfToBooleanTrueHandler,7,2 @@ -65276,18 +65267,18 @@ block_count,JumpIfToBooleanFalseHandler,14,3 block_count,JumpIfToBooleanFalseHandler,15,0 block_count,JumpIfToBooleanFalseHandler,16,2 -block_count,JumpIfToBooleanFalseHandler,17,4 -block_count,JumpIfToBooleanFalseHandler,18,13 +block_count,JumpIfToBooleanFalseHandler,17,3 +block_count,JumpIfToBooleanFalseHandler,18,12 block_count,JumpIfToBooleanFalseHandler,19,12 block_count,JumpIfToBooleanFalseHandler,20,0 block_count,JumpIfToBooleanFalseHandler,21,18 block_count,JumpIfToBooleanFalseHandler,22,7 block_count,JumpIfTrueHandler,0,11 -block_count,JumpIfTrueHandler,1,7 +block_count,JumpIfTrueHandler,1,8 block_count,JumpIfTrueHandler,2,3 -block_count,JumpIfFalseHandler,0,58 -block_count,JumpIfFalseHandler,1,37 -block_count,JumpIfFalseHandler,2,21 +block_count,JumpIfFalseHandler,0,60 +block_count,JumpIfFalseHandler,1,38 +block_count,JumpIfFalseHandler,2,22 block_count,JumpIfNullHandler,0,0 block_count,JumpIfNullHandler,1,0 block_count,JumpIfNullHandler,2,0 @@ -65391,9 +65382,9 @@ block_count,SetPendingMessageHandler,0,0 block_count,ThrowHandler,0,2 block_count,ReThrowHandler,0,0 -block_count,ReturnHandler,0,37 +block_count,ReturnHandler,0,38 block_count,ReturnHandler,1,0 -block_count,ReturnHandler,2,37 +block_count,ReturnHandler,2,38 block_count,ThrowReferenceErrorIfHoleHandler,0,1 block_count,ThrowReferenceErrorIfHoleHandler,1,1 block_count,ThrowReferenceErrorIfHoleHandler,2,0 @@ -65428,7 +65419,7 @@ block_count,ResumeGeneratorHandler,6,0 block_count,ResumeGeneratorHandler,7,0 block_count,GetIteratorHandler,0,0 -block_count,ShortStarHandler,0,105 +block_count,ShortStarHandler,0,106 block_count,LdarWideHandler,0,0 block_count,LdaSmiWideHandler,0,11 block_count,LdaConstantWideHandler,0,1